commit 0d1d619078c34d0bc401070d476c2e560680e1e5
parent e6a8af9f53c963f435087ad59f340467117c6709
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:57:41 -0400
Merge r29/evidence (E1 Bluesky capture, E2 deleted-video fallback) into r29/integration
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
56 files changed, 2997 insertions(+), 53 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -113,7 +113,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. | |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | |
-| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum): a screenshot of each through the connected X profile (a forum thread: its host's forum profile), and its attached media through gallery-dl (a forum thread: the same profile), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | |
+| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/<id>/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | |
| `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "<branch>", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of <id> in <dir> — archilyzer publish build <id>". `get publish` is the status. | |
| `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` |
| `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | |
@@ -142,9 +142,11 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` |
| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` |
| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` |
-| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
+| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items naming the id in their identifier, title, description or original URL, each read for its files -> {query, found, items: \[{identifier, title?, file, url, source, size?}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
+| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
+| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?. Per recording, one at a time: the Wayback Machine (the newest capture of its page that recorded a 200), then archive.org (a mirror naming its YouTube id, an original video file preferred). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". -> {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, tried: \[{from, found, url?, detail?, error?}\], copy?, outcome: fetch \| text-only \| error}\], items, stopped?, jobId?, refused?}. dryRun answers the lookups and starts nothing. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait` |
| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -218,6 +218,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts |
+| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
| `E2E_FAKE_YTDLP_CHUNK_DELAY_MS` | — | Fake yt-dlp: delay between written chunks. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/OPERATING.md b/OPERATING.md
@@ -134,6 +134,8 @@ pnpm ops tag-videos --file ids.json
pnpm archilyzer reports convert sweep <sweep.md> --out <report.json>
pnpm ops fetch-windows --json '{"siteId":"example-site","dryRun":true}'
pnpm ops fetch-windows --json '{"siteId":"example-site"}' --wait
+pnpm ops find-copy --json '{"siteId":"example-site","dryRun":true}'
+pnpm ops find-copy --json '{"siteId":"example-site"}' --wait
pnpm ops reports-prepare --json '{"siteId":"example-site"}' --wait
pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"]}' --wait
```
@@ -143,8 +145,15 @@ pnpm ops reports-export --json '{"siteId":"example-site","formats":["html","md"
report-to-video manifest.
- `fetch-windows` with `siteId` fetches every clip window the site's published reports cite that the disk does not
hold, one paced job per platform; a re-run resumes.
-- `reports-prepare` cuts the cited clips and copies the cited post captures, then exports; it fails naming each
- citation that lacks media. Offline: `pnpm archilyzer reports prepare <siteId>`,
+- A cited recording deleted or made private on its platform cannot be fetched from its page. `find-copy` (a site's
+ `siteId`, an `article`, or `"articles": true`) looks for a copy of each — a Wayback Machine capture of its page,
+ then an archive.org mirror naming its YouTube id — and fetches the cited windows from it as one fetch-windows job;
+ each window's provenance names the copy. `wayback-lookup` and `archive-search` `{"youtubeId"}` are the lookups on
+ their own.
+- `reports-prepare` cuts the cited clips and copies the cited post captures (Bluesky posts too: `capture-posts`),
+ then exports; it fails naming each citation that lacks media — except a moment whose source is gone (a deleted or
+ private recording with no copy on disk, a deleted post never captured), which is a warning: the page shows its
+ words only, marked "Source deleted". Offline: `pnpm archilyzer reports prepare <siteId>`,
`pnpm archilyzer reports export <siteId>`.
- One cited moment's media, from an agent: the MCP's `fetch_clip`.
diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts
@@ -66,6 +66,7 @@ import {
resolveReports,
} from "../publish/composeReports";
import { articlesWorkHost, siteReportHost, type ReportHost } from "../publish/reportHost";
+import { SOURCE_GONE_LABELS } from "../lib/sourceGone";
type Out = { log: (s: string) => void; error: (s: string) => void };
@@ -116,6 +117,10 @@ export async function checkMain(
for (const line of formatComposeReportsProblems(resolved.allowed)) {
out.log(` allowed (--allow-missing-media): ${line}`);
}
+ // A gone source's moment with no media is a warning: its words only.
+ for (const g of resolved.sourceGone) {
+ out.log(` warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`);
+ }
for (const r of resolved.reports) {
const scores = Object.values(r.citations ?? {})
.map((c) => (c.kind === "video" || c.kind === "audio" || c.kind === "post" ? c.verification?.quoteScore : undefined))
diff --git a/common/bin/reports-prepare.ts b/common/bin/reports-prepare.ts
@@ -63,6 +63,12 @@ export async function main(
out.error(`reports prepare: ${(err as Error).message}`);
return opts.signal?.aborted ? 1 : 2;
}
+ // A gone source's moment with no media is a warning: compose shows its words
+ // only, marked "source deleted" (release 29 E2).
+ if (index.warnings?.length) {
+ out.log(`reports prepare ${who}: warning: ${index.warnings.length} moment(s) whose source is gone show their words only:`);
+ for (const line of formatReportMediaProblems(index.warnings)) out.log(` ${line}`);
+ }
if (opts.only && opts.article) return onlyArticle(opts.article, index, opts, out);
if (index.problems.length > 0) {
out.error(`reports prepare ${who}: ${index.problems.length} problem(s):`);
diff --git a/common/components/citations/CitationCard.tsx b/common/components/citations/CitationCard.tsx
@@ -13,6 +13,7 @@ import {
type SpanCitationView,
} from "../../lib/report/views";
import { cn } from "../../lib/utils";
+import { SOURCE_GONE_LABELS } from "../../lib/sourceGone";
import { VerificationBadge } from "./VerificationBadge";
// ONE CITATION, as a reader sees it — kind-aware, from a resolved view
@@ -135,10 +136,17 @@ function Picture({ c, variant }: { c: CitationView; variant: CitationCardVariant
function SpanLinks({ c }: { c: SpanCitationView }) {
return (
<>
- <a href={c.href} className={linkClass}>
- <Play className="size-3 shrink-0" aria-hidden />
- Play {spanLabel(c.start, c.end)}
- </a>
+ {c.sourceGone ? (
+ // Nothing to play: the moment's page has its words.
+ <a href={c.href} className={linkClass}>
+ Open {spanLabel(c.start, c.end)}
+ </a>
+ ) : (
+ <a href={c.href} className={linkClass}>
+ <Play className="size-3 shrink-0" aria-hidden />
+ Play {spanLabel(c.start, c.end)}
+ </a>
+ )}
<RecordLinks r={c.record} />
{c.record.corpusUrl && (
<a href={c.record.corpusUrl} className={linkClass}>
@@ -269,6 +277,11 @@ export function CitationCard({
</span>
)}
{c.label && <span className="truncate normal-case tracking-normal">· {c.label}</span>}
+ {(c.kind === "video" || c.kind === "audio" || c.kind === "post") && c.sourceGone && (
+ <span data-source-gone={c.sourceGone} className="normal-case tracking-normal">
+ · {SOURCE_GONE_LABELS[c.sourceGone]}
+ </span>
+ )}
</div>
<div className="font-medium leading-snug text-foreground break-words">{title}</div>
{meta.length > 0 && <div className="font-mono text-xs text-muted-foreground">{meta.join(" · ")}</div>}
diff --git a/common/components/report/MomentArticle.tsx b/common/components/report/MomentArticle.tsx
@@ -3,6 +3,7 @@ import { VerdictChip } from "./VerdictChip";
import { formatTimestamp } from "../../lib/vtt";
import { CITATION_KIND_LABELS, spanLabel, type MomentPageView, type RecordView } from "../../lib/report/views";
import { ExternalLinkText, Eyebrow, dateLabel, textLink } from "./parts";
+import { SOURCE_GONE_LABELS } from "../../lib/sourceGone";
// ONE CITED MOMENT, from its view (common/lib/report/views.ts): a span's
// self-hosted evidence clip (video, or audio with its poster) or a post's
@@ -47,6 +48,16 @@ export default function MomentArticle({
{meta && <p className="font-mono text-xs text-muted-foreground">{meta}</p>}
</header>
+ {view.sourceGone && (
+ // The source is gone and no copy of the moment is published: its words
+ // only (release 29 E2).
+ <p
+ data-source-gone={view.sourceGone}
+ className="rounded-lg border border-dashed border-border px-3 py-2 text-sm text-muted-foreground"
+ >
+ {SOURCE_GONE_LABELS[view.sourceGone]}
+ </p>
+ )}
{clip && view.kind === "video" && (
<video
data-evidence-clip=""
diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts
@@ -17,6 +17,7 @@ import {
type FetchWindowsDeps,
type FetchWindowsItem,
} from "./fetchWindows";
+import { parseClipProvenance } from "../lib/clipWindow";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -421,3 +422,17 @@ test("a cached unpadded window does not cover a padded ask: it is fetched, its p
const again = await go(paths, [padded, item("v1", "/exact", 10, 20)], harness());
assert.deepEqual([again.cached.length, again.fetched.length], [2, 0]);
});
+
+test("a window of a gone recording fetched from a copy (find-copy) records which copy in its sidecar", async () => {
+ const paths = await corpus();
+ const copy = { from: "wayback" as const, url: "https://web.archive.org/web/20260125093000/https://www.youtube.com/watch?v=v1" };
+ const r = await go(paths, [{ slug: "c", id: "v1", from: 10, to: 20, webpageUrl: copy.url, copy }], harness());
+ assert.equal(r.fetched.length, 1);
+ const clips = path.join(paths.channelsDir, "c", "data", "v1", "clips");
+ const sidecar = JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")) as { copy?: unknown; ytdlp?: { args: string[] } };
+ assert.deepEqual(sidecar.copy, copy);
+ // The copy's URL is what yt-dlp was given.
+ assert.equal(sidecar.ytdlp?.args.at(-1), copy.url);
+ assert.deepEqual(parseClipProvenance(sidecar)?.copy, copy);
+ assert.equal(parseClipProvenance({ requestedBy: "x", copy: { from: "elsewhere", url: copy.url } })?.copy, undefined);
+});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -4,6 +4,7 @@ import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
import { getSettings } from "../lib/settings";
import type { DownloadFailureClass } from "../lib/availability";
+import type { ClipCopy } from "../lib/clipWindow";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { assertChannelTextReadable } from "../lib/channelMedia";
import { detectPlatform } from "../lib/platform";
@@ -127,6 +128,9 @@ export type FetchWindowsItem = {
pad?: number;
// The page URL when the caller has it; else resolved as the single fetch does.
webpageUrl?: string;
+ // The copy of a gone recording `webpageUrl` is (release 29 E2, find-copy):
+ // recorded in the window's provenance.
+ copy?: ClipCopy;
};
export type FetchWindowsFailureClass =
@@ -527,6 +531,7 @@ export async function fetchWindows({
reason: item.reason,
pad: item.pad,
requestedAt,
+ ...(item.copy ? { copy: item.copy } : {}),
},
cookiePolicy: resolveCookiePolicy(settings, config),
maxHeight,
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -194,6 +194,15 @@ export class ArchiveOrgClient {
);
}
+ // A body as text, through the same chain, gap and back-off (the Wayback
+ // CDX API answers an empty body as often as `[]`: lib/waybackClient.ts).
+ getText(url: string, accept: string, signal?: AbortSignal): Promise<string> {
+ return this.serial(async () => {
+ const res = await this.getOnce(url, accept, signal);
+ return res.text();
+ });
+ }
+
getJson(url: string, signal?: AbortSignal): Promise<unknown> {
return this.serial(async () => {
const res = await this.getOnce(url, "application/json", signal);
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -156,8 +156,24 @@ export type ClipProvenance = {
// a window cut from the video's saved container (release 21 D2,
// lib/savedVideoWindow-server.ts). Absent on every fetched window.
source?: ClipWindowSource;
+ // WHICH COPY a window of a gone recording was fetched from (release 29 E2,
+ // publish/findCopy.ts): a Wayback Machine capture of its page, or an
+ // archive.org mirror's file — and its URL. Absent when the window came from
+ // the recording's own page.
+ copy?: ClipCopy;
};
+export const CLIP_COPY_SOURCES = ["wayback", "archive.org"] as const;
+export type ClipCopy = { from: (typeof CLIP_COPY_SOURCES)[number]; url: string };
+
+export function coerceClipCopy(v: unknown): ClipCopy | undefined {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
+ const r = v as Record<string, unknown>;
+ if (!(CLIP_COPY_SOURCES as readonly unknown[]).includes(r.from)) return undefined;
+ if (typeof r.url !== "string" || !/^https?:\/\//.test(r.url)) return undefined;
+ return { from: r.from as ClipCopy["from"], url: r.url };
+}
+
export const CLIP_WINDOW_SOURCES = ["saved-video"] as const;
export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number];
@@ -198,6 +214,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null {
if ((CLIP_WINDOW_SOURCES as readonly unknown[]).includes(r.source)) {
out.source = r.source as ClipWindowSource;
}
+ const copy = coerceClipCopy(r.copy);
+ if (copy) out.copy = copy;
return out;
}
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -215,6 +215,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." },
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts", doc: "The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
{ name: "E2E_FAKE_YTDLP_CHUNK_DELAY_MS", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: delay between written chunks." },
diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts
@@ -21,6 +21,7 @@ import { enumerateOf, type EnumeratedRow } from "../tasks/trace";
import type { CorpusToolsLike } from "../tasks/types";
import { queryKey } from "./basis";
import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types";
+import { goneState } from "../../../sourceGone";
export type CandidateScope = { channels: string[]; from?: string; to?: string };
@@ -191,8 +192,6 @@ export type QuoteReaders = {
postTextOf?: (channel: string, id: string) => Promise<string | null>;
};
-// The states a recording is "gone" in, for the delta's `deleted`.
-const GONE_STATES = new Set(["deleted", "private"]);
const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name);
const isEnOrig = (name: string) => /en-orig/.test(name);
@@ -227,7 +226,8 @@ export async function recheckQuotes(cited: readonly CitedQuote[], readers: Quote
out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` });
continue;
}
- const state = rec.state && GONE_STATES.has(rec.state) ? rec.state : undefined;
+ // A recording "gone" from its platform: the one reading (lib/sourceGone.ts).
+ const state = goneState(rec.state) ?? undefined;
const t = c.start ?? 0;
const cite = { t, end: c.end ?? t };
// The primary first, then every other track: the words on any of them stand.
diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts
@@ -64,6 +64,7 @@ import type { Claim, Report, ReportKind, ReportSlidesSpec, SlideSpec } from "./s
import { reportCitationNumbers } from "./uses";
import { SITE_REPORTS_BASE, type ReportBase } from "./routes";
import { resolveVerdicts, VERDICTS, type Verdict, type VerdictStyle } from "./verdicts";
+import type { GoneState } from "../sourceGone";
export const REPORT_VIEWS_VERSION = 1;
@@ -237,6 +238,10 @@ export type SpanCitationView = CitationViewCommon & {
record: RecordView;
// A still for the card: a site-root path or an http(s) URL.
poster?: string;
+ // The recording is gone from its platform and no copy of the moment is
+ // published: the moment is its words only, said in plain words
+ // (SOURCE_GONE_LABELS, lib/sourceGone.ts). Release 29 E2.
+ sourceGone?: GoneState;
};
export type PostCitationView = CitationViewCommon & {
@@ -249,6 +254,8 @@ export type PostCitationView = CitationViewCommon & {
// The captured screenshot of the post: a site-root path.
shot?: string;
thread?: boolean;
+ // The post is deleted and was never captured: its words only.
+ sourceGone?: GoneState;
};
// A sentence of a document. The document itself (its byline and its archive
@@ -460,6 +467,9 @@ export type MomentPageView = {
cues?: CueLineView[];
// A post.
post?: MomentPostView;
+ // The source is gone and no media of the moment is published (a span with
+ // no clip, a post with no shot): the page says so in plain words.
+ sourceGone?: GoneState;
citedIn: CitedInView[];
};
@@ -477,6 +487,8 @@ export type ReportViewResolver = {
record: (c: SpanCitation | PostCitation) => RecordView;
poster?: (c: SpanCitation) => string | undefined;
post?: (c: PostCitation) => { author?: string; text?: string; shot?: string } | undefined;
+ // A cited moment whose source is gone and whose media is not published.
+ sourceGone?: (c: SpanCitation | PostCitation) => GoneState | undefined;
downloads?: ReportDownloads;
history?: ReportHistoryRef;
// The report's feeds (absolute URLs), carried only by a report with entries.
@@ -539,6 +551,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver)
end: Number(formatMomentSeconds(c.end)),
record: resolve.record(c),
poster: resolve.poster?.(c),
+ sourceGone: resolve.sourceGone?.(c),
});
break;
}
@@ -556,6 +569,7 @@ export function buildReportPageView(report: Report, resolve: ReportViewResolver)
text: post?.text,
shot: post?.shot,
thread: c.thread,
+ sourceGone: resolve.sourceGone?.(c),
});
break;
}
diff --git a/common/lib/sourceGone-server.ts b/common/lib/sourceGone-server.ts
@@ -0,0 +1,33 @@
+// The disk half of the gone reading (./sourceGone.ts): a recording's video
+// directory, a post's availability sidecar.
+//
+// SERVER-ONLY (node:fs).
+
+import path from "node:path";
+import { stateFromAvailability } from "./availability";
+import { resolveEffectiveAvailability } from "./availability-server";
+import { readPostAvailability } from "./posts-server";
+import { resolveVideoDir } from "./videoDir-server.mjs";
+import { goneState, type GoneState } from "./sourceGone";
+
+// A recording's video directory → its gone state, or null (live, or never
+// resolved: a missing or unreadable availability is NOT gone).
+export async function sourceGoneState(videoDir: string): Promise<GoneState | null> {
+ const a = await resolveEffectiveAvailability(videoDir).catch(() => null);
+ return goneState(stateFromAvailability(a));
+}
+
+// The same by channel and record id (the record's directory resolved as every
+// reader resolves it).
+export async function recordGoneState(channelsDir: string, slug: string, id: string): Promise<GoneState | null> {
+ const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null);
+ return dir ? sourceGoneState(dir) : null;
+}
+
+// A post is gone when the channel's posts-availability.json says `deleted`
+// (a deleted-post sweep or a capture saw it so). Anything else — available,
+// an unreachable account, an error, never checked — is not.
+export async function postGoneState(channelsDir: string, slug: string, id: string): Promise<"deleted" | null> {
+ const map = await readPostAvailability(path.join(channelsDir, slug)).catch(() => ({}) as Record<string, { availability: string }>);
+ return map[id]?.availability === "deleted" ? "deleted" : null;
+}
diff --git a/common/lib/sourceGone.test.ts b/common/lib/sourceGone.test.ts
@@ -0,0 +1,62 @@
+// The one gone reading (release 29 E2): deleted or private is gone; members-
+// only, an error probe, an unlisted video and no availability at all are not.
+// A post is gone when posts-availability.json says deleted.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/sourceGone.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { goneState, GONE_STATES, SOURCE_GONE_LABELS } from "./sourceGone";
+import { postGoneState, recordGoneState, sourceGoneState } from "./sourceGone-server";
+
+test("goneState: deleted and private, nothing else", () => {
+ assert.deepEqual([...GONE_STATES], ["deleted", "private"]);
+ assert.equal(goneState("deleted"), "deleted");
+ assert.equal(goneState("private"), "private");
+ for (const s of ["available", "members_only", "unlisted", "maybe_missing", "error", "", null, undefined]) {
+ assert.equal(goneState(s), null, String(s));
+ }
+ assert.equal(SOURCE_GONE_LABELS.deleted, "Source deleted");
+});
+
+test("sourceGoneState reads the video's availability as refresh does; recordGoneState by channel and id; postGoneState", async () => {
+ const channels = await mkdtemp(path.join(os.tmpdir(), "source-gone-"));
+ try {
+ const dir = path.join(channels, "demo", "data", "v1");
+ await mkdir(dir, { recursive: true });
+ assert.equal(await sourceGoneState(dir), null, "never checked: not gone");
+ const write = (availability: string) =>
+ writeFile(path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability }));
+ for (const [a, want] of [
+ ["deleted", "deleted"],
+ ["private", "private"],
+ ["members_only", null],
+ ["needs_auth", null],
+ ["error", null],
+ ["unlisted", null],
+ ["public", null],
+ ] as const) {
+ await write(a);
+ assert.equal(await sourceGoneState(dir), want, a);
+ }
+ await write("deleted");
+ assert.equal(await recordGoneState(channels, "demo", "v1"), "deleted");
+ assert.equal(await recordGoneState(channels, "demo", "nope"), null);
+
+ assert.equal(await postGoneState(channels, "demo", "p1"), null, "no sidecar");
+ await writeFile(
+ path.join(channels, "demo", "posts-availability.json"),
+ JSON.stringify({
+ p1: { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" },
+ p2: { availability: "account_unavailable", checkedAt: "2026-10-01T00:00:00.000Z" },
+ }),
+ );
+ assert.equal(await postGoneState(channels, "demo", "p1"), "deleted");
+ assert.equal(await postGoneState(channels, "demo", "p2"), null, "an unreachable account is not a deleted post");
+ } finally {
+ await rm(channels, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/sourceGone.ts b/common/lib/sourceGone.ts
@@ -0,0 +1,31 @@
+// IS THIS SOURCE GONE? — the one reading (release 29 E2).
+//
+// A recording is gone from its platform when its effective availability
+// (availability-server.ts resolveEffectiveAvailability: the explicit check or
+// the last download's outcome, whichever is newer) reads, as a viewer state
+// (availability.ts stateFromAvailability), `deleted` or `private`. Members-only
+// is not gone: a member's cookies fetch it. An `error` probe is not gone: it
+// never saw the video.
+//
+// The reading R4's refresh made first (draft/refresh/delta.ts), shared by every
+// caller since: refresh's delta, compose (a cited moment of a gone source with
+// no media is a text-only moment, `sourceGone`), the evidence windows a site
+// still needs (reportMedia.ts missingEvidenceWindows, "unfetchable: gone"),
+// fetch-windows' door and find-copy. A post is gone when posts-availability.json
+// says `deleted` (sourceGone-server.ts postGoneState).
+//
+// Pure: client-safe, no node: imports.
+
+export const GONE_STATES = ["deleted", "private"] as const;
+export type GoneState = (typeof GONE_STATES)[number];
+
+// A viewer state (or anything) as a gone state, or null when it is not one.
+export function goneState(state: string | null | undefined): GoneState | null {
+ return state === "deleted" || state === "private" ? state : null;
+}
+
+// What a reader is told about a gone source: plain words.
+export const SOURCE_GONE_LABELS: Readonly<Record<GoneState, string>> = Object.freeze({
+ deleted: "Source deleted",
+ private: "Source made private",
+});
diff --git a/common/lib/waybackClient.test.ts b/common/lib/waybackClient.test.ts
@@ -0,0 +1,80 @@
+// The Wayback CDX client (release 29 E2), over the fake Wayback on loopback
+// (common/testing/web/fakeWayback.mjs) through archive.org's polite client:
+// the JSON answer and its empty forms, the 200 filter, a 429 waited out.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackClient.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import { parseCdxJson, waybackCdxUrl, WaybackClient, waybackReplayUrl } from "./waybackClient";
+import { ArchiveOrgRequestError } from "./archiveOrgClient";
+
+const BREAD = "https://video.example/watch?v=bread-day-01";
+const GONE = "https://video.example/watch?v=gone-video-05";
+
+test("parseCdxJson: the header names the columns; [] and an empty body are none; anything else is an error", () => {
+ const rows = parseCdxJson(
+ JSON.stringify([
+ ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"],
+ ["example,video)/watch?v=x", "20260106120000", "https://video.example/watch?v=x", "text/html", "200", "D", "1"],
+ ["example,video)/watch?v=x", "not-a-time", "https://video.example/watch?v=x", "text/html", "200", "D", "1"],
+ ]),
+ );
+ assert.deepEqual(rows, [
+ {
+ timestamp: "20260106120000",
+ original: "https://video.example/watch?v=x",
+ status: "200",
+ mimetype: "text/html",
+ replayUrl: "https://web.archive.org/web/20260106120000/https://video.example/watch?v=x",
+ },
+ ]);
+ assert.deepEqual(parseCdxJson("[]"), []);
+ assert.deepEqual(parseCdxJson(""), []);
+ assert.deepEqual(parseCdxJson('[["urlkey","timestamp","original"]]'), []);
+ assert.throws(() => parseCdxJson("<html>busy</html>"), /did not answer JSON/);
+ assert.throws(() => parseCdxJson('{"a":1}'), /not a list/);
+ assert.equal(waybackReplayUrl("20260101000000", "https://a.example/x"), "https://web.archive.org/web/20260101000000/https://a.example/x");
+ assert.equal(
+ waybackCdxUrl("https://a.example/x?v=1", { okOnly: true, limit: 5 }),
+ "https://web.archive.org/cdx/search/cdx?url=https%3A%2F%2Fa.example%2Fx%3Fv%3D1&output=json&filter=statuscode%3A200&limit=5",
+ );
+});
+
+test("captures: every one oldest first, only the 200s, none for an uncaptured page", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const c = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 });
+ assert.deepEqual((await c.captures(BREAD)).map((x) => [x.timestamp, x.status]), [
+ ["20260106120000", "200"],
+ ["20260301080000", "302"],
+ ]);
+ assert.deepEqual((await c.captures(BREAD, { okOnly: true })).map((x) => x.timestamp), ["20260106120000"]);
+ const gone = await c.captures(GONE, { okOnly: true });
+ assert.equal(gone[0]!.replayUrl, `https://web.archive.org/web/20260125093000/${GONE}`);
+ assert.deepEqual(await c.captures("https://video.example/watch?v=never"), []);
+ assert.equal(c.requests, 4);
+ } finally {
+ await wb.close();
+ }
+});
+
+test("a 429 is waited out (Retry-After) and asked again; one that persists stops with rateLimited", async () => {
+ const wb = await startFakeWayback({ busyTimes: 1 });
+ try {
+ const waits: number[] = [];
+ const c = new WaybackClient({ fetch: wb.fetch, sleep: async (ms) => void waits.push(ms) }, { minGapMs: 0 });
+ assert.equal((await c.captures(GONE)).length, 1);
+ assert.deepEqual(waits, [1_000]);
+ } finally {
+ await wb.close();
+ }
+ const busy = await startFakeWayback({ busyTimes: 10 });
+ try {
+ const c = new WaybackClient({ fetch: busy.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 3 });
+ await assert.rejects(c.captures(GONE), (e: unknown) => e instanceof ArchiveOrgRequestError && e.rateLimited);
+ } finally {
+ await busy.close();
+ }
+});
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -0,0 +1,118 @@
+// THE WAYBACK MACHINE'S CDX API (release 29 E2): which captures web.archive.org
+// holds of a URL — the deleted-video fallback asks it for a gone recording's
+// watch page (publish/findCopy.ts, `pnpm ops wayback-lookup`).
+//
+// web.archive.org is archive.org's, and is asked with archive.org's manners:
+// the same polite client (lib/archiveOrgClient.ts) — one request at a time, a
+// 2 s gap, the project's User-Agent, 429/503 waited out (Retry-After, else 5 s,
+// 10 s, … capped) a few times and then stopped — as its own instance, so a
+// Wayback lookup and an archive.org import each keep their own gap.
+//
+// A capture's replay URL is `https://web.archive.org/web/<timestamp>/<url>`:
+// the page as captured, which is also what yt-dlp's Wayback extractor reads
+// a YouTube watch page's video from.
+
+import {
+ ArchiveOrgClient,
+ ArchiveOrgRequestError,
+ type ArchiveOrgClientDeps,
+ type ArchiveOrgClientOpts,
+} from "./archiveOrgClient";
+
+export const WAYBACK_ORIGIN = "https://web.archive.org";
+
+export type WaybackCapture = {
+ // YYYYMMDDhhmmss
+ timestamp: string;
+ // The URL as captured.
+ original: string;
+ // The HTTP status the capture recorded ("200", "302", "-" for a revisit).
+ status: string;
+ mimetype?: string;
+ // The capture's page on web.archive.org.
+ replayUrl: string;
+};
+
+export function waybackReplayUrl(timestamp: string, original: string): string {
+ return `${WAYBACK_ORIGIN}/web/${timestamp}/${original}`;
+}
+
+export function waybackCdxUrl(url: string, o: { limit?: number; okOnly?: boolean } = {}): string {
+ const q = new URLSearchParams();
+ q.set("url", url);
+ q.set("output", "json");
+ if (o.okOnly) q.set("filter", "statuscode:200");
+ if (o.limit) q.set("limit", String(o.limit));
+ return `${WAYBACK_ORIGIN}/cdx/search/cdx?${q.toString()}`;
+}
+
+// The CDX API's JSON answer: a header row naming the columns, then one row per
+// capture. `[]`, an empty body or a header alone: no captures. Anything else
+// that is not that shape is an error (the API changed, or answered a page).
+export function parseCdxJson(body: string): WaybackCapture[] {
+ const text = body.trim();
+ if (!text) return [];
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`);
+ }
+ if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list");
+ if (raw.length === 0) return [];
+ const [header, ...rows] = raw as unknown[][];
+ if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row");
+ const col = (name: string) => header.indexOf(name);
+ const ts = col("timestamp");
+ const orig = col("original");
+ const st = col("statuscode");
+ const mt = col("mimetype");
+ if (ts < 0 || orig < 0) throw new Error("the CDX API's header names no timestamp or original");
+ const out: WaybackCapture[] = [];
+ for (const row of rows) {
+ if (!Array.isArray(row)) continue;
+ const timestamp = String(row[ts] ?? "");
+ const original = String(row[orig] ?? "");
+ if (!/^\d{14}$/.test(timestamp) || !original) continue;
+ const mimetype = mt >= 0 && typeof row[mt] === "string" ? (row[mt] as string) : undefined;
+ out.push({
+ timestamp,
+ original,
+ status: st >= 0 ? String(row[st] ?? "") : "",
+ ...(mimetype ? { mimetype } : {}),
+ replayUrl: waybackReplayUrl(timestamp, original),
+ });
+ }
+ return out;
+}
+
+export class WaybackClient {
+ private readonly http: ArchiveOrgClient;
+
+ constructor(deps: ArchiveOrgClientDeps = {}, opts: ArchiveOrgClientOpts = {}) {
+ this.http = new ArchiveOrgClient(deps, opts);
+ }
+
+ // Requests sent (each attempt), for tests and logs.
+ get requests(): number {
+ return this.http.requests;
+ }
+
+ // The captures of `url`, oldest first: every capture, or (`okOnly`) only the
+ // ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept
+ // refusing (`rateLimited`) or answered an error.
+ async captures(
+ url: string,
+ o: { limit?: number; okOnly?: boolean; signal?: AbortSignal } = {},
+ ): Promise<WaybackCapture[]> {
+ const body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal);
+ try {
+ return parseCdxJson(body);
+ } catch (e) {
+ throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false);
+ }
+ }
+}
+
+// THE process's Wayback client: one chain, one gap.
+export const waybackClient = new WaybackClient();
diff --git a/common/publish/composeReports.test.ts b/common/publish/composeReports.test.ts
@@ -512,6 +512,55 @@ test("a citation without prepared media fails compose with the list, unless --al
}
});
+test("a gone source with no prepared media is its words only, marked sourceGone; a live one is still refused", async () => {
+ // The recording deleted on its platform (lib/sourceGone.ts reads
+ // availability.json), the post deleted in posts-availability.json; neither
+ // has prepared media.
+ const avail = path.join(paths.channelsDir, VIDEOS, "data", "abc123", "availability.json");
+ const postsAvail = path.join(paths.channelsDir, SOCIAL, "posts-availability.json");
+ writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" });
+ writeJson(postsAvail, { "3kabc": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" } });
+ seedMedia("cited", [`${VIDEOS}/abc123/10.00-20.00`, `${SOCIAL}/3kabc`]);
+ try {
+ await compose("cited");
+ const span = readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json"));
+ assert.equal(span.sourceGone, "deleted");
+ assert.equal(span.clip, undefined);
+ assert.ok(Array.isArray(span.cues) && (span.cues as unknown[]).length > 0, "its words are there");
+ const post = readJson<Record<string, unknown> & { post: { shot?: string } }>(pub("m", SOCIAL, "3kabc", "moment.json"));
+ assert.equal(post.sourceGone, "deleted");
+ assert.equal(post.post.shot, undefined);
+ const view = readJson<{ citations: Record<string, { sourceGone?: string }> }>(pub("pages", REPORT, "page.json"));
+ assert.equal(view.citations.c01.sourceGone, "deleted");
+ assert.equal(view.citations.p01.sourceGone, "deleted");
+ // A moment of a live recording with media keeps its clip, unmarked.
+ assert.equal(view.citations.c02.sourceGone, undefined);
+ assert.ok(!existsSync(pub("media", "clips", VIDEOS, "abc123")));
+
+ // Made private reads as gone too; live again (no availability): refused.
+ writeJson(avail, { checkedAt: "2026-10-01T00:00:00.000Z", availability: "private" });
+ await compose("cited");
+ assert.equal(readJson<Record<string, unknown>>(pub("m", VIDEOS, "abc123", "10.00-20.00", "moment.json")).sourceGone, "private");
+ rmSync(avail);
+ rmSync(postsAvail);
+ await assert.rejects(compose("cited"), (e: unknown) => {
+ assert.ok(e instanceof ComposeReportsError);
+ assert.deepEqual(
+ e.problems.map((p) => [p.kind, p.moment]),
+ [
+ ["missing-media", `${VIDEOS}/abc123/10.00-20.00`],
+ ["missing-media", `${SOCIAL}/3kabc`],
+ ],
+ );
+ return true;
+ });
+ } finally {
+ rmSync(avail, { force: true });
+ rmSync(postsAvail, { force: true });
+ seedMedia("cited");
+ }
+});
+
test("a report's video: copied beside its page and named in the view; a missing or oversize one fails compose", async () => {
const dir = path.join(paths.sitesDir, "cited", "reports", REPORT);
const file = path.join(dir, "report.json");
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -150,6 +150,8 @@ import { publishReportHistory, readReportHistoryView, reportHistoryRef, storeHis
import { hostCorpusLink, siteReportHost, type ReportHost } from "./reportHost";
import type { ReportHistoryRef, ReportHistoryView } from "../lib/report/revisions";
import { LEGACY_SITE_REPORTS_DIR, SITE_REPORTS_BASE, reportBaseDir, type ReportBase } from "../lib/report/routes";
+import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone";
+import { postGoneState, recordGoneState } from "../lib/sourceGone-server";
// The public dir's entries this stage owns for a host serving its reports
// under `base`: its reports, the moments, the cited media. Every compose
@@ -264,6 +266,8 @@ export type ComposedReports = {
moments: string[];
// Media problems let through by `allowMissingMedia`.
allowed: ComposeReportsProblem[];
+ // The moments published with their words only, their source gone.
+ sourceGone?: SourceGoneMoment[];
// The reports whose revision history was published.
histories?: string[];
};
@@ -504,8 +508,13 @@ export type ResolvedSiteReports = {
mediaOf: Map<string, ReportMediaEntry>;
cacheDir: string;
allowed: ComposeReportsProblem[];
+ // The moments accepted with no media because their source is gone (a
+ // warning, never a problem): each shows its words only, marked.
+ sourceGone: SourceGoneMoment[];
};
+export type SourceGoneMoment = { moment: string; state: GoneState; citations: string[] };
+
export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promise<ResolvedSiteReports> {
const { site, ...rest } = opts;
return resolveReports({ ...rest, host: siteReportHost(opts.paths, site) });
@@ -659,6 +668,8 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const citedIn = buildCitedIn(reports);
const momentInfo = new Map(citedMoments(reports).map((m) => [m.key, m]));
const mediaOf = new Map<string, ReportMediaEntry>();
+ // moment key → its source's gone state, for a moment accepted with no media.
+ const sourceGone = new Map<string, GoneState>();
for (const key of Object.keys(citedIn)) {
const m = momentInfo.get(key);
if (!m || refusedChannel.has(m.moment.channel)) continue;
@@ -667,6 +678,18 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const missing = (kind: ComposeReportsProblemKind, message: string) =>
problems.push({ kind, moment: key, message: `${message} (cited by ${[...new Set(citedBy)].join(", ")})` });
if (!entry) {
+ // A SOURCE GONE FROM ITS PLATFORM with no media prepared (release 29 E2):
+ // accepted as a text-only moment, marked — the recording deleted or made
+ // private (lib/sourceGone.ts), the post deleted in posts-availability.json.
+ // A live source with no media is still refused.
+ const gone =
+ m.kind === "post"
+ ? await postGoneState(paths.channelsDir, m.moment.channel, m.moment.id)
+ : await recordGoneState(paths.channelsDir, m.moment.channel, m.moment.id);
+ if (gone) {
+ sourceGone.set(key, gone);
+ continue;
+ }
missing("missing-media", "no prepared media — run Prepare evidence media (archilyzer reports prepare)");
continue;
}
@@ -787,6 +810,10 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const post = postsByChannel.get(c.channel)?.get(c.id);
return post ? { author: postAuthor(post), text: post.text, shot: postShot(c) } : undefined;
},
+ sourceGone: (c) => {
+ const k = momentKeyOf(c);
+ return k ? sourceGone.get(k) : undefined;
+ },
downloads: opts.downloads?.(report.id),
history: opts.history?.(report.id),
feeds: opts.feeds?.(report.id),
@@ -820,6 +847,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
...(c.speaker ? { speaker: c.speaker } : {}),
...(c.date ? { date: c.date } : {}),
...(c.verification ? { verification: c.verification } : {}),
+ ...(sourceGone.has(key) ? { sourceGone: sourceGone.get(key)! } : {}),
citedIn: citedInViews(entries, views, host.base),
} as const;
if (c.kind === "post") {
@@ -868,7 +896,13 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
});
}
moments.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
- return { reports, views, index, moments, mediaOf, cacheDir, allowed };
+ const gone = [...sourceGone].map(([moment, state]) => ({
+ moment,
+ state,
+ citations: [...new Set(citedIn[moment].map((e) => `${e.reportId}#${e.citationId}`))],
+ }));
+ for (const g of gone) log(`[reports] warning: ${g.moment}: ${SOURCE_GONE_LABELS[g.state].toLowerCase()} — its words only (cited by ${g.citations.join(", ")})`);
+ return { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone: gone };
}
// ─── The stage ───
@@ -937,7 +971,7 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi
if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems, composedReportsNoun(host));
// A timeline's feeds link absolutely: a site with no public URL publishes none.
const siteUrl = host.siteUrl;
- const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveReports({
+ const { reports, views, index, moments, mediaOf, cacheDir, allowed, sourceGone } = await resolveReports({
...opts,
history: (id) => histories.get(id)?.ref,
feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id, base) : undefined,
@@ -1009,9 +1043,16 @@ export async function composeHostReports(opts: ComposeHostReportsOptions): Promi
}
log(
`[reports] ${reports.length} report(s), ${moments.length} moment page(s), ${copied} media file(s)` +
- `${allowed.length ? `, ${allowed.length} without media` : ""}.`,
+ `${allowed.length ? `, ${allowed.length} without media` : ""}` +
+ `${sourceGone.length ? `, ${sourceGone.length} whose source is gone (words only)` : ""}.`,
);
- return { reports: index.reports, moments: moments.map((m) => m.key), allowed, histories: [...histories.keys()] };
+ return {
+ reports: index.reports,
+ moments: moments.map((m) => m.key),
+ allowed,
+ ...(sourceGone.length ? { sourceGone } : {}),
+ histories: [...histories.keys()],
+ };
}
// A clip's published path: the moment's (lib/report/views.ts), `.m4a` for a
diff --git a/common/publish/findCopy.test.ts b/common/publish/findCopy.test.ts
@@ -0,0 +1,209 @@
+// find-copy (release 29 E2) over the fake Wayback and the fake archive.org on
+// loopback, through the real polite clients: per gone recording, Wayback first,
+// archive.org second, none → its words only; the fetch-windows items carry the
+// copy's URL and the copy; one recording at a time; a dry run starts nothing.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopy.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import { ITEMS, startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs";
+import { ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { WaybackClient } from "../lib/waybackClient";
+import type { MissingEvidenceWindows, UnfetchableEvidenceWindow } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { Paths } from "../lib/paths";
+import type { FetchWindowsItem } from "../controller/fetchWindows";
+import {
+ findArchiveOrgMirrors,
+ findCopies,
+ pickMirrorFile,
+ runFindCopy,
+ youtubeIdOf,
+ youtubeIdQuery,
+} from "./findCopy";
+
+const CH = "synth-kitchen";
+const watch = (id: string) => `https://video.example/watch?v=${id}`;
+
+// A second mirror, for a recording the Wayback has no capture of.
+const OTHER_MIRROR = {
+ metadata: {
+ identifier: "youtube-otherupload1",
+ title: "Another lost upload",
+ mediatype: "movies",
+ description: "Mirror of https://video.example/watch?v=otherupload1",
+ },
+ files: [
+ { name: "Another lost upload-otherupload1.mkv", source: "original", format: "Matroska", size: "4000" },
+ { name: "Another lost upload-otherupload1.mp4", source: "original", format: "MPEG4", size: "3000" },
+ ],
+};
+
+const gone = (id: string, from: number, clip: string): UnfetchableEvidenceWindow => ({
+ slug: CH,
+ id,
+ from,
+ to: from + 10,
+ clipId: clip,
+ citations: [clip],
+ reason: `the words of ${id}`,
+ why: "gone",
+ gone: "deleted",
+ message: "the source says the video is deleted",
+});
+
+const NEED: MissingEvidenceWindows = {
+ siteId: "articles",
+ missing: [],
+ onDisk: 0,
+ problems: [],
+ unfetchable: [
+ gone("gone-video-05", 0, "a#c1"),
+ gone("gone-video-05", 30, "a#c2"),
+ gone("otherupload1", 5, "a#c3"),
+ gone("nothing00001", 5, "a#c4"),
+ { ...gone("elsewhere001", 1, "a#c5"), why: "not-in-site", gone: undefined },
+ ],
+};
+
+async function fakes(o: { waybackBusy?: number } = {}) {
+ const wb = await startFakeWayback({ busyTimes: o.waybackBusy ?? 0 });
+ const ia = await startFakeArchiveOrg({ items: [...ITEMS, OTHER_MIRROR] });
+ const deps = {
+ wayback: new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }),
+ archive: new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }),
+ missing: async () => NEED,
+ webpageUrl: async (_p: Paths, _slug: string, id: string) => watch(id),
+ };
+ return { wb, ia, deps, close: async () => Promise.all([wb.close(), ia.close()]) };
+}
+
+const opts = (deps: unknown) => ({ paths: {} as Paths, host: { id: "articles" } as ReportHost, deps: deps as never });
+
+test("youtubeIdOf and the mirror query", () => {
+ assert.equal(youtubeIdOf("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf("https://youtu.be/dQw4w9WgXcQ?t=4", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf("https://www.youtube.com/shorts/dQw4w9WgXcQ", "x"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf(null, "dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+ assert.equal(youtubeIdOf(null, "a/b"), null);
+ assert.match(youtubeIdQuery("dQw4w9WgXcQ"), /^identifier:\(youtube-dQw4w9WgXcQ\) OR originalurl:\(\*dQw4w9WgXcQ\*\)/);
+ assert.throws(() => youtubeIdQuery("no spaces allowed"), /not a YouTube id/);
+});
+
+test("pickMirrorFile: a file naming the id, an original before a derivative, mp4 before webm; a dump of many is no pick", () => {
+ const f = (name: string, source: string) => ({ name, source });
+ assert.deepEqual(pickMirrorFile({ files: [f("x-ID12345.webm", "original"), f("x-ID12345.mp4", "derivative")] }, "ID12345"), {
+ file: "x-ID12345.webm",
+ source: "original",
+ });
+ assert.equal(pickMirrorFile({ files: [f("a.mp4", "original"), f("b.webm", "original")] }, "ID12345"), null);
+ assert.equal(pickMirrorFile({ files: [f("only.mkv", "original"), f("only.mp4", "derivative")] }, "ID12345")?.file, "only.mkv");
+ assert.equal(pickMirrorFile({ files: [f("notes.txt", "original")] }, "ID12345"), null);
+});
+
+test("archive-search by YouTube id: each mirror's direct file URL, an original preferred", async () => {
+ const { deps, close } = await fakes();
+ try {
+ const r = await findArchiveOrgMirrors("gone-video-05", { client: deps.archive });
+ assert.equal(r.found, 1);
+ assert.deepEqual(r.mirrors, [
+ {
+ identifier: "youtube-gone-video-05",
+ title: "The old oven review",
+ file: "The old oven review-gone-video-05.webm",
+ url: "https://archive.org/download/youtube-gone-video-05/The%20old%20oven%20review-gone-video-05.webm",
+ source: "original",
+ size: 3000000,
+ },
+ ]);
+ assert.deepEqual((await findArchiveOrgMirrors("nothing00001", { client: deps.archive })).mirrors, []);
+ } finally {
+ await close();
+ }
+});
+
+test("find-copy: Wayback first, archive.org second, none → words only; one recording at a time", async () => {
+ const { wb, ia, deps, close } = await fakes();
+ try {
+ const lines: string[] = [];
+ const r = await findCopies({ ...opts(deps), onLog: (l) => lines.push(l) });
+ assert.deepEqual(
+ r.recordings.map((x) => [x.id, x.outcome, x.copy?.from ?? null, x.windows.length]),
+ [
+ ["gone-video-05", "fetch", "wayback", 2],
+ ["otherupload1", "fetch", "archive.org", 1],
+ ["nothing00001", "text-only", null, 1],
+ ],
+ );
+ const first = r.recordings[0]!;
+ assert.equal(first.copy!.url, `https://web.archive.org/web/20260125093000/${watch("gone-video-05")}`);
+ assert.deepEqual(first.tried.map((t) => [t.from, t.found]), [["wayback", true]], "archive.org not asked once Wayback had it");
+ assert.deepEqual(r.recordings[2]!.tried.map((t) => [t.from, t.found]), [
+ ["wayback", false],
+ ["archive.org", false],
+ ]);
+ assert.equal(r.recordings[1]!.copy!.url, "https://archive.org/download/youtube-otherupload1/Another%20lost%20upload-otherupload1.mp4");
+ // Per recording, the CDX first; the archive.org search only when it had none.
+ assert.deepEqual(
+ wb.requests.map((q) => new URL(q.path, "http://x").searchParams.get("url")),
+ ["gone-video-05", "otherupload1", "nothing00001"].map(watch),
+ );
+ assert.ok(ia.requests.every((q) => !q.includes("gone-video-05")), "no archive.org search for the one Wayback found");
+ assert.equal(ia.requests.filter((q) => q.startsWith("/advancedsearch.php")).length, 2);
+
+ // The items: each found copy's windows, its URL as webpageUrl, the copy.
+ assert.deepEqual(
+ r.items.map((i) => [i.id, i.from, i.to, i.clipId, i.webpageUrl === i.copy?.url, i.copy?.from]),
+ [
+ ["gone-video-05", 0, 10, "a#c1", true, "wayback"],
+ ["gone-video-05", 30, 40, "a#c2", true, "wayback"],
+ ["otherupload1", 5, 15, "a#c3", true, "archive.org"],
+ ],
+ );
+ assert.ok(lines.some((l) => l.includes("nothing00001") && l.includes("its words only")));
+ } finally {
+ await close();
+ }
+});
+
+test("runFindCopy: the found windows go to ONE fetch-windows call; a dry run and a run that finds nothing start none", async () => {
+ const { deps, close } = await fakes();
+ try {
+ const calls: FetchWindowsItem[][] = [];
+ const start = async (items: FetchWindowsItem[]) => {
+ calls.push(items);
+ return { jobId: "J1" };
+ };
+ const dry = await runFindCopy({ ...opts(deps), dryRun: true, startFetch: start });
+ assert.equal(calls.length, 0);
+ assert.equal(dry.items.length, 3);
+ const run = await runFindCopy({ ...opts(deps), startFetch: start });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0]!.length, 3);
+ assert.deepEqual(run.fetch, { jobId: "J1" });
+ const none = await runFindCopy({
+ ...opts({ ...deps, missing: async () => ({ ...NEED, unfetchable: [NEED.unfetchable[3]] }) }),
+ startFetch: start,
+ });
+ assert.equal(calls.length, 1);
+ assert.equal(none.fetch, undefined);
+ assert.equal(none.recordings[0]!.outcome, "text-only");
+ } finally {
+ await close();
+ }
+});
+
+test("a Wayback that keeps refusing stops the run there; the rest are left for a later run", async () => {
+ const { deps, close } = await fakes({ waybackBusy: 50 });
+ try {
+ const r = await findCopies(opts(deps));
+ assert.equal(r.recordings.length, 1);
+ assert.equal(r.recordings[0]!.outcome, "error");
+ assert.match(r.stopped ?? "", /kept refusing/);
+ assert.deepEqual(r.items, []);
+ } finally {
+ await close();
+ }
+});
diff --git a/common/publish/findCopy.ts b/common/publish/findCopy.ts
@@ -0,0 +1,387 @@
+// FIND A COPY OF A GONE RECORDING (release 29 E2) — the deleted-video fallback.
+//
+// A report cites a moment of a recording its platform no longer serves
+// (deleted or made private: lib/sourceGone.ts). Its window cannot be fetched
+// from its own page, so `missingEvidenceWindows` lists it as "unfetchable:
+// gone". This looks for a copy, per recording, in order:
+//
+// 1. THE WAYBACK MACHINE: a capture of the recording's page that recorded a
+// 200 (the CDX API, lib/waybackClient.ts) — the newest — whose replay URL
+// `https://web.archive.org/web/<ts>/<page>` yt-dlp reads the video from;
+// 2. ARCHIVE.ORG: a mirror that names the YouTube id (in its identifier, its
+// title, its description or its original URL) and holds a video file —
+// an original preferred — fetched by its direct URL
+// `https://archive.org/download/<identifier>/<file>`.
+//
+// A copy found: the recording's cited windows go to fetch-windows with the
+// copy's URL as each item's `webpageUrl` (controller/fetchWindows.ts), so the
+// clips land in the recording's own `data/<id>/clips/`, and each window's
+// sidecar records which copy (`copy: {from, url}`, lib/clipWindow.ts). None
+// found: the windows are left, and compose shows the moments' words only,
+// marked "source deleted".
+//
+// PACED: one recording at a time; every Wayback and archive.org request goes
+// through the polite clients (one at a time, 2 s apart, 429s waited out). A
+// lookup that archive.org keeps refusing stops the run there; the rest are
+// left for a later run. The fetch is ONE fetch-windows job on the archive.org
+// clip queue, which walks its windows one at a time — one stream.
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ClipCopy } from "../lib/clipWindow";
+import type { GoneState } from "../lib/sourceGone";
+import { loadAvailability } from "../lib/availability-server";
+import { archiveOrgClient, ArchiveOrgRequestError, type ArchiveOrgClient } from "../lib/archiveOrgClient";
+import { archiveOrgDownloadUrl } from "../lib/archiveOrgId";
+import { archiveOrgRestriction, searchArchiveOrgItems } from "../controller/archiveOrgImport";
+import { isArchiveOrgVideoFileName, type ArchiveOrgItemMetadata } from "../lib/archiveOrg";
+import { waybackClient, type WaybackCapture } from "../lib/waybackClient";
+import { resolveVideoDirId } from "../lib/videoDir-server.mjs";
+import { channelConfigPlatform } from "../lib/videoId";
+import { readChannelConfig } from "../controller/channels";
+import { findVideoSourceUrl } from "../controller/undownloadedVideos";
+import { missingEvidenceWindows, type EvidenceWindow, type MissingEvidenceWindows } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+import type { FetchWindowsItem } from "../controller/fetchWindows";
+
+// ─── A recording's page and its YouTube id ───
+
+// The page a gone recording was served at: its metadata's `webpage_url`, else
+// the one its availability check recorded, else the playlist's.
+export async function recordWebpageUrl(paths: Paths, slug: string, id: string): Promise<string | null> {
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ const dirId = await resolveVideoDirId(paths.channelsDir, slug, id, config ? { platform: channelConfigPlatform(config) } : {});
+ const dir = path.join(paths.channelsDir, slug, "data", dirId);
+ try {
+ const meta = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")) as { webpage_url?: unknown };
+ if (typeof meta.webpage_url === "string" && /^https?:\/\//.test(meta.webpage_url)) return meta.webpage_url;
+ } catch {
+ // no metadata: the next source
+ }
+ const av = await loadAvailability(dir).catch(() => null);
+ if (av?.webpageUrl && /^https?:\/\//.test(av.webpageUrl)) return av.webpageUrl;
+ return config ? findVideoSourceUrl(paths, slug, dirId, config).catch(() => null) : null;
+}
+
+const YOUTUBE_ID = /^[A-Za-z0-9_-]{6,20}$/;
+
+// The id a mirror would name: a watch URL's `v`, a youtu.be path, a
+// /shorts/ or /live/ path — else the record's own id.
+export function youtubeIdOf(watchUrl: string | null, recordId: string): string | null {
+ if (watchUrl) {
+ try {
+ const u = new URL(watchUrl);
+ const v = u.searchParams.get("v");
+ if (v && YOUTUBE_ID.test(v)) return v;
+ const seg = u.pathname.split("/").filter(Boolean);
+ if (u.hostname.endsWith("youtu.be") && seg[0] && YOUTUBE_ID.test(seg[0])) return seg[0];
+ const k = seg.findIndex((s) => s === "shorts" || s === "live" || s === "embed");
+ if (k >= 0 && seg[k + 1] && YOUTUBE_ID.test(seg[k + 1])) return seg[k + 1];
+ } catch {
+ // not a URL: the record's id
+ }
+ }
+ return YOUTUBE_ID.test(recordId) ? recordId : null;
+}
+
+// ─── archive.org: a mirror by YouTube id ───
+
+// archive.org's advanced search for a mirror of one YouTube upload: a
+// mirroring tool's identifier (`youtube-<id>`), its original URL, or the id
+// in its description or title.
+export function youtubeIdQuery(id: string): string {
+ if (!YOUTUBE_ID.test(id)) throw new Error(`"${id}" is not a YouTube id`);
+ return `identifier:(youtube-${id}) OR originalurl:(*${id}*) OR description:("${id}") OR title:("${id}")`;
+}
+
+const EXT_RANK = ["mp4", "webm", "mkv", "m4v", "mov"];
+const extOf = (name: string) => (/\.([A-Za-z0-9]{1,8})$/.exec(name)?.[1] ?? "").toLowerCase();
+
+// The item's video file for the upload: among its video files (a file naming
+// the id first, else every one when the item holds a single original video),
+// an ORIGINAL before a derivative, then mp4, webm, mkv, … Null when the item
+// holds none, or several originals none of which names the id (a channel
+// dump: which file is the upload cannot be told).
+export function pickMirrorFile(
+ item: Pick<ArchiveOrgItemMetadata, "files">,
+ youtubeId: string,
+): { file: string; source: "original" | "derivative"; size?: number } | null {
+ const videos = item.files.filter(
+ (f) => isArchiveOrgVideoFileName(f.name) && (f.source === "original" || f.source === "derivative"),
+ );
+ const named = videos.filter((f) => f.name.includes(youtubeId));
+ const originals = videos.filter((f) => f.source === "original");
+ const pool = named.length > 0 ? named : originals.length === 1 ? videos : [];
+ if (pool.length === 0) return null;
+ const rank = (f: { name: string; source?: string }) =>
+ (f.source === "original" ? 0 : 100) + (EXT_RANK.includes(extOf(f.name)) ? EXT_RANK.indexOf(extOf(f.name)) : EXT_RANK.length);
+ const best = [...pool].sort((a, b) => rank(a) - rank(b))[0]!;
+ const size = best.size && /^\d+$/.test(best.size) ? Number(best.size) : undefined;
+ return { file: best.name, source: best.source === "original" ? "original" : "derivative", ...(size !== undefined ? { size } : {}) };
+}
+
+export type ArchiveOrgMirror = {
+ identifier: string;
+ title?: string;
+ file: string;
+ // The file's direct download URL.
+ url: string;
+ source: "original" | "derivative";
+ size?: number;
+};
+
+export type ArchiveOrgMirrorSearch = {
+ youtubeId: string;
+ query: string;
+ found: number;
+ mirrors: ArchiveOrgMirror[];
+ // Items the search found that are not a usable mirror, and why.
+ skipped: { identifier: string; why: string }[];
+};
+
+const textOf = (v: unknown): string =>
+ typeof v === "string" ? v : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(" ") : "";
+
+// archive.org mirrors of one YouTube upload: the search (one request), then
+// each hit's metadata (one request each, cached), at most `limit` items. An
+// item that does not name the id, is restricted, or holds no video file the
+// upload can be told by is skipped, with why.
+export async function findArchiveOrgMirrors(
+ youtubeId: string,
+ o: { client?: ArchiveOrgClient; signal?: AbortSignal; limit?: number } = {},
+): Promise<ArchiveOrgMirrorSearch> {
+ const client = o.client ?? archiveOrgClient;
+ const query = youtubeIdQuery(youtubeId);
+ const hits = await searchArchiveOrgItems(query, { client, rows: o.limit ?? 10, ...(o.signal ? { signal: o.signal } : {}) });
+ const mirrors: ArchiveOrgMirror[] = [];
+ const skipped: { identifier: string; why: string }[] = [];
+ for (const hit of hits.items) {
+ const item = await client.itemMetadata(hit.identifier, o.signal);
+ const meta = item.metadata as Record<string, unknown>;
+ const said = [item.metadata.identifier, textOf(meta.title), textOf(meta.description), textOf(meta.originalurl), ...item.files.map((f) => f.name)].join(" ");
+ if (!said.includes(youtubeId)) {
+ skipped.push({ identifier: hit.identifier, why: "it does not name the id" });
+ continue;
+ }
+ if (archiveOrgRestriction(item).item) {
+ skipped.push({ identifier: hit.identifier, why: "archive.org restricts it" });
+ continue;
+ }
+ const pick = pickMirrorFile(item, youtubeId);
+ if (!pick) {
+ skipped.push({ identifier: hit.identifier, why: "no video file of the upload can be told in it" });
+ continue;
+ }
+ const title = textOf(meta.title) || hit.title;
+ mirrors.push({
+ identifier: item.metadata.identifier,
+ ...(title ? { title } : {}),
+ file: pick.file,
+ url: archiveOrgDownloadUrl(item.metadata.identifier, pick.file),
+ source: pick.source,
+ ...(pick.size !== undefined ? { size: pick.size } : {}),
+ });
+ }
+ // Originals first, then the search's order.
+ mirrors.sort((a, b) => (a.source === b.source ? 0 : a.source === "original" ? -1 : 1));
+ return { youtubeId, query, found: hits.found, mirrors, skipped };
+}
+
+// ─── Wayback: the captures of a page ───
+
+export type WaybackLookup = { url: string; captures: WaybackCapture[] };
+
+// The captures of a page (every one, or only the 200s). Throws
+// ArchiveOrgRequestError when the CDX API keeps refusing.
+export async function waybackLookup(
+ url: string,
+ o: { client?: { captures: typeof waybackClient.captures }; okOnly?: boolean; limit?: number; signal?: AbortSignal } = {},
+): Promise<WaybackLookup> {
+ const client = o.client ?? waybackClient;
+ const captures = await client.captures(url, {
+ ...(o.okOnly ? { okOnly: true } : {}),
+ ...(o.limit ? { limit: o.limit } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ return { url, captures };
+}
+
+// ─── find-copy ───
+
+export type FindCopyAttempt = {
+ from: ClipCopy["from"];
+ found: boolean;
+ url?: string;
+ // What was found or why not, in a phrase.
+ detail?: string;
+ error?: string;
+};
+
+export type FindCopyRecording = {
+ slug: string;
+ id: string;
+ gone: GoneState;
+ watchUrl: string | null;
+ youtubeId: string | null;
+ // The cited windows of the recording.
+ windows: EvidenceWindow[];
+ tried: FindCopyAttempt[];
+ copy?: ClipCopy;
+ // fetch a copy found: its windows go to fetch-windows
+ // text-only no copy: the moments show their words only ("source deleted")
+ // error a lookup failed: a later run tries again
+ outcome: "fetch" | "text-only" | "error";
+};
+
+export type FindCopyResult = {
+ host: string;
+ recordings: FindCopyRecording[];
+ // The fetch-windows items: each found copy's windows, its URL as the item's
+ // webpageUrl and the copy for the provenance.
+ items: FetchWindowsItem[];
+ // Why the run stopped before its last recording, when it did.
+ stopped?: string;
+};
+
+export type FindCopyDeps = {
+ wayback: { captures: typeof waybackClient.captures };
+ archive: ArchiveOrgClient;
+ missing: (paths: Paths, host: ReportHost) => Promise<MissingEvidenceWindows>;
+ webpageUrl: (paths: Paths, slug: string, id: string) => Promise<string | null>;
+};
+
+const DEFAULT_DEPS: FindCopyDeps = {
+ wayback: waybackClient,
+ archive: archiveOrgClient,
+ missing: (paths, host) => missingEvidenceWindows(paths, host),
+ webpageUrl: recordWebpageUrl,
+};
+
+// Look for a copy of every gone recording the host's reports cite: Wayback,
+// then archive.org, one recording at a time. Nothing is fetched here; the
+// answer's `items` are what fetch-windows is given (the caller starts it).
+export async function findCopies(opts: {
+ paths: Paths;
+ host: ReportHost;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindCopyDeps>;
+}): Promise<FindCopyResult> {
+ const deps: FindCopyDeps = { ...DEFAULT_DEPS, ...opts.deps };
+ const log = (line: string) => opts.onLog?.(line);
+ const need = await deps.missing(opts.paths, opts.host);
+ const byRecording = new Map<string, { slug: string; id: string; gone: GoneState; windows: EvidenceWindow[] }>();
+ for (const w of need.unfetchable) {
+ if (w.why !== "gone" || !w.gone) continue;
+ const key = `${w.slug}/${w.id}`;
+ const r = byRecording.get(key) ?? { slug: w.slug, id: w.id, gone: w.gone, windows: [] };
+ r.windows.push(w);
+ byRecording.set(key, r);
+ }
+ const result: FindCopyResult = { host: opts.host.id, recordings: [], items: [] };
+ log(`find-copy ${opts.host.id}: ${byRecording.size} gone recording(s) cited, ${[...byRecording.values()].reduce((n, r) => n + r.windows.length, 0)} window(s).`);
+
+ for (const r of byRecording.values()) {
+ if (opts.signal?.aborted) {
+ result.stopped = "cancelled";
+ break;
+ }
+ const watchUrl = await deps.webpageUrl(opts.paths, r.slug, r.id);
+ const youtubeId = youtubeIdOf(watchUrl, r.id);
+ const rec: FindCopyRecording = { ...r, watchUrl, youtubeId, tried: [], outcome: "text-only" };
+ result.recordings.push(rec);
+ let refused: string | undefined;
+
+ // 1. The Wayback Machine: the newest capture of the page that recorded a 200.
+ if (watchUrl) {
+ try {
+ const { captures } = await waybackLookup(watchUrl, { client: deps.wayback, okOnly: true, ...(opts.signal ? { signal: opts.signal } : {}) });
+ const ok = captures.filter((c) => c.status === "200");
+ const newest = ok[ok.length - 1];
+ if (newest) {
+ rec.copy = { from: "wayback", url: newest.replayUrl };
+ rec.tried.push({ from: "wayback", found: true, url: newest.replayUrl, detail: `${ok.length} capture(s) of the page; the newest, ${newest.timestamp}` });
+ } else {
+ rec.tried.push({ from: "wayback", found: false, detail: "no capture of the page" });
+ }
+ } catch (e) {
+ rec.tried.push({ from: "wayback", found: false, error: (e as Error).message });
+ if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message;
+ }
+ } else {
+ rec.tried.push({ from: "wayback", found: false, detail: "the recording's page is not known" });
+ }
+
+ // 2. archive.org: a mirror naming the YouTube id.
+ if (!rec.copy && !refused) {
+ if (youtubeId) {
+ try {
+ const found = await findArchiveOrgMirrors(youtubeId, { client: deps.archive, ...(opts.signal ? { signal: opts.signal } : {}) });
+ const m = found.mirrors[0];
+ if (m) {
+ rec.copy = { from: "archive.org", url: m.url };
+ rec.tried.push({ from: "archive.org", found: true, url: m.url, detail: `${m.identifier}: ${m.file} (${m.source})` });
+ } else {
+ rec.tried.push({
+ from: "archive.org",
+ found: false,
+ detail: found.found ? `${found.found} item(s), none a mirror (${found.skipped.map((s) => `${s.identifier}: ${s.why}`).join("; ")})` : "no item names the id",
+ });
+ }
+ } catch (e) {
+ rec.tried.push({ from: "archive.org", found: false, error: (e as Error).message });
+ if (e instanceof ArchiveOrgRequestError && e.rateLimited) refused = (e as Error).message;
+ }
+ } else {
+ rec.tried.push({ from: "archive.org", found: false, detail: "no YouTube id to search for" });
+ }
+ }
+
+ if (rec.copy) {
+ rec.outcome = "fetch";
+ for (const w of r.windows) {
+ result.items.push({
+ slug: w.slug,
+ id: w.id,
+ from: w.from,
+ to: w.to,
+ clipId: w.clipId,
+ ...(w.reason ? { reason: w.reason.slice(0, 400) } : {}),
+ webpageUrl: rec.copy.url,
+ copy: rec.copy,
+ });
+ }
+ } else if (rec.tried.some((t) => t.error)) {
+ rec.outcome = "error";
+ }
+ log(
+ ` ${r.slug}/${r.id} (${r.gone}, ${r.windows.length} window(s)): ` +
+ rec.tried.map((t) => `${t.from} ${t.found ? `found — ${t.detail}` : t.error ? `failed — ${t.error}` : `none — ${t.detail}`}`).join("; ") +
+ ` → ${rec.outcome === "fetch" ? `fetch from the ${rec.copy!.from === "wayback" ? "Wayback capture" : "archive.org file"}` : rec.outcome === "text-only" ? "its words only" : "try again later"}`,
+ );
+ if (refused) {
+ result.stopped = `archive.org kept refusing (${refused}); the rest are left for a later run`;
+ log(`find-copy: ${result.stopped}.`);
+ break;
+ }
+ }
+ return result;
+}
+
+// find-copy, whole: the lookups, then (unless `dryRun`) ONE fetch-windows of
+// every found copy's windows through `startFetch` (the editor's job). A run
+// with nothing found starts nothing.
+export async function runFindCopy<T>(opts: {
+ paths: Paths;
+ host: ReportHost;
+ dryRun?: boolean;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindCopyDeps>;
+ startFetch: (items: FetchWindowsItem[]) => Promise<T>;
+}): Promise<FindCopyResult & { fetch?: T }> {
+ const found = await findCopies(opts);
+ if (opts.dryRun || found.items.length === 0) return found;
+ return { ...found, fetch: await opts.startFetch(found.items) };
+}
diff --git a/common/publish/missingEvidenceWindows.test.ts b/common/publish/missingEvidenceWindows.test.ts
@@ -124,6 +124,8 @@ test("on disk, to fetch, and what no window can fill", async () => {
elsewhere: "not-in-site",
});
assert.match(r.unfetchable.find((u) => u.id === "gone1")!.message, /deleted/);
+ // Release 29 E2: the one gone reading (lib/sourceGone.ts) names which.
+ assert.equal(r.unfetchable.find((u) => u.id === "gone1")!.gone, "deleted");
// The refusal names both keys that would let the site cite the channel.
assert.match(r.unfetchable.find((u) => u.id === "elsewhere")!.message, /`channels` nor its `citedChannels`/);
});
diff --git a/common/publish/reportMedia.test.ts b/common/publish/reportMedia.test.ts
@@ -281,3 +281,39 @@ test("a cited-only channel's moment is prepared; a channel in neither key is not
);
assert.match(index.problems[0].message, /"elsewhere" is in neither this site's `channels` nor its `citedChannels`/);
});
+
+// RELEASE 29 E2: a gone source with no media is a WARNING (`source-gone`), never
+// a problem — compose shows its words only. A live one with no media is still
+// a problem.
+test("a gone recording or a deleted, never-captured post with no media is a warning, not a problem", async () => {
+ const GSITE = "gone-site";
+ writeJson(path.join(videoDir(CH, "gone2"), "availability.json"), { checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" });
+ writeJson(path.join(paths.channelsDir, X, "posts-availability.json"), {
+ "333": { availability: "deleted", checkedAt: "2026-10-01T00:00:00.000Z" },
+ });
+ writeJson(path.join(paths.sitesDir, GSITE, "site.json"), { title: "Gone", channels: [{ slug: CH }, { slug: X }], reports: ["g1"] });
+ writeJson(
+ path.join(paths.sitesDir, GSITE, "reports", "g1", "report.json"),
+ report("g1", {
+ g01: { kind: "video", channel: CH, id: "gone2", start: 1, end: 2, quote: "gone" },
+ g02: { kind: "post", channel: X, id: "333", quote: "deleted" },
+ g03: { kind: "video", channel: CH, id: "missing2", start: 1, end: 2, quote: "live, no media" },
+ }),
+ );
+ const lines: string[] = [];
+ const index = await prepareReportMedia({ siteId: GSITE, settings: PUBLIC, onLog: (l) => lines.push(l) });
+ assert.deepEqual(
+ (index.warnings ?? []).map((w) => [w.kind, w.moment, w.citations]),
+ [
+ ["source-gone", `${CH}/gone2/1.00-2.00`, ["g1#g01"]],
+ ["source-gone", `${X}/333`, ["g1#g02"]],
+ ],
+ );
+ assert.match(index.warnings![0].message, /deleted.*words only.*Source deleted/);
+ assert.deepEqual(
+ index.problems.map((p) => [p.kind, p.moment]),
+ [["missing-media", `${CH}/missing2/1.00-2.00`]],
+ );
+ assert.ok(lines.some((l) => l.startsWith(` ! ${CH}/gone2/`)));
+ assert.ok(lines.some((l) => /1 problem\(s\), 2 warning\(s\)/.test(l)));
+});
diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts
@@ -65,9 +65,9 @@ import { momentKey, momentOf, momentProblem, type Moment } from "../lib/citation
import type { CitationPad } from "../lib/citations/schema";
import { parseReport } from "../lib/report/validate";
import { isReportId, type Report } from "../lib/report/schema";
-import { isPermanentlyGone } from "../lib/availability";
-import { loadAvailability } from "../lib/availability-server";
import { resolveVideoDir } from "../lib/videoDir-server.mjs";
+import { SOURCE_GONE_LABELS, type GoneState } from "../lib/sourceGone";
+import { postGoneState, sourceGoneState } from "../lib/sourceGone-server";
import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow";
import {
citedEvidenceSpan,
@@ -159,7 +159,11 @@ export type ReportMediaProblemKind =
| "missing-media"
| "unreachable"
| "too-big"
- | "cut-failed";
+ | "cut-failed"
+ // A WARNING, never a problem (release 29 E2): a cited moment whose source is
+ // gone (lib/sourceGone.ts) and whose media is not on disk. Compose takes it
+ // as a text-only moment marked "source deleted".
+ | "source-gone";
export type ReportMediaProblem = {
kind: ReportMediaProblemKind;
@@ -180,6 +184,9 @@ export type ReportMediaIndex = {
preparedAt: string;
moments: Record<string, ReportMediaEntry>;
problems: ReportMediaProblem[];
+ // What does not fail the run: a gone source's moment with no media
+ // (`source-gone`). Absent when there is none.
+ warnings?: ReportMediaProblem[];
};
// One cited moment and everything that cites it.
@@ -292,6 +299,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
problems.push({ kind, moment: m.key, citations: m.citedBy, message });
log(` ✗ ${m.key}: ${message}`);
};
+ const warnings: ReportMediaProblem[] = [];
+ const warnGone = (m: CitedMoment, message: string) => {
+ warnings.push({ kind: "source-gone", moment: m.key, citations: m.citedBy, message });
+ log(` ! ${m.key}: ${message}`);
+ };
const posts: CitedMoment[] = [];
for (const m of moments) {
@@ -339,6 +351,11 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
fail(m, "unreachable", `${r.message}; the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`);
continue;
}
+ const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, m.moment.id));
+ if (gone) {
+ warnGone(m, `the source says the video is ${gone} and no copy is on disk: the moment shows its words only, marked "${SOURCE_GONE_LABELS[gone]}" (pnpm ops find-copy looks for a copy)`);
+ continue;
+ }
fail(m, "missing-media", `${r.message} — fetch the window or persist the video in the editor`);
continue;
}
@@ -359,7 +376,12 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
}
for (const miss of copiedPosts.missing) {
const m = postMoment.get(`${miss.channel}/${miss.id}`);
- if (m) fail(m, "missing-media", miss.message);
+ if (!m) continue;
+ if (await postGoneState(paths.channelsDir, miss.channel, miss.id)) {
+ warnGone(m, `the post is deleted and was never captured: the moment shows its words only, marked "${SOURCE_GONE_LABELS.deleted}"`);
+ continue;
+ }
+ fail(m, "missing-media", miss.message);
}
// The cache holds what the manifest names: a clip no moment names goes.
@@ -372,6 +394,7 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
preparedAt: (opts.now?.() ?? new Date()).toISOString(),
moments: Object.fromEntries(Object.keys(entries).sort().map((k) => [k, entries[k]])),
problems,
+ ...(warnings.length > 0 ? { warnings } : {}),
};
await writeJsonAtomic(storeMediaIndexFile(host), index, { mkdir: true });
const bytes = Object.values(entries).reduce(
@@ -380,7 +403,9 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi
);
log(
`${Object.keys(entries).length} of ${moments.length} moment(s) prepared (${mib(bytes)}); ` +
- `${problems.length} problem(s).`,
+ `${problems.length} problem(s)` +
+ (warnings.length ? `, ${warnings.length} warning(s) (a gone source's moment shows its words only)` : "") +
+ ".",
);
return index;
}
@@ -442,7 +467,9 @@ export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir">
// not-in-site the channel is not one of the site's (prepare's not-in-site)
// unreachable the channel's media is on a drive that is not answering —
// not missing, and a fetch would write beside the wrong thing
-// gone availability.json says deleted, private or members-only
+// gone the source says the video is deleted or private (the one
+// reading, lib/sourceGone.ts; `gone` names which) — no window
+// can be fetched from it; find-copy looks for a copy
// audio-only a feed record: its media is the episode's audio, which a
// download fetches; a window selector has no picture to pick
// too-long longer than one window may be — persist the video instead
@@ -468,6 +495,8 @@ export type UnfetchableReason = "not-in-site" | "unreachable" | "gone" | "audio-
export type UnfetchableEvidenceWindow = EvidenceWindow & {
why: UnfetchableReason;
+ // A `gone` window: what the source says (lib/sourceGone.ts).
+ gone?: GoneState;
message: string;
};
@@ -545,9 +574,9 @@ export async function missingEvidenceWindows(paths: Paths, siteOrHost: string |
unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`);
continue;
}
- const availability = (await loadAvailability(await resolveVideoDir(paths.channelsDir, slug, id)))?.availability;
- if (isPermanentlyGone(availability)) {
- unfetchable("gone", `the source says the video is ${availability}`);
+ const gone = await sourceGoneState(await resolveVideoDir(paths.channelsDir, slug, id));
+ if (gone) {
+ out.unfetchable.push({ ...window, why: "gone", gone, message: `the source says the video is ${gone}` });
continue;
}
if (audioOnly) {
diff --git a/common/social/blueskyEndpoints.ts b/common/social/blueskyEndpoints.ts
@@ -0,0 +1,58 @@
+// Where Bluesky is: the public AppView (the read API, no login), the web app
+// (bsky.app, the page a post capture screenshots) and the CDN (a post's
+// images). One place, so a test can put all three on a fake.
+//
+// TEST-ONLY: E2E_BLUESKY_ORIGIN_FILE names a file holding ONE loopback origin
+// (`http://127.0.0.1:<port>`). While that file exists, all three hosts are
+// that origin — the editor e2e suite's fake Bluesky
+// (common/testing/social/fakeBluesky.mjs), which a spec starts and names in
+// the file. The file is read per call, so a spec can start its fake after the
+// test server booted. Anything but a loopback origin in it is ignored. Unset
+// everywhere but the editor's e2e server. Unit tests pass endpoints directly.
+
+import { readFileSync } from "node:fs";
+
+export type BlueskyEndpoints = {
+ // The public AppView: com.atproto.identity.resolveHandle,
+ // app.bsky.feed.getPosts, getAuthorFeed, getProfile.
+ appview: string;
+ // The web app: /profile/<handle>/post/<rkey>.
+ web: string;
+ // The image CDN: a post's `embed.images[].fullsize`.
+ cdn: string;
+};
+
+export const BLUESKY_ENDPOINTS: Readonly<BlueskyEndpoints> = Object.freeze({
+ appview: "https://public.api.bsky.app",
+ web: "https://bsky.app",
+ cdn: "https://cdn.bsky.app",
+});
+
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function blueskyEndpoints(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): BlueskyEndpoints {
+ const file = env.E2E_BLUESKY_ORIGIN_FILE;
+ if (file) {
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/$/, "");
+ } catch {
+ origin = "";
+ }
+ if (LOOPBACK_ORIGIN.test(origin)) return { appview: origin, web: origin, cdn: origin };
+ }
+ return { ...BLUESKY_ENDPOINTS };
+}
+
+// A Bluesky URL (one of the three real hosts) on `endpoints`: the AppView's
+// image URLs name cdn.bsky.app, which a fake must serve. Any other URL is
+// returned as it is.
+export function onBlueskyEndpoints(url: string, endpoints: BlueskyEndpoints): string {
+ for (const key of ["appview", "web", "cdn"] as const) {
+ const real = BLUESKY_ENDPOINTS[key];
+ if (url === real || url.startsWith(`${real}/`)) return endpoints[key] + url.slice(real.length);
+ }
+ return url;
+}
diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts
@@ -30,8 +30,11 @@ import {
type SocialFetcher,
type SocialFetcherProbe,
} from "./fetchers";
+import { blueskyEndpoints } from "./blueskyEndpoints";
+import { captureBlueskyPosts, liveBlueskyCaptureDeps } from "./blueskyPostCapture";
-const APPVIEW = "https://public.api.bsky.app";
+// The AppView's origin, read per call (blueskyEndpoints.ts: a test's fake).
+const appview = () => blueskyEndpoints().appview;
const PLC_DIRECTORY = "https://plc.directory";
// getAuthorFeed's documented ceiling.
@@ -293,7 +296,7 @@ export async function resolveHandle(
handle: string,
signal?: AbortSignal,
): Promise<string> {
- const url = `${APPVIEW}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
+ const url = `${appview()}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
const body = await getJson<{ did?: string }>(url, signal);
if (!body.did) throw new Error(`No DID for handle ${handle}`);
return body.did;
@@ -312,7 +315,7 @@ export async function getProfile(
actor: string,
signal?: AbortSignal,
): Promise<BskyProfile> {
- const url = `${APPVIEW}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
+ const url = `${appview()}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
return getJson<BskyProfile>(url, signal);
}
@@ -354,7 +357,7 @@ async function getAuthorFeed(
});
if (cursor) params.set("cursor", cursor);
return getJson<BskyFeedResponse>(
- `${APPVIEW}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
signal,
);
}
@@ -517,7 +520,7 @@ blueskyFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => {
}
try {
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
signal,
);
const alive = new Set(
@@ -551,7 +554,7 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
const uri = `at://${did}/app.bsky.feed.post/${post.id}`;
onLog?.(`Reading ${uri}`);
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
signal,
);
const view = (body.posts ?? []).find((v) => rkeyFromAtUri(v.uri) === post.id);
@@ -561,4 +564,9 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
}
};
+// A screenshot of each post as bsky.app renders it, and its images (release
+// 29 E1): blueskyPostCapture.ts — the AppView for liveness and image URLs, a
+// headless browser with no login for the shot.
+blueskyFetcher.captureByIds = (input) => captureBlueskyPosts(input, liveBlueskyCaptureDeps(input));
+
registerSocialFetcher(blueskyFetcher);
diff --git a/common/social/blueskyPostCapture.test.ts b/common/social/blueskyPostCapture.test.ts
@@ -0,0 +1,313 @@
+// The Bluesky post capture (release 29 E1), over the fake Bluesky on loopback
+// (common/testing/social/fakeBluesky.mjs): its AppView answers liveness and
+// image URLs, its CDN the images, and its bsky.app-shaped page the shot — in
+// a stub page for the run's logic, and in a real headless Chromium for the
+// crop (skipped, saying why, on a host with no browser). No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/blueskyPostCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { PNG as FAKE_PNG, startFakeBluesky } from "../testing/social/fakeBluesky.mjs";
+import { blueskyEndpoints, onBlueskyEndpoints, BLUESKY_ENDPOINTS } from "./blueskyEndpoints";
+import {
+ blueskyPageGapMs,
+ blueskyPostImages,
+ captureBlueskyPosts,
+ openFreshBlueskyPage,
+ shootBlueskyPost,
+ type BlueskyCaptureDeps,
+} from "./blueskyPostCapture";
+import { blueskyFetcher } from "./blueskyFetcher";
+import { capturePostsProblem } from "../controller/capturePosts";
+import { readPostCapture, SHOT_FILENAME } from "./postCapture";
+import type { PageLike } from "./playwrightRuntime";
+import type { PostCaptureInput } from "./fetchers";
+import { pngSize } from "../publish/citedPostCaptures";
+
+const HANDLE = "synthbaker.bsky.social";
+const IMAGE_POST = "3lsynthpost0001";
+const TEXT_POST = "3lsynthpost0002";
+const DELETED_POST = "3lsynthpost0003";
+
+// A page that answers the capture's calls without a browser: the post is
+// there (one thread item by the author), its box a fixed rect, its shot a PNG.
+function stubPage() {
+ const visited: string[] = [];
+ const page: PageLike = {
+ goto: async (url: string) => {
+ visited.push(url);
+ return { status: () => 200 };
+ },
+ waitForSelector: async () => ({}),
+ waitForTimeout: async () => {},
+ evaluate: async (fn: string) =>
+ fn.includes("postThreadItem-by-") ? { count: 1, rect: { x: 220, y: 70, width: 600, height: 300 }, text: "" } : 0,
+ on: () => {},
+ screenshot: async () => new Uint8Array(FAKE_PNG),
+ };
+ return { page, visited };
+}
+
+async function setup(opts: { busyTimes?: number } = {}) {
+ const bsky = await startFakeBluesky(opts);
+ const outDir = await mkdtemp(path.join(os.tmpdir(), "bsky-capture-"));
+ const pauses: number[] = [];
+ const stub = stubPage();
+ let opened = 0;
+ const deps: BlueskyCaptureDeps = {
+ fetch: (url, init) => bsky.fetch(url, init),
+ endpoints: { ...BLUESKY_ENDPOINTS },
+ openPage: async () => {
+ opened++;
+ return { page: stub.page, close: async () => {} };
+ },
+ pageGapMs: () => 3_500,
+ imageGapMs: () => 1_200,
+ pause: async (ms) => {
+ pauses.push(ms);
+ },
+ now: () => new Date("2026-10-15T12:00:00.000Z"),
+ };
+ const input = (ids: string[], extra: Partial<PostCaptureInput> = {}): PostCaptureInput => ({
+ ids,
+ handle: HANDLE,
+ outDir,
+ signal: new AbortController().signal,
+ ...extra,
+ });
+ return {
+ bsky,
+ outDir,
+ pauses,
+ stub,
+ deps,
+ input,
+ opened: () => opened,
+ close: async () => {
+ await bsky.close();
+ await rm(outDir, { recursive: true, force: true });
+ },
+ };
+}
+
+test("endpoints: the real hosts by default; a test's loopback origin from E2E_BLUESKY_ORIGIN_FILE, nothing else", async () => {
+ assert.deepEqual(blueskyEndpoints({}), BLUESKY_ENDPOINTS);
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-origin-"));
+ try {
+ const file = path.join(dir, "origin");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "no file yet");
+ await writeFile(file, "http://127.0.0.1:4567\n");
+ const o = "http://127.0.0.1:4567";
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), { appview: o, web: o, cdn: o });
+ await writeFile(file, "https://evil.example");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "not loopback: ignored");
+ const fake = { appview: o, web: o, cdn: o };
+ assert.equal(onBlueskyEndpoints("https://cdn.bsky.app/img/x/y@jpeg", fake), `${o}/img/x/y@jpeg`);
+ assert.equal(onBlueskyEndpoints("https://bsky.app/profile/a/post/b", fake), `${o}/profile/a/post/b`);
+ assert.equal(onBlueskyEndpoints("https://example.com/a.png", fake), "https://example.com/a.png");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the fetcher can capture: capturePostsProblem passes a Bluesky channel with no special case", () => {
+ assert.equal(typeof blueskyFetcher.captureByIds, "function");
+ assert.equal(capturePostsProblem(blueskyFetcher), null);
+});
+
+test("images: an images embed, a recordWithMedia's media, the full size first", () => {
+ assert.deepEqual(
+ blueskyPostImages({ embed: { images: [{ fullsize: "https://cdn.bsky.app/a", thumb: "https://cdn.bsky.app/t", alt: "A" }] } }),
+ [{ url: "https://cdn.bsky.app/a", alt: "A" }],
+ );
+ assert.deepEqual(blueskyPostImages({ embed: { media: { images: [{ thumb: "https://cdn.bsky.app/t" }] } } }), [
+ { url: "https://cdn.bsky.app/t" },
+ ]);
+ assert.deepEqual(blueskyPostImages({}), []);
+});
+
+test("the page gap: at least 3 s, jittered up to double; a channel's longer pause raises it", () => {
+ assert.equal(blueskyPageGapMs(() => 0), 3_000);
+ assert.equal(blueskyPageGapMs(() => 0.999), 5_997);
+ assert.equal(blueskyPageGapMs(() => 0, 1_000), 3_000, "never under the floor");
+ assert.equal(blueskyPageGapMs(() => 0.5, 10_000), 15_000);
+});
+
+test("a capture: the image post (shot, 2 images, record), the text post, the deleted post — paced, one page at a time", async () => {
+ const s = await setup();
+ try {
+ const res = await captureBlueskyPosts(s.input([IMAGE_POST, TEXT_POST, DELETED_POST]), s.deps);
+ assert.equal(res.stoppedEarly, undefined);
+ assert.deepEqual(
+ res.outcomes.map((o) => [o.id, o.state, o.availability, o.files]),
+ [
+ [IMAGE_POST, "captured", "available", 3],
+ [TEXT_POST, "captured", "available", 1],
+ [DELETED_POST, "deleted", "deleted", 0],
+ ],
+ );
+
+ const imageDir = path.join(s.outDir, IMAGE_POST);
+ assert.deepEqual((await readdir(imageDir)).sort(), ["capture.json", "media-1.png", "media-2.png", SHOT_FILENAME]);
+ assert.deepEqual(new Uint8Array(await readFile(path.join(imageDir, "media-1.png"))), new Uint8Array(FAKE_PNG));
+ const rec = await readPostCapture(imageDir);
+ assert.equal(rec?.state, "captured");
+ assert.equal(rec?.url, `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`);
+ assert.equal(rec?.shot?.name, SHOT_FILENAME);
+ assert.equal(rec?.mediaState, "ok");
+ assert.deepEqual(
+ rec?.media.map((m) => [m.name, m.url]),
+ [
+ ["media-1.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/oven.png"],
+ ["media-2.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/shop.png"],
+ ],
+ );
+
+ const text = await readPostCapture(path.join(s.outDir, TEXT_POST));
+ assert.equal(text?.mediaState, "none");
+ assert.ok(text?.shot);
+
+ const gone = await readPostCapture(path.join(s.outDir, DELETED_POST));
+ assert.equal(gone?.state, "deleted");
+ assert.equal(gone?.shot, undefined);
+
+ // Two pages (never the deleted post's), one browser, the gap before the second.
+ assert.deepEqual(s.stub.visited, [
+ `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ `https://bsky.app/profile/${HANDLE}/post/${TEXT_POST}`,
+ ]);
+ assert.equal(s.opened(), 1);
+ assert.deepEqual(s.pauses, [1_200, 3_500], "an image gap, then the page gap");
+ // One handle lookup, ONE getPosts for all three.
+ const xrpc = s.bsky.requests.filter((r) => r.startsWith("/xrpc/"));
+ assert.equal(xrpc.length, 2);
+ assert.match(xrpc[1], /getPosts\?uris=.*uris=.*uris=/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a second run skips what is captured; force asks again; a deleted post is settled", async () => {
+ const s = await setup();
+ try {
+ await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ const before = s.bsky.requests.length;
+ const again = await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ assert.deepEqual(again.outcomes, []);
+ assert.equal(s.bsky.requests.length, before, "nothing asked");
+ const forced = await captureBlueskyPosts(s.input([IMAGE_POST], { force: true }), s.deps);
+ assert.deepEqual(forced.outcomes.map((o) => o.state), ["captured"]);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 from the AppView is waited out (its Retry-After) and asked again", async () => {
+ const s = await setup({ busyTimes: 1 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), s.deps);
+ assert.deepEqual(res.outcomes.map((o) => o.state), ["captured"]);
+ assert.equal(s.pauses[0], 1_000, "Retry-After: 1");
+ assert.equal(s.bsky.requests.filter((r) => r.includes("resolveHandle")).length, 2);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 that persists stops the run with nothing recorded about the posts", async () => {
+ const s = await setup({ busyTimes: 50 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST]), { ...s.deps, maxAttempts: 3 });
+ assert.deepEqual(res.outcomes, []);
+ assert.match(res.stoppedEarly ?? "", /Could not resolve .*429/);
+ assert.equal(s.pauses.length, 2, "two waits between three attempts");
+ } finally {
+ await s.close();
+ }
+});
+
+test("a cancelled run stops between posts; the rest are left", async () => {
+ const s = await setup();
+ try {
+ const ctl = new AbortController();
+ const deps: BlueskyCaptureDeps = {
+ ...s.deps,
+ pause: async (ms) => {
+ s.pauses.push(ms);
+ ctl.abort();
+ },
+ };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST, IMAGE_POST], { signal: ctl.signal, media: false }), deps);
+ assert.deepEqual(res.outcomes.map((o) => o.id), [TEXT_POST]);
+ assert.match(res.stoppedEarly ?? "", /Cancelled/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a page that does not show the post is an error; the AppView's liveness stands", async () => {
+ const s = await setup();
+ try {
+ const stub = stubPage();
+ stub.page.waitForSelector = async () => {
+ throw new Error("Timeout 20000ms exceeded");
+ };
+ stub.page.evaluate = async () => ({ count: 0, rect: null, text: "post not found" });
+ const deps: BlueskyCaptureDeps = { ...s.deps, openPage: async () => ({ page: stub.page, close: async () => {} }) };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), deps);
+ assert.equal(res.outcomes[0].state, "error");
+ assert.equal(res.outcomes[0].availability, "available", "the AppView said it is live");
+ assert.match(res.outcomes[0].error ?? "", /did not render/);
+ } finally {
+ await s.close();
+ }
+});
+
+// ─── A real browser over the fake's page ───
+
+test("a real headless Chromium shoots the post, cropped to it, over the fake page on loopback", async (t) => {
+ let opened;
+ try {
+ opened = await openFreshBlueskyPage();
+ } catch (e) {
+ t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`);
+ return;
+ }
+ const bsky = await startFakeBluesky();
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-shot-"));
+ try {
+ const res = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, IMAGE_POST),
+ canonicalUrl: `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ handle: HANDLE,
+ text: "The second shop opens in the spring. Small place, big oven.",
+ dir,
+ signal: new AbortController().signal,
+ });
+ assert.equal(res.state, "captured", res.error);
+ const size = await pngSize(path.join(dir, SHOT_FILENAME));
+ assert.ok(size, "a PNG");
+ // The thread item is 600 CSS px wide in a 1280-px window, at 2x: cropped to
+ // the post, not the page (its header, side bar and the reply below).
+ assert.equal(size!.width, 1200);
+ assert.ok(size!.height > 100 && size!.height < 800, `height ${size!.height}`);
+ const gone = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, DELETED_POST),
+ canonicalUrl: "x",
+ handle: HANDLE,
+ text: "",
+ dir: path.join(dir, "gone"),
+ signal: new AbortController().signal,
+ postTimeoutMs: 1_500,
+ });
+ assert.equal(gone.state, "error");
+ } finally {
+ await opened.close();
+ await bsky.close();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/blueskyPostCapture.ts b/common/social/blueskyPostCapture.ts
@@ -0,0 +1,579 @@
+// Capturing specific Bluesky posts (release 29 E1): a screenshot of each post
+// as bsky.app renders it, and its images, into `posts-media/<id>/`
+// (postCapture.ts owns the layout and the record). No login, ever.
+//
+// TWO SOURCES, EACH ASKED AS LITTLE AS IT CAN BE:
+// - the public AppView (`app.bsky.feed.getPosts`, 25 posts a request, the
+// same batch the deleted-post sweep uses) says which posts are live — one
+// absent from the answer is deleted, recorded as X's capture records it —
+// and where each live post's images are (`embed.images[].fullsize`, or a
+// recordWithMedia's `media.images`);
+// - a headless Chromium, ONE fresh context with no profile and no cookies,
+// opens each live post's page (`bsky.app/profile/<handle>/post/<rkey>`),
+// waits for the post (`[data-testid="postThreadItem-by-<handle>"]`) and
+// shoots that element — cropped to the post, not the page — as shot.png.
+//
+// PACED: one page at a time, a real gap (3–6 s, jittered; a channel's
+// `postPagePauseSeconds` raises it) before every page after the first, a
+// timeout per page, cancellable between and during posts. A 429 from the
+// AppView or the CDN is waited out (its Retry-After, else 5 s, 10 s, … capped)
+// and asked again a few times; one that persists stops the run there, the
+// rest left for a later run. A page that answers 429 is waited out once; a
+// second stops the run.
+//
+// What a capture finds, per post:
+// captured live, shot (and its images downloaded)
+// deleted absent from getPosts — the platform says the post is gone; no
+// page is opened, and what an earlier capture took is kept
+// error the page did not show the post (a timeout, an author who
+// shows posts only to signed-in users, a post the page could
+// not tell from others), or an image failed; a later run tries
+// again
+//
+// Base URLs are injectable (deps.endpoints; blueskyEndpoints.ts for the e2e
+// suite's fake), and so is everything that waits or touches the network.
+
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { postPermalink, type PostAvailability } from "../lib/posts";
+import { parseRetryAfterMs } from "../lib/archiveOrgClient";
+import { blueskyEndpoints, onBlueskyEndpoints, type BlueskyEndpoints } from "./blueskyEndpoints";
+import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import {
+ captureWork,
+ describeCapturedFile,
+ postCaptureDir,
+ readPostCapture,
+ SHOT_FILENAME,
+ writePostCapture,
+ type CapturedFile,
+ type CaptureMediaState,
+ type PostCaptureRecord,
+ type PostCaptureState,
+} from "./postCapture";
+
+// ─── The AppView's answer (only what the capture reads) ───
+
+type ImageView = { fullsize?: string; thumb?: string; alt?: string };
+export type BlueskyPostView = {
+ uri?: string;
+ author?: { did?: string; handle?: string };
+ record?: { text?: string };
+ embed?: { $type?: string; images?: ImageView[]; media?: { images?: ImageView[] } };
+};
+
+const rkeyOf = (uri: string | undefined): string | null => {
+ const i = uri?.lastIndexOf("/") ?? -1;
+ return uri && i >= 0 && i < uri.length - 1 ? uri.slice(i + 1) : null;
+};
+
+// A live post's images, as the AppView names them: an images embed, or the
+// media half of a recordWithMedia. The full-size URL, else the thumbnail.
+export function blueskyPostImages(view: BlueskyPostView): { url: string; alt?: string }[] {
+ const list = view.embed?.images ?? view.embed?.media?.images ?? [];
+ const out: { url: string; alt?: string }[] = [];
+ for (const im of list) {
+ const url = im?.fullsize ?? im?.thumb;
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) continue;
+ out.push({ url, ...(im.alt ? { alt: im.alt } : {}) });
+ }
+ return out;
+}
+
+// getPosts' documented ceiling.
+export const GET_POSTS_BATCH = 25;
+
+// The gap before each page after a run's first: 3–6 s, or the channel's own
+// pause (at least 3 s) jittered to [1, 2) of itself.
+export const MIN_PAGE_GAP_MS = 3_000;
+export function blueskyPageGapMs(random: () => number, baseMs?: number): number {
+ const base = Math.max(MIN_PAGE_GAP_MS, baseMs ?? MIN_PAGE_GAP_MS);
+ return Math.round(base * (1 + random()));
+}
+
+// ─── Deps ───
+
+export type BlueskyCaptureDeps = {
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
+ endpoints: BlueskyEndpoints;
+ // A page in a fresh browser context: opened on the first shot, closed at the
+ // end of the run.
+ openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>;
+ // The gap before each page after the first, and between two images.
+ pageGapMs: () => number;
+ imageGapMs: () => number;
+ pause: (ms: number, signal: AbortSignal) => Promise<void>;
+ now?: () => Date;
+ // A 429/503 retry's wait when the answer names none (doubling per attempt),
+ // its cap, and how many attempts a request gets.
+ backoffBaseMs?: number;
+ backoffMaxMs?: number;
+ maxAttempts?: number;
+ // How long a page may take to load, and the post to appear on it.
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+};
+
+export function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (ms <= 0 || signal.aborted) return resolve();
+ const timer = setTimeout(done, ms);
+ function done() {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+// A headless Chromium with a fresh context: no profile directory, no cookies,
+// no stored state — what a logged-out reader sees.
+export async function openFreshBlueskyPage(): Promise<{ page: PageLike; close: () => Promise<void> }> {
+ const { chromium } = await importPlaywright();
+ const browser = await chromium.launch({ headless: true });
+ try {
+ const context = await browser.newContext({
+ viewport: { width: 1280, height: 1600 },
+ deviceScaleFactor: 2,
+ locale: "en-US",
+ colorScheme: "light",
+ });
+ const page = await context.newPage();
+ return {
+ page,
+ close: async () => {
+ await context.close().catch(() => {});
+ await browser.close().catch(() => {});
+ },
+ };
+ } catch (err) {
+ await browser.close().catch(() => {});
+ throw err;
+ }
+}
+
+export function liveBlueskyCaptureDeps(input: Pick<PostCaptureInput, "pagePauseMs">): BlueskyCaptureDeps {
+ return {
+ fetch: (url, init) => fetch(url, init),
+ endpoints: blueskyEndpoints(),
+ openPage: openFreshBlueskyPage,
+ pageGapMs: () => blueskyPageGapMs(Math.random, input.pagePauseMs),
+ imageGapMs: () => 1_000 + Math.round(Math.random() * 1_000),
+ pause: sleepUnlessAborted,
+ };
+}
+
+// ─── Requests, with the 429 back-off ───
+
+type Got =
+ | { ok: true; res: Response }
+ | { ok: false; error: string; rateLimited?: boolean; status?: number };
+
+async function politeGet(
+ deps: BlueskyCaptureDeps,
+ url: string,
+ accept: string,
+ signal: AbortSignal,
+ onLog?: (line: string) => void,
+): Promise<Got> {
+ const attempts = deps.maxAttempts ?? 4;
+ const base = deps.backoffBaseMs ?? 5_000;
+ const cap = deps.backoffMaxMs ?? 120_000;
+ const now = () => (deps.now ?? (() => new Date()))().getTime();
+ let last = "";
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ let res: Response;
+ try {
+ res = await deps.fetch(url, { signal, headers: { accept } });
+ } catch (err) {
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ return { ok: false, error: firstLine(err) };
+ }
+ if (res.ok) return { ok: true, res };
+ if (res.status !== 429 && res.status !== 503) {
+ await res.arrayBuffer().catch(() => {});
+ return { ok: false, error: `HTTP ${res.status}`, status: res.status };
+ }
+ last = `HTTP ${res.status}`;
+ await res.arrayBuffer().catch(() => {});
+ if (attempt === attempts) break;
+ const wait = Math.min(cap, parseRetryAfterMs(res.headers.get("retry-after"), now()) ?? base * 2 ** (attempt - 1));
+ onLog?.(`Bluesky answered ${res.status}; waiting ${Math.round(wait / 1000)} s before asking again.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ }
+ return { ok: false, error: `Bluesky kept answering ${last} after ${attempts} attempts`, rateLimited: true };
+}
+
+// ─── One page's shot ───
+
+// The post on its page: the thread items by its author (a self-thread's
+// parents and replies share the test id), the one holding the post's text —
+// or the only one. Marked for the shot; its box in document coordinates.
+const SNAPSHOT_SCRIPT = (handle: string, text: string) => `(() => {
+ const sel = ${JSON.stringify(`[data-testid="postThreadItem-by-${handle}"]`)};
+ const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase();
+ const want = norm(${JSON.stringify(text)}).slice(0, 80);
+ const all = Array.from(document.querySelectorAll(sel));
+ let own = all.length === 1 ? all[0] : null;
+ if (!own && want) own = all.find((el) => norm(el.innerText).includes(want)) || null;
+ for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture");
+ if (!own) return { count: all.length, rect: null, text: norm(document.body && document.body.innerText).slice(0, 2000) };
+ own.setAttribute("data-archilyzer-capture", "");
+ const r = own.getBoundingClientRect();
+ return { count: all.length, rect: { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }, text: "" };
+})()`;
+
+// Let the post's images finish loading (each capped), so the shot is not of
+// grey boxes.
+const IMAGES_LOADED_SCRIPT = `(() => {
+ const own = document.querySelector("[data-archilyzer-capture]") || document;
+ const imgs = Array.from(own.querySelectorAll("img")).filter((i) => !i.complete);
+ return Promise.all(imgs.map((i) => new Promise((r) => {
+ i.addEventListener("load", r, { once: true });
+ i.addEventListener("error", r, { once: true });
+ setTimeout(r, 5000);
+ }))).then(() => imgs.length);
+})()`;
+
+type Snapshot = { count: number; rect: { x: number; y: number; width: number; height: number } | null; text: string };
+
+export type BlueskyShotResult = {
+ state: PostCaptureState;
+ shot?: CapturedFile;
+ error?: string;
+ // The page answered 429.
+ rateLimited?: boolean;
+};
+
+function raceAbort<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) return Promise.reject(new Error("cancelled"));
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new Error("cancelled"));
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(v);
+ },
+ (e) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(e);
+ },
+ );
+ });
+}
+
+// One post's screenshot: load its page, wait for the post, shoot that element.
+// Writes `shot.png` into `dir` only for a post that rendered. `url` is the
+// page to open; `canonicalUrl` the bsky.app URL the record names.
+export async function shootBlueskyPost(
+ page: PageLike,
+ o: {
+ url: string;
+ canonicalUrl: string;
+ handle: string;
+ text: string;
+ dir: string;
+ signal: AbortSignal;
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+ },
+): Promise<BlueskyShotResult> {
+ let response: unknown;
+ try {
+ response = await raceAbort(
+ page.goto(o.url, { waitUntil: "domcontentloaded", timeout: o.pageTimeoutMs ?? 45_000 }),
+ o.signal,
+ );
+ } catch (err) {
+ return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` };
+ }
+ const status = (response as { status?: () => number } | null)?.status?.();
+ if (status === 429) return { state: "error", error: "bsky.app answered 429", rateLimited: true };
+ const sel = `[data-testid="postThreadItem-by-${o.handle}"]`;
+ const appeared = await raceAbort(
+ page.waitForSelector(sel, { timeout: o.postTimeoutMs ?? 20_000 }).then(
+ () => true,
+ () => false,
+ ),
+ o.signal,
+ ).catch(() => false);
+ if (o.signal.aborted) return { state: "error", error: "cancelled" };
+ if (!appeared) {
+ const snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text)).catch(() => null)) as Snapshot | null;
+ const body = snap?.text ?? "";
+ if (/sign in|log in/.test(body) && /(required|to view|logged-in|signed-in)/.test(body)) {
+ return { state: "error", error: "The author shows their posts only to signed-in users; the capture has no login." };
+ }
+ return { state: "error", error: `The post did not render (no ${sel} on the page).` };
+ }
+ await page.waitForTimeout(1_000);
+ let snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ if (!snap.rect) {
+ return { state: "error", error: `${snap.count} posts by @${o.handle} on the page, none of them this one's text.` };
+ }
+ await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => {});
+ // Re-read the box: images that loaded may have grown it.
+ snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ const rect = snap.rect;
+ if (!rect || rect.width < 1 || rect.height < 1) {
+ return { state: "error", error: "The post rendered with no size to shoot." };
+ }
+ let png: Uint8Array;
+ try {
+ // fullPage, so a post taller than the window is shot whole; the clip is in
+ // document coordinates, which is what the snapshot measured.
+ png = await page.screenshot({
+ type: "png",
+ fullPage: true,
+ clip: {
+ x: Math.max(0, Math.floor(rect.x)),
+ y: Math.max(0, Math.floor(rect.y)),
+ width: Math.ceil(rect.width),
+ height: Math.ceil(rect.height),
+ },
+ });
+ } catch (err) {
+ return { state: "error", error: `The screenshot failed: ${firstLine(err)}` };
+ }
+ await mkdir(o.dir, { recursive: true });
+ await writeFile(path.join(o.dir, SHOT_FILENAME), png);
+ return { state: "captured", shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl) };
+}
+
+// ─── The images ───
+
+const EXT_BY_TYPE: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+};
+
+function imageExt(url: string, contentType: string | null): string {
+ const ct = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct];
+ // The CDN names the format after an "@": …/<cid>@jpeg.
+ const at = /@(jpeg|jpg|png|webp|gif)$/i.exec(url);
+ if (at) return at[1].toLowerCase() === "jpeg" ? "jpg" : at[1].toLowerCase();
+ const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(url);
+ return m ? m[1].toLowerCase() : "jpg";
+}
+
+// ─── The run ───
+
+// A run's errors in a row that stop it: a host whose network or browser is
+// failing every post should not page through the rest of the list.
+const STOP_AFTER_ERRORS = 3;
+
+export async function captureBlueskyPosts(
+ input: PostCaptureInput,
+ deps: BlueskyCaptureDeps,
+): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false };
+ const now = deps.now ?? (() => new Date());
+ const outcomes: PostCaptureOutcome[] = [];
+ const stopped = (why: string): PostCaptureResult => {
+ onLog?.(why);
+ return { outcomes, stoppedEarly: why };
+ };
+
+ // What each post is owed, from what is on disk.
+ const owed: { id: string; dir: string; existing: PostCaptureRecord | null; shot: boolean; media: boolean }[] = [];
+ for (const id of input.ids) {
+ const dir = postCaptureDir(input.outDir, id);
+ const existing = await readPostCapture(dir);
+ const work = captureWork(existing, { ...wanted, articles: false });
+ if (!work.shot && !work.media) {
+ onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`);
+ continue;
+ }
+ owed.push({ id, dir, existing, shot: work.shot, media: work.media });
+ }
+ if (owed.length === 0) return { outcomes };
+
+ // The account's DID: getPosts takes AT-URIs.
+ const appview = deps.endpoints.appview;
+ let did = input.handle;
+ if (!did.startsWith("did:")) {
+ const got = await politeGet(
+ deps,
+ `${appview}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(input.handle)}`,
+ "application/json",
+ signal,
+ onLog,
+ );
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) return stopped(`Could not resolve @${input.handle}: ${got.error}. Nothing was recorded.`);
+ const body = (await got.res.json().catch(() => null)) as { did?: string } | null;
+ if (!body?.did) return stopped(`Could not resolve @${input.handle}: no DID in the answer. Nothing was recorded.`);
+ did = body.did;
+ }
+
+ // Liveness and images, 25 posts a request. A post absent from a batch that
+ // answered is deleted; a batch that failed says nothing about its posts.
+ const views = new Map<string, BlueskyPostView>();
+ const unanswered = new Map<string, string>();
+ for (let i = 0; i < owed.length; i += GET_POSTS_BATCH) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const batch = owed.slice(i, i + GET_POSTS_BATCH);
+ const params = new URLSearchParams();
+ for (const o of batch) params.append("uris", `at://${did}/app.bsky.feed.post/${o.id}`);
+ const got = await politeGet(deps, `${appview}/xrpc/app.bsky.feed.getPosts?${params.toString()}`, "application/json", signal, onLog);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) {
+ if (got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`);
+ for (const o of batch) unanswered.set(o.id, `getPosts failed: ${got.error}`);
+ continue;
+ }
+ const body = (await got.res.json().catch(() => null)) as { posts?: BlueskyPostView[] } | null;
+ if (!body || !Array.isArray(body.posts)) {
+ for (const o of batch) unanswered.set(o.id, "getPosts answered no post list");
+ continue;
+ }
+ for (const v of body.posts) {
+ const rkey = rkeyOf(v.uri);
+ if (rkey) views.set(rkey, v);
+ }
+ }
+
+ let pages = 0;
+ let errorsInARow = 0;
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ try {
+ for (const [i, o] of owed.entries()) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run.");
+ const { id, dir, existing } = o;
+ onLog?.(`[${i + 1}/${owed.length}] ${id}`);
+ const view = views.get(id);
+ const failedLookup = unanswered.get(id);
+ const author = view?.author?.handle || input.handle;
+ const canonicalUrl = postPermalink("bluesky", author, id);
+
+ let state: PostCaptureState;
+ let availability: PostAvailability | undefined;
+ let shot = existing?.shot;
+ let mediaState: CaptureMediaState = existing?.mediaState ?? "skipped";
+ let media: CapturedFile[] = existing?.media ?? [];
+ let error: string | undefined;
+ let stop: string | undefined;
+
+ if (failedLookup) {
+ // Nothing learned about the post: what is on disk stands.
+ state = "error";
+ error = failedLookup;
+ } else if (!view) {
+ // The platform says it is gone. What an earlier capture took is kept.
+ state = "deleted";
+ availability = "deleted";
+ } else {
+ availability = "available";
+ // A run that does not shoot keeps the shot's verdict on disk.
+ state = o.shot ? "error" : (existing?.state ?? "captured");
+ if (o.shot) {
+ if (pages++ > 0) await deps.pause(deps.pageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ browser ??= await deps.openPage();
+ const shotArgs = {
+ url: onBlueskyEndpoints(`https://bsky.app/profile/${author}/post/${id}`, deps.endpoints),
+ canonicalUrl,
+ handle: author,
+ text: view.record?.text ?? "",
+ dir,
+ signal,
+ ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}),
+ ...(deps.postTimeoutMs ? { postTimeoutMs: deps.postTimeoutMs } : {}),
+ };
+ let res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) {
+ const wait = Math.max(deps.backoffBaseMs ?? 30_000, deps.pageGapMs());
+ onLog?.(`bsky.app answered 429; waiting ${Math.round(wait / 1000)} s before one more try.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) stop = "bsky.app answered 429 twice; stopping.";
+ }
+ state = res.state;
+ if (res.shot) shot = res.shot;
+ if (res.error) error = res.error;
+ }
+ const postIsThere = state === "captured" || !o.shot;
+ if (o.media && postIsThere && !stop) {
+ const images = blueskyPostImages(view);
+ if (images.length === 0) {
+ mediaState = "none";
+ media = [];
+ } else {
+ media = [];
+ let failed = 0;
+ for (const [n, im] of images.entries()) {
+ if (n > 0) await deps.pause(deps.imageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const got = await politeGet(deps, onBlueskyEndpoints(im.url, deps.endpoints), "image/*", signal, onLog);
+ if (!got.ok) {
+ failed++;
+ onLog?.(`${id}: image ${n + 1} failed: ${got.error}`);
+ if (got.rateLimited) {
+ stop = `${got.error}; stopping.`;
+ break;
+ }
+ continue;
+ }
+ const name = `media-${n + 1}.${imageExt(im.url, got.res.headers.get("content-type"))}`;
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, name), new Uint8Array(await got.res.arrayBuffer()));
+ media.push(await describeCapturedFile(dir, name, im.url));
+ }
+ mediaState = failed > 0 ? "error" : "ok";
+ if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`;
+ }
+ if (!o.shot && !existing && mediaState === "error") state = "error";
+ }
+ }
+
+ const record: PostCaptureRecord = {
+ version: 1,
+ id,
+ url: canonicalUrl,
+ capturedAt: now().toISOString(),
+ state,
+ ...(shot ? { shot } : {}),
+ mediaState,
+ media,
+ ...(error ? { error } : {}),
+ };
+ await writePostCapture(dir, record);
+ outcomes.push({
+ id,
+ state,
+ ...(availability ? { availability } : {}),
+ files: (shot ? 1 : 0) + media.length,
+ ...(error ? { error } : {}),
+ });
+ onLog?.(
+ `${id}: ${state}` +
+ (state === "captured" && o.shot ? ", shot" : "") +
+ (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" && view ? ", no images" : "") +
+ (error ? ` — ${error}` : ""),
+ );
+ if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`);
+ errorsInARow = state === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`);
+ }
+ }
+ return { outcomes };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
+
+function firstLine(err: unknown): string {
+ return ((err as Error)?.message ?? String(err)).split("\n")[0];
+}
diff --git a/common/testing/archiveOrg/fakeArchiveOrg.mjs b/common/testing/archiveOrg/fakeArchiveOrg.mjs
@@ -13,7 +13,12 @@
// Routes:
// GET /advancedsearch.php?q=…&rows=N items whose identifier, title or
// subject contains every word of q
-// (`*` matches all), identifier order
+// (`*` matches all), identifier order;
+// a q of `field:value` clauses joined by
+// OR (release 29: a YouTube id search)
+// matches an item whose metadata field
+// contains any clause's value (quotes,
+// parentheses, `*` and `\` dropped)
// GET /metadata/<id> the item, or {} (archive.org's answer
// for an unknown id)
// opts.busyTimes the first N requests answer 429
@@ -50,6 +55,26 @@ export const ITEMS = [
},
files: [{ name: "members.mp4", source: "original", format: "MPEG4", size: "5000" }],
},
+ // A mirror of a recording deleted on its platform (release 29): the corpus's
+ // GONE_RECORD, uploaded by a mirroring tool with the id in its identifier,
+ // its description and its original URL. Not "bakery": the search tests
+ // count those.
+ {
+ metadata: {
+ identifier: "youtube-gone-video-05",
+ title: "The old oven review",
+ date: "2026-01-20",
+ mediatype: "movies",
+ collection: ["opensource_movies"],
+ description: "Mirror of https://video.example/watch?v=gone-video-05",
+ originalurl: "https://video.example/watch?v=gone-video-05",
+ },
+ files: [
+ { name: "The old oven review-gone-video-05.webm", source: "original", format: "WebM", size: "3000000", length: "20.0" },
+ { name: "The old oven review-gone-video-05.mp4", source: "derivative", format: "h.264", original: "The old oven review-gone-video-05.webm", size: "2000000" },
+ { name: "The old oven review-gone-video-05.info.json", source: "original", format: "JSON", size: "1500" },
+ ],
+ },
{
metadata: {
identifier: "synth-radio-tape-01",
@@ -88,8 +113,18 @@ export async function startFakeArchiveOrg(opts = {}) {
const q = u.searchParams.get("q") ?? "";
const rows = Number(u.searchParams.get("rows") ?? 50);
const want = q.trim() === "*" ? [] : words(q);
+ const clauses = q.split(/\s+OR\s+/).map((c) => c.trim().replace(/^\(+|\)+$/g, ""));
+ const fielded = clauses.length > 0 && clauses.every((c) => /^[a-z_]+:/i.test(c));
+ const fieldMatch = (it) =>
+ clauses.some((c) => {
+ const i = c.indexOf(":");
+ const field = c.slice(0, i);
+ const value = c.slice(i + 1).replace(/["()*\\]/g, "").trim().toLowerCase();
+ return value !== "" && flat(it.metadata[field]).toLowerCase().includes(value);
+ });
const hits = items
.filter((it) => {
+ if (fielded) return fieldMatch(it);
const hay = new Set(words(`${it.metadata.identifier} ${flat(it.metadata.title)} ${flat(it.metadata.subject)}`));
return want.every((w) => hay.has(w));
})
diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts
@@ -34,6 +34,7 @@ import {
clipsDirFor,
clipWindowFile,
clipWindowName,
+ type ClipCopy,
type ClipProvenance,
} from "../lib/clipWindow";
import {
@@ -92,6 +93,8 @@ export type FetchWindowProvenance = {
reason?: string;
pad?: number;
requestedAt?: string;
+ // The copy of a gone recording the URL is (release 29 E2, find-copy).
+ copy?: ClipCopy;
};
export type FetchWindowOpts = {
@@ -353,6 +356,7 @@ export async function fetchWindowManaged(
...(typeof opts.provenance.pad === "number"
? { pad: opts.provenance.pad }
: {}),
+ ...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}),
bytes: st.size,
fetchedAt: new Date().toISOString(),
ytdlp: { args },
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -4,6 +4,11 @@
- **The verdict bench asks to the operator's standard, and says which prompt it asked with.** What each verdict means is written once (`common/lib/report/verdicts.mjs`) and read by the bench's prompt, REPORT.md and umtool's bench page: CORROBORATED when the substance of the claim is shown by the cited words (framing, emphasis or a detail the transcript does not show does not demote it), PARTLY only when a part is shown overstated or wrong, and when in doubt between the two, CORROBORATED. The model now writes its reason before its verdict, and sees the report's title, the claim's section, and each cited line's speaker and recording date. Each run records its prompt version and a hash of its items; a run made before this is version 1, and a run is never resumed under another version. Needs a restart of the editor and umtool.
- **`archilyzer reports bench-verdicts` takes `--items-from <run>`, `--window-mode seconds|turn` and a stratified `--limit`.** `--items-from vb-r28` asks the same items again (for example a local model on a new prompt, at no cost). `--window-mode turn` shows the cited speaker's turn instead of a fixed number of seconds either side, bounded by `--window`. `--limit` keeps every verdict the operator ruled, in proportion. A re-run of a run asks only the models it names, so a local-only re-run never asks a paid model again. A citation that gives no transcript is listed with its reason instead of being left out silently. `pnpm ops bench-verdicts` takes the same keys (`itemsFrom`, `windowMode`, `limit`).
- **umtool's verdict bench compares runs and takes your marks.** `/tools/bench` shows each run's prompt version and items hash, and **compare with** lists the runs over the same items: each model's agreement in both and every claim whose answer changed. Each disagreement has **Right** and **Wrong** (was the model right?), kept beside the run, and the not-CORROBORATED precision and recall beside the bar are shown as ruled and with your marks, so the bar can be set from what you marked. "What the verdicts mean" lists the definitions.
+- **A cited video that was deleted no longer stops a report from publishing.** When a report cites a moment of a recording that its platform has since deleted or made private, and no copy of it is on disk, the report's page now shows that moment's words only, marked **Source deleted** (or **Source made private**), on its card and its moment page — instead of `reports prepare` and the build refusing the whole report. A deleted post that was never captured is shown the same way. `reports prepare` and `reports check` list each one as a warning. A moment of a recording that is still up and has no clip is still refused, as before. Needs a restart of the editor; the sites show it after their next build.
+- **`pnpm ops find-copy` looks for a copy of a deleted video and fetches the cited seconds from it.** For one article (`{"article": "<id>"}`), every published article (`{"articles": true}`) or a site's reports (`{"siteId": "<id>"}`), it takes each cited recording that is deleted or private, looks for a Wayback Machine capture of its page, then for an archive.org mirror that names its YouTube id, and fetches the cited windows from the copy it finds as one paced job. The clips land with the recording's other clips, and each one's record says which copy it came from. With `"dryRun": true` it only says what it found. A recording with no copy anywhere is left to show its words only. Needs a restart of the editor.
+- **`pnpm ops wayback-lookup` lists the Wayback Machine's captures of a page** — a URL, or a recording's own page (`{"slug", "id"}`), with `"okOnly": true` for the captures that loaded. **`pnpm ops archive-search --json '{"youtubeId": "<id>"}'`** finds archive.org mirrors of one YouTube video and gives each one's direct video file link. Both are read only and paced as archive.org asks.
+- **Fetch windows refuses a window of a deleted or private video** unless the item names another page to fetch it from (what `find-copy` does), instead of asking the dead page.
+- **Capture posts works for Bluesky channels, with no login.** `pnpm ops capture-posts --json '{"slug": "<channel>", "ids": [...]}'` on a Bluesky channel now reads which posts are still up from Bluesky's public API, opens each live post's bsky.app page in a headless browser with no account, and saves a screenshot cropped to the post (`shot.png`) and the post's images beside it, in the channel's `posts-media/<id>/` — what a report's moment page shows. A post Bluesky no longer has is recorded as deleted in the channel's post availability, and nothing is opened for it. One page at a time, a few seconds apart; a "slow down" from Bluesky is waited out, and one that persists stops the run with the rest left for later. Needs a restart of the editor.
- **The research board keeps a key pressed just after a save, too.** A key that arrived after a save's answer, or after its redraw but before the moved line took the focus back, could still lose `e`'s field (the claim then went nowhere). The board now waits until the redraw is fully done before acting on any key. Needs a restart of umtool.
- **A recurring report's tick no longer calls a capped scan "nothing new".** Triage used to take the scope from one `enumerate_matches(".")`, which stops at 2,000 recordings — the co-host pilot's five channels hold 23,284, the newest read last, so its first tick found "0 new" and ended quiet. Tier 0 now lists the scope from the build's own per-channel manifests (every recording, uncapped, dated by the build's index) and reads the terms only over the new recordings (and, on a first run, from the start date). A scan that still hits a cap or misses a channel is **partial**: the tick says "partial — not reached: …" as a **Your call** card in umtool (never quiet, no quiet edition recorded), the triage run says so on its page, and its set of seen recordings is not kept, so the next run counts new from the last complete run (or from its start date). The same rule holds for a Refresh's search again (a capped search with nothing new ends **partial**, not "no change"), a series' window check, and the Inbox's daily refresh check (a partial check still raises its card, naming what it did not reach; `umtool refresh --check` prints PARTIAL). Needs a restart of the editor and umtool.
- **`enumerate_matches` takes `ids`.** Only the pages that hold those recordings are read, so the scan is bounded by them rather than by the scope; the footer says how many the scope holds. A sweep restricted to given recordings (a refresh's update, a triage's escalation) now scans only theirs.
diff --git a/editor/app/api/ops/_research.test.ts b/editor/app/api/ops/_research.test.ts
@@ -50,3 +50,51 @@ test("import-post: refused before any job — not a post URL, not a posts channe
assert.equal(noUrl.status, 400);
assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued");
});
+
+// Release 29 E2: archive-search's YouTube-id mode, wayback-lookup and find-copy
+// — refused at the door before anything reaches archive.org.
+test("archive-search: youtubeId or query, not both; an id is an id", async () => {
+ const search = await route("archive-search");
+ const both = await callPost(search, { query: "x", youtubeId: "dQw4w9WgXcQ" });
+ assert.equal(both.status, 400);
+ assert.match(String(both.body.error), /either "query" or "youtubeId"/);
+ const bad = await callPost(search, { youtubeId: "not an id" });
+ assert.equal(bad.status, 400);
+ assert.match(String(bad.body.error), /is not a YouTube id/);
+});
+
+test("wayback-lookup: a URL or a record, not both; an http(s) URL; a record with no known page is a 404", async () => {
+ const lookup = await route("wayback-lookup");
+ const none = await callPost(lookup, {});
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /"url" \(a page\) or "slug" and "id"/);
+ const both = await callPost(lookup, { url: "https://a.example/x", slug: "test-youtube", id: "x" });
+ assert.equal(both.status, 400);
+ const ftp = await callPost(lookup, { url: "ftp://a.example/x" });
+ assert.equal(ftp.status, 400);
+ assert.match(String(ftp.body.error), /http\(s\) URL/);
+ const big = await callPost(lookup, { url: "https://a.example/x", limit: 501 });
+ assert.equal(big.status, 400);
+ // A record of no channel: no page to look up (a YouTube channel's record would
+ // be given its watch URL from its id, and asked of the real Wayback — never
+ // in a test).
+ const unknown = await callPost(lookup, { slug: "no-such-channel", id: "no-such-video" });
+ assert.equal(unknown.status, 404);
+ assert.match(String(unknown.body.error), /no page is known for no-such-channel\/no-such-video/);
+});
+
+test("find-copy: exactly one of article, articles, siteId; an unknown one is refused before any lookup", async () => {
+ const find = await route("find-copy");
+ const before = await corpus.listJobIds();
+ assert.equal((await callPost(find, {})).status, 400);
+ const two = await callPost(find, { article: "a", siteId: "b" });
+ assert.equal(two.status, 400);
+ assert.match(String(two.body.error), /send one of "article"/);
+ const noArticle = await callPost(find, { article: "no-such-article", dryRun: true });
+ assert.equal(noArticle.status, 400);
+ assert.match(String(noArticle.body.error), /no article "no-such-article"/);
+ const noSite = await callPost(find, { siteId: "no-such-site" });
+ assert.equal(noSite.status, 400);
+ assert.match(String(noSite.body.error), /No site "no-such-site"/);
+ assert.deepEqual(await corpus.listJobIds(), before, "nothing was queued");
+});
diff --git a/editor/app/api/ops/archive-search/route.ts b/editor/app/api/ops/archive-search/route.ts
@@ -4,21 +4,50 @@ import {
ARCHIVE_ORG_SEARCH_MAX_ROWS,
searchArchiveOrgItems,
} from "yt-dlp-transcript-common/controller/archiveOrgImport";
-import { OpsInputError, ops, opsFail, optPositiveInt, reqString } from "../_lib";
+import { findArchiveOrgMirrors } from "yt-dlp-transcript-common/publish/findCopy";
+import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib";
export const dynamic = "force-dynamic";
// POST { query, limit? } -> { ok: true, query, found, items: [{ identifier, title? }] }
+// | { youtubeId, limit? } -> { ok: true, youtubeId, query, found,
+// items: [{ identifier, title?, file, url, source, size? }],
+// skipped: [{ identifier, why }] }
//
// An archive.org search (its advanced-search syntax), read only: ONE request
// through the editor's polite archive.org client — the same client, gap and
// back-off an import uses (controller/archiveOrgImport.ts) — the first
// `limit` items (default 50, at most 500) in identifier order. Nothing is
// written; `import-archive-org` with `query` imports what a search finds.
+//
+// `youtubeId` (release 29 E2) looks for MIRRORS of one YouTube upload: items
+// naming the id in their identifier, title, description or original URL
+// (publish/findCopy.ts), each read for its files (one request each), and
+// answers each mirror's direct video file URL
+// (`https://archive.org/download/<identifier>/<file>`, an original preferred).
+// An item that does not name the id, is restricted, or holds no file the
+// upload can be told by is `skipped`, with why. `limit` defaults to 10 here.
const ARCHIVE_SEARCH_DEFAULT_LIMIT = 50;
+const MIRROR_DEFAULT_LIMIT = 10;
export async function POST(request: Request) {
- return ops(request, ["query", "limit"], async (body) => {
+ return ops(request, ["query", "limit", "youtubeId"], async (body) => {
+ const youtubeId = optString(body, "youtubeId")?.trim();
+ if (youtubeId !== undefined && body.query !== undefined) {
+ throw new OpsInputError('send either "query" or "youtubeId", not both');
+ }
+ if (youtubeId !== undefined) {
+ if (!/^[A-Za-z0-9_-]{6,20}$/.test(youtubeId)) throw new OpsInputError(`"${youtubeId}" is not a YouTube id`);
+ const limit = optPositiveInt(body, "limit") ?? MIRROR_DEFAULT_LIMIT;
+ if (limit > ARCHIVE_ORG_SEARCH_MAX_ROWS) throw new OpsInputError(`"limit" is at most ${ARCHIVE_ORG_SEARCH_MAX_ROWS}`);
+ try {
+ const r = await findArchiveOrgMirrors(youtubeId, { limit });
+ return NextResponse.json({ ok: true, youtubeId, query: r.query, found: r.found, items: r.mirrors, skipped: r.skipped });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502);
+ throw e;
+ }
+ }
const query = reqString(body, "query");
const limit = optPositiveInt(body, "limit") ?? ARCHIVE_SEARCH_DEFAULT_LIMIT;
if (limit > ARCHIVE_ORG_SEARCH_MAX_ROWS) {
diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts
@@ -94,6 +94,16 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
name: "Example (Bluesky)",
url: "https://bsky.app/profile/example.bsky.social",
});
+ // An X channel on the Nitter fetcher, which has no capture.
+ await channel("example-nitter", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-nitter",
+ socialHandle: "example_user",
+ name: "Example (X, Nitter)",
+ url: "https://x.com/example_user",
+ });
// An X channel with an empty posts archive.
await channel("example-x", {
handling: "transcribe",
@@ -109,9 +119,15 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
assert.equal(video.status, 400);
assert.equal(video.error, "test-filter is not a social channel.");
+ const nitter = await post({ slug: "example-nitter", ids: ["1"] });
+ assert.equal(nitter.status, 400);
+ assert.match(nitter.error, /cannot capture posts/);
+
+ // Bluesky captures (release 29 E1): its fetcher passes, and the id that is
+ // not in the channel's archive is what is refused.
const bsky = await post({ slug: "example-bsky", ids: ["1"] });
assert.equal(bsky.status, 400);
- assert.match(bsky.error, /cannot capture posts/);
+ assert.equal(bsky.error, "1 id(s) not in example-bsky's posts archive: 1");
const neither = await post({ slug: "example-x", ids: ["1"], shots: false, media: false });
assert.equal(neither.status, 400);
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -0,0 +1,40 @@
+import { NextResponse } from "next/server";
+import { findCopyAction } from "../../../channels/[slug]/videos/findCopyAction";
+import { OpsInputError, ops, opsFail, optBool, optString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { article } | { siteId } | { articles: true }, dryRun?
+// -> { ok, dryRun, host, recordings: [{ slug, id, gone, watchUrl, youtubeId,
+// windows, tried: [{ from, found, url?, detail?, error? }], copy?,
+// outcome: fetch | text-only | error }], items, stopped?, jobId? }
+//
+// A COPY OF EVERY GONE RECORDING THE REPORTS CITE (release 29 E2,
+// publish/findCopy.ts): of one article (`article`), every published
+// article (`articles`), or a site's reports (`siteId`), the cited windows
+// whose recording is deleted or private ("unfetchable: gone"). Per recording,
+// one at a time: the Wayback Machine (a capture of its page that recorded a
+// 200, the newest) then archive.org (a mirror naming its YouTube id, an
+// original video file preferred). The windows of every copy found go to ONE
+// fetch-windows job on the archive.org clip queue, each with the copy's URL as
+// its page, so the clips land in the recording's own clips/ with the copy in
+// their provenance. A recording with no copy is left: its moments show their
+// words only ("source deleted"). `dryRun` answers the lookups and starts
+// nothing. The lookups run in the request, paced.
+export async function POST(request: Request) {
+ return ops(request, ["article", "siteId", "articles", "dryRun"], async (body) => {
+ const article = optString(body, "article")?.trim();
+ const siteId = optString(body, "siteId")?.trim();
+ const articles = optBool(body, "articles") === true;
+ if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) {
+ throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"');
+ }
+ const r = await findCopyAction({
+ ...(article ? { article } : {}),
+ ...(siteId ? { siteId } : {}),
+ dryRun: optBool(body, "dryRun") === true,
+ });
+ if (!r.ok) return opsFail(r.error);
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from "next/server";
+import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { url } | { slug, id }, okOnly?, limit? -> { ok: true, url, found,
+// captures: [{ timestamp, status, mimetype?, replayUrl }] }
+//
+// The Wayback Machine's captures of a page (its CDX API, release 29 E2): a
+// URL as given, or a record's page — its metadata's webpage_url, else the one
+// its availability check recorded, else the playlist's. Oldest first;
+// `okOnly` keeps only the captures that recorded a 200; `limit` at most 500
+// (default 100). ONE request through the editor's Wayback client, with
+// archive.org's manners (one at a time, a 2 s gap, the project's User-Agent,
+// 429s waited out a few times, then a 502). Read only; nothing is fetched.
+// `find-copy` is what fetches a gone recording's windows from a capture.
+const MAX_LIMIT = 500;
+
+export async function POST(request: Request) {
+ return ops(request, ["url", "slug", "id", "okOnly", "limit"], async (body) => {
+ const given = optString(body, "url")?.trim();
+ const hasRecord = body.slug !== undefined || body.id !== undefined;
+ if (given && hasRecord) throw new OpsInputError('send either "url" or "slug" and "id", not both');
+ let url: string;
+ if (given) {
+ if (!/^https?:\/\/[^\s]+$/.test(given)) throw new OpsInputError(`"url" must be an http(s) URL`);
+ url = given;
+ } else if (hasRecord) {
+ const slug = reqSlug(body, "slug");
+ const id = reqVideoId(body, "id");
+ const found = await recordWebpageUrl(getPaths(), slug, id);
+ if (!found) return opsFail(`no page is known for ${slug}/${id} (no metadata, availability check or playlist entry names one)`, 404);
+ url = found;
+ } else {
+ throw new OpsInputError('"url" (a page) or "slug" and "id" (a record) is required');
+ }
+ const limit = optPositiveInt(body, "limit") ?? 100;
+ if (limit > MAX_LIMIT) throw new OpsInputError(`"limit" is at most ${MAX_LIMIT}`);
+ try {
+ const r = await waybackLookup(url, { okOnly: optBool(body, "okOnly") === true, limit });
+ return NextResponse.json({ ok: true, url, found: r.captures.length, captures: r.captures });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502);
+ throw e;
+ }
+ });
+}
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.test.ts
@@ -153,3 +153,29 @@ test("a held window a queued saved-video job will already cut is answered in inF
reg.forceRelease("HOLDER");
}
});
+
+// Release 29 E2: a recording gone from its platform (lib/sourceGone.ts) has no
+// page to fetch from — refused at the door — unless the item names a copy's
+// URL (find-copy), which is the only way such a window is fetched.
+test("a gone recording's window is refused at the door unless the item names a copy's URL", async () => {
+ const dir = path.join(ROOT, "channels", SLUG, "data", "deleted1");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "deleted1", webpage_url: "https://www.youtube.com/watch?v=deleted1" }));
+ await writeFile(path.join(dir, "availability.json"), JSON.stringify({ checkedAt: "2026-10-01T00:00:00.000Z", availability: "deleted" }));
+ const plain = await fetchWindowsAction({ items: [{ slug: SLUG, id: "deleted1", from: 1, to: 3 }], requestedBy: "test", dryRun: true });
+ assert.ok(plain.ok);
+ if (!plain.ok) return;
+ assert.equal(plain.groups.length, 0);
+ assert.equal(plain.unresolved.length, 1);
+ assert.match(plain.unresolved[0].error, /says the video is deleted.*find-copy/);
+ const copy = "https://web.archive.org/web/20260125093000/https://www.youtube.com/watch?v=deleted1";
+ const viaCopy = await fetchWindowsAction({
+ items: [{ slug: SLUG, id: "deleted1", from: 1, to: 3, webpageUrl: copy }],
+ requestedBy: "find-copy",
+ dryRun: true,
+ });
+ assert.ok(viaCopy.ok);
+ if (!viaCopy.ok) return;
+ assert.deepEqual(viaCopy.unresolved, []);
+ assert.deepEqual(viaCopy.groups.flatMap((g) => g.items.map((i) => i.webpageUrl)), [copy]);
+});
diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts
@@ -19,6 +19,7 @@ import {
isFetchMaxHeight,
} from "yt-dlp-transcript-common/lib/clipWindow";
import { findContainingClipWindow } from "yt-dlp-transcript-common/lib/clipWindow-server";
+import { sourceGoneState } from "yt-dlp-transcript-common/lib/sourceGone-server";
import { savedWindowSource } from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
import {
@@ -222,6 +223,23 @@ async function planFetchWindows(
groups.set(queueKey, group);
continue;
}
+ // A RECORDING GONE FROM ITS PLATFORM (lib/sourceGone.ts) has no page to
+ // fetch a window from: refused here, before any request — unless the item
+ // names a copy's URL (`webpageUrl`: find-copy's Wayback capture or
+ // archive.org file, release 29 E2), which is the only way such a window is
+ // fetched.
+ if (!item.webpageUrl?.trim()) {
+ const gone = await sourceGoneState(videoDir);
+ if (gone) {
+ unresolved.push({
+ item,
+ error:
+ `The source says the video is ${gone}: there is no page to fetch a window from. ` +
+ "pnpm ops find-copy looks for a copy (Wayback, archive.org) and fetches from it.",
+ });
+ continue;
+ }
+ }
const url =
item.webpageUrl?.trim() ||
(await findVideoSourceUrl(paths, item.slug, dirId, config));
diff --git a/editor/app/channels/[slug]/videos/findCopyAction.ts b/editor/app/channels/[slug]/videos/findCopyAction.ts
@@ -0,0 +1,71 @@
+"use server";
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
+import { clipWindowQueueKey } from "yt-dlp-transcript-common/lib/queueKeys";
+import { platformQueueKey } from "yt-dlp-transcript-common/lib/platform";
+import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
+import { runFindCopy, type FindCopyResult } from "yt-dlp-transcript-common/publish/findCopy";
+import { fetchWindowsJobAction } from "./fetchWindowsAction";
+
+// FIND A COPY OF THE GONE RECORDINGS A REPORT CITES, and fetch their windows
+// from it (release 29 E2; the lookups are publish/findCopy.ts). The windows
+// of every copy found go to ONE fetch-windows job on the archive.org clip
+// queue — Wayback captures and archive.org files are both archive.org's — so
+// they are fetched one at a time, paced, one stream.
+
+export type FindCopyActionResult =
+ | { ok: false; error: string }
+ | (FindCopyResult & {
+ ok: true;
+ dryRun: boolean;
+ // The fetch-windows job, when one started.
+ jobId?: string;
+ // Why the fetch did not start, when it did not.
+ refused?: string;
+ });
+
+// The archive.org clip queue: every copy's windows, one job, one stream.
+const FIND_COPY_QUEUE = clipWindowQueueKey(platformQueueKey("archiveorg"));
+
+export async function findCopyAction(req: { article?: string; siteId?: string; dryRun?: boolean }): Promise<FindCopyActionResult> {
+ const paths = getPaths();
+ let host: ReportHost;
+ try {
+ if (req.article) {
+ host = await articlesWorkHost(paths, [req.article], { only: true });
+ } else if (req.siteId) {
+ if (!isValidSiteId(req.siteId)) return { ok: false, error: `"${req.siteId}" is not a valid site id` };
+ if (!listSiteIds(paths).includes(req.siteId)) return { ok: false, error: `No site "${req.siteId}"` };
+ host = siteReportHost(paths, getSite(req.siteId, paths));
+ } else {
+ host = await articlesWorkHost(paths);
+ }
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ let refused: string | undefined;
+ const r = await runFindCopy({
+ paths,
+ host,
+ dryRun: req.dryRun,
+ startFetch: async (items) => {
+ const res = await fetchWindowsJobAction({ items, requestedBy: "find-copy", manifest: host.id, queueKey: FIND_COPY_QUEUE });
+ if (!res.ok) {
+ refused = res.error;
+ return null;
+ }
+ // Nobody reads the stream: the job's log is on disk.
+ void res.stream.cancel().catch(() => {});
+ return res.jobId;
+ },
+ });
+ const { fetch: jobId, ...found } = r;
+ return {
+ ok: true,
+ dryRun: req.dryRun === true,
+ ...found,
+ ...(typeof jobId === "string" ? { jobId } : {}),
+ ...(refused ? { refused } : {}),
+ };
+}
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -8,6 +8,7 @@
// Server-only: reached through the retry actions in actions.ts ("use server"),
// so it is never bundled to the client.
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow";
import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
@@ -113,6 +114,8 @@ function windowItems(v: unknown): FetchWindowsItem[] {
reason: str(r.reason),
pad: num(r.pad),
webpageUrl: str(r.webpageUrl),
+ // find-copy's copy (release 29 E2): a replay records it again.
+ copy: coerceClipCopy(r.copy),
});
}
return out;
diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts
@@ -0,0 +1,130 @@
+// Capture posts for a Bluesky channel (release 29 E1), end to end over the
+// fake Bluesky (common/testing/social/fakeBluesky.mjs): the AppView, the
+// bsky.app-shaped post page and the image CDN all on one loopback origin,
+// named to the test server through E2E_BLUESKY_ORIGIN_FILE (e2e/servers.ts).
+// The real Bluesky is never contacted.
+//
+// The job runs as `pnpm ops capture-posts` runs it: the AppView says which
+// posts are live and where their images are, a headless Chromium with no login
+// shoots each live post cropped to it, the images come down beside the shot,
+// and the deleted post lands in posts-availability.json as deleted.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { startFakeBluesky, BSKY_POSTS, ACCOUNTS } from "yt-dlp-transcript-common/testing/social/fakeBluesky.mjs";
+import { writePosts } from "yt-dlp-transcript-common/lib/posts-server";
+import { uploadDateFromCreatedAt, type Post } from "yt-dlp-transcript-common/lib/posts";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { blueskyOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "synth-bsky";
+const HANDLE = ACCOUNTS[0].handle;
+
+async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> {
+ let last = { status: "", tail: [] as string[] };
+ await expect
+ .poll(
+ async () => {
+ const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH });
+ const body = (await res.json()) as { job: { status: string }; tail?: string[] };
+ last = { status: body.job.status, tail: body.tail ?? [] };
+ return last.status;
+ },
+ { timeout: 90_000, intervals: [1_000] },
+ )
+ .toMatch(/^(done|failed|cancelled)$/);
+ return last;
+}
+
+test("capture-posts on a Bluesky channel: shots cropped to the post, its images, and the deleted post recorded", async ({
+ request,
+}) => {
+ test.setTimeout(150_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+
+ const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify(
+ {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "bluesky",
+ postFetcher: "bluesky-atproto",
+ socialHandle: HANDLE,
+ name: "Synth Baker (Bluesky)",
+ url: `https://bsky.app/profile/${HANDLE}`,
+ },
+ null,
+ 2,
+ ),
+ );
+ // The three invented posts, archived as a fetch would have left them.
+ const posts: Post[] = BSKY_POSTS.map((p) => ({
+ id: p.rkey,
+ slug: `${SLUG}/${p.rkey}`,
+ channelSlug: SLUG,
+ author: p.handle,
+ createdAt: p.createdAt,
+ uploadDate: uploadDateFromCreatedAt(p.createdAt),
+ text: p.text,
+ url: `https://bsky.app/profile/${p.handle}/post/${p.rkey}`,
+ platform: "bluesky",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }));
+ await writePosts(channelRoot, posts);
+
+ const bsky = await startFakeBluesky();
+ const originFile = blueskyOriginFile(resolvePath(testPaths().transcriptsDir));
+ await writeFile(originFile, bsky.base);
+ try {
+ const ids = BSKY_POSTS.map((p) => p.rkey);
+ const res = await request.post(`${baseUrl}/api/ops/capture-posts`, { headers: AUTH, data: { slug: SLUG, ids } });
+ const body = (await res.json()) as { ok?: boolean; jobId?: string; error?: string };
+ expect(res.status(), body.error).toBe(200);
+ const job = await waitForJob(request, body.jobId!);
+ expect(job.status, job.tail.join("\n")).toBe("done");
+
+ const media = path.join(channelRoot, "posts-media");
+ const [withImages, textOnly, deleted] = ids;
+ expect((await readdir(path.join(media, withImages))).sort()).toEqual([
+ "capture.json",
+ "media-1.png",
+ "media-2.png",
+ "shot.png",
+ ]);
+ expect((await readdir(path.join(media, textOnly))).sort()).toEqual(["capture.json", "shot.png"]);
+ const gone = JSON.parse(await readFile(path.join(media, deleted, "capture.json"), "utf8")) as { state: string; shot?: unknown };
+ expect(gone.state).toBe("deleted");
+ expect(gone.shot).toBeUndefined();
+
+ // The shot is the post, not the page: the fake's thread item is 600 CSS
+ // px wide in a 1280-px window, shot at 2x.
+ const png = await readFile(path.join(media, withImages, "shot.png"));
+ expect(png.readUInt32BE(16)).toBe(1200);
+
+ const availability = JSON.parse(await readFile(path.join(channelRoot, "posts-availability.json"), "utf8")) as Record<
+ string,
+ { availability: string }
+ >;
+ expect(availability[deleted]?.availability).toBe("deleted");
+ expect(availability[withImages]?.availability).toBe("available");
+
+ // The page was opened for the live posts only; the deleted one never.
+ const pages = bsky.requests.filter((r) => r.startsWith("/profile/"));
+ expect(pages).toEqual([
+ `/profile/${HANDLE}/post/${withImages}`,
+ `/profile/${HANDLE}/post/${textOnly}`,
+ ]);
+ } finally {
+ await rm(originFile, { force: true });
+ await bsky.close();
+ }
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -47,6 +47,11 @@ export const E2E_SERVER_ENV: Record<string, string> = {
EXPORT_NEXT_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-next.mjs"),
};
+/** The file naming a slot's fake Bluesky (common/social/blueskyEndpoints.ts). */
+export function blueskyOriginFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-bluesky-origin");
+}
+
/** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */
export const E2E_DIST_DIR = ".next/e2e";
const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites");
@@ -192,6 +197,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
const ports = slotPorts(slot, env);
const paths = testPathsFor(slotRoot(slot));
const editorEnv: Record<string, string> = { ...E2E_SERVER_ENV };
+ // Where a spec names its fake Bluesky's origin (capture-posts.spec): the
+ // slot's own test data, so two slots never share one.
+ editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
// A start-mode server runs the stamped build (shared, read-only); a second
// `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`).
if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR;
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -30,6 +30,10 @@ import { currentSlot } from "./e2e/testPaths";
// batch (30–45 s in production; 2 s here), so
// fetch-window.spec sees the one it owes
// (common/controller/fetchWindows.ts)
+// E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
+// writes its fake Bluesky's loopback origin into,
+// which the AppView, bsky.app and the image CDN
+// then are (common/social/blueskyEndpoints.ts)
// E2E_MODE `start` (the default): the editor runs under
// `next start` from a build the stamp vouches for
// (scripts/e2e-stamp.mjs — rebuilt through the
diff --git a/export/app/lib/reports.test.ts b/export/app/lib/reports.test.ts
@@ -77,6 +77,7 @@ test("params: every report and every moment, as the index files list them", () =
{ moment: ["demo-channel", "abc123", "3126.00-3151.00"] },
{ moment: ["demo-podcast", "ep-042", "610.50-628.00"] },
{ moment: ["demo-social", "1234567890"] },
+ { moment: ["demo-channel", "gone99", "1200.00-1210.00"] },
]);
});
@@ -147,7 +148,7 @@ test("the report page: header, tally, sections and claims, inline cites, referen
assert.match(html, /data-inline-cite="w01"[^]*?data-cite-number="4"/);
// every numbered citation has its reference entry, in number order
const refs = [...html.matchAll(/<li id="c-([^"]+)" value="(\d+)"/g)].map((m) => `${m[2]}:${m[1]}`);
- assert.deepEqual(refs, ["1:c01", "2:au1", "3:a01", "4:w01", "5:a02", "6:p01"]);
+ assert.deepEqual(refs, ["1:c01", "2:au1", "3:a01", "4:w01", "5:a02", "6:p01", "7:g01"]);
assert.match(html, /href="\/pages\/demo-factcheck\/citations.json" download=""/);
assert.match(html, /href="\/pages\/demo-factcheck\/citations.csv" download=""/);
const meta = await reportPage.generateMetadata({ params });
diff --git a/export/e2e-report/report-site.spec.ts b/export/e2e-report/report-site.spec.ts
@@ -18,14 +18,16 @@ import { readFixtureReport } from "../fixtures/report-site/fixture";
//
// The site is export/fixtures/report-site, staged and built by
// e2e-report/stage.ts: one fact-check citing a video span (c01), an audio
-// span (au1), a post (p01), the article's own sentences (a01, a02) and a web
-// page (w01). It has two revisions (report.v1.json, then report.json), and
+// span (au1), a post (p01), the article's own sentences (a01, a02), a web
+// page (w01), and a span of a stream deleted since (g01: its words only,
+// "Source deleted"). It has two revisions (report.v1.json, then report.json), and
// publishes their history.
const REPORT = "/pages/demo-factcheck/";
const VIDEO_MOMENT = "/m/demo-channel/abc123/3126.00-3151.00/";
const AUDIO_MOMENT = "/m/demo-podcast/ep-042/610.50-628.00/";
const POST_MOMENT = "/m/demo-social/1234567890/";
+const GONE_MOMENT = "/m/demo-channel/gone99/1200.00-1210.00/";
const HISTORY = "/pages/demo-factcheck/history/";
const inlineCite = (page: Page, id: string): Locator => page.locator(`[data-inline-cite="${id}"]`).first();
@@ -235,10 +237,10 @@ test("a post citation's preview shows the captured shot", async ({ page }) => {
test("a citation's number jumps to its entry in the reference list", async ({ page }) => {
await page.goto(REPORT);
const refs = page.locator("[data-reference-list] [data-reference]");
- await expect(refs).toHaveCount(6);
+ await expect(refs).toHaveCount(7);
await expect
.poll(() => refs.evaluateAll((els) => els.map((el) => el.id)))
- .toEqual(["c-c01", "c-au1", "c-a01", "c-w01", "c-a02", "c-p01"]);
+ .toEqual(["c-c01", "c-au1", "c-a01", "c-w01", "c-a02", "c-p01", "c-g01"]);
await inlineCite(page, "w01").locator("[data-cite-number]").click();
await expect(page).toHaveURL(`${REPORT}#c-w01`);
@@ -298,7 +300,7 @@ test("report.html opens with no network: one file, no script, every image inline
expect(await img.getAttribute("src")).toMatch(/^data:image\//);
await expect.poll(() => img.evaluate((el) => (el as HTMLImageElement).naturalWidth)).toBeGreaterThan(0);
}
- await expect(page.locator("[data-reference-list] > li")).toHaveCount(6);
+ await expect(page.locator("[data-reference-list] > li")).toHaveCount(7);
// The page's tiers, its flag pill and the added mark, as the site has them.
await expect(page.locator("[data-report-tier]")).toHaveCount(3);
await expect(page.locator("[data-claim-flag]").first()).toContainText("No source given");
@@ -435,6 +437,21 @@ test("an audio moment plays its clip as sound", async ({ page, request }) => {
await expect(page.locator(`[data-cited-in] a[href="${REPORT}#claim-2"]`)).toHaveCount(1);
});
+// Release 29 E2: a cited recording deleted on its platform with no copy found
+// is its words only, said in plain words on its card and its moment page.
+test("a source-deleted moment: its words, no clip, \"Source deleted\" on the card and the page", async ({ page }) => {
+ await page.goto(REPORT);
+ const card = page.locator('#c-g01');
+ await expect(card.locator("[data-source-gone]")).toHaveText(/Source deleted/);
+ await expect(card.getByRole("link", { name: /^Open / })).toHaveAttribute("href", /\/m\/demo-channel\/gone99\/1200\.00-1210\.00\//);
+ await page.goto(GONE_MOMENT);
+ await expect(page.locator("[data-moment]")).toHaveAttribute("data-moment-kind", "video");
+ await expect(page.locator('[data-moment] p[data-source-gone="deleted"]')).toHaveText("Source deleted");
+ await expect(page.locator("video, audio")).toHaveCount(0);
+ await expect(page.locator("[data-cue-lines] li[data-in-span]")).toHaveText([/I was standing right there when they cut the ribbon\./]);
+ await expect(page.locator(`[data-cited-in] a[href="${REPORT}#claim-5"]`)).toHaveCount(1);
+});
+
test("a post moment shows the captured shot and the post", async ({ page }) => {
await page.goto(POST_MOMENT);
await expect(page.locator("[data-moment]")).toHaveAttribute("data-moment-kind", "post");
diff --git a/export/fixtures/report-site/fixture.ts b/export/fixtures/report-site/fixture.ts
@@ -69,6 +69,16 @@ const RECORDS: Record<string, RecordView> = {
date: "2026-01-10",
platform: "youtube",
},
+ // A stream deleted on its platform since (release 29 E2): no copy of it was
+ // found, so its moment is its words only, marked "Source deleted".
+ "demo-channel/gone99": {
+ channel: "demo-channel",
+ channelTitle: "Demo Channel",
+ id: "gone99",
+ title: "Demo stream: the ribbon, told again",
+ date: "2026-03-01",
+ platform: "youtube",
+ },
"demo-podcast/ep-042": {
channel: "demo-podcast",
channelTitle: "Demo Podcast",
@@ -87,6 +97,11 @@ const RECORDS: Record<string, RecordView> = {
const POSTER = "/pages/demo-factcheck/stills/poster.png";
+// The recordings gone from their platform with no media published: compose's
+// `sourceGone` (common/publish/composeReports.ts).
+const GONE: Record<string, "deleted" | "private"> = { "demo-channel/gone99": "deleted" };
+const goneOf = (c: { channel: string; id: string }) => GONE[`${c.channel}/${c.id}`];
+
// A post's captured screenshot, where compose copies a cited capture
// (publish/citedPostCaptures.ts): committed under public/media/posts/.
function shotFor(c: { channel: string; id: string }): string {
@@ -116,7 +131,8 @@ function recordFor(channel: string, id: string, seconds?: number): RecordView {
export function buildFixtureReportView(report = readFixtureReport()): ReportPageView {
return buildReportPageView(report, {
record: (c) => recordFor(c.channel, c.id, c.kind === "post" ? undefined : c.start),
- poster: (c) => (c.kind === "video" ? POSTER : undefined),
+ poster: (c) => (c.kind === "video" && !goneOf(c) ? POSTER : undefined),
+ sourceGone: (c) => goneOf(c),
post: (c) => ({
author: "@demo_account",
text: `${c.quote}\n\nPosted to settle it.`,
@@ -152,6 +168,11 @@ const CUES: Record<string, { start: number; end: number; text: string }[]> = {
{ start: 3151, end: 3160, text: "Anyway, back to the mail." },
{ start: 3160, end: 3170, text: "Next letter is from a long-time viewer." },
],
+ "demo-channel/gone99": [
+ { start: 1190, end: 1200, text: "People keep asking about the ribbon thing." },
+ { start: 1200, end: 1210, text: "I was standing right there when they cut the ribbon." },
+ { start: 1210, end: 1220, text: "Anyway, that was years ago." },
+ ],
"demo-podcast/ep-042": [
{ start: 600, end: 610.5, text: "So when did you first go back there?" },
{ start: 610.5, end: 628, text: "Like I said before, spring twenty nineteen." },
@@ -187,14 +208,15 @@ export function buildFixtureMomentViews(
...(c.verification ? { verification: c.verification } : {}),
start: span.start,
end: span.end,
- clip: {
+ ...(goneOf(c) ? { sourceGone: goneOf(c) } : {}),
+ ...(goneOf(c) ? {} : { clip: {
// A clip cut as sound is an .m4a beside the video clips (compose's
// clipPath).
src: c.kind === "audio" ? evidenceClipPath(span).replace(/\.mp4$/, ".m4a") : evidenceClipPath(span),
start: Math.max(0, span.start - before),
end: span.end + after,
...(c.kind === "video" ? { poster: POSTER } : {}),
- },
+ } }),
cues: (CUES[`${c.channel}/${c.id}`] ?? []).map((q) => ({
...q,
inSpan: q.end > span.start && q.start < span.end,
diff --git a/export/fixtures/report-site/public/m/demo-channel/gone99/1200.00-1210.00/moment.json b/export/fixtures/report-site/public/m/demo-channel/gone99/1200.00-1210.00/moment.json
@@ -0,0 +1,57 @@
+{
+ "format": "archilyzer-moment-page",
+ "version": 1,
+ "key": "demo-channel/gone99/1200.00-1210.00",
+ "kind": "video",
+ "record": {
+ "channel": "demo-channel",
+ "channelTitle": "Demo Channel",
+ "id": "gone99",
+ "title": "Demo stream: the ribbon, told again",
+ "date": "2026-03-01",
+ "platform": "youtube",
+ "originalUrl": "https://media.example.org/demo-channel/gone99?t=1200"
+ },
+ "quote": "I was standing right there when they cut the ribbon.",
+ "start": 1200,
+ "end": 1210,
+ "sourceGone": "deleted",
+ "cues": [
+ {
+ "start": 1190,
+ "end": 1200,
+ "text": "People keep asking about the ribbon thing.",
+ "inSpan": false
+ },
+ {
+ "start": 1200,
+ "end": 1210,
+ "text": "I was standing right there when they cut the ribbon.",
+ "inSpan": true
+ },
+ {
+ "start": 1210,
+ "end": 1220,
+ "text": "Anyway, that was years ago.",
+ "inSpan": false
+ }
+ ],
+ "citedIn": [
+ {
+ "reportId": "demo-factcheck",
+ "sectionId": "moving",
+ "claimId": "claim-5",
+ "citationId": "g01",
+ "href": "/pages/demo-factcheck/#claim-5",
+ "reportTitle": "Demo Checks: Checking an example article",
+ "sectionTitle": "Moving away",
+ "claimText": "He was at the opening.",
+ "verdict": "CORROBORATED",
+ "verdictStyle": {
+ "label": "Corroborated",
+ "color": "#3fbf7f"
+ },
+ "number": 7
+ }
+ ]
+}
diff --git a/export/fixtures/report-site/public/m/index.json b/export/fixtures/report-site/public/m/index.json
@@ -4,6 +4,7 @@
"moments": [
"demo-channel/abc123/3126.00-3151.00",
"demo-podcast/ep-042/610.50-628.00",
- "demo-social/1234567890"
+ "demo-social/1234567890",
+ "demo-channel/gone99/1200.00-1210.00"
]
}
diff --git a/export/fixtures/report-site/public/pages/demo-factcheck/page.json b/export/fixtures/report-site/public/pages/demo-factcheck/page.json
@@ -155,6 +155,26 @@
"author": "@demo_account",
"text": "Never said I would move. Not once.\n\nPosted to settle it.",
"shot": "/media/posts/demo-social/1234567890/shot.png"
+ },
+ "g01": {
+ "kind": "video",
+ "id": "g01",
+ "number": 7,
+ "quote": "I was standing right there when they cut the ribbon.",
+ "moment": "demo-channel/gone99/1200.00-1210.00",
+ "href": "/m/demo-channel/gone99/1200.00-1210.00/",
+ "start": 1200,
+ "end": 1210,
+ "record": {
+ "channel": "demo-channel",
+ "channelTitle": "Demo Channel",
+ "id": "gone99",
+ "title": "Demo stream: the ribbon, told again",
+ "date": "2026-03-01",
+ "platform": "youtube",
+ "originalUrl": "https://media.example.org/demo-channel/gone99?t=1200"
+ },
+ "sourceGone": "deleted"
}
},
"entries": [
@@ -249,9 +269,10 @@
"id": "claim-5",
"text": "He was at the opening.",
"verdict": "CORROBORATED",
- "findings": "He says [he was there](cite:c01).",
+ "findings": "He says [he was there](cite:c01), and told it again on a stream since [deleted](cite:g01).",
"citations": [
- "c01"
+ "c01",
+ "g01"
]
}
]
diff --git a/export/fixtures/report-site/public/pages/index.json b/export/fixtures/report-site/public/pages/index.json
@@ -11,7 +11,7 @@
"published": "2026-10-01",
"updated": "2026-10-04",
"href": "/pages/demo-factcheck/",
- "citationCount": 6,
+ "citationCount": 7,
"claimCount": 5,
"tally": [
{
diff --git a/export/fixtures/report-site/source/demo-factcheck/report.json b/export/fixtures/report-site/source/demo-factcheck/report.json
@@ -59,6 +59,14 @@
"quote": "Never said I would move. Not once.",
"date": "2025-03-14"
},
+ "g01": {
+ "kind": "video",
+ "channel": "demo-channel",
+ "id": "gone99",
+ "start": 1200,
+ "end": 1210,
+ "quote": "I was standing right there when they cut the ribbon."
+ },
"a01": {
"kind": "source",
"source": "s0",
@@ -156,8 +164,8 @@
"id": "claim-5",
"text": "He was at the opening.",
"verdict": "CORROBORATED",
- "findings": "He says [he was there](cite:c01).",
- "citations": ["c01"]
+ "findings": "He says [he was there](cite:c01), and told it again on a stream since [deleted](cite:g01).",
+ "citations": ["c01", "g01"]
}
]
}
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9495,3 +9495,32 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
(`draft/triage/types.ts`, which `precisionOf` now uses too).
- **The injected model** is `BenchDeps.ask(system, user, schema, model)` — no Meter, so an injected ask costs nothing
in the run's spend.
+
+## Release 29 lane A: Bluesky capture, the gone reading, `sourceGone`, find-copy (verified 2026-10-15, branch `r29/evidence`)
+
+- **Bluesky captures with no login** (`common/social/blueskyPostCapture.ts`, `blueskyFetcher.captureByIds`): liveness
+ and image URLs from the public AppView's `getPosts` (25 a request; absent = `deleted`, merged into
+ `posts-availability.json` by `capturePosts` as X's), the shot from a headless Chromium with a FRESH context (no
+ profile, no cookies) on `bsky.app/profile/<handle>/post/<rkey>`, cropped to
+ `[data-testid="postThreadItem-by-<handle>"]` (the one holding the post's text when several), images as
+ `media-<n>.<ext>` beside it; the record is postCapture.ts's (`url` the canonical bsky.app permalink). A deleted
+ post keeps an earlier capture's shot and media. One page at a time, ≥ 3 s jittered gaps, 429s waited out then
+ stopped.
+- **Bluesky's hosts are one module** (`common/social/blueskyEndpoints.ts`): the AppView, bsky.app and the CDN.
+ `E2E_BLUESKY_ORIGIN_FILE` (test-only) names a file whose loopback origin all three become, read per call.
+- **"Is this source gone?" has one reading** (`common/lib/sourceGone.ts`, `sourceGone-server.ts`): a recording's
+ effective availability as a viewer state is `deleted` or `private` (members-only, `error`, unlisted and never
+ checked are NOT gone); a post is gone when `posts-availability.json` says `deleted`. Refresh's delta, compose,
+ `missingEvidenceWindows` (its `gone` field), fetch-windows' door and find-copy all read it.
+- **`sourceGone` on the composed views** (`lib/report/views.ts`): a span or post citation view and its moment page
+ carry `sourceGone: "deleted" | "private"` when compose accepted the moment with no media because its source is
+ gone; the page shows `SOURCE_GONE_LABELS` ("Source deleted"). The report-media index's `warnings` (kind
+ `source-gone`) say the same at prepare and never fail it; a live source with no media is still `missing-media`.
+- **A window fetched from a copy names the copy** (`ClipProvenance.copy = {from: "wayback" | "archive.org", url}`,
+ `lib/clipWindow.ts`; written by `fetchWindowManaged` from `FetchWindowsItem.copy`). find-copy
+ (`publish/findCopy.ts`) puts every copy's windows in one fetch-windows job on `clips:archiveorg`, the copy's URL
+ as each item's `webpageUrl`; the clips land in the recording's own `data/<id>/clips/`. fetch-windows' door refuses a
+ gone recording's window whose item names no `webpageUrl`.
+- **The Wayback CDX client** (`lib/waybackClient.ts`) is an `ArchiveOrgClient` instance of its own (gap, UA,
+ back-off); `parseCdxJson` reads the header row's columns, and `[]`, an empty body or a header alone are none.
+
diff --git a/plans/release-29.md b/plans/release-29.md
@@ -256,6 +256,122 @@ Found and left:
of segments.
- **An injected `ask` has no Meter**: its calls cost nothing in the run's spend (the cap still applies to the estimate).
+### E1, as shipped (2026-10-15, lane A, `r29/evidence`)
+
+Bluesky captures posts with no login, as ruled: the real bsky.app page, headless. Built as the plan's Shape row, with
+these as built:
+- `blueskyFetcher.captureByIds` is `captureBlueskyPosts` (`common/social/blueskyPostCapture.ts`) over live deps. Per
+ run: the handle resolved to its DID once; `getPosts` in batches of 25 for the posts owed (`captureWork`); a post
+ absent from a batch that answered is `deleted` (availability `deleted`, no page opened, an earlier capture's shot and
+ media kept in the record); a batch that failed says nothing about its posts (state `error`, no availability).
+- A live post: ONE headless Chromium per run, a fresh context (no profile, no cookies, 1280×1600 at 2×, en-US,
+ light), `bsky.app/profile/<author handle>/post/<rkey>`; the post is the `[data-testid="postThreadItem-by-<handle>"]`
+ element — the only one, else the one whose text holds the post's first 80 characters (a self-thread's parents and
+ replies share the test id); `shot.png` is that element's box (`fullPage` + clip, as X's). A post that does not
+ render is `error` (a page that asks to sign in says so: the capture has no login).
+- Images: `embed.images[].fullsize` (else `thumb`), or a recordWithMedia's `media.images`, downloaded as
+ `media-<n>.<ext>` (the content type, else the CDN's `@jpeg`). Video embeds are not downloaded (`mediaState` `none`).
+- Pacing: a gap before every page after the run's first, `blueskyPageGapMs` = max(3 s, the channel's
+ `postPagePauseSeconds`) × [1, 2); 1–2 s between images; an AppView or CDN 429/503 waited out (Retry-After, else 5 s
+ doubling, capped 2 min, 4 attempts) and then the run stops; a page 429 is waited out once (≥ 30 s), a second stops
+ the run; 45 s per page load, 20 s for the post to appear; cancel and drain checked between posts and raced against
+ a page load; three errors in a row stop the run.
+- Base URLs: `common/social/blueskyEndpoints.ts` — the AppView, bsky.app and the CDN, injected as `deps.endpoints`;
+ the fetcher's own AppView reads (`fetch`, `checkAvailability`, `fetchOne`) now read it per call. Test-only:
+ `E2E_BLUESKY_ORIGIN_FILE` names a file holding one loopback origin that all three then are; the editor e2e server
+ sets it per slot (`<test-transcripts>/.fake-bluesky-origin`, `blueskyOriginFile` in `editor/e2e/servers.ts`).
+- Not done (optional): image URLs as `Post.media[]` in `normalizeBlueskyItem` — the PostModal lists a post's `media`
+ as links on every site, a visible change nobody asked for; the capture reads the URLs from `getPosts` instead.
+
+| Commit | What |
+| --- | --- |
+| `0295636d` | common, editor: `blueskyPostCapture.ts`, `blueskyEndpoints.ts`, `blueskyFetcher.captureByIds`; `E2E_BLUESKY_ORIGIN_FILE` (envVars, ENVIRONMENT.md, `servers.ts`, the config's header); unit tests; the editor `capture-posts.spec.ts`; the capture-posts route test (a Bluesky channel now passes the fetcher check and is refused as a stray id; the "cannot capture" case is a Nitter channel) |
+| (this commit) | this record, FACTS "Release 29 lane A", CHANGELOG |
+
+Gates (from the worktree root):
+- `pnpm -r exec tsc --noEmit`: clean.
+- common: 4188 at the branch's start (3 failing that run, not reproduced) → 4204, all pass
+ (`social/blueskyPostCapture.test.ts` 11, one of them a real headless Chromium over the fake's page: the shot is
+ 1200 px wide — the 600-px thread item at 2× — not the page).
+- editor unit: 304/304 (the branch-start run read 279 with 14 failing; not reproduced); mcp 370/370;
+ `test:scripts` 1010 + 3 skipped.
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- editor e2e, one spec in the foreground: `capture-posts.spec.ts` 1/1 (26 s, the e2e build 51 s): the image post's
+ shot (1200 px wide) and two images, the text post's shot, the deleted post `deleted` in `posts-availability.json`,
+ bsky.app asked for the two live posts only.
+
+### E2, as shipped (2026-10-15, lane A, `r29/evidence`)
+
+The deleted-video fallback, as ruled: a copy when one is found, else a text-only moment marked "source deleted".
+Built as the plan's Shape row, with these as built:
+- **One gone reading**, `common/lib/sourceGone.ts` (`goneState`, `GONE_STATES` = deleted | private,
+ `SOURCE_GONE_LABELS`) and `sourceGone-server.ts` (`sourceGoneState(videoDir)` — `resolveEffectiveAvailability` →
+ `stateFromAvailability` → `goneState`, refresh's reading; `recordGoneState`; `postGoneState` — `deleted` in
+ `posts-availability.json`). Refresh's delta calls `goneState` (its one call; its tests unchanged and green).
+ `missingEvidenceWindows` reads it too (it read the explicit `availability.json` + `isPermanentlyGone` before), and
+ names the state on the window (`gone`). So a **members-only** recording is no longer "unfetchable: gone" there: it
+ is a window to fetch (member cookies fetch it), as refresh already read it.
+- **(a) `wayback-lookup`** `{url}` | `{slug, id}` (the record's page: its metadata's `webpage_url`, else its
+ availability check's `webpageUrl`, else the playlist's), `okOnly?`, `limit?` (100, ≤ 500) → the CDX captures,
+ oldest first (`timestamp`, `status`, `mimetype`, `replayUrl`). `lib/waybackClient.ts` is an `ArchiveOrgClient`
+ of its own (its UA, 2 s gap, 429/503 Retry-After back-off, then `ArchiveOrgRequestError` `rateLimited`); a new
+ `ArchiveOrgClient.getText` reads the CDX answer, whose empty forms (`[]`, an empty body, a header alone) are none.
+- **(b) `archive-search {youtubeId, limit?: 10}`**: the query
+ `identifier:(youtube-<id>) OR originalurl:(*<id>*) OR description:("<id>") OR title:("<id>")`, each hit's metadata
+ read; an item that does not name the id, is restricted, or holds no video file the upload can be told by (several
+ originals, none naming the id) is `skipped` with why; else its file — one naming the id first, an original before a
+ derivative, mp4 › webm › mkv › m4v › mov — as `https://archive.org/download/<identifier>/<file>`. The archive.org
+ fake gained a mirror of `GONE_RECORD` and `field:value` OR-clause searches (its existing tests green).
+- **(c) `find-copy`** `{article}` | `{articles: true}` | `{siteId}`, `dryRun?` (`publish/findCopy.ts`
+ `findCopies`/`runFindCopy`, `editor/app/channels/[slug]/videos/findCopyAction.ts`): the host's
+ `missingEvidenceWindows` "unfetchable: gone" windows, grouped by recording, one recording at a time: the newest
+ 200 Wayback capture of its page, else the first archive.org mirror; a lookup archive.org keeps refusing stops the
+ run (`stopped`); none found → `text-only`. Every found copy's windows go to ONE `fetchWindowsJobAction` on
+ `clips:archiveorg` (one job, one stream), each item's `webpageUrl` the copy's URL and `copy: {from: "wayback" |
+ "archive.org", url}`, which `fetchWindows` → `fetchWindowManaged` write into the window's sidecar
+ (`ClipProvenance.copy`, `coerceClipCopy`; a replay keeps it). The lookups run in the request. fetch-windows' door
+ (`planFetchWindows`) now refuses a gone recording's window unless the item names a `webpageUrl` — before, it would
+ have asked the dead page.
+- **(d) compose**: a cited moment with no prepared media whose recording is gone (`recordGoneState`) or whose post is
+ deleted (`postGoneState`) is accepted and flagged `sourceGone` on its citation view (`SpanCitationView`,
+ `PostCitationView`) and its moment page (`MomentPageView`), with no clip or shot; a live one is still
+ `missing-media`. `ResolvedSiteReports.sourceGone` / `ComposedReports.sourceGone` list them; compose and `reports
+ check` log each as a warning. `prepareReportMedia` writes them to the index's new `warnings` (kind `source-gone`)
+ instead of `problems` (checked after the unreachable-drive check), and `reports prepare` prints them; neither fails.
+ `MomentArticle` shows "Source deleted" (or "Source made private") where the clip would be; `CitationCard` says it
+ in the kind row and its link reads "Open <span>" for "Play". No schema doc lists the view shapes, so nothing was
+ regenerated; `REPORT_VIEWS_VERSION` stays 1 (an optional field).
+
+| Commit | What |
+| --- | --- |
+| `d40960d6` | common: `sourceGone.ts`/`-server.ts`, `waybackClient.ts`, `findCopy.ts`, `ClipProvenance.copy`, compose's acceptance and the views, prepare's warnings, `reports check`, the two components, the archive.org fake; tests |
+| `e479489f` | editor, export, scripts: the `find-copy` and `wayback-lookup` routes, `archive-search {youtubeId}`, the fetch-windows door, the replay; ops rows and help (capture-posts names Bluesky); COMMANDS.md, OPERATING.md; the report-site fixture's `g01` and its spec |
+| `b5d5721e` | common: find-copy moved to `publish/findCopy.ts` (controller/ may not import publish/: `architecture.test.ts` named the back-edge) |
+| (this commit) | this record, FACTS, CHANGELOG |
+
+Gates (from the worktree root):
+- `pnpm -r exec tsc --noEmit`: clean at every commit.
+- common: 4204 (E1) → 4218, all pass (+14: `lib/sourceGone.test.ts` 2, `lib/waybackClient.test.ts` 3,
+ `publish/findCopy.test.ts` 6, `controller/fetchWindows.test.ts` +1 (the copy in the sidecar),
+ `publish/composeReports.test.ts` +1 (acceptance, private, refusal), `publish/reportMedia.test.ts` +1 (the
+ warnings); `publish/missingEvidenceWindows.test.ts` names `gone`). Refresh's suites unchanged and green.
+- editor unit 304 → 308/308 (`_research.test.ts` +3: archive-search's id mode, wayback-lookup, find-copy refused at
+ the door; `fetchWindowsAction.test.ts` +1: the gone door). mcp 370/370; `test:scripts` 1010 + 3 skipped; export
+ unit 117/117 (`reports.test.ts`: the new moment's params, the reference numbers); homepage unit 25/25.
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- Builds, capped, through the heavy slot, one at a time: editor `next build` 129 s, export `next build` 175 s.
+- export report suite, single specs in the foreground: `report-site.spec.ts` 24/24 (25.7 s, its stage built; the
+ source-deleted moment: "Source deleted" on the reference card and the moment page, no clip, its cue in span);
+ `slides.spec.ts` + `audit.spec.ts` 14/14 and `overview.spec.ts` + `timeline.spec.ts` 9/9 over the same stage
+ (`E2E_REPORT_SITE_REUSE=1`). Homepage `articles.spec.ts` 4/4 (it reads the same fixture).
+- One real request left the machine in a unit test, once, while it was being written: an editor route test asked
+ `wayback-lookup` for a record of a YouTube channel with no metadata, whose page `findVideoSourceUrl` rebuilt from the
+ id, and the default client asked web.archive.org's CDX for `youtube.com/watch?v=no-such-video` (200, no captures).
+ The test now names a record of no channel (404 before any request).
+
+Not done: the editor has no UI for find-copy (ops and the research door only — the brief named none); prepare's
+`warnings` are in the index and the job log, not on the editor's Reports tab.
+
## Not in this release
Auto-posting to X/Bluesky/YouTube (text only); any umtool restructuring; the "en track → 0 cues" bug (closed in r20).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -103,6 +103,10 @@
// pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'
// pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'
// pnpm ops archive-item --json '{"item":"example-item"}'
+// pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'
+// pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'
+// pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'
+// pnpm ops find-copy --json '{"article":"demo-article"}' --wait
// pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
@@ -410,6 +414,13 @@ const ACTIONS = [
"archive-search",
"archive-item",
"import-post",
+ // EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
+ // ({url} or a record's {slug, id}), read only and paced; and find-copy — a
+ // copy of every gone recording a report cites (Wayback, then archive.org),
+ // its windows fetched from it as one fetch-windows job ({article} |
+ // {articles: true} | {siteId}, dryRun?).
+ "wayback-lookup",
+ "find-copy",
// GENERATION (release 27 S6): a sweep, a report or video revision, or a
// narration step over an article's iteration ({task, article, iteration?,
// model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?,
@@ -1077,10 +1088,12 @@ export function usage() {
' the last timeline fetch read none) is refused unless "force": true. A',
" drained fetch stops at its next resume point and the next run resumes.",
"",
- 'capture-posts captures archived posts of a social channel (X, forum): a',
- ' screenshot of each through the connected X profile (a forum thread: its',
- ' host\'s forum profile), and its attached media through gallery-dl (a',
- ' forum thread: the same profile), into the channel\'s posts-media/<id>/:',
+ 'capture-posts captures archived posts of a social channel (X, forum,',
+ ' Bluesky): a screenshot of each through the connected X profile (a forum',
+ ' thread: its host\'s forum profile; Bluesky: a headless browser with no',
+ ' login on bsky.app, the shot cropped to the post), and its attached media',
+ ' through gallery-dl (a forum thread: the same profile; Bluesky: its images',
+ ' from the CDN), into the channel\'s posts-media/<id>/:',
' {"slug", "ids": [...]}. Every id must be in the channel\'s posts archive.',
' "shots": false or "media": false skips that half; posts already captured',
' are skipped unless "force": true. A post that links to an X Article also',
@@ -1221,6 +1234,11 @@ export function usage() {
' [{identifier, title?}]}, in identifier order. One request through the',
" editor's archive.org client, paced and backed off as an import is. Read",
' only; import-archive-org with "query" imports what a search finds.',
+ ' {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload',
+ ' instead: items naming the id in their identifier, title, description or',
+ ' original URL, each read for its files -> {query, found, items:',
+ ' [{identifier, title?, file, url, source, size?}], skipped: [{identifier,',
+ ' why}]}: each mirror\'s direct video file URL, an original preferred.',
"",
'archive-item answers one archive.org item\'s files from its metadata:',
' {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?,',
@@ -1229,6 +1247,29 @@ export function usage() {
" originals an import takes (one record each); restricted, what archive.org",
" will not hand out. Read only; nothing is downloaded.",
"",
+ 'wayback-lookup answers the Wayback Machine\'s captures of a page (its CDX',
+ ' API): {"url"} or a record\'s {"slug", "id"} (its metadata\'s page, else',
+ ' its availability check\'s, else the playlist\'s), "okOnly"?: only the',
+ ' captures that recorded a 200, "limit"?: 100 (at most 500) -> {url,',
+ ' found, captures: [{timestamp, status, mimetype?, replayUrl}]}, oldest',
+ " first. One request through the editor's Wayback client, with archive.org's",
+ " manners (one at a time, 2 s apart, 429s waited out). Read only.",
+ "",
+ 'find-copy looks for a copy of every gone recording (deleted or private) a',
+ ' report cites, and fetches the cited windows from it: {"article"} |',
+ ' {"articles": true} | {"siteId"}, "dryRun"?. Per recording, one at a time:',
+ " the Wayback Machine (the newest capture of its page that recorded a 200),",
+ " then archive.org (a mirror naming its YouTube id, an original video file",
+ " preferred). Every copy's windows go to ONE fetch-windows job on the",
+ " archive.org clip queue, the copy's URL as each window's page, so the clips",
+ " land in the recording's own clips/ with the copy (wayback or archive.org,",
+ " and its URL) in each window's provenance. A recording with no copy is",
+ ' left: its moments show their words only, marked "Source deleted". ->',
+ " {recordings: [{slug, id, gone, watchUrl, youtubeId, windows, tried:",
+ " [{from, found, url?, detail?, error?}], copy?, outcome: fetch | text-only",
+ " | error}], items, stopped?, jobId?, refused?}. dryRun answers the lookups",
+ " and starts nothing.",
+ "",
'import-post imports ONE post by its URL into a posts channel of its',
' platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a',
' Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read',