commit c132af2efd359cd0fa568c943387f877cb357f2d
parent bbe4aa30be3520b652e42492882b549720a97c2a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 15:37:56 -0400
Merge main (lane E: liveness, Save Page Now, find-copy for pages) into r37/archive-sources
Conflicts kept both sides (ops actions and their tests, the fake Wayback, envVars,
CHANGELOG, FACTS); COMMANDS/ENVIRONMENT regenerated by the gate. find-copy's page mode
finds its capture through nearestAcrossSources (Wayback, then archive.today; an exclusion
passes on) and imports the row's own copy URL.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
45 files changed, 3291 insertions(+), 19 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -68,7 +68,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer duplicates` | `[--threshold N] [--all-durations] [--blocking title\|duration\|both] [--near F] [--tolerance N] …` | on-demand duplicate detection (after index + stats) *(passthrough)* |
| `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages) *(passthrough)* |
| `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched |
-| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source *(passthrough)* |
+| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* |
| `archilyzer diarize backfill` | `[--dry-run] [--scope transcribed\|channel:<slug>\|video:<slug>/<id>] [--limit N] [--force] …` | diarize videos whose audio is still on disk *(passthrough)* |
| `archilyzer digest plan` | `[--lane local\|remote] [--channels a,b] [--top N] [--json] [--census] …` | price the digest backfill; writes nothing *(passthrough)* |
| `archilyzer digest validate` | `<channel> [<channel> …]` | score digests already on disk *(passthrough)* |
@@ -161,9 +161,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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` |
| `import-page` | import-page imports ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel (platform "webpage"): {"slug", "url"} — a capture's replay URL (web.archive.org/web/<timestamp>/<page>) — or {"slug", "url": <the page>, "at": "YYYYMMDD\[hhmmss\]"} for the capture nearest that date (one CDX lookup). An import-page job on the archive.org queue, at archive.org's pace: the raw (id\_) body, at most 2 MB, html, plain text or JSON only, redirects followed inside the archive only and the FINAL capture recorded; stored under the channel's pages/, read by the first site extractor that claims it (else the generic one), its page records written to the channel's posts. Refused, before any job: no such channel, not a Wayback pages channel, a URL that names no capture, a video (use import-video), an X capture outside an X channel while social.x.visibility is "private". A capture already stored is not fetched again. "dryRun" answers what it would fetch and starts nothing. The log ends with @@import-page {ok, slug, url, captureTs, originalUrl, records, written, updated, unchanged, extractor, already?, error?}. archive.today (release 37 lane F): "url" may be an archive.today copy (archive.ph/<id>, /<timestamp>/<page>, /newest/<page>), or the page's own URL with "at" and "source": "archive.today" for its copy nearest that date (one timemap request); the job runs on the platform:archive.today queue at archive.today's pace (one request at a time, 8 s apart; a 429 stops it and rests the client). The copy is stored as served with its source and URL. A check page (a CAPTCHA) is refused, never solved: Connect archive session on the channel page or Settings, then again. The result carries "source", "mementoUrl" and, for a refusal, "refusal": "excluded" (the Wayback Machine answered 403 for the page), "challenge", "rate-limited", …. | `pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait` |
| `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` |
-| `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -> {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` |
-| `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. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
-| `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait` |
+| `check-post-availability` | check-post-availability checks which of a posts channel's archived posts are gone at their source: {"slug", "mode"?: "stale" (default) \| "unchecked" \| "all", "limit"?: 200}, as a check-post-availability job. A Wayback pages channel's records are checked by their ORIGINAL URL at its own site (never the Wayback Machine), one request per distinct URL through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD is refused or the platform has a "gone" page; available (2xx on the same site), deleted (404/410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page), account\_unavailable (suspended, not shared), error otherwise — with the status. A deleted original means the Wayback copy is the only copy. Verdicts go to posts-availability.json. | `pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait` |
+| `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now, with archive.org's S3 keys): {"url", "slug"?, "dryRun"?}. A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. Refused, before any job: no keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --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, as a find-copy job: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?, "retryFailed"? -> {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -> {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.<fmt>; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. The page mode (release 37): {"article"} \| {"articles": true} \| {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100), "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose original is gone at its own site gets the Wayback capture nearest the citation's date (one CDX lookup) imported into the Wayback pages channel named, else the one whose targets cover the page; a cited page record whose original is gone has its capture imported again when it is not stored. A live page is left (save-page-now it). The answer names the record each citation should cite (pointTo) and the citation as a post citation of it (as); the report is not rewritten. A find-copy job on the archive.org queue; dryRun asks the same paced questions and imports nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts, items: \[{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?, as?, records?}\], left, stopped?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait` |
| `wayback-scan` | wayback-scan lists the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json, as a wayback-scan job on archive.org's queue: {"slug", "dryRun"?, "maxRows"? (50000, at most 200000), "full"?} -> {jobId}. The CDX API per target (its matchType exact \| prefix \| host \| domain, status 200, its mimes — text/html unless it names text/plain or application/json — collapse=digest, its from/to), in pages of 5,000 with a resume key; obvious assets (css, js, images, fonts) dropped unless the target's include names them. One row per distinct (URL, digest) with first/last seen. No bodies: import-page fetches a capture. A run cut short (the row cap, a refusal, a drain) keeps each target's resume key and the next continues; once every target is complete the next run is a new pass, from 30 days before the last began, and what it adds is marked new; "full" starts a new pass from each target's start. Paced as archive.org asks (one at a time, 2 s apart, 429/503 waited out; a refusal stops the job). dryRun asks nothing and writes nothing: it logs the next request per target. The log ends with @@wayback-scan {slug, dryRun, pass, newPass, targets: \[{url, match, requests, rows, added, complete, resumeKey?, next?}\], requests, rowsRead, added, totalRows, complete, stopped?, error?}. | `pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait`<br>`pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait` |
| `wayback-import` | wayback-import imports chosen rows of a Wayback pages channel's scan, one import-page job per row (the capture the content was first listed at), queued on archive.org's queue: {"slug", "keys"?: \["<digest> <url>", ...\]} or a range — "year"? (first seen), "prefix"? ("host/path/"), "q"? (text in the URL), "show"? (all \| new \| not-imported \| imported) — and "dryRun"? -> {ok, slug, dryRun, chosen, queued: \[{key, url, jobId?}\], skipped: \[{key, why}\], left}. Rows already imported are skipped; at most 500 are queued a call (left: how many remain). The Captures tab's Import selected and Import all in range. | `pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}'` |
| `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}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -59,6 +59,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
|---|---|---|---|
| `WORKER_TOKEN` | unset (both surfaces off) | Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped "agent"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end. | common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs |
| `ANTHROPIC_API_KEY` | unset (the API key file is read instead) | The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript. | common/lib/llm/anthropic.ts |
+| `ARCHIVE_ORG_S3_ACCESS` | unset (the S3 key file is read instead) | archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why. | common/lib/waybackPages/savePageNow-server.ts |
+| `ARCHIVE_ORG_S3_SECRET` | unset (the S3 key file is read instead) | archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above). | common/lib/waybackPages/savePageNow-server.ts |
| `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts |
| `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts |
| `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts |
@@ -234,8 +236,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts |
| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts |
| `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts |
-| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts |
-| `E2E_ARCHIVE_TODAY_ORIGIN_FILE` | unset (the real archive.today) | A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts |
+| `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.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 |
diff --git a/OPERATING.md b/OPERATING.md
@@ -168,6 +168,36 @@ pnpm ops wayback-import --json '{"slug":"example-pages","year":"2014","show":"no
same pace. Off by default: nothing crawls a host unless its channel opts in.
- Offline, without the editor: `pnpm archilyzer wayback scan <slug> --dry-run`.
+### Is the original still up? Save it now; find a gone page's copy
+
+```sh
+pnpm ops check-post-availability --json '{"slug":"old-blog"}' --wait
+pnpm ops save-page-now --json '{"url":"https://blog.example/still-up.html","slug":"old-blog","dryRun":true}'
+pnpm ops save-page-now --json '{"url":"https://blog.example/still-up.html","slug":"old-blog"}' --wait
+pnpm ops find-copy --json '{"article":"<article>","pages":true,"dryRun":true}' --wait
+pnpm ops find-copy --json '{"siteId":"<site>","pages":true,"channel":"old-blog"}' --wait
+```
+
+- **Originals** (the channel page's **Check originals**, `check-post-availability`): each page record's ORIGINAL
+ URL asked at its own site — never the Wayback Machine — one request per distinct URL, through the editor's web
+ pacer (3 s apart). `available` (a 2xx on the same site), `deleted` (404/410, or X's, Tumblr's, Google Docs' or
+ YouTube's "does not exist" page), `account_unavailable` (suspended, not shared), `error` otherwise, with the
+ status. A deleted original means the Wayback copy is the only copy; the record reads as deleted everywhere a
+ deleted post does (`posts-availability.json`, merged by the index).
+- **Save Page Now** ("Ask the Wayback Machine to capture this now", on the channel page: any URL, or a record whose
+ original is still up): archive.org captures the page alone, the job waits for it, then imports the capture
+ into the channel. It needs archive.org's S3 keys (archive.org/account/s3.php): `ARCHIVE_ORG_S3_ACCESS` and
+ `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or two such lines in the mode-600 file
+ `settings.archiveOrg.s3KeyFile` names (default `~/.config/archilyzer/archive-org.env`). Without them the button is
+ off and says why. One capture at a time, on archive.org's queue. Other code starts one with
+ `startSavePageNowJob({url, slug})` (`common/controller/savePageNow.ts`).
+- **find-copy, page mode** (`"pages": true`): every `page` citation of a report whose original is gone gets the
+ Wayback capture nearest the citation's date imported into the Wayback pages channel named (`"channel"`), else
+ the one whose targets cover the page; a cited page record whose original is gone has its capture imported again
+ only when its body is not stored. A live page is left (save it now instead). The log's `@@find-copy` names, per
+ citation, the record to cite (`pointTo`) and the citation as a `post` citation of it (`as`); the report itself
+ is not rewritten. Dry run first: it asks the same paced questions and imports nothing.
+
## Fetch and capture posts
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -813,6 +813,7 @@ How archive.org files are fetched (controller/archiveOrgDownload.ts). Over BitTo
| `maxPeers` | `30` | Most peers per torrent (aria2c --bt-max-peers). Clamped to [1, 500]; default 30. |
| `maxDownloadKiBps` | `0` | Download rate cap for a torrent fetch, KiB/s (aria2c --max-overall-download-limit). 0 = unlimited. |
| `maxUploadKiBps` | `0` | Upload rate cap while downloading and seeding, KiB/s (aria2c --max-overall-upload-limit). 0 = unlimited. |
+| `s3KeyFile` | `"~/.config/archilyzer/archive-org.env"` | Release 37: the file holding archive.org's S3 keys for Save Page Now ("Ask the Wayback Machine to capture this now"): two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the editor's environment win over the file. No keys: Save Page Now is off, and says why. |
Default:
@@ -824,7 +825,8 @@ Default:
"stallMinutes": 5,
"maxPeers": 30,
"maxDownloadKiBps": 0,
- "maxUploadKiBps": 0
+ "maxUploadKiBps": 0,
+ "s3KeyFile": "~/.config/archilyzer/archive-org.env"
}
```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -875,7 +875,7 @@ export const COMMANDS: Command[] = [
},
},
script(["posts", "check"], "check-post-availability.ts",
- "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source"),
+ "--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site)"),
script(["diarize", "backfill"], "diarize-backfill.ts",
"[--dry-run] [--scope transcribed|channel:<slug>|video:<slug>/<id>] [--limit N] [--force] … diarize videos whose audio is still on disk"),
script(["digest", "plan"], "digest-plan.ts",
diff --git a/common/controller/checkPageAvailability.test.ts b/common/controller/checkPageAvailability.test.ts
@@ -0,0 +1,152 @@
+// Release 37 S5: check-post-availability on a Wayback pages channel — each
+// record's ORIGINAL URL asked at its own site (a stub fetch behind a web
+// pacer), ONE request per distinct URL however many records share it, the
+// verdicts and their status/reason in posts-availability.json, history only
+// on a change, modes and limits counted in URLs. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/checkPageAvailability.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Post } from "../lib/posts";
+import { readPostAvailability, upsertPosts } from "../lib/posts-server";
+import { WebPacer } from "../lib/web/pacer";
+import { checkPostAvailability } from "./checkPostAvailability";
+import { selectUrlsToCheck } from "./checkPageAvailability";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "check-pages-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT } as unknown as Paths;
+
+function record(slug: string, id: string, originalUrl: string, captureTs: string): Post {
+ return {
+ id,
+ slug: `${slug}/${id}`,
+ channelSlug: slug,
+ author: "blog.example",
+ createdAt: "2014-03-05T12:00:00.000Z",
+ uploadDate: "20140305",
+ text: `the words of ${id}`,
+ url: originalUrl,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page: {
+ originalUrl,
+ captureTs,
+ waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`,
+ rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`,
+ kind: "generic",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+ };
+}
+
+async function pagesChannel(slug: string, posts: Post[]) {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ name: slug,
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ }),
+ );
+ await upsertPosts(dir, posts);
+ return dir;
+}
+
+function stub(statusOf: (url: string) => number) {
+ const sent: string[] = [];
+ const pacer = new WebPacer(
+ {
+ fetch: async (url, init) => {
+ sent.push(`${init.method} ${url}`);
+ return new Response(null, { status: statusOf(url) });
+ },
+ sleep: async () => {},
+ },
+ { minGapMs: 0, maxAttempts: 1 },
+ );
+ return { sent, pageCheck: { pacer, resolve: async () => ["93.184.216.34"] } };
+}
+
+const GONE = "https://blog.example/2014/gone.html";
+const LIVE = "https://blog.example/2014/live.html";
+const DOWN = "https://blog.example/2014/down.html";
+
+test("one request per original URL; every record of it gets the verdict, with its status and reason", async () => {
+ const dir = await pagesChannel("old-blog", [
+ record("old-blog", "20140305120000-aaaa", GONE, "20140305120000"),
+ record("old-blog", "20150611090000-aaaa", GONE, "20150611090000"),
+ record("old-blog", "20140101000000-bbbb", LIVE, "20140101000000"),
+ record("old-blog", "20140202000000-cccc", DOWN, "20140202000000"),
+ ]);
+ const s = stub((url) => (url === GONE ? 404 : url === DOWN ? 500 : 200));
+ const lines: string[] = [];
+ const r = await checkPostAvailability({ paths, slug: "old-blog", pageCheck: s.pageCheck, onLog: (l) => lines.push(l) });
+ assert.equal(r.ok, true);
+ assert.deepEqual(s.sent.sort(), [`HEAD ${DOWN}`, `HEAD ${GONE}`, `HEAD ${LIVE}`]);
+ assert.equal(r.checked, 4);
+ assert.deepEqual(r.newlyDeleted.sort(), ["20140305120000-aaaa", "20150611090000-aaaa"]);
+ const av = await readPostAvailability(dir);
+ assert.deepEqual(
+ [av["20140305120000-aaaa"]!.availability, av["20140305120000-aaaa"]!.status, av["20140305120000-aaaa"]!.reason],
+ ["deleted", 404, "HTTP 404"],
+ );
+ assert.equal(av["20150611090000-aaaa"]!.availability, "deleted");
+ assert.equal(av["20140101000000-bbbb"]!.availability, "available");
+ // An error is an error, never a deletion.
+ assert.deepEqual([av["20140202000000-cccc"]!.availability, av["20140202000000-cccc"]!.status], ["error", 500]);
+ assert.ok(lines.some((l) => /3 of 3 original URL\(s\) \(4 page record\(s\)\)/.test(l)));
+ assert.ok(lines.some((l) => /newly GONE/.test(l)));
+
+ // Again, the down page back up: history appended for the change only.
+ const s2 = stub((url) => (url === GONE ? 404 : 200));
+ await checkPostAvailability({ paths, slug: "old-blog", mode: "all", pageCheck: s2.pageCheck });
+ const av2 = await readPostAvailability(dir);
+ assert.equal(av2["20140202000000-cccc"]!.availability, "available");
+ assert.deepEqual(av2["20140202000000-cccc"]!.history?.map((h) => h.availability), ["error"]);
+ assert.deepEqual(av2["20140305120000-aaaa"]!.history ?? [], []);
+
+ // `unchecked`: nothing left to ask.
+ const s3 = stub(() => 200);
+ const r3 = await checkPostAvailability({ paths, slug: "old-blog", mode: "unchecked", pageCheck: s3.pageCheck });
+ assert.equal(r3.checked, 0);
+ assert.equal(s3.sent.length, 0);
+});
+
+test("the limit counts URLs, least recently checked first", () => {
+ const groups = new Map([
+ ["https://a.example/", ["a1", "a2"]],
+ ["https://b.example/", ["b1"]],
+ ["https://c.example/", ["c1"]],
+ ]);
+ const av = {
+ a1: { availability: "available" as const, checkedAt: "2026-10-01T00:00:00Z" },
+ a2: { availability: "available" as const, checkedAt: "2026-10-02T00:00:00Z" },
+ b1: { availability: "available" as const, checkedAt: "2026-09-01T00:00:00Z" },
+ };
+ assert.deepEqual(selectUrlsToCheck(groups, av, "stale", 2), ["https://c.example/", "https://b.example/"]);
+ assert.deepEqual(selectUrlsToCheck(groups, av, "unchecked", 5), ["https://c.example/"]);
+ assert.deepEqual(selectUrlsToCheck(groups, av, "all", 5).length, 3);
+});
+
+test("a channel with no page records checks nothing", async () => {
+ await pagesChannel("empty-pages", []);
+ const s = stub(() => 200);
+ const r = await checkPostAvailability({ paths, slug: "empty-pages", pageCheck: s.pageCheck });
+ assert.deepEqual([r.ok, r.checked, s.sent.length], [true, 0, 0]);
+});
diff --git a/common/controller/checkPageAvailability.ts b/common/controller/checkPageAvailability.ts
@@ -0,0 +1,101 @@
+// IS EACH PAGE RECORD'S ORIGINAL STILL UP? (release 37 S5) — the Wayback
+// pages channel's branch of check-post-availability
+// (./checkPostAvailability.ts). A page record's availability is the state of
+// the ORIGINAL URL it was captured from, never the Wayback Machine's:
+// lib/waybackPages/liveness-server.ts checkOriginalUrl, through the process's
+// web pacer (one request at a time, 3 s apart, 429/503 backed off).
+//
+// ONE REQUEST PER DISTINCT URL: a capture split into many records (an X
+// profile's tweets, a Tumblr index's posts) and the versions of one page share
+// an original URL, and each of them gets the URL's verdict. `limit` counts
+// URLs. The verdicts land in the same sidecar every post channel uses
+// (posts-availability.json, mergePostAvailability: history appended only when
+// a verdict changes), with the answer's status and reason; the index merges
+// them in, so a record whose original is gone is `isDeleted` — the Wayback
+// copy is then the only copy.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { mergePostAvailability, readAllPosts, readPostAvailability, writePostAvailability } from "../lib/posts-server";
+import type { PostAvailability, PostAvailabilityMap } from "../lib/posts";
+import { groupByOriginalUrl, type OriginalCheck } from "../lib/waybackPages/liveness";
+import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import type { CheckPostAvailabilityMode, CheckPostAvailabilityResult } from "./checkPostAvailability";
+
+// Which original URLs to ask this run: `stale` (the default) the
+// never-checked first, then the least recently checked (by the oldest check
+// among the URL's records); `unchecked` only URLs with a record never
+// checked; `all` every URL. At most `limit`.
+export function selectUrlsToCheck(
+ groups: ReadonlyMap<string, readonly string[]>,
+ availability: PostAvailabilityMap,
+ mode: CheckPostAvailabilityMode,
+ limit: number,
+): string[] {
+ const oldest = (ids: readonly string[]) =>
+ ids.reduce((min, id) => {
+ const at = availability[id]?.checkedAt ?? "";
+ return at < min ? at : min;
+ }, "");
+ let urls = [...groups.keys()];
+ if (mode === "unchecked") urls = urls.filter((u) => groups.get(u)!.some((id) => !availability[id]));
+ if (mode === "stale") {
+ const at = new Map(urls.map((u) => [u, oldest(groups.get(u)!)]));
+ urls.sort((a, b) => at.get(a)!.localeCompare(at.get(b)!));
+ }
+ return urls.slice(0, Math.max(0, limit));
+}
+
+export async function checkPageAvailability(opts: {
+ paths: Paths;
+ slug: string;
+ mode: CheckPostAvailabilityMode;
+ limit: number;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ // Tests: the pacer, the fence's resolver, loopback allowed.
+ check?: CheckOriginalOptions;
+ now?: () => Date;
+}): Promise<CheckPostAvailabilityResult & { urls?: OriginalCheck[] }> {
+ const log = (line: string) => opts.onLog?.(line);
+ const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
+ const empty = { checked: 0, deleted: 0, newlyDeleted: [] as string[], changed: 0, remaining: 0 };
+ const records = (await readAllPosts(channelRoot)).filter((p) => p.page);
+ if (records.length === 0) return { ok: true, ...empty };
+ const availability = await readPostAvailability(channelRoot);
+ const groups = groupByOriginalUrl(records);
+ const batch = selectUrlsToCheck(groups, availability, opts.mode, opts.limit);
+ if (batch.length === 0) {
+ log(`Nothing to check for ${opts.slug} (mode: ${opts.mode}).`);
+ return { ok: true, ...empty };
+ }
+ log(
+ `Checking ${batch.length} of ${groups.size} original URL(s) (${records.length} page record(s)) of ${opts.slug} ` +
+ `at their own sites, not the Wayback Machine (mode: ${opts.mode}).`,
+ );
+ const observations = new Map<string, PostAvailability>();
+ const details = new Map<string, { status: number | null; reason: string }>();
+ const urls: OriginalCheck[] = [];
+ for (const url of batch) {
+ if (opts.signal?.aborted) break;
+ const verdict = await checkOriginalUrl(url, { ...opts.check, ...(opts.signal ? { signal: opts.signal } : {}) });
+ urls.push(verdict);
+ const ids = groups.get(url)!;
+ for (const id of ids) {
+ observations.set(id, verdict.availability);
+ details.set(id, { status: verdict.status, reason: verdict.reason });
+ }
+ log(` ${url}: ${verdict.availability} — ${verdict.reason}${ids.length > 1 ? ` (${ids.length} records)` : ""}`);
+ }
+ const checkedAt = (opts.now?.() ?? new Date()).toISOString();
+ const { map, newlyDeleted, changed } = mergePostAvailability(availability, observations, checkedAt, details);
+ await writePostAvailability(channelRoot, map);
+ const deleted = Object.values(map).filter((r) => r.availability === "deleted").length;
+ const remaining = records.filter((r) => !map[r.id]).length;
+ if (newlyDeleted.length > 0) {
+ log(`${newlyDeleted.length} page record(s) whose original is newly GONE (the Wayback copy is the only copy): ${newlyDeleted.slice(0, 10).join(", ")}${newlyDeleted.length > 10 ? ` (+${newlyDeleted.length - 10} more)` : ""}`);
+ }
+ log(`Done: ${urls.length} URL(s) checked (${observations.size} record(s)), ${changed} changed, ${deleted} gone overall, ${remaining} never checked.`);
+ if (opts.signal?.aborted) log("Cancelled; the rest are left for a later run.");
+ return { ok: true, checked: observations.size, deleted, newlyDeleted, changed, remaining, urls };
+}
diff --git a/common/controller/checkPostAvailability.ts b/common/controller/checkPostAvailability.ts
@@ -37,6 +37,9 @@ import "../social/xenforoFetcher";
import "../social/xGalleryDlFetcher";
import "../social/xPlaywrightFetcher";
import "../social/xNitterFetcher";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import type { CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import { checkPageAvailability } from "./checkPageAvailability";
export type CheckPostAvailabilityMode = "stale" | "unchecked" | "all";
@@ -58,6 +61,9 @@ export type CheckPostAvailabilityOptions = {
limit?: number;
onLog?: (line: string) => void;
signal?: AbortSignal;
+ // A Wayback pages channel's check (release 37 S5): tests pass the pacer,
+ // the fence's resolver and loopback.
+ pageCheck?: CheckOriginalOptions;
};
export type CheckPostAvailabilityResult = {
@@ -119,6 +125,19 @@ export async function checkPostAvailability(
if (!isSocialChannel(config)) {
return { ok: false, ...empty, error: `${slug} is not a social channel.` };
}
+ // A Wayback pages channel (release 37 S5): each record's ORIGINAL URL,
+ // asked at its own site — no fetcher, never the Wayback Machine.
+ if (isWaybackPagesChannel(config)) {
+ return checkPageAvailability({
+ paths,
+ slug,
+ mode,
+ limit,
+ ...(onLog ? { onLog } : {}),
+ ...(signal ? { signal } : {}),
+ ...(opts.pageCheck ? { check: opts.pageCheck } : {}),
+ });
+ }
const fetcher = resolveSocialFetcher(config.postFetcher, config.url);
if (!fetcher) {
diff --git a/common/controller/savePageNow.test.ts b/common/controller/savePageNow.test.ts
@@ -0,0 +1,197 @@
+// Release 37 S5: Save Page Now on the fake Wayback — the keys read (env, a
+// mode-600 file, refused when others can read it, never a setting), the
+// refusals before any request, the capture asked → pending → success → the
+// capture imported into the channel, and the error paths: no keys, wrong keys,
+// a 429 that does not clear, a refused URL, a failed capture, a capture still
+// pending. The keys never appear in a log line or a result. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/savePageNow.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { FAKE_SPN_ACCESS, FAKE_SPN_SECRET, SPN_CAPTURE_TS, startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import type { Paths } from "../lib/paths";
+import { WaybackClient } from "../lib/waybackClient";
+import { readAllPosts } from "../lib/posts-server";
+import { pageRecordId } from "../lib/waybackPages/types";
+import { parseSpnStatus, parseSpnSubmit, spnSaveBody } from "../lib/waybackPages/savePageNow";
+import { readSpnKeys } from "../lib/waybackPages/savePageNow-server";
+import { looksLikeS3Key } from "../lib/archiveOrgTorrent";
+import { sanitizeArchiveOrg } from "../lib/settingsSchema";
+import { importPage } from "./importPage";
+import { planSavePageNow, queueSavePageNow, savePageNow, savePageNowAvailability } from "./savePageNow";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "save-page-now-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths;
+const ENV = { ARCHIVE_ORG_S3_ACCESS: FAKE_SPN_ACCESS, ARCHIVE_ORG_S3_SECRET: FAKE_SPN_SECRET };
+const NO_KEYS = path.join(ROOT, "no-such-keys.env");
+const SETTINGS = { archiveOrg: { s3KeyFile: NO_KEYS }, social: { x: { visibility: "private" } } };
+const LIVE = "https://live.example/notes/today.html";
+
+async function channel(slug: string, config: Record<string, unknown>) {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config }));
+ return dir;
+}
+const pagesChannel = (slug: string, target: string) =>
+ channel(slug, {
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "live.example",
+ url: `https://web.archive.org/web/*/${target}*`,
+ wayback: { targets: [{ url: target, match: "prefix" }] },
+ });
+
+const noSleep = async () => {};
+
+test("the keys: the environment first, else a mode-600 file; a file others can read is refused; never a setting", () => {
+ assert.deepEqual(readSpnKeys({ keyFile: NO_KEYS, env: ENV }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "env" });
+ const none = readSpnKeys({ keyFile: NO_KEYS, env: {} });
+ assert.equal(none.ok, false);
+ assert.match(none.ok ? "" : none.reason, /Save Page Now needs archive\.org S3 keys/);
+ const file = path.join(ROOT, "keys.env");
+ writeFileSync(file, `# archive.org\nARCHIVE_ORG_S3_ACCESS="${FAKE_SPN_ACCESS}"\nexport ARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`);
+ chmodSync(file, 0o644);
+ const open = readSpnKeys({ keyFile: file, env: {} });
+ assert.match(open.ok ? "" : open.reason, /readable by others — chmod 600/);
+ chmodSync(file, 0o600);
+ assert.deepEqual(readSpnKeys({ keyFile: file, env: {} }), { ok: true, keys: { access: FAKE_SPN_ACCESS, secret: FAKE_SPN_SECRET }, from: "file" });
+ const half = path.join(ROOT, "half.env");
+ writeFileSync(half, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\n`, { mode: 0o600 });
+ assert.match((r => (r.ok ? "" : r.reason))(readSpnKeys({ keyFile: half, env: {} })), /no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines/);
+ // The setting is a path; a key pasted there is refused, never stored.
+ assert.equal(looksLikeS3Key(FAKE_SPN_ACCESS), true);
+ assert.equal(looksLikeS3Key("~/.config/archilyzer/archive-org.env"), false);
+ assert.equal(sanitizeArchiveOrg({ s3KeyFile: FAKE_SPN_SECRET }).s3KeyFile, "~/.config/archilyzer/archive-org.env");
+ assert.equal(sanitizeArchiveOrg({ s3KeyFile: "/etc/keys/ia.env" }).s3KeyFile, "/etc/keys/ia.env");
+ assert.equal(sanitizeArchiveOrg({}).s3KeyFile, "~/.config/archilyzer/archive-org.env");
+ // The button: off, with the sentence; on with keys.
+ assert.deepEqual(savePageNowAvailability({ settings: SETTINGS, env: ENV }), { on: true });
+ const off = savePageNowAvailability({ settings: SETTINGS, env: {} });
+ assert.equal(off.on, false);
+});
+
+test("SPN's answers read: a job id, a refusal by status_ext, the keys refused; pending, success, a failed capture", () => {
+ assert.deepEqual(parseSpnSubmit(200, JSON.stringify({ url: LIVE, job_id: "spn2-1" })), { ok: true, jobId: "spn2-1" });
+ const blocked = parseSpnSubmit(200, JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "blocked" }));
+ assert.deepEqual([blocked.ok, blocked.ok ? "" : blocked.code], [false, "error:blocked-url"]);
+ assert.equal((parseSpnSubmit(401, "{}") as { code?: string }).code, "auth");
+ assert.deepEqual(parseSpnStatus(200, '{"status":"pending"}'), { state: "pending" });
+ assert.deepEqual(parseSpnStatus(200, JSON.stringify({ status: "success", timestamp: SPN_CAPTURE_TS, original_url: LIVE })), {
+ state: "success",
+ timestamp: SPN_CAPTURE_TS,
+ originalUrl: LIVE,
+ });
+ assert.equal(parseSpnStatus(200, '{"status":"success"}').state, "error");
+ assert.match((parseSpnStatus(200, '{"status":"error","status_ext":"error:not-found","message":"404"}') as { error: string }).error, /error:not-found/);
+ assert.equal(spnSaveBody(LIVE), `url=${encodeURIComponent(LIVE)}&capture_outlinks=0`);
+});
+
+test("refused before any request: no keys, not http(s), a Wayback URL, not a pages channel, a video, X while private", async () => {
+ await pagesChannel("live-notes", "live.example/");
+ await channel("a-video-channel", { url: "https://www.youtube.com/@x/videos" });
+ const ask = async (url: string, slug?: string, env: Record<string, string> = ENV) => {
+ const r = await planSavePageNow(paths, { url, ...(slug ? { slug } : {}), settings: SETTINGS, env });
+ return r.ok ? "" : r.error;
+ };
+ assert.match(await ask(LIVE, "live-notes", {}), /Save Page Now needs archive\.org S3 keys/);
+ assert.match(await ask("ftp://live.example/x"), /only http and https/);
+ assert.match(await ask(`https://web.archive.org/web/2014/${LIVE}`), /on the Wayback Machine already/);
+ assert.match(await ask(LIVE, "a-video-channel"), /not a Wayback pages channel/);
+ assert.match(await ask(LIVE, "nope"), /No such channel: nope/);
+ assert.match(await ask("https://www.youtube.com/watch?v=abcdefghijk", "live-notes"), /is a video/);
+ assert.match(await ask("https://x.com/someone", "live-notes"), /on X, whose posts are private here/);
+ assert.equal(await ask(LIVE, "live-notes"), "");
+ assert.equal(await ask(LIVE), "", "no channel: the capture alone");
+ // The job door refuses the same way and starts nothing.
+ const q = await queueSavePageNow({ paths, url: LIVE, slug: "live-notes", settings: SETTINGS });
+ assert.equal(q.ok, false);
+});
+
+test("asked → pending → success → the capture imported into the channel; the keys in no log line or result", async () => {
+ const wb = await startFakeWayback({ spn: { pendingPolls: 2 } });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0 });
+ const dir = await pagesChannel("live-notes-2", "live.example/");
+ const lines: string[] = [];
+ const dry = await savePageNow({ paths, url: LIVE, slug: "live-notes-2", dryRun: true, settings: SETTINGS, env: ENV, deps: { client, sleep: noSleep } });
+ assert.equal(dry.ok, true);
+ assert.match(dry.wouldAsk ?? "", /POST https:\/\/web\.archive\.org\/save .*then import the capture into live-notes-2/);
+ assert.equal(wb.requests.length, 0, "a dry run asks nothing");
+
+ const r = await savePageNow({
+ paths,
+ url: LIVE,
+ slug: "live-notes-2",
+ settings: SETTINGS,
+ env: ENV,
+ pollMs: 0,
+ deps: {
+ client,
+ sleep: noSleep,
+ importCapture: async (slug, url) => {
+ const imp = await importPage({ paths, slug, url, client, settings: SETTINGS });
+ assert.equal(imp.ok, true, imp.error);
+ return { jobId: "import-1" };
+ },
+ },
+ onLog: (l) => lines.push(l),
+ });
+ assert.equal(r.ok, true, r.error);
+ assert.deepEqual([r.captureTs, r.originalUrl, r.polls, r.importJobId], [SPN_CAPTURE_TS, LIVE, 3, "import-1"]);
+ assert.equal(r.waybackUrl, `https://web.archive.org/web/${SPN_CAPTURE_TS}/${LIVE}`);
+ assert.deepEqual(wb.spnForms, [{ url: LIVE, capture_outlinks: "0" }]);
+ assert.deepEqual(
+ wb.requests.map((q) => `${q.method} ${q.path.replace(/\?.*$/, "")}`).slice(0, 4),
+ ["POST /save", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1", "GET /save/status/spn2-fake-1"],
+ );
+ const posts = await readAllPosts(dir);
+ assert.deepEqual(posts.map((p) => p.id), [pageRecordId(SPN_CAPTURE_TS, LIVE)]);
+ assert.match(posts[0]!.text, /captured by the fake Save Page Now/);
+ const all = JSON.stringify({ lines, r });
+ assert.ok(!all.includes(FAKE_SPN_SECRET) && !all.includes(FAKE_SPN_ACCESS), "the keys never leave");
+ } finally {
+ await wb.close();
+ }
+});
+
+test("error paths: wrong keys, a 429 that does not clear, a refused URL, a failed capture, still pending", async () => {
+ const wb = await startFakeWayback({ spn: { busyTimes: 9, failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"] } });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: noSleep }, { minGapMs: 0, maxAttempts: 3 });
+ const run = (url: string, env: Record<string, string> = ENV, maxPolls?: number) =>
+ savePageNow({ paths, url, settings: SETTINGS, env, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } });
+ const wrong = await run(LIVE, { ARCHIVE_ORG_S3_ACCESS: "WRONGACCESS", ARCHIVE_ORG_S3_SECRET: "WRONGSECRET" });
+ assert.match(wrong.error ?? "", /refused the S3 keys \(HTTP 401\)/);
+ assert.ok(!(wrong.error ?? "").includes("WRONGSECRET"));
+ const busy = await run(LIVE);
+ assert.equal(busy.ok, false);
+ assert.match(busy.error ?? "", /did not answer .* after 3 attempts \(HTTP 429\); stopping/);
+ } finally {
+ await wb.close();
+ }
+ const wb2 = await startFakeWayback({ spn: { failUrls: ["https://live.example/gone"], refuseUrls: ["https://live.example/blocked"], pendingPolls: 1 } });
+ try {
+ const client = new WaybackClient({ fetch: wb2.fetch, sleep: noSleep }, { minGapMs: 0 });
+ const run = (url: string, maxPolls?: number) =>
+ savePageNow({ paths, url, settings: SETTINGS, env: ENV, pollMs: 0, ...(maxPolls ? { maxPolls } : {}), deps: { client, sleep: noSleep } });
+ const blocked = await run("https://live.example/blocked");
+ assert.match(blocked.error ?? "", /refused the capture \(HTTP 200, error:blocked-url\)/);
+ const failed = await run("https://live.example/gone");
+ assert.match(failed.error ?? "", /the capture failed \(HTTP 200, error:not-found\)/);
+ assert.ok(failed.spnJobId);
+ const pending = await run("https://live.example/slow", 1);
+ assert.match(pending.error ?? "", /still pending after 1 status checks/);
+ // No slug: the capture is made, nothing imported.
+ const alone = await run("https://live.example/alone");
+ assert.deepEqual([alone.ok, alone.importJobId], [true, undefined]);
+ } finally {
+ await wb2.close();
+ }
+});
diff --git a/common/controller/savePageNow.ts b/common/controller/savePageNow.ts
@@ -0,0 +1,297 @@
+// SAVE PAGE NOW (release 37 S5, `save-page-now`): "Ask the Wayback Machine to
+// capture this now" — for a live page likely to be taken down. One page per
+// job: archive.org's SPN2 API (lib/waybackPages/savePageNow.ts) with the
+// operator's S3 keys, the capture waited for, then (when a Wayback pages
+// channel is named) an `import-page` job of the new capture into it
+// (controller/importPage.ts startImportPageJob), queued behind this one.
+//
+// {url, slug?} slug: the Wayback pages channel the capture is imported
+// into (absent: the capture is made and named, not
+// imported)
+//
+// Refused before any request, with the sentence a caller shows: no keys (the
+// button is off and says why), a URL that is not http(s), a page on the
+// Wayback Machine itself, a channel that is not a Wayback pages channel, a
+// video ("use import-video"), an X page outside an X-scoped channel while X
+// posts are private (importPage's own rule).
+//
+// POLITE: every request goes through the process's Wayback client (one
+// stream, the 2 s gap, 429/503 waited out, then stopped), on the
+// `platform:archive.org` queue — one capture asked at a time; the status is
+// polled every SPN_POLL_MS, at most SPN_MAX_POLLS times. The keys are sent in
+// the Authorization header only, and never logged.
+
+import { getPaths, type Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { readChannelConfig } from "./channels";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import { isWaybackHost, waybackPageUrl } from "../lib/wayback";
+import { videoPageOf } from "../lib/waybackPages/urls";
+import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
+import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import {
+ parseSpnStatus,
+ parseSpnSubmit,
+ SPN_SAVE_URL,
+ spnAuthorization,
+ spnSaveBody,
+ spnStatusUrl,
+ type SpnKeys,
+} from "../lib/waybackPages/savePageNow";
+import { readSpnKeys, redactSpnKeys } from "../lib/waybackPages/savePageNow-server";
+import { startImportPageJob, WAYBACK_PAGES_QUEUE, xCaptureRefusal } from "./importPage";
+
+export const SAVE_PAGE_NOW_JOB_KIND = "save-page-now";
+export const SAVE_PAGE_NOW_RESULT_MARKER = "@@save-page-now ";
+
+// SPN2 asks status pollers to wait a few seconds between polls; a capture
+// usually completes within a minute or two.
+export const SPN_POLL_MS = 10_000;
+export const SPN_MAX_POLLS = 30;
+
+type SpnSettings = { archiveOrg?: { s3KeyFile?: string }; social?: { x?: { visibility?: unknown } } };
+
+export type SavePageNowAvailability = { on: true } | { on: false; reason: string };
+
+// Whether the button is on, and why not: the keys' presence (never their
+// value).
+export function savePageNowAvailability(o: { settings?: SpnSettings; env?: Readonly<Record<string, string | undefined>> } = {}): SavePageNowAvailability {
+ const settings = o.settings ?? (getSettings() as SpnSettings);
+ const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) });
+ return read.ok ? { on: true } : { on: false, reason: read.reason };
+}
+
+export type SavePageNowPlan = { url: string; slug?: string; keys: SpnKeys };
+
+// Everything checked before a request: the plan, or the refusal.
+export async function planSavePageNow(
+ paths: Paths,
+ opts: { url: string; slug?: string; settings?: SpnSettings; env?: Readonly<Record<string, string | undefined>> },
+): Promise<{ ok: true; plan: SavePageNowPlan } | { ok: false; error: string }> {
+ const settings = opts.settings ?? (getSettings() as SpnSettings);
+ const url = opts.url.trim();
+ let u: URL;
+ try {
+ u = new URL(url);
+ } catch {
+ return { ok: false, error: `"${url}" is not a URL` };
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: `only http and https pages are captured (not ${u.protocol})` };
+ if (isWaybackHost(u.hostname)) return { ok: false, error: `${url} is on the Wayback Machine already: import it (import-page) instead` };
+ const slug = opts.slug?.trim() || undefined;
+ if (slug) {
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `No such channel: ${slug}` };
+ if (!isWaybackPagesChannel(config)) {
+ return { ok: false, error: `${slug} is not a Wayback pages channel; a capture is imported into a channel on platform "webpage"` };
+ }
+ const video = videoPageOf(url);
+ if (video) return { ok: false, error: `${url} is a video (${video}), not a page: use import-video for a video` };
+ const x = xCaptureRefusal(config, slug, url, settings);
+ if (x) return { ok: false, error: x };
+ }
+ const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(opts.env ? { env: opts.env } : {}) });
+ if (!read.ok) return { ok: false, error: read.reason };
+ return { ok: true, plan: { url, ...(slug ? { slug } : {}), keys: read.keys } };
+}
+
+export type SavePageNowResult = {
+ ok: boolean;
+ url: string;
+ slug?: string;
+ dryRun?: boolean;
+ // What a dry run would ask.
+ wouldAsk?: string;
+ // SPN's job id.
+ spnJobId?: string;
+ captureTs?: string;
+ originalUrl?: string;
+ waybackUrl?: string;
+ // The import-page job of the capture.
+ importJobId?: string;
+ importError?: string;
+ polls?: number;
+ error?: string;
+};
+
+export type SavePageNowDeps = {
+ client: Pick<WaybackClient, "send">;
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
+ // The capture into the channel (default: an import-page job).
+ importCapture: (slug: string, waybackUrl: string) => Promise<{ jobId: string }>;
+};
+
+const defaultSleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
+ const t = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(t);
+ reject(signal.reason ?? new Error("aborted"));
+ },
+ { once: true },
+ );
+ });
+
+// ONE CAPTURE ASKED, waited for, and (with a slug) imported.
+export async function savePageNow(opts: {
+ paths: Paths;
+ url: string;
+ slug?: string;
+ dryRun?: boolean;
+ settings?: SpnSettings;
+ env?: Readonly<Record<string, string | undefined>>;
+ pollMs?: number;
+ maxPolls?: number;
+ deps?: Partial<SavePageNowDeps>;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+}): Promise<SavePageNowResult> {
+ const base: SavePageNowResult = { ok: false, url: opts.url.trim(), ...(opts.slug?.trim() ? { slug: opts.slug.trim() } : {}) };
+ const planned = await planSavePageNow(opts.paths, opts);
+ if (!planned.ok) return { ...base, error: planned.error };
+ const { plan } = planned;
+ if (opts.dryRun) {
+ return {
+ ...base,
+ ok: true,
+ dryRun: true,
+ wouldAsk: `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`,
+ };
+ }
+ const deps: SavePageNowDeps = {
+ client: opts.deps?.client ?? defaultWaybackClient,
+ sleep: opts.deps?.sleep ?? defaultSleep,
+ importCapture:
+ opts.deps?.importCapture ??
+ ((slug, waybackUrl) => startImportPageJob({ slug, url: waybackUrl, requestedBy: "save-page-now", paths: opts.paths })),
+ };
+ const log = (line: string) => opts.onLog?.(redactSpnKeys(line, plan.keys));
+ const headers = { authorization: spnAuthorization(plan.keys) };
+ const pollMs = opts.pollMs ?? SPN_POLL_MS;
+ const maxPolls = opts.maxPolls ?? SPN_MAX_POLLS;
+ try {
+ log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now).`);
+ const sent = await deps.client.send(SPN_SAVE_URL, {
+ method: "POST",
+ headers: { ...headers, "content-type": "application/x-www-form-urlencoded" },
+ body: spnSaveBody(plan.url),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const submit = parseSpnSubmit(sent.status, sent.text);
+ if (!submit.ok) return { ...base, error: redactSpnKeys(submit.error, plan.keys) };
+ log(`Save Page Now job ${submit.jobId}: waiting for the capture.`);
+ let polls = 0;
+ for (;;) {
+ if (polls >= maxPolls) {
+ return {
+ ...base,
+ spnJobId: submit.jobId,
+ polls,
+ error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with wayback-lookup, then import-page it)`,
+ };
+ }
+ await deps.sleep(pollMs, opts.signal);
+ polls++;
+ const st = await deps.client.send(spnStatusUrl(submit.jobId), {
+ method: "GET",
+ headers,
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const status = parseSpnStatus(st.status, st.text);
+ if (status.state === "pending") continue;
+ if (status.state === "error") return { ...base, spnJobId: submit.jobId, polls, error: redactSpnKeys(status.error, plan.keys) };
+ const waybackUrl = waybackPageUrl({ captureTs: status.timestamp, originalUrl: status.originalUrl });
+ log(`Captured: ${waybackUrl}`);
+ const out: SavePageNowResult = {
+ ...base,
+ ok: true,
+ spnJobId: submit.jobId,
+ polls,
+ captureTs: status.timestamp,
+ originalUrl: status.originalUrl,
+ waybackUrl,
+ };
+ if (plan.slug) {
+ try {
+ const imp = await deps.importCapture(plan.slug, waybackUrl);
+ out.importJobId = imp.jobId;
+ log(`Import into ${plan.slug}: job ${imp.jobId}.`);
+ } catch (e) {
+ // The capture exists either way; the import is a click away.
+ out.importError = (e as Error).message;
+ log(`The import into ${plan.slug} was refused: ${out.importError}`);
+ }
+ }
+ return out;
+ }
+ } catch (e) {
+ if (opts.signal?.aborted) return { ...base, error: "cancelled" };
+ if (e instanceof ArchiveOrgRequestError) return { ...base, error: redactSpnKeys(e.message, plan.keys) };
+ throw e;
+ }
+}
+
+// THE JOB: a `save-page-now` job on the archive.org queue, refused (no job)
+// with the plan's sentence. The log ends with `@@save-page-now {…}`.
+export async function queueSavePageNow(opts: {
+ paths: Paths;
+ url: string;
+ slug?: string;
+ requestedBy?: string;
+ settings?: SpnSettings;
+ deps?: Partial<SavePageNowDeps>;
+ pollMs?: number;
+ onDone?: (result: SavePageNowResult) => void;
+}): Promise<StreamActionResult> {
+ const planned = await planSavePageNow(opts.paths, opts);
+ if (!planned.ok) return { ok: false, error: planned.error };
+ const slug = planned.plan.slug;
+ return runManagedFunction({
+ kind: SAVE_PAGE_NOW_JOB_KIND,
+ queueKey: WAYBACK_PAGES_QUEUE,
+ paths: opts.paths,
+ ...(slug ? { channelSlug: slug } : {}),
+ fn: async (onLog, signal) => {
+ onLog(`Save Page Now: ${planned.plan.url}${slug ? ` into ${slug}` : ""}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`);
+ const result = await savePageNow({
+ paths: opts.paths,
+ url: planned.plan.url,
+ ...(slug ? { slug } : {}),
+ ...(opts.settings ? { settings: opts.settings } : {}),
+ ...(opts.deps ? { deps: opts.deps } : {}),
+ ...(opts.pollMs !== undefined ? { pollMs: opts.pollMs } : {}),
+ onLog,
+ signal,
+ });
+ onLog(`${SAVE_PAGE_NOW_RESULT_MARKER}${JSON.stringify(result)}`);
+ opts.onDone?.(result);
+ if (!result.ok) throw new Error(result.error ?? "Save Page Now failed");
+ },
+ });
+}
+
+export class SavePageNowRefusal extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SavePageNowRefusal";
+ }
+}
+
+// LANE B's DOOR (the Captures tab's targets): one `save-page-now` job for one
+// URL, its capture imported into `slug`. Throws SavePageNowRefusal with the
+// sentence when it is refused (no keys among them).
+export async function startSavePageNowJob(opts: {
+ url: string;
+ slug?: string;
+ requestedBy?: string;
+ paths?: Paths;
+}): Promise<{ jobId: string }> {
+ const res = await queueSavePageNow({ ...opts, paths: opts.paths ?? getPaths() });
+ if (!res.ok) throw new SavePageNowRefusal(res.error);
+ void res.stream.cancel();
+ return { jobId: res.jobId };
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -618,6 +618,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "platform",
needsText: true,
},
+ // Save Page Now (release 37 S5, controller/savePageNow.ts): ask the Wayback
+ // Machine to capture a live page now (SPN2, archive.org's S3 keys), wait for
+ // the capture, then start an import-page of it into the channel named. On
+ // the archive.org queue, like the imports; it writes nothing itself (the
+ // import does). Not drainable (one capture); not replayable (each run asks
+ // archive.org for a new capture).
+ "save-page-now": {
+ kind: "save-page-now",
+ label: "Save Page Now",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "platform",
+ },
// A screenshot and the attached media of specific archived posts (and the X
// Article a post links to), into the channel's `posts-media/`
// (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts:
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -304,6 +304,57 @@ export class ArchiveOrgClient {
});
}
+ // ANY METHOD, ONE REQUEST (release 37 S5, Save Page Now: a form POST and its
+ // status polls carry an Authorization header) through the same chain and
+ // gap. A 429/503 (and 502/504, a dropped connection) is waited out and
+ // retried as getOnce does, then ArchiveOrgRequestError `rateLimited`; any
+ // other answer — a 4xx included — is handed back with its body as text, for
+ // the caller to read (SPN answers its refusals as JSON). The headers given
+ // are sent and never put in an error or a log line.
+ send(
+ url: string,
+ init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
+ ): Promise<{ status: number; text: string }> {
+ return this.serial(async () => {
+ let lastError = "";
+ for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
+ const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now();
+ if (wait > 0) await this.deps.sleep(wait, init.signal);
+ this.requests++;
+ let res: Response | null = null;
+ let text = "";
+ try {
+ const timeout = AbortSignal.timeout(this.opts.timeoutMs);
+ res = await this.deps.fetch(url, {
+ method: init.method,
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
+ redirect: "follow",
+ headers: { accept: init.accept ?? "application/json", "user-agent": ARCHIVE_ORG_USER_AGENT, ...init.headers },
+ ...(init.body !== undefined ? { body: init.body } : {}),
+ });
+ text = await res.text();
+ } catch (err) {
+ if (init.signal?.aborted) throw err;
+ lastError = (err as Error).message;
+ res = null;
+ } finally {
+ this.lastDoneAt = this.deps.now();
+ }
+ if (res && !RETRYABLE.has(res.status)) return { status: res.status, text };
+ if (res) lastError = `HTTP ${res.status}`;
+ if (attempt === this.opts.maxAttempts) break;
+ const retryAfter = res ? parseRetryAfterMs(res.headers.get("retry-after"), this.deps.now()) : null;
+ const delay = Math.min(this.opts.maxBackoffMs, retryAfter ?? this.backoffMs(attempt));
+ await this.deps.sleep(delay, init.signal);
+ }
+ throw new ArchiveOrgRequestError(
+ `archive.org did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`,
+ null,
+ true,
+ );
+ });
+ }
+
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/archiveOrgTorrent.ts b/common/lib/archiveOrgTorrent.ts
@@ -150,8 +150,14 @@ export type ArchiveOrgFetchSettings = {
// 0 = unlimited.
maxDownloadKiBps: number;
maxUploadKiBps: number;
+ // Release 37 S5: the PATH of the mode-600 file holding archive.org's S3
+ // keys for Save Page Now (lib/waybackPages/savePageNow-server.ts). Never
+ // the keys themselves.
+ s3KeyFile: string;
};
+export const DEFAULT_ARCHIVE_ORG_S3_KEY_FILE = "~/.config/archilyzer/archive-org.env";
+
export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = {
torrent: true,
seedMinutes: 10,
@@ -160,8 +166,16 @@ export const DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS: ArchiveOrgFetchSettings = {
maxPeers: 30,
maxDownloadKiBps: 0,
maxUploadKiBps: 0,
+ s3KeyFile: DEFAULT_ARCHIVE_ORG_S3_KEY_FILE,
};
+// A value for `s3KeyFile` that is not a path (no "/", no leading "~") is
+// taken for a key pasted in the wrong place: refused, never stored.
+export function looksLikeS3Key(v: string): boolean {
+ const s = v.trim();
+ return !!s && !s.includes("/") && !s.startsWith("~");
+}
+
// ─── The aria2c command line ───
export type Aria2cSpec = {
diff --git a/common/lib/archives/index.ts b/common/lib/archives/index.ts
@@ -142,4 +142,27 @@ export async function archiveLookup(
return { url, found: entries.reduce((n, e) => n + e.captures.length, 0), sources: entries };
}
+// THE COPY NEAREST A TIME, across sources (lane E's find-copy page mode): each
+// source asked in turn (the Wayback Machine first), the first that holds a
+// copy answers. A source that EXCLUDES the page (a Wayback 403) or holds none
+// passes to the next; any other refusal or error is thrown, so the caller's
+// stop rules still apply.
+export async function nearestAcrossSources(
+ url: string,
+ at: string,
+ o: { sources?: readonly ArchiveSource[]; signal?: AbortSignal } = {},
+): Promise<ArchiveCaptureRow | null> {
+ for (const s of o.sources ?? ARCHIVE_SOURCES) {
+ try {
+ const near = await s.closestCapture(url, at, o.signal ? { signal: o.signal } : {});
+ if (near) return near;
+ } catch (e) {
+ if (o.signal?.aborted) throw e;
+ if (archiveRefusalOf(e)?.code === "excluded") continue;
+ throw e;
+ }
+ }
+ return null;
+}
+
export { archiveSourceLabel, WAYBACK_EXCLUDED_PHRASE };
diff --git a/common/lib/archives/wayback.test.ts b/common/lib/archives/wayback.test.ts
@@ -12,7 +12,7 @@ import { startFakeArchiveToday, AT_ARTICLE_URL, AT_ARTICLE_TS } from "../../test
import { ArchiveOrgRequestError } from "../archiveOrgClient";
import { isWaybackExcluded, WaybackCaptureRefusal, WaybackClient, WaybackExcludedError, waybackCdxUrl } from "../waybackClient";
import { parseWaybackMemento, waybackSource } from "./wayback";
-import { archiveLookup, archiveRefusalOf, archiveSource, archiveTodaySource, sourceForUrl } from "./index";
+import { archiveLookup, archiveRefusalOf, archiveSource, archiveTodaySource, nearestAcrossSources, sourceForUrl } from "./index";
import { ArchiveTodayClient } from "./archiveTodayClient";
const fast = { minGapMs: 0, baseBackoffMs: 1, maxBackoffMs: 2 };
@@ -117,3 +117,20 @@ test("the lookup across sources: each source its own entry — an exclusion one,
await at.close();
}
});
+
+test("the copy nearest a time across sources: an exclusion or none passes to the next source", async () => {
+ const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] });
+ const at = await startFakeArchiveToday();
+ try {
+ const sources = [
+ waybackSource(new WaybackClient({ fetch: wb.fetch }, fast)),
+ archiveTodaySource(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 })),
+ ];
+ assert.equal((await nearestAcrossSources(AT_ARTICLE_URL, "2019", { sources }))?.source, "archive.today");
+ assert.equal((await nearestAcrossSources(PAGE_ARTICLE_URL, "2014", { sources }))?.source, "wayback");
+ assert.equal(await nearestAcrossSources("https://nowhere.example/", "2014", { sources }), null);
+ } finally {
+ await wb.close();
+ await at.close();
+ }
+});
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -95,6 +95,8 @@ const DECLARED: EnvVarDecl[] = [
// ── runtime ────────────────────────────────────────────────────────────
{ name: "WORKER_TOKEN", audience: "runtime", default: "unset (both surfaces off)", readBy: "common/lib/workerToken.ts, scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, mcp/src/archivalTools.ts, umtool/lib/annotations/agentAuth.mjs", doc: "Bearer token for the remote-worker API and for `/api/ops/*` (`pnpm ops` and `archilyzer gen`; the MCP's `fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate` and `get_transcript`'s editor fallback), and for an agent's write to umtool's notes (the MCP's `notes` reply, stamped \"agent\"; umtool reads it from its environment, else the editor's `editor/.env`). Set the same value on every end." },
{ name: "ANTHROPIC_API_KEY", audience: "runtime", default: "unset (the API key file is read instead)", readBy: "common/lib/llm/anthropic.ts", doc: "The Claude API key for report and video generation on the API (release 27): read first, before the mode-600 key file the generation settings name. Sent only to the Messages API in `x-api-key`; never logged, and never in an error, a job record or a transcript." },
+ { name: "ARCHIVE_ORG_S3_ACCESS", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why." },
+ { name: "ARCHIVE_ORG_S3_SECRET", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above)." },
{ name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." },
{ name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." },
{ name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." },
@@ -231,7 +233,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
{ name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
- { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
+ { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_ARCHIVE_TODAY_ORIGIN_FILE", audience: "test", default: "unset (the real archive.today)", readBy: "common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts", doc: "A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored." },
{ 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." },
diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts
@@ -416,6 +416,8 @@ export async function readPostAvailability(
availability: r.availability,
checkedAt: r.checkedAt,
...(Array.isArray(r.history) ? { history: r.history } : {}),
+ ...(typeof r.status === "number" || r.status === null ? { status: r.status } : {}),
+ ...(typeof r.reason === "string" ? { reason: r.reason } : {}),
};
}
return out;
@@ -436,19 +438,24 @@ export async function writePostAvailability(
// Fold new observations in, appending to history ONLY when the availability
// actually changes. That keeps the file small and, more importantly, preserves
// the moment a post was first seen deleted — which is the fact worth keeping.
+// `details` (release 37 S5, a page record's original-URL check) carries the
+// answer's status and reason, kept on the record (the latest only).
export function mergePostAvailability(
existing: PostAvailabilityMap,
observations: ReadonlyMap<string, PostAvailability>,
checkedAt: string,
+ details?: ReadonlyMap<string, { status: number | null; reason: string }>,
): { map: PostAvailabilityMap; newlyDeleted: string[]; changed: number } {
const map: PostAvailabilityMap = { ...existing };
const newlyDeleted: string[] = [];
let changed = 0;
for (const [id, availability] of observations) {
const prev = map[id];
+ const detail = details?.get(id);
+ const facts = detail ? { status: detail.status, reason: detail.reason } : {};
if (prev?.availability === availability) {
// Same verdict — just refresh when we last looked.
- map[id] = { ...prev, checkedAt };
+ map[id] = { ...prev, checkedAt, ...facts };
continue;
}
changed++;
@@ -458,6 +465,7 @@ export function mergePostAvailability(
map[id] = {
availability,
checkedAt,
+ ...facts,
history: [
...(prev?.history ?? []),
...(prev
diff --git a/common/lib/posts.ts b/common/lib/posts.ts
@@ -188,6 +188,10 @@ export type PostAvailabilityRecord = {
// Appended only when the availability CHANGES, so the file stays small and
// the first-seen-deleted moment is preserved. Mirrors the video record.
history?: { availability: PostAvailability; at: string }[];
+ // Release 37 S5 (a page record: its ORIGINAL URL's check): the last
+ // answer's HTTP status (null: none) and why, in a phrase.
+ status?: number | null;
+ reason?: string;
};
// postId -> record, stored once per channel. Videos keep a file per video dir,
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -74,6 +74,7 @@ import {
import { ATTRIBUTION_PROMPT_VERSION } from "./attribution";
import {
DEFAULT_ARCHIVE_ORG_FETCH_SETTINGS,
+ looksLikeS3Key,
type ArchiveOrgFetchSettings,
} from "./archiveOrgTorrent";
import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
@@ -541,6 +542,12 @@ export const ARCHIVE_ORG_SETTINGS_FIELD_DOCS: FieldDocs<ArchiveOrgFetchSettings>
maxUploadKiBps:
"Upload rate cap while downloading and seeding, KiB/s (aria2c " +
"--max-overall-upload-limit). 0 = unlimited.",
+ s3KeyFile:
+ "Release 37: the file holding archive.org's S3 keys for Save Page Now (\"Ask the Wayback Machine to capture this now\"): " +
+ "two lines, `ARCHIVE_ORG_S3_ACCESS=…` and `ARCHIVE_ORG_S3_SECRET=…` (from archive.org/account/s3.php), mode 600 — " +
+ "refused when the group or others can read it. `~` is the editor's home. The KEYS themselves are never a setting: " +
+ "a value that is not a path is refused, never stored. `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the " +
+ "editor's environment win over the file. No keys: Save Page Now is off, and says why.",
};
function clampNumber(value: unknown, fallback: number, min: number, max: number): number {
@@ -560,6 +567,10 @@ export function sanitizeArchiveOrg(value: unknown): ArchiveOrgFetchSettings {
maxPeers: Math.floor(clampNumber(r.maxPeers, d.maxPeers, 1, 500)),
maxDownloadKiBps: Math.floor(clampNumber(r.maxDownloadKiBps, d.maxDownloadKiBps, 0, 10_000_000)),
maxUploadKiBps: Math.floor(clampNumber(r.maxUploadKiBps, d.maxUploadKiBps, 0, 10_000_000)),
+ s3KeyFile:
+ typeof r.s3KeyFile === "string" && r.s3KeyFile.trim() && !looksLikeS3Key(r.s3KeyFile)
+ ? r.s3KeyFile.trim()
+ : d.s3KeyFile,
};
}
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -248,6 +248,16 @@ export class WaybackClient {
return this.http.requests;
}
+ // One request of any method to web.archive.org through this client's chain
+ // and gap (release 37 S5: Save Page Now's POST and status polls,
+ // lib/waybackPages/savePageNow.ts). ArchiveOrgClient.send's contract.
+ send(
+ url: string,
+ init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
+ ): Promise<{ status: number; text: string }> {
+ return this.http.send(url, init);
+ }
+
// Whether the Wayback Machine holds the YouTube VIDEO itself (formats in
// its videoinfo index — what yt-dlp asks), not only captures of its page.
async youtubeVideoArchived(youtubeId: string, o: { signal?: AbortSignal } = {}): Promise<boolean> {
diff --git a/common/lib/waybackPages/liveness-server.ts b/common/lib/waybackPages/liveness-server.ts
@@ -0,0 +1,106 @@
+// ONE ORIGINAL URL'S STATE (release 37 S5): the request side of
+// ./liveness.ts. Through the process's web pacer (lib/web/pacer.ts: one
+// request at a time, 3 s apart, 429/503 backed off) — never the Wayback
+// Machine, never a burst — and behind the web fetch's fence (http(s) only,
+// no private or loopback host, every redirect hop checked the same way).
+//
+// HEAD, following redirects by hand (at most WEB_FETCH_MAX_REDIRECTS);
+// a GET instead when the HEAD is refused (405, 403, 501) or when the page's
+// platform has a "gone" page that answers 200 (its words decide), its body
+// read up to LIVENESS_MAX_BODY_BYTES.
+//
+// Answers an OriginalCheck; never throws for what the site answered (a
+// cancelled run's abort is rethrown).
+
+import { fetchRefusal, WEB_FETCH_MAX_REDIRECTS, type WebFetchOptions } from "../web/fetchPage";
+import { webPacer, WebRequestError, type WebPacer } from "../web/pacer";
+import { classifyOriginalAnswer, hasGoneMarkers, type OriginalCheck } from "./liveness";
+
+// A "gone" page's words are near its top: the body is read no further.
+export const LIVENESS_MAX_BODY_BYTES = 256 * 1024;
+
+// A HEAD these statuses refuse is asked again as a GET.
+const HEAD_REFUSED = new Set([403, 405, 501]);
+
+export type CheckOriginalOptions = Pick<WebFetchOptions, "allowPrivate" | "resolve"> & {
+ pacer?: WebPacer;
+ signal?: AbortSignal;
+};
+
+async function readCapped(res: Response, maxBytes: number): Promise<string> {
+ if (!res.body) return "";
+ const reader = res.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let n = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ chunks.push(value);
+ n += value.byteLength;
+ if (n >= maxBytes) {
+ await reader.cancel().catch(() => {});
+ break;
+ }
+ }
+ return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes));
+}
+
+type Hop = { redirect: string } | { status: number; body?: string };
+
+// One method's walk: redirects followed by hand, each hop fenced.
+async function walk(
+ url: string,
+ method: "HEAD" | "GET",
+ o: CheckOriginalOptions,
+): Promise<{ finalUrl: string; status: number; body?: string } | { refusal: string; status: number | null; finalUrl: string }> {
+ const pacer = o.pacer ?? webPacer;
+ let at = url;
+ for (let hop = 0; hop <= WEB_FETCH_MAX_REDIRECTS; hop++) {
+ const refusal = await fetchRefusal(at, o);
+ if (refusal) return { refusal, status: null, finalUrl: at };
+ const step: Hop = await pacer.request(
+ at,
+ {
+ method,
+ redirect: "manual",
+ headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" },
+ ...(o.signal ? { signal: o.signal } : {}),
+ },
+ async (res): Promise<Hop> => {
+ const loc = res.headers.get("location");
+ if (res.status >= 300 && res.status < 400 && loc) {
+ await res.body?.cancel().catch(() => {});
+ return { redirect: new URL(loc, at).toString() };
+ }
+ if (method === "HEAD") {
+ await res.body?.cancel().catch(() => {});
+ return { status: res.status };
+ }
+ return { status: res.status, body: await readCapped(res, LIVENESS_MAX_BODY_BYTES) };
+ },
+ );
+ if ("redirect" in step) {
+ at = step.redirect;
+ continue;
+ }
+ return { finalUrl: at, status: step.status, ...(step.body !== undefined ? { body: step.body } : {}) };
+ }
+ return { refusal: `more than ${WEB_FETCH_MAX_REDIRECTS} redirects`, status: null, finalUrl: at };
+}
+
+export async function checkOriginalUrl(url: string, o: CheckOriginalOptions = {}): Promise<OriginalCheck> {
+ try {
+ let answer = await walk(url, "HEAD", o);
+ const headRefused = !("refusal" in answer) && HEAD_REFUSED.has(answer.status);
+ const needsBody = !("refusal" in answer) && answer.status >= 200 && answer.status < 300 && hasGoneMarkers(answer.finalUrl);
+ if (headRefused || needsBody) answer = await walk(url, "GET", o);
+ if ("refusal" in answer) {
+ return { url, availability: "error", status: answer.status, ...(answer.finalUrl !== url ? { finalUrl: answer.finalUrl } : {}), reason: answer.refusal };
+ }
+ return classifyOriginalAnswer({ url, finalUrl: answer.finalUrl, status: answer.status, ...(answer.body !== undefined ? { body: answer.body } : {}) });
+ } catch (e) {
+ if (o.signal?.aborted) throw e;
+ const status = e instanceof WebRequestError ? e.status : null;
+ return { url, availability: "error", status, reason: (e as Error).message };
+ }
+}
diff --git a/common/lib/waybackPages/liveness.test.ts b/common/lib/waybackPages/liveness.test.ts
@@ -0,0 +1,173 @@
+// Release 37 S5: a page record's ORIGINAL — the marker table, the verdict on
+// one answer, the same-site rule, grouping by original URL, and the request
+// side (HEAD, then GET) through a web pacer over a stub fetch. No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/liveness.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyOriginalAnswer,
+ foldPageText,
+ groupByOriginalUrl,
+ hasGoneMarkers,
+ PAGE_GONE_MARKERS,
+ pageGoneMarker,
+ sameSite,
+ siteOf,
+} from "./liveness";
+import { checkOriginalUrl } from "./liveness-server";
+import { WebPacer } from "../web/pacer";
+
+// Synthetic "gone" pages: each marker's words in the platform's own furniture.
+const page = (words: string) => `<!doctype html><html><head><title>t</title><script>var x="${words.slice(0, 3)}";</script></head><body><div class="x"><h1>${words}</h1><p>Try something else.</p></div></body></html>`;
+
+const MARKER_CASES: { id: string; url: string; html: string }[] = [
+ { id: "x-no-account", url: "https://x.com/someone", html: page("This account doesn’t exist") },
+ { id: "x-no-page", url: "https://twitter.com/someone/status/1", html: page("Hmm...this page doesn’t exist. Try searching for something else.") },
+ { id: "x-suspended", url: "https://mobile.twitter.com/someone", html: page("Account suspended") },
+ { id: "tumblr-nothing-here", url: "https://someone.tumblr.com/post/123", html: page("There's nothing here.") },
+ { id: "tumblr-nothing-here", url: "https://www.tumblr.com/someone", html: page("Whatever you were looking for doesn't currently exist at this address. Unless you were looking for this error page, in which case: Congrats!") },
+ { id: "gdocs-no-file", url: "https://docs.google.com/document/d/abc/edit", html: page("Sorry, the file you have requested does not exist.") },
+ { id: "gdocs-permission", url: "https://drive.google.com/file/d/abc/view", html: page("You need access") },
+ { id: "youtube-no-channel", url: "https://www.youtube.com/@someone/about", html: page("This channel does not exist.") },
+ { id: "youtube-terminated", url: "https://m.youtube.com/channel/UCabc", html: page("This account has been terminated for a violation of YouTube's Terms of Service.") },
+];
+
+test("the marker table: every platform's gone page is told by its words, on its own hosts only", () => {
+ for (const c of MARKER_CASES) {
+ assert.equal(pageGoneMarker(c.url, c.html)?.id, c.id, c.url);
+ }
+ // Every marker has a case.
+ assert.deepEqual(new Set(MARKER_CASES.map((c) => c.id)), new Set(PAGE_GONE_MARKERS.map((m) => m.id)));
+ // The same words elsewhere are not a gone page (a blog quoting X's message).
+ assert.equal(pageGoneMarker("https://blog.example/post", page("This account doesn't exist")), null);
+ assert.equal(pageGoneMarker("https://example.tumblr.net/", page("There's nothing here.")), null);
+ // A live page on the platform is not one either.
+ assert.equal(pageGoneMarker("https://someone.tumblr.com/post/1", page("A post about bread")), null);
+ // Words inside a script are not the page's.
+ assert.equal(pageGoneMarker("https://x.com/a", `<html><script>var m = "Account suspended";</script><p>hello</p></html>`), null);
+ assert.equal(hasGoneMarkers("https://www.youtube.com/@a/about"), true);
+ assert.equal(hasGoneMarkers("https://blog.example/"), false);
+ assert.equal(foldPageText("<p>Doesn’t <b>EXIST</b></p>"), "doesn't exist");
+});
+
+test("one answer's verdict: 404/410 deleted, 2xx available on the same site, a marker, anything else an error with its status", () => {
+ const v = (url: string, finalUrl: string, status: number, body?: string) =>
+ classifyOriginalAnswer({ url, finalUrl, status, ...(body !== undefined ? { body } : {}) });
+ assert.deepEqual(
+ [v("https://a.example/x", "https://a.example/x", 404).availability, v("https://a.example/x", "https://a.example/x", 410).availability],
+ ["deleted", "deleted"],
+ );
+ const ok = v("http://a.example/x", "https://www.a.example/x/", 200);
+ assert.equal(ok.availability, "available");
+ assert.equal(ok.finalUrl, "https://www.a.example/x/");
+ const off = v("https://a.example/x", "https://parked.example/", 200);
+ assert.equal(off.availability, "error");
+ assert.match(off.reason, /redirects to another site \(parked\.example\)/);
+ const gone = v("https://someone.tumblr.com/post/1", "https://www.tumblr.com/someone", 200, page("There's nothing here."));
+ assert.deepEqual([gone.availability, gone.reason], ["deleted", "Tumblr says there's nothing here"]);
+ const walled = v("https://x.com/a", "https://x.com/a", 403);
+ assert.deepEqual([walled.availability, walled.status, walled.reason], ["error", 403, "HTTP 403"]);
+ assert.equal(v("https://a.example/", "https://a.example/", 500).availability, "error");
+ // A gone page behind another status still says so.
+ assert.equal(v("https://docs.google.com/d/1", "https://docs.google.com/d/1", 401, page("You need permission")).availability, "account_unavailable");
+});
+
+test("same site: www, http→https, a subdomain of the same domain, two-label suffixes, moved houses", () => {
+ assert.equal(sameSite("http://blog.example/", "https://www.blog.example/a"), true);
+ assert.equal(sameSite("https://someone.tumblr.com/", "https://www.tumblr.com/someone"), true);
+ assert.equal(sameSite("https://twitter.com/a", "https://x.com/a"), true);
+ assert.equal(sameSite("https://a.example.co.uk/", "https://b.example.co.uk/"), true);
+ assert.equal(sameSite("https://a.co.uk/", "https://b.co.uk/"), false);
+ assert.equal(sameSite("https://blog.example/", "https://other.example/"), false);
+ assert.equal(siteOf("www.news.bbc.co.uk"), "bbc.co.uk");
+});
+
+test("records grouped by original URL: one request per URL, whatever a capture split into", () => {
+ const rec = (id: string, originalUrl?: string) => ({ id, ...(originalUrl ? { page: { originalUrl } } : {}) });
+ const g = groupByOriginalUrl([rec("t1", "https://x.com/a"), rec("p1", "https://blog.example/"), rec("t2", "https://x.com/a"), rec("none")]);
+ assert.deepEqual([...g.entries()], [
+ ["https://x.com/a", ["t1", "t2"]],
+ ["https://blog.example/", ["p1"]],
+ ]);
+});
+
+// ─── The request side, over a stub fetch ───
+
+type Route = (method: string, url: string) => { status: number; headers?: Record<string, string>; body?: string };
+
+function stubPacer(route: Route) {
+ const sent: string[] = [];
+ const pacer = new WebPacer(
+ {
+ fetch: async (url, init) => {
+ const method = (init.method ?? "GET").toUpperCase();
+ sent.push(`${method} ${url}`);
+ const r = route(method, url);
+ return new Response(method === "HEAD" ? null : (r.body ?? ""), { status: r.status, headers: r.headers ?? {} });
+ },
+ sleep: async () => {},
+ },
+ { minGapMs: 0, maxAttempts: 2 },
+ );
+ // Every public name resolves to a public address; nothing is looked up.
+ return { pacer, sent, opts: { pacer, resolve: async () => ["93.184.216.34"] } };
+}
+
+test("checkOriginalUrl: a HEAD is enough for a plain page; a refused HEAD is asked again as a GET", async () => {
+ const live = stubPacer(() => ({ status: 200 }));
+ assert.equal((await checkOriginalUrl("https://blog.example/a", live.opts)).availability, "available");
+ assert.deepEqual(live.sent, ["HEAD https://blog.example/a"]);
+
+ const refused = stubPacer((m) => (m === "HEAD" ? { status: 405 } : { status: 200, body: "<p>hi</p>" }));
+ const r = await checkOriginalUrl("https://blog.example/a", refused.opts);
+ assert.equal(r.availability, "available");
+ assert.deepEqual(refused.sent, ["HEAD https://blog.example/a", "GET https://blog.example/a"]);
+
+ const gone = stubPacer(() => ({ status: 410 }));
+ assert.deepEqual(
+ [(await checkOriginalUrl("https://blog.example/a", gone.opts)).availability, gone.sent.length],
+ ["deleted", 1],
+ );
+});
+
+test("checkOriginalUrl: redirects followed by hand; a platform with a gone page is read with a GET", async () => {
+ const s = stubPacer((m, url) => {
+ if (url === "https://someone.tumblr.com/post/1") return { status: 301, headers: { location: "https://www.tumblr.com/someone/1" } };
+ return m === "HEAD" ? { status: 200 } : { status: 200, body: page("There’s nothing here.") };
+ });
+ const r = await checkOriginalUrl("https://someone.tumblr.com/post/1", s.opts);
+ assert.deepEqual([r.availability, r.finalUrl, r.reason], ["deleted", "https://www.tumblr.com/someone/1", "Tumblr says there's nothing here"]);
+ assert.deepEqual(s.sent, [
+ "HEAD https://someone.tumblr.com/post/1",
+ "HEAD https://www.tumblr.com/someone/1",
+ "GET https://someone.tumblr.com/post/1",
+ "GET https://www.tumblr.com/someone/1",
+ ]);
+ const off = stubPacer((_m, url) => (url.includes("blog.example") ? { status: 302, headers: { location: "https://parked.example/" } } : { status: 200 }));
+ const o = await checkOriginalUrl("https://blog.example/", off.opts);
+ assert.equal(o.availability, "error");
+ assert.match(o.reason, /another site/);
+});
+
+test("checkOriginalUrl: an error never reads as deleted — a 403 wall, a 503 that stays, a private address, no answer", async () => {
+ const wall = stubPacer(() => ({ status: 403 }));
+ const w = await checkOriginalUrl("https://blog.example/", wall.opts);
+ assert.deepEqual([w.availability, w.status], ["error", 403]);
+ assert.equal(wall.sent.length, 2, "HEAD, then GET");
+
+ const down = stubPacer(() => ({ status: 503 }));
+ const d = await checkOriginalUrl("https://blog.example/", down.opts);
+ assert.deepEqual([d.availability, d.status], ["error", 503]);
+
+ const inside = stubPacer(() => ({ status: 200 }));
+ const p = await checkOriginalUrl("http://127.0.0.1:9/", inside.opts);
+ assert.equal(p.availability, "error");
+ assert.match(p.reason, /private address/);
+ assert.equal(inside.sent.length, 0);
+
+ const dead = new WebPacer({ fetch: async () => { throw new Error("getaddrinfo ENOTFOUND"); }, sleep: async () => {} }, { minGapMs: 0 });
+ const n = await checkOriginalUrl("https://blog.example/", { pacer: dead, resolve: async () => ["93.184.216.34"] });
+ assert.deepEqual([n.availability, n.status], ["error", null]);
+});
diff --git a/common/lib/waybackPages/liveness.ts b/common/lib/waybackPages/liveness.ts
@@ -0,0 +1,227 @@
+// IS THE ORIGINAL STILL UP? (release 37 S5, plans/release-37/wayback-pages.md
+// "S5") — the pure half of a page record's availability: what one answer from
+// the ORIGINAL URL (never the Wayback Machine) says about it.
+//
+// available a 2xx, after any redirects that stayed on the same
+// site, whose body carries no platform's "gone" page
+// deleted 404 or 410, or a platform's "this does not exist"
+// page (PAGE_GONE_MARKERS) — the Wayback copy is then
+// the only copy
+// account_unavailable a platform's "this account is suspended / this
+// document is not shared" page: the page is not served,
+// and that may reverse
+// error anything else (a 403, a 5xx, a redirect to another
+// site, no answer), with the status — never a deletion
+// reported from ignorance
+//
+// Pure and client-safe: the request side is ./liveness-server.ts.
+
+import type { PostAvailability } from "../posts";
+
+// One platform's "gone" page: the hosts it applies to and the words it shows.
+export type PageGoneMarker = {
+ // A short name for logs and tests.
+ id: string;
+ // The page's host (no "www."), tested against each pattern.
+ hosts: readonly RegExp[];
+ // Matched against the page's text (tags dropped, entities and curly quotes
+ // folded, whitespace collapsed, lower case).
+ text: RegExp;
+ availability: Extract<PostAvailability, "deleted" | "account_unavailable">;
+ // What the log and the sidecar say.
+ reason: string;
+};
+
+const X_HOSTS = [/^(?:mobile\.)?(?:x|twitter)\.com$/];
+const TUMBLR_HOSTS = [/(?:^|\.)tumblr\.com$/];
+const GOOGLE_DOCS_HOSTS = [/^(?:docs|drive)\.google\.com$/];
+const YOUTUBE_HOSTS = [/^(?:m\.)?youtube\.com$/];
+
+// THE TABLE (unit-tested in liveness.test.ts). A platform that serves its
+// "nothing here" page with a 200 is only told apart by its words; one that
+// answers 404 needs no entry (the status says it).
+export const PAGE_GONE_MARKERS: readonly PageGoneMarker[] = [
+ {
+ id: "x-no-account",
+ hosts: X_HOSTS,
+ text: /this account doesn't exist/,
+ availability: "deleted",
+ reason: "X says the account doesn't exist",
+ },
+ {
+ id: "x-no-page",
+ hosts: X_HOSTS,
+ text: /(?:hmm\.\.\.\s*)?this page doesn't exist|sorry, that page doesn't exist/,
+ availability: "deleted",
+ reason: "X says the page doesn't exist",
+ },
+ {
+ id: "x-suspended",
+ hosts: X_HOSTS,
+ text: /account suspended/,
+ availability: "account_unavailable",
+ reason: "X says the account is suspended",
+ },
+ {
+ id: "tumblr-nothing-here",
+ hosts: TUMBLR_HOSTS,
+ text: /there's nothing here\.?|whatever you were looking for doesn't currently exist at this address/,
+ availability: "deleted",
+ reason: "Tumblr says there's nothing here",
+ },
+ {
+ id: "gdocs-no-file",
+ hosts: GOOGLE_DOCS_HOSTS,
+ text: /sorry, the file you have requested does not exist/,
+ availability: "deleted",
+ reason: "Google Docs says the file does not exist",
+ },
+ {
+ id: "gdocs-permission",
+ hosts: GOOGLE_DOCS_HOSTS,
+ text: /you need (?:access|permission)/,
+ availability: "account_unavailable",
+ reason: "Google Docs says the file is not shared",
+ },
+ {
+ id: "youtube-no-channel",
+ hosts: YOUTUBE_HOSTS,
+ text: /this channel does not exist/,
+ availability: "deleted",
+ reason: "YouTube says the channel does not exist",
+ },
+ {
+ id: "youtube-terminated",
+ hosts: YOUTUBE_HOSTS,
+ text: /this account has been terminated/,
+ availability: "account_unavailable",
+ reason: "YouTube says the account has been terminated",
+ },
+];
+
+// The host without "www.", lower case; "" for no URL.
+export function bareHost(url: string): string {
+ try {
+ return new URL(url).hostname.toLowerCase().replace(/^www\./, "");
+ } catch {
+ return "";
+ }
+}
+
+// Whether a platform has a "gone" page worth reading the body for.
+export function hasGoneMarkers(url: string): boolean {
+ const host = bareHost(url);
+ return !!host && PAGE_GONE_MARKERS.some((m) => m.hosts.some((h) => h.test(host)));
+}
+
+// The page's words, folded for matching: tags and scripts dropped, a few
+// entities and curly quotes folded, whitespace collapsed, lower case.
+export function foldPageText(html: string): string {
+ return html
+ .replace(/<(script|style|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<[^>]+>/g, " ")
+ .replace(/�*39;|�*27;|'|’|‘|’|’/gi, "'")
+ .replace(/ | /gi, " ")
+ .replace(/&/gi, "&")
+ .replace(/[‘’ʼ]/g, "'")
+ .replace(/\s+/g, " ")
+ .trim()
+ .toLowerCase();
+}
+
+// The platform's "gone" page this body is, or null.
+export function pageGoneMarker(url: string, html: string): PageGoneMarker | null {
+ const host = bareHost(url);
+ if (!host || !html) return null;
+ const text = foldPageText(html);
+ for (const m of PAGE_GONE_MARKERS) {
+ if (!m.hosts.some((h) => h.test(host))) continue;
+ if (m.text.test(text)) return m;
+ }
+ return null;
+}
+
+// Two-label public suffixes the "same site" test must not stop at.
+const SECOND_LEVEL = /^(?:co|com|net|org|gov|ac|edu|ne|or)\.[a-z]{2}$/;
+
+// A host's registrable part, roughly: its last two labels, or three under a
+// two-label suffix (co.uk, com.au).
+// Sites that moved house: a redirect between them stays on the site.
+const SITE_ALIASES: Readonly<Record<string, string>> = { "twitter.com": "x.com", "youtu.be": "youtube.com" };
+
+export function siteOf(host: string): string {
+ const labels = host.toLowerCase().replace(/^www\./, "").split(".").filter(Boolean);
+ const last2 = labels.slice(-2).join(".");
+ const site = labels.length > 2 && SECOND_LEVEL.test(last2) ? labels.slice(-3).join(".") : last2;
+ return SITE_ALIASES[site] ?? site;
+}
+
+// Whether a redirect from `a` to `b` stayed on the same site (http→https,
+// www, a subdomain of the same registrable domain: tumblr's blog → www).
+export function sameSite(a: string, b: string): boolean {
+ const ha = bareHost(a);
+ const hb = bareHost(b);
+ if (!ha || !hb) return false;
+ return ha === hb || siteOf(ha) === siteOf(hb);
+}
+
+// One check's verdict on an original URL.
+export type OriginalCheck = {
+ url: string;
+ availability: PostAvailability;
+ // The final answer's HTTP status (null: no answer).
+ status: number | null;
+ // Where the redirects (if any) ended.
+ finalUrl?: string;
+ // Why, in a phrase (the marker's reason, the status, the redirect, the
+ // network error).
+ reason: string;
+};
+
+// THE VERDICT on one final answer. `body` is the page's text when it was
+// read (a GET), else undefined (a HEAD).
+export function classifyOriginalAnswer(a: {
+ url: string;
+ finalUrl: string;
+ status: number;
+ body?: string;
+}): OriginalCheck {
+ const base = { url: a.url, status: a.status, ...(a.finalUrl !== a.url ? { finalUrl: a.finalUrl } : {}) };
+ if (a.status === 404 || a.status === 410) {
+ return { ...base, availability: "deleted", reason: `HTTP ${a.status}` };
+ }
+ if (a.status >= 200 && a.status < 300) {
+ if (!sameSite(a.url, a.finalUrl)) {
+ return { ...base, availability: "error", reason: `redirects to another site (${bareHost(a.finalUrl) || a.finalUrl})` };
+ }
+ const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null;
+ if (marker) return { ...base, availability: marker.availability, reason: marker.reason };
+ return { ...base, availability: "available", reason: `HTTP ${a.status}` };
+ }
+ // A platform's gone page can come with another status (a 403 wall).
+ const marker = a.body !== undefined ? pageGoneMarker(a.finalUrl, a.body) : null;
+ if (marker) return { ...base, availability: marker.availability, reason: `${marker.reason} (HTTP ${a.status})` };
+ return { ...base, availability: "error", reason: `HTTP ${a.status}` };
+}
+
+// A webpage record's ids grouped by the original URL they were captured
+// from: one request per distinct URL, whatever number of records a capture
+// split into. Order: the order of `records` (first appearance).
+export function groupByOriginalUrl(
+ records: ReadonlyArray<{ id: string; page?: { originalUrl: string } }>,
+): Map<string, string[]> {
+ const out = new Map<string, string[]>();
+ for (const r of records) {
+ const url = r.page?.originalUrl;
+ if (!url) continue;
+ const list = out.get(url);
+ if (list) list.push(r.id);
+ else out.set(url, [r.id]);
+ }
+ return out;
+}
+
+// What a reader is told about a page record whose original is gone (the
+// source-gone label's page sentence, lib/sourceGone.ts SOURCE_GONE_LABELS
+// for everything else).
+export const PAGE_ORIGINAL_GONE_LABEL = "Original gone — the Wayback Machine copy is the only copy";
diff --git a/common/lib/waybackPages/savePageNow-server.ts b/common/lib/waybackPages/savePageNow-server.ts
@@ -0,0 +1,63 @@
+// archive.org's S3 KEYS for Save Page Now (release 37 S5), kept the way the
+// Claude API key is (lib/llm/anthropic.ts readApiKey): the environment first
+// (ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, both), else a mode-600
+// file whose PATH is the setting `archiveOrg.s3KeyFile` (two lines
+// `ARCHIVE_ORG_S3_ACCESS=…`, `ARCHIVE_ORG_S3_SECRET=…`). A file the group or
+// others can read is refused. The keys are never a setting, never logged,
+// never in an error, a job record or a result.
+
+import { readFileSync, statSync } from "node:fs";
+import os from "node:os";
+import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../archiveOrgTorrent";
+import { spnOffSentence, type SpnKeys } from "./savePageNow";
+
+export type SpnKeysRead = { ok: true; keys: SpnKeys; from: "env" | "file" } | { ok: false; reason: string };
+
+const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p);
+
+const unquote = (v: string) => v.trim().replace(/^(["'])(.*)\1$/, "$2").trim();
+
+export function readSpnKeys(o: {
+ keyFile?: string;
+ env?: Readonly<Record<string, string | undefined>>;
+}): SpnKeysRead {
+ const env = o.env ?? process.env;
+ const keyFile = o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE;
+ const envAccess = (env.ARCHIVE_ORG_S3_ACCESS ?? "").trim();
+ const envSecret = (env.ARCHIVE_ORG_S3_SECRET ?? "").trim();
+ if (envAccess && envSecret) return { ok: true, keys: { access: envAccess, secret: envSecret }, from: "env" };
+ const file = expandHome(keyFile);
+ let mode: number;
+ try {
+ mode = statSync(file).mode;
+ } catch {
+ return { ok: false, reason: spnOffSentence(keyFile) };
+ }
+ if (mode & 0o077) return { ok: false, reason: `${keyFile} is readable by others — chmod 600 it first; Save Page Now is off until then.` };
+ let text: string;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch {
+ return { ok: false, reason: `${keyFile} could not be read; Save Page Now is off.` };
+ }
+ let access = "";
+ let secret = "";
+ for (const raw of text.split("\n")) {
+ const line = raw.trim().replace(/^export\s+/, "");
+ if (line.startsWith("ARCHIVE_ORG_S3_ACCESS=")) access = unquote(line.slice("ARCHIVE_ORG_S3_ACCESS=".length));
+ if (line.startsWith("ARCHIVE_ORG_S3_SECRET=")) secret = unquote(line.slice("ARCHIVE_ORG_S3_SECRET=".length));
+ }
+ if (!access || !secret) {
+ return { ok: false, reason: `${keyFile} has no ARCHIVE_ORG_S3_ACCESS= and ARCHIVE_ORG_S3_SECRET= lines; Save Page Now is off.` };
+ }
+ return { ok: true, keys: { access, secret }, from: "file" };
+}
+
+// Replace the keys wherever they appear in a text: the last line of defence
+// for a message that leaves the module.
+export function redactSpnKeys(text: string, keys: SpnKeys | undefined): string {
+ if (!keys) return text;
+ let out = text;
+ for (const k of [keys.secret, keys.access]) if (k && k.length >= 4) out = out.split(k).join("[redacted]");
+ return out;
+}
diff --git a/common/lib/waybackPages/savePageNow.ts b/common/lib/waybackPages/savePageNow.ts
@@ -0,0 +1,106 @@
+// SAVE PAGE NOW (release 37 S5) — asking the Wayback Machine to capture a
+// live page now, through its SPN2 API (archive.org's documented
+// "Save Page Now 2 Public API"):
+//
+// POST https://web.archive.org/save
+// Authorization: LOW <access>:<secret> (archive.org's S3 keys)
+// Accept: application/json
+// url=<page>&capture_outlinks=0 (the page alone)
+// → {url, job_id} or {status: "error", status_ext, message}
+// GET https://web.archive.org/save/status/<job_id>
+// → {status: "pending"} ask again later
+// → {status: "success", timestamp, original_url}
+// → {status: "error", status_ext, message}
+//
+// Pure: what the answers mean. The keys, the requests and the job are
+// ./savePageNow-server.ts and controller/savePageNow.ts.
+
+// The archive's origin, spelled here (lib/waybackClient.ts's WAYBACK_ORIGIN
+// carries node:fs with it); the process client sends it to a test's fake.
+const ORIGIN = "https://web.archive.org";
+
+export const SPN_SAVE_URL = `${ORIGIN}/save`;
+
+export function spnStatusUrl(jobId: string): string {
+ return `${ORIGIN}/save/status/${encodeURIComponent(jobId)}`;
+}
+
+// The form a capture request sends: the page alone, no outlinks.
+export function spnSaveBody(url: string): string {
+ return new URLSearchParams({ url, capture_outlinks: "0" }).toString();
+}
+
+export type SpnKeys = { access: string; secret: string };
+
+// The Authorization header's value. Never logged.
+export function spnAuthorization(keys: SpnKeys): string {
+ return `LOW ${keys.access}:${keys.secret}`;
+}
+
+export type SpnSubmit = { ok: true; jobId: string } | { ok: false; error: string; code?: string };
+
+const json = (text: string): Record<string, unknown> | null => {
+ try {
+ const v = JSON.parse(text) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+};
+
+const str = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
+
+// What archive.org answered a capture request. A 401/403 is the keys; an
+// error body names its `status_ext` (error:too-many-daily-captures, …).
+export function parseSpnSubmit(status: number, text: string): SpnSubmit {
+ const body = json(text);
+ if (status === 401 || status === 403) {
+ return { ok: false, code: "auth", error: `archive.org refused the S3 keys (HTTP ${status}); check them at archive.org/account/s3.php` };
+ }
+ const jobId = str(body?.job_id);
+ if (status >= 200 && status < 300 && jobId) return { ok: true, jobId };
+ const ext = str(body?.status_ext);
+ const message = str(body?.message);
+ return {
+ ok: false,
+ ...(ext ? { code: ext } : {}),
+ error: `Save Page Now refused the capture (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`,
+ };
+}
+
+export type SpnStatus =
+ | { state: "pending" }
+ | { state: "success"; timestamp: string; originalUrl: string }
+ | { state: "error"; error: string; code?: string };
+
+// What a status poll answered.
+export function parseSpnStatus(status: number, text: string): SpnStatus {
+ const body = json(text);
+ if (status === 401 || status === 403) {
+ return { state: "error", code: "auth", error: `archive.org refused the S3 keys (HTTP ${status})` };
+ }
+ const state = str(body?.status);
+ if (status >= 200 && status < 300 && state === "pending") return { state: "pending" };
+ if (status >= 200 && status < 300 && state === "success") {
+ const timestamp = str(body?.timestamp);
+ const originalUrl = str(body?.original_url);
+ if (/^\d{14}$/.test(timestamp) && /^https?:\/\//i.test(originalUrl)) return { state: "success", timestamp, originalUrl };
+ return { state: "error", error: "Save Page Now said success but named no capture (timestamp, original_url)" };
+ }
+ const ext = str(body?.status_ext);
+ const message = str(body?.message);
+ return {
+ state: "error",
+ ...(ext ? { code: ext } : {}),
+ error: `the capture failed (HTTP ${status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}`,
+ };
+}
+
+// Why Save Page Now is off, in the sentence the button shows, when no keys
+// are configured.
+export function spnOffSentence(keyFile: string): string {
+ return (
+ `Save Page Now needs archive.org S3 keys: ARCHIVE_ORG_S3_ACCESS and ARCHIVE_ORG_S3_SECRET in the editor's ` +
+ `environment, or in ${keyFile} (mode 600; settings archiveOrg.s3KeyFile).`
+ );
+}
diff --git a/common/publish/findCopyPages.test.ts b/common/publish/findCopyPages.test.ts
@@ -0,0 +1,229 @@
+// Release 37 S5: find-copy's page mode on the fake Wayback — a cited page
+// whose original is gone gets the capture nearest its date imported into the
+// channel whose targets cover it, and the answer names the record to cite (and
+// the citation as a post citation of it); a dry run imports nothing; a live
+// page, an uncovered one and one the archive never captured are left with
+// their reason; a page already held is not fetched again; a cited page record
+// whose original is gone is "held" when its capture is stored, imported again
+// when it is not. The original sites are a stub; no network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/findCopyPages.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import {
+ startFakeWayback,
+ PAGE_ARTICLE_LATER_TS,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ PAGE_TOOLBAR_TS,
+ PAGE_TOOLBAR_URL,
+} from "../testing/web/fakeWayback.mjs";
+import type { Paths } from "../lib/paths";
+import type { Citation } from "../lib/citations/schema";
+import type { ReportHost } from "./reportHost";
+import type { OriginalCheck } from "../lib/waybackPages/liveness";
+import { WaybackClient } from "../lib/waybackClient";
+import { readAllPosts, upsertPosts, writePostAvailability } from "../lib/posts-server";
+import { pageRecordId } from "../lib/waybackPages/types";
+import { importPage } from "../controller/importPage";
+import { captureAtOf, channelsCovering, findPageCopies, pageCitationAsPost, recordForQuote, targetCoversUrl } from "./findCopyPages";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "find-page-copy-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths;
+const SETTINGS = { social: { x: { visibility: "private" } } };
+const HOST = { id: "demo-site" } as unknown as ReportHost;
+const NOW = new Date("2026-10-20T12:00:00Z");
+
+async function pagesChannel(slug: string, target: string, match = "prefix") {
+ const dir = path.join(paths.channelsDir, slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ name: slug,
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: target.split("/")[0],
+ url: `https://web.archive.org/web/*/${target}*`,
+ wayback: { targets: [{ url: target, match }] },
+ }),
+ );
+ return dir;
+}
+
+const verdict = (url: string, availability: OriginalCheck["availability"], status: number | null): OriginalCheck => ({
+ url,
+ availability,
+ status,
+ reason: status ? `HTTP ${status}` : "no answer",
+});
+
+test("which channel covers a page; the date a citation asks for; the record a quote is from; a page citation as a post", () => {
+ assert.equal(targetCoversUrl({ url: "blog.example/2014/", match: "prefix" }, "https://www.blog.example/2014/03/a.html"), true);
+ assert.equal(targetCoversUrl({ url: "blog.example/2015/", match: "prefix" }, "https://blog.example/2014/03/a.html"), false);
+ assert.equal(targetCoversUrl({ url: "https://blog.example/a", match: "exact" }, "http://blog.example/a/"), true);
+ assert.equal(targetCoversUrl({ url: "blog.example", match: "host" }, "https://sub.blog.example/"), false);
+ assert.equal(targetCoversUrl({ url: "blog.example", match: "domain" }, "https://sub.blog.example/"), true);
+ assert.deepEqual(
+ channelsCovering(
+ [
+ { slug: "vids", config: { url: "x" } as never },
+ { slug: "blog", config: { sourceKind: "social", platform: "webpage", wayback: { targets: [{ url: "blog.example", match: "host" }] } } },
+ ],
+ "https://blog.example/a",
+ ),
+ ["blog"],
+ );
+ assert.equal(captureAtOf({ date: "2015-06-01" }, NOW), "20150601");
+ assert.equal(captureAtOf({ date: "2015" }, NOW), "2015");
+ assert.equal(captureAtOf({ archiveUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` }, NOW), PAGE_ARTICLE_TS);
+ assert.equal(captureAtOf({}, NOW), "20261020");
+ assert.equal(recordForQuote([{ id: "a", text: "one thing" }, { id: "b", text: "Another “thing” said" }], 'another "thing"'), "b");
+ assert.equal(recordForQuote([{ id: "a", text: "x" }], "not there"), "a");
+ assert.deepEqual(
+ pageCitationAsPost({ kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x", quote: "q", label: "L", note: "n" }, { channel: "blog", id: "r1" }),
+ { kind: "post", channel: "blog", id: "r1", quote: "q", label: "L", note: "n" },
+ );
+});
+
+test("a gone cited page: dry run names the nearest capture; the run imports it and names the record to cite; again = held", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 });
+ const dir = await pagesChannel("old-blog", "blog.example/");
+ const citations: Record<string, Citation> = {
+ c1: { kind: "page", url: PAGE_ARTICLE_URL, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" },
+ c2: { kind: "page", url: "https://live.example/up", quote: "still here" },
+ c3: { kind: "page", url: "https://elsewhere.example/gone", quote: "nobody covers this" },
+ c4: { kind: "page", url: "https://blog.example/never-captured.html", quote: "never captured" },
+ c5: { kind: "video", channel: "v", id: "abc", start: 1, end: 2, quote: "a video" },
+ };
+ const reports = [
+ { id: "r1", citations },
+ { id: "r2", citations: { x1: { kind: "page", url: PAGE_ARTICLE_URL, quote: "The first loaf came out flat" } as Citation } },
+ ];
+ const checks = new Map<string, OriginalCheck>([
+ [PAGE_ARTICLE_URL, verdict(PAGE_ARTICLE_URL, "deleted", 404)],
+ ["https://live.example/up", verdict("https://live.example/up", "available", 200)],
+ ["https://elsewhere.example/gone", verdict("https://elsewhere.example/gone", "deleted", 410)],
+ ["https://blog.example/never-captured.html", verdict("https://blog.example/never-captured.html", "deleted", 404)],
+ ]);
+ const asked: string[] = [];
+ const deps = {
+ reports: async () => reports,
+ check: async (url: string) => {
+ asked.push(url);
+ return checks.get(url) ?? verdict(url, "error", null);
+ },
+ nearest: (url: string, at: string) => client.closestCapture(url, at),
+ importCapture: (o: { slug: string; url: string }) => importPage({ paths, slug: o.slug, url: o.url, client, settings: SETTINGS }),
+ now: () => NOW,
+ };
+ const lines: string[] = [];
+ const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps, onLog: (l) => lines.push(l) });
+ assert.deepEqual([dry.pages, dry.posts], [4, 0]);
+ const byUrl = (r: typeof dry) => new Map(r.items.map((i) => [i.url, i]));
+ const d = byUrl(dry);
+ assert.equal(d.get(PAGE_ARTICLE_URL)!.outcome, "would-import");
+ assert.equal(d.get(PAGE_ARTICLE_URL)!.capture!.timestamp, PAGE_ARTICLE_LATER_TS, "the capture nearest 2015-06");
+ assert.deepEqual(d.get(PAGE_ARTICLE_URL)!.citedBy, ["r1#c1", "r2#x1"]);
+ assert.equal(d.get("https://live.example/up")!.outcome, "live");
+ assert.equal(d.get("https://elsewhere.example/gone")!.outcome, "no-channel");
+ assert.equal(d.get("https://blog.example/never-captured.html")!.outcome, "none-found");
+ assert.deepEqual(await readAllPosts(dir), [], "a dry run imports nothing");
+ assert.ok(lines.some((l) => /1 capture\(s\) would be imported \(dry run: nothing imported\)/.test(l)));
+
+ const run = await findPageCopies({ paths, host: HOST, deps });
+ const item = byUrl(run).get(PAGE_ARTICLE_URL)!;
+ const id = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL);
+ assert.equal(item.outcome, "imported", item.detail);
+ assert.deepEqual(item.pointTo, { channel: "old-blog", id });
+ assert.deepEqual(item.as, { kind: "post", channel: "old-blog", id, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" });
+ assert.deepEqual((await readAllPosts(dir)).map((p) => p.id), [id]);
+
+ // Again: the channel holds the page — nothing fetched.
+ const before = wb.requests.length;
+ const again = await findPageCopies({ paths, host: HOST, deps });
+ assert.equal(byUrl(again).get(PAGE_ARTICLE_URL)!.outcome, "held");
+ assert.deepEqual(byUrl(again).get(PAGE_ARTICLE_URL)!.pointTo, { channel: "old-blog", id });
+ assert.equal(wb.requests.length - before, 1, "only the never-captured page's CDX lookup");
+
+ // `max` leaves the rest for a later run.
+ const capped = await findPageCopies({ paths, host: HOST, deps, max: 1, dryRun: true });
+ assert.deepEqual([capped.items.length, capped.left], [1, 3]);
+
+ // A named channel that is not a pages channel is refused.
+ await assert.rejects(findPageCopies({ paths, host: HOST, deps, channel: "nope" }), /not a Wayback pages channel/);
+ } finally {
+ await wb.close();
+ }
+});
+
+test("a cited page record whose original is gone: held when its capture is stored, imported again when it is not", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0 });
+ const dir = await pagesChannel("home-site", "home.example/");
+ // One record whose capture is stored (imported), one whose is not (its
+ // record written alone).
+ const imp = await importPage({ paths, slug: "home-site", url: `https://web.archive.org/web/${PAGE_TOOLBAR_TS}/${PAGE_TOOLBAR_URL}`, client, settings: SETTINGS });
+ assert.equal(imp.ok, true, imp.error);
+ const stored = imp.records![0]!;
+ const loose = (await readAllPosts(dir))[0]!;
+ const looseUrl = "https://home.example/links";
+ const looseTs = "20150101000000";
+ const looseId = pageRecordId(looseTs, looseUrl);
+ await upsertPosts(dir, [
+ {
+ ...loose,
+ id: looseId,
+ slug: `home-site/${looseId}`,
+ url: looseUrl,
+ page: { ...loose.page!, originalUrl: looseUrl, captureTs: looseTs, waybackUrl: `https://web.archive.org/web/${looseTs}/${looseUrl}`, rawUrl: `https://web.archive.org/web/${looseTs}id_/${looseUrl}` },
+ },
+ ]);
+ await writePostAvailability(dir, {
+ [stored]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" },
+ [looseId]: { availability: "deleted", checkedAt: "2026-10-19T00:00:00Z", status: 404, reason: "HTTP 404" },
+ });
+ const imported: string[] = [];
+ const deps = {
+ reports: async () => [
+ {
+ id: "r9",
+ citations: {
+ a: { kind: "post", channel: "home-site", id: stored, quote: "zines" } as Citation,
+ b: { kind: "post", channel: "home-site", id: looseId, quote: "links" } as Citation,
+ c: { kind: "post", channel: "not-a-pages-channel", id: "1", quote: "x" } as Citation,
+ },
+ },
+ ],
+ check: async (url: string) => verdict(url, "error", null),
+ nearest: (url: string, at: string) => client.closestCapture(url, at),
+ importCapture: async (o: { slug: string; url: string }) => {
+ imported.push(o.url);
+ return { ok: true, slug: o.slug, url: o.url, written: 0, updated: 0, unchanged: 1, records: [looseId] };
+ },
+ now: () => NOW,
+ };
+ const dry = await findPageCopies({ paths, host: HOST, dryRun: true, deps });
+ assert.equal(dry.posts, 2);
+ const of = (r: typeof dry, id: string) => r.items.find((i) => i.record?.id === id)!;
+ assert.equal(of(dry, stored).outcome, "held");
+ assert.equal(of(dry, looseId).outcome, "would-import");
+ assert.deepEqual(imported, []);
+ const run = await findPageCopies({ paths, host: HOST, deps });
+ assert.equal(of(run, looseId).outcome, "imported");
+ assert.deepEqual(imported, [`https://web.archive.org/web/${looseTs}/${looseUrl}`]);
+ assert.deepEqual(of(run, stored).pointTo, { channel: "home-site", id: stored });
+ } finally {
+ await wb.close();
+ }
+});
diff --git a/common/publish/findCopyPages.ts b/common/publish/findCopyPages.ts
@@ -0,0 +1,434 @@
+// FIND A COPY OF A GONE PAGE A REPORT CITES (release 37 S5) — find-copy's
+// page mode, beside its video modes (./findCopy.ts). A report cites a web page
+// either as a `page` citation (`{url, archiveUrl?}`: the page is not in the
+// corpus) or as a `post` citation of a page record (a Wayback Machine capture
+// already imported into a Wayback pages channel). When the page's ORIGINAL is
+// gone, the Wayback Machine's copy is the only copy, and the report should
+// cite it as a record:
+//
+// a `page` citation its original URL asked at its own site
+// (lib/waybackPages/liveness-server.ts, the web pacer);
+// gone (deleted, or the account/document unavailable) →
+// the capture NEAREST the citation's date (its `date`,
+// else its archiveUrl's timestamp, else today: the latest)
+// through ONE CDX request (WaybackClient.closestCapture),
+// imported into the Wayback pages channel named
+// (`channel`) or the one whose targets cover the URL
+// (import-page, controller/importPage.ts) — unless that
+// channel already holds a record of the page. Live: left
+// (Save Page Now is the act for a live page). The answer
+// names the record the citation should cite (`pointTo`)
+// and the citation as a `post` citation of it (`as`).
+// a `post` citation of a page record whose original the availability
+// check found deleted: its capture is held (nothing to
+// do) or, when its raw body is not stored, imported again.
+//
+// THE CITATION IS NOT REWRITTEN HERE: `pointTo`/`as` are what the report's
+// citation becomes (the report editor's "Import this capture" rewrites a page
+// citation to a post citation and keeps the page citation as its fallback;
+// release 37 lane D). A dry run asks the same paced questions and imports
+// nothing.
+//
+// PACED: one page at a time, at most `max` lookups per run; every Wayback
+// request goes through the process's Wayback client (one stream, 2 s apart,
+// 429s waited out — a refusal stops the run there), every original-site
+// request through the web pacer. The job runs on the archive.org queue.
+
+import { nearestAcrossSources } from "../lib/archives/index";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema";
+import type { Post } from "../lib/posts";
+import { readAllPosts, readPostAvailability } from "../lib/posts-server";
+import { listChannelConfigs } from "../controller/channels";
+import { isWaybackPagesChannel, type WaybackTarget } from "../lib/waybackPages/config";
+import { bareHost, type OriginalCheck } from "../lib/waybackPages/liveness";
+import { checkOriginalUrl, type CheckOriginalOptions } from "../lib/waybackPages/liveness-server";
+import { hasStoredCapture } from "../lib/waybackPages/store-server";
+import { parseWaybackUrl, waybackPageUrl } from "../lib/wayback";
+import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
+import { waybackClient, type WaybackCapture, type WaybackClient } from "../lib/waybackClient";
+import { importPage, type ImportPageResult } from "../controller/importPage";
+import { loadHostReports } from "./reportMedia";
+import type { ReportHost } from "./reportHost";
+
+export const FIND_PAGE_COPY_DEFAULT_MAX = 10;
+export const FIND_PAGE_COPY_MAX_LIMIT = 100;
+
+// ─── Which channel a page belongs in ───
+
+const bare = (u: string) =>
+ u
+ .trim()
+ .replace(/^https?:\/\//i, "")
+ .replace(/^www\./i, "")
+ .replace(/#.*$/, "")
+ .replace(/\/+$/, "")
+ .toLowerCase();
+
+// Whether a Wayback pages channel's target covers a page.
+export function targetCoversUrl(target: Pick<WaybackTarget, "url" | "match">, url: string): boolean {
+ const host = bareHost(/^https?:\/\//i.test(url) ? url : `https://${url}`);
+ const targetHost = bareHost(/^https?:\/\//i.test(target.url) ? target.url : `https://${target.url}`);
+ if (!host || !targetHost) return false;
+ switch (target.match) {
+ case "exact":
+ return bare(url) === bare(target.url);
+ case "prefix":
+ return bare(url).startsWith(bare(target.url));
+ case "host":
+ return host === targetHost;
+ case "domain":
+ return host === targetHost || host.endsWith(`.${targetHost}`);
+ default:
+ return false;
+ }
+}
+
+// The Wayback pages channels whose targets cover `url`, by slug.
+export function channelsCovering(
+ channels: ReadonlyArray<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>,
+ url: string,
+): string[] {
+ return channels
+ .filter((c) => isWaybackPagesChannel(c.config) && (c.config.wayback?.targets ?? []).some((t) => targetCoversUrl(t, url)))
+ .map((c) => c.slug);
+}
+
+// ─── What the reports cite ───
+
+export type CitedPage = {
+ // `<report>#<citation id>` of each citation of it.
+ citedBy: string[];
+ url: string;
+ // The citation's own date or archive copy, for the nearest capture.
+ at?: string;
+ // The first citation's words (to pick the record of a split capture).
+ quote: string;
+ citation: PageCitation;
+};
+
+export type CitedPageRecord = {
+ citedBy: string[];
+ channel: string;
+ id: string;
+};
+
+// "2014-03-05…" / "2014-03" / "2014" → a capture time prefix.
+export function captureAtOf(c: Pick<PageCitation, "date" | "archiveUrl">, today: Date): string {
+ const d = /^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?/.exec(c.date ?? "");
+ if (d) return `${d[1]}${d[2] ?? ""}${d[3] ?? ""}`;
+ const ref = parseWaybackUrl(c.archiveUrl ?? "");
+ if (ref && /^\d{4,14}$/.test(ref.captureTs)) return ref.captureTs;
+ return today.toISOString().slice(0, 10).replaceAll("-", "");
+}
+
+export function citedPages(
+ reports: ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>,
+ today: Date,
+): { pages: CitedPage[]; posts: CitedPageRecord[] } {
+ const pages = new Map<string, CitedPage>();
+ const posts = new Map<string, CitedPageRecord>();
+ for (const r of reports) {
+ for (const [cid, c] of Object.entries(r.citations ?? {})) {
+ const by = `${r.id}#${cid}`;
+ if (c.kind === "page") {
+ if (!/^https?:\/\//i.test(c.url)) continue;
+ const key = bare(c.url);
+ const seen = pages.get(key);
+ if (seen) seen.citedBy.push(by);
+ else pages.set(key, { citedBy: [by], url: c.url.trim(), at: captureAtOf(c, today), quote: c.quote, citation: c });
+ } else if (c.kind === "post") {
+ const key = `${c.channel}/${c.id}`;
+ const seen = posts.get(key);
+ if (seen) seen.citedBy.push(by);
+ else posts.set(key, { citedBy: [by], channel: c.channel, id: c.id });
+ }
+ }
+ }
+ return { pages: [...pages.values()], posts: [...posts.values()] };
+}
+
+// The record a quote is from, among a capture's records: the one whose text
+// holds the quote's words, else the first (a whole page's one record).
+export function recordForQuote(records: ReadonlyArray<Pick<Post, "id" | "text">>, quote: string): string | null {
+ if (records.length === 0) return null;
+ const fold = (s: string) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, " ").trim().toLowerCase();
+ const q = fold(quote);
+ if (q) {
+ const hit = records.find((r) => fold(r.text).includes(q));
+ if (hit) return hit.id;
+ }
+ return records[0]!.id;
+}
+
+// A page citation as a post citation of the record: its words and editorial
+// fields kept; the record carries the URL, the title and the Wayback copy.
+export function pageCitationAsPost(c: PageCitation, pointTo: { channel: string; id: string }): PostCitation {
+ const { kind: _kind, url: _url, title: _title, archiveUrl: _archive, ...common } = c;
+ return { kind: "post", channel: pointTo.channel, id: pointTo.id, ...common };
+}
+
+// ─── find-copy, page mode ───
+
+export type FindPageCopyOutcome =
+ // imported the nearest capture imported; `pointTo` is its record
+ // would-import (dry run) what an import would fetch
+ // held the channel already holds a record of the page (or the
+ // cited record's capture is stored): nothing fetched
+ // live the original still answers: left (Save Page Now it)
+ // none-found the Wayback Machine holds no capture that recorded a page
+ // no-channel no Wayback pages channel covers the URL and none was named
+ // refused the import was refused (its sentence: X, a video, …)
+ // error a check or a lookup failed: a later run asks again
+ | "imported"
+ | "would-import"
+ | "held"
+ | "live"
+ | "none-found"
+ | "no-channel"
+ | "refused"
+ | "error";
+
+export type FindPageCopyItem = {
+ citedBy: string[];
+ // The page cited, or the record cited.
+ url: string;
+ record?: { channel: string; id: string };
+ original?: Pick<OriginalCheck, "availability" | "status" | "reason">;
+ channel?: string;
+ capture?: { timestamp: string; original: string; waybackUrl: string };
+ outcome: FindPageCopyOutcome;
+ detail: string;
+ pointTo?: { channel: string; id: string };
+ // The citation as a post citation of `pointTo` (a page citation only).
+ as?: PostCitation;
+ records?: string[];
+};
+
+export type FindPageCopiesResult = {
+ host: string;
+ dryRun: boolean;
+ max: number;
+ pages: number;
+ posts: number;
+ items: FindPageCopyItem[];
+ // Cited pages left for a later run by `max`.
+ left: number;
+ stopped?: string;
+};
+
+export type FindPageCopiesDeps = {
+ reports: (host: ReportHost) => Promise<ReadonlyArray<{ id: string; citations?: Record<string, Citation> }>>;
+ channels: (paths: Paths) => Promise<Array<{ slug: string; config: { sourceKind?: string; platform?: string; wayback?: { targets?: WaybackTarget[] } } }>>;
+ check: (url: string, signal?: AbortSignal) => Promise<OriginalCheck>;
+ // THE ONE CAPTURE LOOKUP: the capture of `url` nearest `at` (default: the
+ // Wayback Machine's CDX `closest`). An archive-source registry can stand in
+ // here without the rest of the mode changing.
+ nearest: (url: string, at: string, signal?: AbortSignal) => Promise<WaybackCapture | null>;
+ importCapture: (o: { slug: string; url: string; signal?: AbortSignal; onLog?: (line: string) => void }) => Promise<ImportPageResult>;
+ now: () => Date;
+};
+
+export function defaultFindPageCopiesDeps(paths: Paths, o: { check?: CheckOriginalOptions; client?: WaybackClient } = {}): FindPageCopiesDeps {
+ const client = o.client ?? waybackClient;
+ return {
+ reports: async (host) => (await loadHostReports(host)).reports,
+ channels: (p) => listChannelConfigs(p),
+ check: (url, signal) => checkOriginalUrl(url, { ...o.check, ...(signal ? { signal } : {}) }),
+ // Release 37 lane F: across archive sources (the Wayback Machine, then
+ // archive.today); a row's copy URL is its replayUrl, so the import reads
+ // whichever source holds it. A Wayback client given here keeps the
+ // Wayback-only lookup (tests).
+ nearest: o.client
+ ? (url, at, signal) => client.closestCapture(url, at, signal ? { signal } : {})
+ : async (url, at, signal) => {
+ const row = await nearestAcrossSources(url, at, signal ? { signal } : {});
+ return row
+ ? { timestamp: row.captureTs, original: row.originalUrl, status: row.status ?? "200", replayUrl: row.mementoUrl, ...(row.mimetype ? { mimetype: row.mimetype } : {}) }
+ : null;
+ },
+ importCapture: (io) => importPage({ paths, slug: io.slug, url: io.url, client, ...(io.signal ? { signal: io.signal } : {}), ...(io.onLog ? { onLog: io.onLog } : {}) }),
+ now: () => new Date(),
+ };
+}
+
+const GONE = new Set(["deleted", "account_unavailable"]);
+
+export async function findPageCopies(opts: {
+ paths: Paths;
+ host: ReportHost;
+ // The Wayback pages channel every capture goes to (else: the one whose
+ // targets cover the page).
+ channel?: string;
+ dryRun?: boolean;
+ max?: number;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ deps?: Partial<FindPageCopiesDeps>;
+}): Promise<FindPageCopiesResult> {
+ const deps: FindPageCopiesDeps = { ...defaultFindPageCopiesDeps(opts.paths), ...opts.deps };
+ const log = (line: string) => opts.onLog?.(line);
+ const signal = opts.signal;
+ const dryRun = opts.dryRun === true;
+ const max = Math.min(FIND_PAGE_COPY_MAX_LIMIT, Math.max(1, Math.floor(opts.max ?? FIND_PAGE_COPY_DEFAULT_MAX)));
+ const today = deps.now();
+ const cited = citedPages(await deps.reports(opts.host), today);
+ const channels = await deps.channels(opts.paths);
+ const pagesChannels = new Set(channels.filter((c) => isWaybackPagesChannel(c.config)).map((c) => c.slug));
+ if (opts.channel && !pagesChannels.has(opts.channel)) {
+ throw new Error(`${opts.channel} is not a Wayback pages channel; name one on platform "webpage", or none (the channel whose targets cover each page)`);
+ }
+ // The post citations of page records only.
+ const postCitations = cited.posts.filter((p) => pagesChannels.has(p.channel));
+ const result: FindPageCopiesResult = { host: opts.host.id, dryRun, max, pages: cited.pages.length, posts: postCitations.length, items: [], left: 0 };
+ log(
+ `find-copy ${opts.host.id} (pages${dryRun ? ", dry run" : ""}): ${cited.pages.length} cited page(s), ` +
+ `${postCitations.length} cited page record(s); at most ${max} looked up.`,
+ );
+ const recordsOf = new Map<string, Post[]>();
+ const channelRecords = async (slug: string): Promise<Post[]> => {
+ let list = recordsOf.get(slug);
+ if (!list) {
+ list = (await readAllPosts(path.join(opts.paths.channelsDir, slug)).catch(() => [] as Post[])).filter((p) => p.page);
+ recordsOf.set(slug, list);
+ }
+ return list;
+ };
+
+ let lookups = 0;
+ const stopOn = (e: unknown): string | null =>
+ e instanceof ArchiveOrgRequestError && e.rateLimited ? `archive.org kept refusing (${e.message}); the rest are left for a later run` : null;
+
+ // 1. Cited pages.
+ for (const page of cited.pages) {
+ if (signal?.aborted || result.stopped) break;
+ if (lookups >= max) {
+ result.left++;
+ continue;
+ }
+ lookups++;
+ const item: FindPageCopyItem = { citedBy: page.citedBy, url: page.url, outcome: "error", detail: "" };
+ result.items.push(item);
+ const checked = await deps.check(page.url, signal);
+ item.original = { availability: checked.availability, status: checked.status, reason: checked.reason };
+ if (checked.availability === "available") {
+ item.outcome = "live";
+ item.detail = `the original still answers (${checked.reason}): left — Save Page Now captures a live page`;
+ } else if (!GONE.has(checked.availability)) {
+ item.outcome = "error";
+ item.detail = `the original could not be checked (${checked.reason}): try again later`;
+ } else {
+ const covering = opts.channel ? [opts.channel] : channelsCovering(channels, page.url);
+ const slug = covering[0];
+ if (!slug) {
+ item.outcome = "no-channel";
+ item.detail = `the original is gone (${checked.reason}), and no Wayback pages channel covers ${bareHost(page.url) || page.url}: name one ("channel") or create one targeting it`;
+ } else {
+ item.channel = slug;
+ const held = (await channelRecords(slug)).filter((r) => bare(r.page!.originalUrl) === bare(page.url));
+ if (held.length > 0) {
+ const id = recordForQuote(held, page.quote)!;
+ item.outcome = "held";
+ item.pointTo = { channel: slug, id };
+ item.as = pageCitationAsPost(page.citation, item.pointTo);
+ item.detail = `the original is gone (${checked.reason}); ${slug} already holds ${held.length} record(s) of the page`;
+ } else {
+ try {
+ const near: WaybackCapture | null = await deps.nearest(page.url, page.at ?? "", signal);
+ if (!near) {
+ item.outcome = "none-found";
+ item.detail = `the original is gone (${checked.reason}), and no archive source holds a copy of it that recorded a page`;
+ } else {
+ // The copy's own URL (a Wayback replay URL, or an archive.today
+ // copy's from the source registry — release 37 lane F).
+ const waybackUrl = near.replayUrl || waybackPageUrl({ captureTs: near.timestamp, originalUrl: near.original });
+ item.capture = { timestamp: near.timestamp, original: near.original, waybackUrl };
+ if (dryRun) {
+ item.outcome = "would-import";
+ item.detail = `the original is gone (${checked.reason}); would import the capture ${near.timestamp} (nearest ${page.at}) into ${slug}`;
+ } else {
+ const imp = await deps.importCapture({ slug, url: waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) });
+ if (!imp.ok) {
+ // archive.org kept refusing (the client's sentence): stop the run there.
+ const busy = /did not answer .* attempts/.test(imp.error ?? "");
+ item.outcome = busy ? "error" : "refused";
+ item.detail = busy ? (imp.error ?? "") : `the import was refused: ${imp.error}`;
+ if (busy) result.stopped = `archive.org kept refusing (${imp.error}); the rest are left for a later run`;
+ } else {
+ recordsOf.delete(slug);
+ const records = (await channelRecords(slug)).filter((r) => (imp.records ?? []).includes(r.id));
+ const id = recordForQuote(records.length ? records : (imp.records ?? []).map((rid) => ({ id: rid, text: "" })), page.quote);
+ item.outcome = "imported";
+ item.records = imp.records ?? [];
+ if (id) {
+ item.pointTo = { channel: slug, id };
+ item.as = pageCitationAsPost(page.citation, item.pointTo);
+ }
+ item.detail = `the original is gone (${checked.reason}); ${imp.already ? "the capture was already stored" : "imported"} the capture ${imp.captureTs} into ${slug}`;
+ }
+ }
+ }
+ } catch (e) {
+ if (signal?.aborted) break;
+ item.outcome = "error";
+ item.detail = (e as Error).message;
+ const stop = stopOn(e);
+ if (stop) result.stopped = stop;
+ }
+ }
+ }
+ }
+ log(` ${page.url} (${page.citedBy.join(", ")}): ${item.outcome} — ${item.detail}${item.pointTo ? ` → cite ${item.pointTo.channel}/${item.pointTo.id}` : ""}`);
+ }
+
+ // 2. Cited page records whose original the availability check found gone.
+ for (const cite of postCitations) {
+ if (signal?.aborted || result.stopped) break;
+ const channelRoot = path.join(opts.paths.channelsDir, cite.channel);
+ const av = (await readPostAvailability(channelRoot))[cite.id];
+ if (!av || !GONE.has(av.availability)) continue;
+ const record = (await channelRecords(cite.channel)).find((r) => r.id === cite.id);
+ if (!record?.page) continue;
+ const item: FindPageCopyItem = {
+ citedBy: cite.citedBy,
+ url: record.page.originalUrl,
+ record: { channel: cite.channel, id: cite.id },
+ original: { availability: av.availability, status: av.status ?? null, reason: av.reason ?? "the availability check" },
+ channel: cite.channel,
+ capture: { timestamp: record.page.captureTs, original: record.page.originalUrl, waybackUrl: record.page.waybackUrl },
+ outcome: "held",
+ detail: "",
+ pointTo: { channel: cite.channel, id: cite.id },
+ };
+ result.items.push(item);
+ if (await hasStoredCapture(channelRoot, record.page.captureTs, record.page.originalUrl)) {
+ item.detail = `the original is gone (${item.original!.reason}); the record's capture is held — the Wayback copy is the only copy`;
+ } else if (dryRun) {
+ item.outcome = "would-import";
+ item.detail = `the original is gone; the record's capture is not stored: would import ${record.page.waybackUrl} into ${cite.channel}`;
+ } else {
+ try {
+ const imp = await deps.importCapture({ slug: cite.channel, url: record.page.waybackUrl, ...(signal ? { signal } : {}), onLog: (l) => log(` ${l}`) });
+ item.outcome = imp.ok ? "imported" : "refused";
+ item.records = imp.records ?? [];
+ item.detail = imp.ok ? `the original is gone; the record's capture imported again into ${cite.channel}` : `the import was refused: ${imp.error}`;
+ } catch (e) {
+ if (signal?.aborted) break;
+ item.outcome = "error";
+ item.detail = (e as Error).message;
+ const stop = stopOn(e);
+ if (stop) result.stopped = stop;
+ }
+ }
+ log(` ${cite.channel}/${cite.id} (${cite.citedBy.join(", ")}): ${item.outcome} — ${item.detail}`);
+ }
+
+ if (signal?.aborted && !result.stopped) result.stopped = "cancelled; the rest are left for a later run";
+ if (result.stopped) log(`find-copy: ${result.stopped}.`);
+ if (result.left > 0) log(`find-copy: ${result.left} more cited page(s) are left for a later run (max ${max}).`);
+ const imported = result.items.filter((i) => i.outcome === "imported").length;
+ const would = result.items.filter((i) => i.outcome === "would-import").length;
+ log(`find-copy: ${dryRun ? `${would} capture(s) would be imported (dry run: nothing imported)` : `${imported} capture(s) imported`}.`);
+ return result;
+}
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. |
| `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. |
| `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. |
-| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. |
+| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane E): Save Page Now — `POST /save` (the fake keys `FAKE_SPN_ACCESS`/`FAKE_SPN_SECRET` in `Authorization: LOW …`, else 401; `spn.busyTimes` 429s; `spn.refuseUrls` answered `error:blocked-url`) and `GET /save/status/<job>` (`spn.pendingPolls` pending, then success at `SPN_CAPTURE_TS`, or `spn.failUrls` → `error:not-found`); a saved page is then served raw like a page capture (`spn.pages[url]` or a synthetic page); `wb.spnForms`, `wb.spnCaptures`. |
| `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. |
| `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. |
| `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. |
diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts
@@ -27,9 +27,17 @@ export const PAGE_JUMP_URL: string;
export const PAGE_JUMP_TS: string;
export const VIDEOS: string[];
+// Release 37 (lane E): Save Page Now.
+export const FAKE_SPN_ACCESS: string;
+export const FAKE_SPN_SECRET: string;
+export const SPN_CAPTURE_TS: string;
+
export type FakeWayback = {
base: string;
- requests: { path: string; at: number }[];
+ requests: { path: string; at: number; method?: string }[];
+ // (release 37 lane E) the SPN forms posted, and the captures SPN made.
+ spnForms: Record<string, string>[];
+ spnCaptures: FakePageCapture[];
fetch(url: string | URL, init?: RequestInit): Promise<Response>;
close(): Promise<void>;
};
@@ -48,6 +56,19 @@ export function startFakeWayback(opts?: {
excluded?: string[];
// (release 37 S2) the Nth scan listing request and every one after answer 503.
scanRefuseFrom?: number;
+ // (release 37 lane E) Save Page Now: the keys it takes, 429s first, polls
+ // answered pending, URLs whose capture fails or is refused, bodies by URL,
+ // the capture timestamp.
+ spn?: {
+ access?: string;
+ secret?: string;
+ busyTimes?: number;
+ pendingPolls?: number;
+ failUrls?: string[];
+ refuseUrls?: string[];
+ pages?: Record<string, string>;
+ timestamp?: string;
+ };
}): Promise<FakeWayback>;
// (release 37 S2) the scan listing: a blog with posts, assets, a 404, a second host.
diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs
@@ -176,6 +176,88 @@ function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) {
return true;
}
+// ─── Release 37 (lane E): Save Page Now (SPN2) ──────────────────────────────
+//
+// POST /save url=<page>&capture_outlinks=0, Authorization
+// `LOW <access>:<secret>` → {url, job_id}; a wrong
+// or missing key → 401; opts.spn.busyTimes → 429
+// (Retry-After: 1) first; a url in opts.spn.refuseUrls
+// → 200 {status: "error", status_ext: "error:blocked-url"}
+// GET /save/status/<job_id> {status: "pending"} for opts.spn.pendingPolls polls
+// (default 1), then {status: "success", timestamp,
+// original_url} — and the capture is served raw like a
+// page capture from then on (opts.spn.pages[url] or a
+// synthetic page) — or, for a url in opts.spn.failUrls,
+// {status: "error", status_ext: "error:not-found"}
+// The keys are FAKE_SPN_ACCESS / FAKE_SPN_SECRET; nothing real.
+export const FAKE_SPN_ACCESS = "FAKEACCESS0001";
+export const FAKE_SPN_SECRET = "FAKESECRET0001";
+export const SPN_CAPTURE_TS = "20261020120000";
+
+const spnPageHtml = (url) => `<!doctype html><html lang="en"><head><meta charset="utf-8">
+<title>A page saved now</title></head><body>
+<nav><a href="/">Home</a></nav>
+<main><h1>A page saved now</h1>
+<p>This synthetic page stands for ${url}, captured by the fake Save Page Now while it was still up.</p>
+<p>It says what the page said on the day it was saved, which is the point of saving it.</p></main>
+<footer>Footer</footer></body></html>`;
+
+function readBody(req) {
+ return new Promise((resolve) => {
+ const chunks = [];
+ req.on("data", (c) => chunks.push(c));
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
+ });
+}
+
+// The SPN routes; true when the request was one of them.
+function spnAnswer(spn, req, u, send) {
+ if (u.pathname === "/save" && req.method === "POST") {
+ void readBody(req).then((body) => {
+ if (req.headers.authorization !== `LOW ${spn.access}:${spn.secret}`) {
+ return send(401, "application/json", JSON.stringify({ message: "You need to be logged in to use Save Page Now." }));
+ }
+ if (spn.busy > 0) {
+ spn.busy--;
+ return send(429, "application/json", JSON.stringify({ message: "You have already reached the limit of active sessions." }), { "retry-after": "1" });
+ }
+ const url = new URLSearchParams(body).get("url") ?? "";
+ spn.forms.push(Object.fromEntries(new URLSearchParams(body)));
+ if (spn.refuseUrls.includes(url)) {
+ return send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:blocked-url", message: "This URL is in the Save Page Now service block list." }));
+ }
+ const jobId = `spn2-fake-${++spn.seq}`;
+ spn.jobs.set(jobId, { url, polls: 0 });
+ return send(200, "application/json", JSON.stringify({ url, job_id: jobId }));
+ });
+ return true;
+ }
+ const st = /^\/save\/status\/([^/]+)$/.exec(u.pathname);
+ if (st && req.method === "GET") {
+ const job = spn.jobs.get(decodeURIComponent(st[1]));
+ if (!job) {
+ send(404, "application/json", JSON.stringify({ status: "error", message: "Job not found." }));
+ return true;
+ }
+ job.polls++;
+ if (job.polls <= spn.pendingPolls) {
+ send(200, "application/json", JSON.stringify({ status: "pending", job_id: st[1] }));
+ return true;
+ }
+ if (spn.failUrls.includes(job.url)) {
+ send(200, "application/json", JSON.stringify({ status: "error", status_ext: "error:not-found", message: "Server returned a 404 for this page." }));
+ return true;
+ }
+ if (!spn.captured.some((c) => c.original === job.url)) {
+ const page = spn.pages[job.url];
+ spn.captured.push({ original: job.url, timestamp: spn.timestamp, statuscode: "200", mimetype: "text/html", body: () => page ?? spnPageHtml(job.url) });
+ }
+ send(200, "application/json", JSON.stringify({ status: "success", job_id: st[1], timestamp: spn.timestamp, original_url: job.url, duration_sec: 3 }));
+ return true;
+ }
+ return false;
+}
+
// YouTube ids whose video (not only its page) the fake archive holds.
export const VIDEOS = ["gone-video-05"];
@@ -192,9 +274,24 @@ export async function startFakeWayback(opts = {}) {
let down = opts.downTimes ?? 0;
const excluded = opts.excluded ?? [];
let scanRequests = 0;
+ // Release 37 (lane E): Save Page Now's state.
+ const spn = {
+ access: opts.spn?.access ?? FAKE_SPN_ACCESS,
+ secret: opts.spn?.secret ?? FAKE_SPN_SECRET,
+ busy: opts.spn?.busyTimes ?? 0,
+ pendingPolls: opts.spn?.pendingPolls ?? 1,
+ failUrls: opts.spn?.failUrls ?? [],
+ refuseUrls: opts.spn?.refuseUrls ?? [],
+ pages: opts.spn?.pages ?? {},
+ timestamp: opts.spn?.timestamp ?? SPN_CAPTURE_TS,
+ jobs: new Map(),
+ seq: 0,
+ forms: [],
+ captured: [],
+ };
const server = http.createServer((req, res) => {
const u = new URL(req.url ?? "/", "http://fake");
- requests.push({ path: u.pathname + u.search, at: Date.now() });
+ requests.push({ path: u.pathname + u.search, at: Date.now(), method: req.method });
const send = (status, type, body, headers = {}) => {
res.writeHead(status, { "content-type": type, ...headers });
res.end(body);
@@ -208,6 +305,10 @@ export async function startFakeWayback(opts = {}) {
return send(403, "text/html", "<p>Sorry. This URL has been excluded from the Wayback Machine.</p>");
}
}
+ // Release 37 (lane E): Save Page Now, and the captures it made (raw).
+ if (spnAnswer(spn, req, u, send)) return;
+ const spc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search);
+ if (spc && pageCaptureAnswer(spn.captured, spc[1], spc[2] ?? "", spc[3], send, res)) return;
if (u.pathname === "/cdx/search/cdx") {
if (busy > 0) {
busy--;
@@ -276,6 +377,9 @@ export async function startFakeWayback(opts = {}) {
return {
base,
requests,
+ // Release 37 (lane E): the SPN forms posted (no headers), and the captures made.
+ spnForms: spn.forms,
+ spnCaptures: spn.captured,
fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/web\.archive\.org/, base), init),
close: () => new Promise((r) => server.close(() => r())),
};
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,6 +3,8 @@
## [Unreleased]
- **archive.today copies are page records too, like Wayback captures.** The channel kind is now **Archived pages** on the New channel form (paste an archive.today copy's URL, `archive.ph/newest/<page>`, and the channel's target is that page on archive.today), and each target says where its copies are looked for: the Wayback Machine, archive.today, or both. The channel page's **Import a capture** takes an archive.today copy's URL (`archive.ph/<id>`, or any of its other names), or the page's own URL, a date and **on archive.today** for the copy nearest that date; the copy is kept as archive.today served it and read without its header bar, links back to the pages they pointed at, so a tweet, a Tumblr post or an article gives the same records it would from the Wayback Machine — each saying it came from archive.today and linking that copy, its images archive.today's own copies. archive.today is asked one request at a time, eight seconds apart; when it says "too many requests" the import stops with a sentence and nothing more is asked of it for half an hour. When it answers with a CAPTCHA instead of the copy, the import is refused and never reads the CAPTCHA as a page: **Connect archive session** (on the channel page, and in Settings → Archive sources) opens a window on the editor's machine to pass the check once, and the next import reads through it; nothing is ever solved for you. **Look up a page** lists every copy each archive holds of a page, with an Import button on each. From a terminal: `pnpm ops import-page` takes `"source": "archive.today"`, `pnpm ops archive-lookup` lists the copies, and `pnpm archilyzer archive lookup <url>` runs without the editor. Needs a restart of the editor.
- **A page the Wayback Machine will not show says so.** When the Wayback Machine answers "forbidden" for one page while it answers others, that page is excluded from it, and Wayback lookups, page imports and archive lookups now say "excluded from the Wayback Machine (cause unknown)" instead of reporting an error.
+- **Is a Wayback page's original still up? The channel page says, and can ask the Wayback Machine to save one now.** A Wayback pages channel's page has **Originals**: **Check originals** asks each record's original address at its own site — never the Wayback Machine — once per address, a few seconds apart, and the page lists every original that is gone (404 or 410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page) with "the only copy" linking its Wayback copy; a suspended account or a document no longer shared reads as unavailable, and anything else (a wall, an outage, a redirect to another site) as an error, never as gone. Gone records read as deleted wherever a deleted post does. **Save Page Now** — "Ask the Wayback Machine to capture this now" — takes any address, or a record whose original is still up (**Capture now**): archive.org captures the page, the job waits for it, and the new capture is imported into the channel. It needs your archive.org S3 keys (`ARCHIVE_ORG_S3_ACCESS` and `ARCHIVE_ORG_S3_SECRET` in the editor's environment, or in the mode-600 file `archiveOrg.s3KeyFile` names); without them the button is off and says why, and the keys are never logged. From a terminal: `pnpm ops check-post-availability`, `pnpm ops save-page-now` (`dryRun` first). Needs a restart of the editor.
+- **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten.
- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor.
- **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on.
- **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model.
diff --git a/editor/app/api/ops/check-post-availability/route.ts b/editor/app/api/ops/check-post-availability/route.ts
@@ -0,0 +1,32 @@
+import { checkPostAvailabilityAction } from "../../../channels/[slug]/socialActions";
+import {
+ CHECK_POST_AVAILABILITY_MODES,
+ type CheckPostAvailabilityMode,
+} from "yt-dlp-transcript-common/controller/checkPostAvailability";
+import { OpsInputError, jobResponse, ops, optPositiveInt, optString, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, mode?, limit? } -> { ok: true, jobId }
+//
+// WHICH ARCHIVED POSTS ARE GONE AT THEIR SOURCE (the channel page's "Check
+// deleted posts"; release 37 S5 adds this door): a check-post-availability
+// job. A Wayback pages channel's records are checked by their ORIGINAL URL at
+// its own site (lib/waybackPages/liveness-server.ts, the web pacer — never
+// the Wayback Machine), one request per distinct URL; any other posts
+// channel through its fetcher's own check. `mode`: "stale" (default) |
+// "unchecked" | "all"; `limit` (default 200) counts posts, or URLs for a
+// pages channel. The verdicts land in posts-availability.json.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "mode", "limit"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const mode = optString(body, "mode");
+ if (mode !== undefined && !(CHECK_POST_AVAILABILITY_MODES as string[]).includes(mode)) {
+ throw new OpsInputError(`"mode" must be one of ${CHECK_POST_AVAILABILITY_MODES.join(", ")}`);
+ }
+ const limit = optPositiveInt(body, "limit");
+ return jobResponse(
+ await checkPostAvailabilityAction(slug, undefined, mode as CheckPostAvailabilityMode | undefined, limit),
+ );
+ });
+}
diff --git a/editor/app/api/ops/find-copy/route.ts b/editor/app/api/ops/find-copy/route.ts
@@ -1,6 +1,8 @@
import { findCopyAction, findWholeCopiesAction } from "../../../channels/[slug]/videos/findCopyAction";
import { FIND_COPY_MAX_LIMIT, GONE_SCOPES, type GoneScope } from "yt-dlp-transcript-common/publish/findCopy";
import { OpsInputError, jobResponse, ops, optBool, optPositiveInt, optString } from "../_lib";
+import { findPageCopiesAction } from "../../../channels/[slug]/waybackLiveActions";
+import { FIND_PAGE_COPY_MAX_LIMIT } from "yt-dlp-transcript-common/publish/findCopyPages";
export const dynamic = "force-dynamic";
@@ -36,12 +38,48 @@ export const dynamic = "force-dynamic";
// with `@@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,
// looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?,
// via?, outcome}], left, items, stopped?, fetchJobId?, refused?}`.
+//
+// POST { article } | { siteId } | { articles: true }, pages: true, channel?,
+// max?, dryRun? -> { ok, jobId } — THE PAGE MODE (release 37 S5,
+// publish/findCopyPages.ts): every page the reports cite whose ORIGINAL is
+// gone at its own site gets the Wayback capture nearest the citation's date
+// imported into the Wayback pages channel named (`channel`) or the one whose
+// targets cover it; a cited page record whose original is gone has its
+// capture imported again when it is not stored. A find-copy job on the
+// archive.org queue; at most `max` (default 10, at most 100) pages looked up.
+// The log ends with `@@find-copy {host, dryRun, max, pages, posts, items:
+// [{citedBy, url, original, channel?, capture?, outcome, detail, pointTo?,
+// as?, records?}], left, stopped?}` — `pointTo`/`as` name the record a
+// citation should cite; the report is not rewritten.
export async function POST(request: Request) {
- return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max"], async (body) => {
+ return ops(request, ["article", "siteId", "articles", "dryRun", "retryFailed", "slug", "gone", "max", "pages", "channel"], async (body) => {
const article = optString(body, "article")?.trim();
const siteId = optString(body, "siteId")?.trim();
const articles = optBool(body, "articles") === true;
const gone = optString(body, "gone");
+ if (optBool(body, "pages") === true) {
+ if (gone !== undefined || optString(body, "slug") !== undefined || body.retryFailed !== undefined) {
+ throw new OpsInputError('"pages" is its own mode: send "article", "articles": true or "siteId", with "channel"?, "max"?, "dryRun"? — not "gone", "slug" or "retryFailed"');
+ }
+ if ([article, siteId, articles || undefined].filter(Boolean).length !== 1) {
+ throw new OpsInputError('send one of "article" (an article id), "articles": true or "siteId"');
+ }
+ const max = optPositiveInt(body, "max");
+ if (max !== undefined && max > FIND_PAGE_COPY_MAX_LIMIT) {
+ throw new OpsInputError(`"max" must be at most ${FIND_PAGE_COPY_MAX_LIMIT}`);
+ }
+ const channel = optString(body, "channel")?.trim() || undefined;
+ return jobResponse(
+ await findPageCopiesAction({
+ ...(article ? { article } : {}),
+ ...(siteId ? { siteId } : {}),
+ ...(channel ? { channel } : {}),
+ ...(max !== undefined ? { max } : {}),
+ dryRun: optBool(body, "dryRun") === true,
+ }),
+ );
+ }
+ if (optString(body, "channel") !== undefined) throw new OpsInputError('"channel" goes with "pages": true (the page mode)');
if (gone !== undefined) {
if (!(GONE_SCOPES as readonly string[]).includes(gone)) {
throw new OpsInputError(`"gone" must be one of ${GONE_SCOPES.join(", ")}`);
diff --git a/editor/app/api/ops/save-page-now/route.ts b/editor/app/api/ops/save-page-now/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { savePageNowAction, savePageNowDryRunAction } from "../../../channels/[slug]/waybackLiveActions";
+import { jobResponse, ops, optBool, optString, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { url, slug?, dryRun? } -> { ok: true, jobId } | (dryRun) { ok: true, dryRun: true, wouldAsk, … }
+//
+// SAVE PAGE NOW (release 37 S5, controller/savePageNow.ts): the Wayback
+// Machine asked to capture `url` now, with archive.org's S3 keys (the
+// editor's ARCHIVE_ORG_S3_ACCESS + ARCHIVE_ORG_S3_SECRET, else the mode-600
+// file settings `archiveOrg.s3KeyFile` names) — a `save-page-now` job on the
+// archive.org queue that asks for the capture (the page alone), polls its
+// status, and, with `slug` (a Wayback pages channel), starts an import-page
+// job of the capture. The log ends with `@@save-page-now {ok, url, slug?,
+// spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?,
+// polls, error?}`. `dryRun` answers what it would ask and starts nothing.
+// Every refusal is the controller's sentence (no keys among them); the keys
+// are never echoed.
+export async function POST(request: Request) {
+ return ops(request, ["url", "slug", "dryRun"], async (body) => {
+ const url = reqString(body, "url");
+ const slug = optString(body, "slug")?.trim() || undefined;
+ if (optBool(body, "dryRun") === true) {
+ const r = await savePageNowDryRunAction(url, slug);
+ if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 });
+ return NextResponse.json(r);
+ }
+ return jobResponse(await savePageNowAction(url, slug, "ops"));
+ });
+}
diff --git a/editor/app/api/ops/settings/route.ts b/editor/app/api/ops/settings/route.ts
@@ -5,6 +5,7 @@ import { OpsInputError, ops, opsFail } from "../_lib";
import { readRoute, redactSecrets } from "../_read";
import { settingsPatchProblem } from "./patch";
import { looksLikeApiKey } from "yt-dlp-transcript-common/lib/generationSettings";
+import { looksLikeS3Key } from "yt-dlp-transcript-common/lib/archiveOrgTorrent";
export const dynamic = "force-dynamic";
@@ -65,6 +66,14 @@ export async function POST(request: Request) {
"generation.apiKeyFile is the PATH of the mode-600 file that holds the key, and the value sent looks like a key itself — refused, not stored",
);
}
+ // archive.org's S3 keys are never a setting either (release 37 S5): the
+ // same refusal for archiveOrg.s3KeyFile, without the value.
+ const s3KeyFile = (patch as { archiveOrg?: { s3KeyFile?: unknown } }).archiveOrg?.s3KeyFile;
+ if (typeof s3KeyFile === "string" && looksLikeS3Key(s3KeyFile)) {
+ throw new OpsInputError(
+ "archiveOrg.s3KeyFile is the PATH of the mode-600 file that holds archive.org's S3 keys, and the value sent is not a path — refused, not stored",
+ );
+ }
const current = getSettings();
const problem = settingsPatchProblem(
patch as Record<string, unknown>,
diff --git a/editor/app/channels/[slug]/components/WaybackLivePanel.tsx b/editor/app/channels/[slug]/components/WaybackLivePanel.tsx
@@ -0,0 +1,185 @@
+"use client";
+
+// A WAYBACK PAGES channel, live (release 37 S5): whether each record's
+// ORIGINAL is still up (check-post-availability, asked at the original's own
+// site — never the Wayback Machine), the records whose original is gone (the
+// Wayback copy is then the only copy), and Save Page Now — "Ask the Wayback
+// Machine to capture this now" — for a page still up, its capture imported
+// here. Save Page Now is off without archive.org's S3 keys, and says why.
+
+import { useState, useTransition } from "react";
+import Link from "next/link";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { cancelJobAction } from "../../../jobs/actions";
+import { checkPostAvailabilityAction } from "../socialActions";
+import { savePageNowAction } from "../waybackLiveActions";
+
+export type WaybackLiveRow = {
+ id: string;
+ title: string;
+ originalUrl: string;
+ waybackUrl: string;
+ // posts-availability.json's verdict on the original, when checked.
+ availability?: string;
+ reason?: string;
+ checkedAt?: string;
+};
+
+export type WaybackLiveState = {
+ // Distinct original URLs, and how many were checked / are gone.
+ originals: number;
+ checked: number;
+ gone: number;
+ unavailable: number;
+ // Records whose original is gone (deleted or unavailable), newest first.
+ goneRows: WaybackLiveRow[];
+ // Records whose original answered, one per original URL (Save Page Now).
+ liveRows: WaybackLiveRow[];
+ spn: { on: true } | { on: false; reason: string };
+};
+
+function CaptureNow({ slug, url, disabled }: { slug: string; url: string; disabled: boolean }) {
+ const [pending, start] = useTransition();
+ const [job, setJob] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ return (
+ <span className="inline-flex items-center gap-2">
+ <button
+ type="button"
+ disabled={disabled || pending}
+ aria-label={`capture ${url} now`}
+ onClick={() =>
+ start(async () => {
+ setErr(null);
+ const res = await savePageNowAction(url, slug);
+ if (res.ok) {
+ void res.stream.cancel();
+ setJob(res.jobId);
+ } else {
+ setErr(res.error);
+ }
+ })
+ }
+ className="rounded border border-border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-50"
+ >
+ {pending ? "Asking…" : "Capture now"}
+ </button>
+ {job && (
+ <Link href={`/jobs/${job}`} className="text-xs underline underline-offset-2">
+ job
+ </Link>
+ )}
+ {err && (
+ <span role="alert" className="text-xs text-destructive">
+ {err}
+ </span>
+ )}
+ </span>
+ );
+}
+
+export function WaybackLivePanel({ slug, state }: { slug: string; state: WaybackLiveState }) {
+ const [url, setUrl] = useState("");
+ const [checkJob, setCheckJob] = useState<string | null>(null);
+ const [spnJob, setSpnJob] = useState<string | null>(null);
+ const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono";
+ const spnOff = !state.spn.on;
+ return (
+ <div className="flex flex-col gap-4">
+ <section aria-label="originals" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h4 className="text-sm font-semibold">Originals</h4>
+ <span role="status" aria-label="originals checked" className="text-sm text-muted-foreground">
+ {state.checked} of {state.originals} original URL{state.originals === 1 ? "" : "s"} checked · {state.gone} gone
+ {state.unavailable > 0 ? ` · ${state.unavailable} unavailable` : ""}
+ </span>
+ </div>
+ <StreamActionLog
+ trigger={() => checkPostAvailabilityAction(slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Check originals"
+ runningLabel="Checking…"
+ label={`Check the originals of ${slug}`}
+ disabled={state.originals === 0}
+ onSettled={(started, out) => setCheckJob(started ? out.jobId : null)}
+ />
+ {checkJob && (
+ <Link href={`/jobs/${checkJob}`} className="text-xs underline underline-offset-2">
+ Open the check job
+ </Link>
+ )}
+ {state.goneRows.length > 0 && (
+ <table aria-label="originals gone" className="mt-1 w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-muted-foreground">
+ <th className="py-1 pr-2 font-medium">Page</th>
+ <th className="py-1 pr-2 font-medium">Original</th>
+ <th className="py-1 font-medium">Wayback copy</th>
+ </tr>
+ </thead>
+ <tbody>
+ {state.goneRows.map((r) => (
+ <tr key={r.id} data-original-gone={r.id} className="border-t border-border align-top">
+ <td className="py-1 pr-2">{r.title}</td>
+ <td className="py-1 pr-2 text-xs">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono underline underline-offset-2">
+ {r.availability === "deleted" ? "gone" : "unavailable"}
+ </a>
+ {r.reason && <span className="text-muted-foreground"> · {r.reason}</span>}
+ </td>
+ <td className="py-1 text-xs">
+ <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2">
+ the only copy
+ </a>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </section>
+ <section aria-label="save page now" className="flex flex-col gap-2 rounded-lg border border-border p-3">
+ <h4 className="text-sm font-semibold">Save Page Now</h4>
+ {spnOff && (
+ <p role="status" aria-label="save page now off" className="text-xs text-muted-foreground">
+ {state.spn.on ? "" : state.spn.reason}
+ </p>
+ )}
+ <input
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ aria-label="page to capture"
+ placeholder="https://…"
+ disabled={spnOff}
+ className={`${input} w-[36rem] max-w-full`}
+ />
+ <StreamActionLog
+ trigger={() => savePageNowAction(url.trim(), slug)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Ask the Wayback Machine to capture this now"
+ runningLabel="Capturing…"
+ label={`Save Page Now into ${slug}`}
+ disabled={spnOff || !url.trim()}
+ onSettled={(started, out) => setSpnJob(started ? out.jobId : null)}
+ />
+ {spnJob && (
+ <Link href={`/jobs/${spnJob}`} aria-label="save page now job" className="text-xs underline underline-offset-2">
+ Open the capture job
+ </Link>
+ )}
+ {state.liveRows.length > 0 && (
+ <ul aria-label="originals still up" className="mt-1 flex flex-col gap-1 text-sm">
+ {state.liveRows.map((r) => (
+ <li key={r.id} data-original-live={r.id} className="flex flex-wrap items-center gap-2">
+ <a href={r.originalUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2">
+ {r.originalUrl}
+ </a>
+ <CaptureNow slug={slug} url={r.originalUrl} disabled={spnOff} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -22,6 +22,9 @@ import { readForumSessionStatus } from "yt-dlp-transcript-common/social/forumSes
import { parseXenforoThreadUrl } from "yt-dlp-transcript-common/social/xenforoParse";
import { SocialChannelPanel } from "./components/SocialChannelPanel";
import { WaybackPagesPanel } from "./components/WaybackPagesPanel";
+import { WaybackLivePanel } from "./components/WaybackLivePanel";
+import { waybackLiveState } from "./waybackLiveState";
+import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/savePageNow";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server";
import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
@@ -187,11 +190,11 @@ export default async function ChannelDetailPage({
: undefined;
// A WAYBACK PAGES channel (release 37): its captures, its scope, Import a
// capture — no fetcher, nothing to fetch.
+ const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : [];
const wayback = isWaybackPagesChannel(config)
? {
captureCount: await countStoredCaptures(channelRoot),
- recent: (await readAllPosts(channelRoot))
- .filter((p) => p.page)
+ recent: pageRecords
.sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))
.slice(0, 20)
.map((p) => ({
@@ -213,6 +216,7 @@ export default async function ChannelDetailPage({
<div className="flex flex-col gap-6">
<RunningJobsList jobs={socialRunningJobs} hideChannelSlug />
{wayback ? (
+ <>
<WaybackPagesPanel
slug={slug}
state={{
@@ -223,6 +227,12 @@ export default async function ChannelDetailPage({
archiveSession: wayback.archiveSession,
}}
/>
+ {/* Release 37 S5: is each original still up; Save Page Now. */}
+ <WaybackLivePanel
+ slug={slug}
+ state={waybackLiveState(pageRecords, postAvailability, savePageNowAvailability())}
+ />
+ </>
) : (
<SocialChannelPanel
slug={slug}
diff --git a/editor/app/channels/[slug]/waybackLiveActions.ts b/editor/app/channels/[slug]/waybackLiveActions.ts
@@ -0,0 +1,102 @@
+"use server";
+
+// WAYBACK PAGES, LIVE (release 37 S5): Save Page Now — "Ask the Wayback
+// Machine to capture this now" (controller/savePageNow.ts) — and find-copy's
+// page mode, a copy of every gone page a report cites (publish/findCopyPages.ts).
+// Both on the archive.org queue; the controllers' refusals in their own
+// sentences, before a job exists. The original-URL availability check is the
+// posts' own action (socialActions.ts checkPostAvailabilityAction).
+
+import { safeRevalidate } from "../../lib/safeRevalidate";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSite, isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
+import { articlesWorkHost, siteReportHost, type ReportHost } from "yt-dlp-transcript-common/publish/reportHost";
+import { runManagedFunction, type StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ queueSavePageNow,
+ savePageNow,
+ savePageNowAvailability,
+ type SavePageNowAvailability,
+ type SavePageNowResult,
+} from "yt-dlp-transcript-common/controller/savePageNow";
+import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
+import { findPageCopies } from "yt-dlp-transcript-common/publish/findCopyPages";
+import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
+
+export async function savePageNowAction(url: string, slug?: string, requestedBy?: string): Promise<StreamActionResult> {
+ return queueSavePageNow({
+ paths: getPaths(),
+ url: url.trim(),
+ ...(slug?.trim() ? { slug: slug.trim() } : {}),
+ ...(requestedBy ? { requestedBy } : {}),
+ onDone: () => {
+ if (slug) safeRevalidate([`/channels/${slug}`]);
+ },
+ });
+}
+
+// What a capture WOULD ask, answered now (no job, no request).
+export async function savePageNowDryRunAction(url: string, slug?: string): Promise<SavePageNowResult> {
+ return savePageNow({ paths: getPaths(), url: url.trim(), ...(slug?.trim() ? { slug: slug.trim() } : {}), dryRun: true });
+}
+
+// Whether the button is on, and why not (the keys' presence, never their
+// value).
+export async function savePageNowAvailabilityAction(): Promise<SavePageNowAvailability> {
+ return savePageNowAvailability();
+}
+
+// FIND-COPY, PAGE MODE: `{article} | {articles: true} | {siteId}`, `channel?`,
+// `max?`, `dryRun?` — one find-copy job on the archive.org queue. Its log ends
+// with `@@find-copy {host, dryRun, max, pages, posts, items, left, stopped?}`.
+export async function findPageCopiesAction(req: {
+ article?: string;
+ siteId?: string;
+ channel?: string;
+ max?: number;
+ dryRun?: boolean;
+}): Promise<StreamActionResult> {
+ 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 };
+ }
+ if (req.channel) {
+ const config = await readChannelConfig(paths, req.channel);
+ if (!config) return { ok: false, error: `No such channel: ${req.channel}` };
+ if (!isWaybackPagesChannel(config)) return { ok: false, error: `${req.channel} is not a Wayback pages channel` };
+ }
+ return runManagedFunction({
+ kind: "find-copy",
+ queueKey: WAYBACK_PAGES_QUEUE,
+ paths,
+ ...(req.channel ? { channelSlug: req.channel } : {}),
+ fn: async (onLog, signal) => {
+ const r = await findPageCopies({
+ paths,
+ host,
+ ...(req.channel ? { channel: req.channel } : {}),
+ ...(req.max !== undefined ? { max: req.max } : {}),
+ dryRun: req.dryRun === true,
+ signal,
+ onLog,
+ });
+ onLog(`${FIND_COPY_RESULT_MARKER}${JSON.stringify(r)}`);
+ const touched = new Set(r.items.filter((i) => i.outcome === "imported" && i.channel).map((i) => `/channels/${i.channel}`));
+ if (touched.size > 0) safeRevalidate([...touched]);
+ if (signal.aborted) throw new Error("cancelled");
+ },
+ });
+}
diff --git a/editor/app/channels/[slug]/waybackLiveState.ts b/editor/app/channels/[slug]/waybackLiveState.ts
@@ -0,0 +1,51 @@
+// The Wayback pages channel's live panel's state (release 37 S5,
+// components/WaybackLivePanel.tsx), from its page records and the
+// availability sidecar: one row per original URL.
+
+import type { Post, PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts";
+import { groupByOriginalUrl } from "yt-dlp-transcript-common/lib/waybackPages/liveness";
+import type { WaybackLiveRow, WaybackLiveState } from "./components/WaybackLivePanel";
+
+const ROWS = 20;
+
+export function waybackLiveState(
+ records: ReadonlyArray<Post>,
+ availability: PostAvailabilityMap,
+ spn: WaybackLiveState["spn"],
+): WaybackLiveState {
+ const groups = groupByOriginalUrl(records);
+ const byId = new Map(records.map((r) => [r.id, r]));
+ let checked = 0;
+ let gone = 0;
+ let unavailable = 0;
+ const goneRows: WaybackLiveRow[] = [];
+ const liveRows: WaybackLiveRow[] = [];
+ for (const [url, ids] of groups) {
+ // The newest capture of the page stands for it.
+ const newest = ids
+ .map((id) => byId.get(id)!)
+ .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))[0]!;
+ const av = ids.map((id) => availability[id]).find(Boolean);
+ const row: WaybackLiveRow = {
+ id: newest.id,
+ title: newest.page!.title || newest.text.split("\n")[0]!.slice(0, 120) || url,
+ originalUrl: url,
+ waybackUrl: newest.page!.waybackUrl,
+ ...(av ? { availability: av.availability, checkedAt: av.checkedAt, ...(av.reason ? { reason: av.reason } : {}) } : {}),
+ };
+ if (av) checked++;
+ if (av?.availability === "deleted") gone++;
+ if (av?.availability === "account_unavailable") unavailable++;
+ if (av && (av.availability === "deleted" || av.availability === "account_unavailable")) goneRows.push(row);
+ else if (av?.availability === "available") liveRows.push(row);
+ }
+ return {
+ originals: groups.size,
+ checked,
+ gone,
+ unavailable,
+ goneRows: goneRows.slice(0, ROWS),
+ liveRows: liveRows.slice(0, ROWS),
+ spn,
+ };
+}
diff --git a/editor/e2e/wayback-live.spec.ts b/editor/e2e/wayback-live.spec.ts
@@ -0,0 +1,146 @@
+// Wayback pages, live (release 37 S5), over the fake Wayback Machine
+// (common/testing/web/fakeWayback.mjs, its Save Page Now block) named to the
+// test server through E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). Neither the
+// real web.archive.org nor any original site is contacted: the originals'
+// verdicts are written to posts-availability.json as the check would.
+//
+// A Wayback pages channel's page shows Originals (checked / gone, the gone
+// table) and Save Page Now: off with its sentence while no archive.org keys
+// are configured; with keys (a mode-600 file the settings name), "Ask the
+// Wayback Machine to capture this now" runs a save-page-now job whose capture
+// is imported into the channel. The ops door answers a dry run.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { chmod, mkdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ startFakeWayback,
+ FAKE_SPN_ACCESS,
+ FAKE_SPN_SECRET,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ SPN_CAPTURE_TS,
+} from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs";
+import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { waybackOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "old-blog-live";
+const LIVE = "https://blog.example/still-up.html";
+
+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("Originals and Save Page Now on a Wayback pages channel: off without keys, then a capture imported", async ({ page, request }) => {
+ test.setTimeout(180_000);
+ await resetData("empty");
+ const root = resolvePath(testPaths().transcriptsDir);
+ const keyFile = path.join(root, "spn-keys.env");
+ await rm(keyFile, { force: true });
+ await writeSettings({ minFreeDiskGB: 0, archiveOrg: { s3KeyFile: keyFile } });
+ const channelRoot = path.join(root, "channels", SLUG);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify({
+ name: "Old blog (live)",
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ }),
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+
+ const wb = await startFakeWayback();
+ const originFile = waybackOriginFile(root);
+ await writeFile(originFile, wb.base);
+ try {
+ // One record, imported from the fake.
+ const imp = await request.post(`${baseUrl}/api/ops/import-page`, {
+ headers: AUTH,
+ data: { slug: SLUG, url: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}` },
+ });
+ const impBody = (await imp.json()) as { jobId?: string; error?: string };
+ expect(imp.status(), impBody.error).toBe(200);
+ expect((await waitForJob(request, impBody.jobId!)).status).toBe("done");
+ const articleId = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL);
+
+ await page.goto(`/channels/${SLUG}`);
+ const originals = page.getByRole("region", { name: "originals" });
+ await expect(originals.getByLabel("originals checked")).toHaveText("0 of 1 original URL checked · 0 gone");
+ await expect(originals.getByRole("button", { name: "Check originals" })).toBeEnabled();
+ // No keys: the button is off and says why; nothing was asked of SPN.
+ const spn = page.getByRole("region", { name: "save page now" });
+ await expect(spn.getByLabel("save page now off")).toContainText("Save Page Now needs archive.org S3 keys");
+ await expect(spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" })).toBeDisabled();
+ const refused = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG } });
+ expect(refused.status()).toBe(400);
+ expect(((await refused.json()) as { error: string }).error).toContain("needs archive.org S3 keys");
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // The original's verdict, as the check writes it: gone — the Wayback copy is the only copy.
+ await writeFile(
+ path.join(channelRoot, "posts-availability.json"),
+ JSON.stringify({ [articleId]: { availability: "deleted", checkedAt: "2026-10-20T10:00:00.000Z", status: 404, reason: "HTTP 404" } }),
+ );
+ // The keys, in a mode-600 file the settings name.
+ await writeFile(keyFile, `ARCHIVE_ORG_S3_ACCESS=${FAKE_SPN_ACCESS}\nARCHIVE_ORG_S3_SECRET=${FAKE_SPN_SECRET}\n`);
+ await chmod(keyFile, 0o600);
+ await page.reload();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 1 original URL checked · 1 gone");
+ const goneRow = page.locator(`[data-original-gone="${articleId}"]`);
+ await expect(goneRow.getByRole("link", { name: "the only copy" })).toHaveAttribute(
+ "href",
+ `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`,
+ );
+ await expect(goneRow).toContainText("HTTP 404");
+ await expect(spn.getByLabel("save page now off")).toHaveCount(0);
+
+ // A dry run over ops asks nothing.
+ const dry = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG, dryRun: true } });
+ const dryBody = (await dry.json()) as { ok: boolean; wouldAsk?: string };
+ expect(dryBody.ok).toBe(true);
+ expect(dryBody.wouldAsk).toContain(`then import the capture into ${SLUG}`);
+ expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
+
+ // Ask the Wayback Machine to capture the live page now: the capture, then its import.
+ await spn.getByLabel("page to capture").fill(LIVE);
+ await spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" }).click();
+ const log = page.getByRole("log", { name: `Save Page Now into ${SLUG} output` });
+ await expect(log).toContainText('"ok":true', { timeout: 90_000 });
+ const text = (await log.textContent()) ?? "";
+ expect(text).toContain(`"captureTs":"${SPN_CAPTURE_TS}"`);
+ expect(text).not.toContain(FAKE_SPN_SECRET);
+ const importJobId = /"importJobId":"([^"]+)"/.exec(text)?.[1];
+ expect(importJobId, text).toBeTruthy();
+ expect((await waitForJob(request, importJobId!)).status).toBe("done");
+ expect(wb.spnForms).toEqual([{ url: LIVE, capture_outlinks: "0" }]);
+
+ await page.reload();
+ await expect(page.getByRole("region", { name: "Wayback pages" }).getByLabel("pages held")).toHaveText("2 records from 2 captures");
+ await expect(page.locator(`[data-page-record="${pageRecordId(SPN_CAPTURE_TS, LIVE)}"]`)).toBeVisible();
+ await expect(originals.getByLabel("originals checked")).toHaveText("1 of 2 original URLs checked · 1 gone");
+ } finally {
+ await rm(originFile, { force: true });
+ await rm(keyFile, { force: true });
+ await wb.close();
+ }
+});
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11244,3 +11244,54 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
- **Ops / CLI:** `archive-lookup {url, source?, limit?}` (read only) → `{url, found, sources: [{source, label, ok,
captures, refusal?, error?}]}`; `import-page` takes `source`; `archilyzer archive lookup <url>` and `wayback pages
import --source`.
+
+## Release 37 lane E: liveness, Save Page Now, find-copy for pages (verified 2026-10-20, branch `r37/live`)
+
+- **A page record's availability is its ORIGINAL URL's**, never the Wayback Machine's: `checkPostAvailability`
+ branches on `isWaybackPagesChannel` to `controller/checkPageAvailability.ts` (no fetcher needed). One request per
+ distinct `page.originalUrl` (`groupByOriginalUrl`); every record sharing it gets the verdict; `limit` counts URLs;
+ `stale` orders URLs by the OLDEST check among their records. The request side is
+ `lib/waybackPages/liveness-server.ts` `checkOriginalUrl`: through `webPacer` (3 s gap, 429/503 backed off), behind
+ `fetchRefusal` (the web fetch's private-host fence) on every hop, HEAD with manual redirects (≤ 5), a GET instead
+ when the HEAD answers 403/405/501 or when the final host has a gone-page marker (body read to 256 KB). Verdicts
+ (`lib/waybackPages/liveness.ts`): 404/410 `deleted`; 2xx on the same site (`sameSite`: www, http→https, same
+ registrable domain, two-label suffixes, twitter.com≡x.com, youtu.be≡youtube.com) `available` unless a
+ `PAGE_GONE_MARKERS` row matches the folded text; a 2xx after a redirect to another site, any other status, no
+ answer or a fence refusal `error`. Marker rows: X no-account / no-page (`deleted`), X suspended
+ (`account_unavailable`), Tumblr "There's nothing here" (`deleted`), Google Docs "file … does not exist"
+ (`deleted`) / "You need access|permission" (`account_unavailable`), YouTube "This channel does not exist"
+ (`deleted`) / terminated (`account_unavailable`) — each on its own hosts only.
+- **`posts-availability.json` records gained `status?: number | null` and `reason?: string`** (the latest answer;
+ `readPostAvailability` keeps them; `mergePostAvailability(existing, obs, at, details?)` — the 4th arg optional).
+ History is still appended only on a change. The index's `isDeleted` comes from `deleted` as for every post.
+ `PAGE_ORIGINAL_GONE_LABEL` ("Original gone — the Wayback Machine copy is the only copy") is exported from
+ `liveness.ts` for the citation surfaces; nothing renders it yet.
+- **Save Page Now** (`controller/savePageNow.ts`, job kind `save-page-now`, queue `platform:archive.org`, not
+ drainable/replayable): SPN2 `POST https://web.archive.org/save` (`url`, `capture_outlinks=0`, `Authorization: LOW
+ <access>:<secret>`) → `job_id`; `GET /save/status/<job_id>` every `SPN_POLL_MS` 10 s, at most `SPN_MAX_POLLS` 30;
+ success → `waybackPageUrl(timestamp, original_url)` and, with a slug, `startImportPageJob` (an import-page job
+ queued behind it; a refused import is `importError`, the capture stands). Requests go through
+ `WaybackClient.send` → `ArchiveOrgClient.send` (new: any method, same chain/gap/retry; a non-retryable status is
+ handed back with its body). Keys (`lib/waybackPages/savePageNow-server.ts` `readSpnKeys`): env
+ `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` (both), else the mode-600 file `settings.archiveOrg.s3KeyFile`
+ (default `~/.config/archilyzer/archive-org.env`, lines `ARCHIVE_ORG_S3_ACCESS=` / `ARCHIVE_ORG_S3_SECRET=`); a
+ group/other-readable file is refused; a settings value that is not a path is refused (`looksLikeS3Key`, also in
+ `/api/ops/settings`). `redactSpnKeys` runs on every log line and error. Lane B's door: `startSavePageNowJob({url,
+ slug?})` (throws `SavePageNowRefusal`).
+- **find-copy, page mode** (`publish/findCopyPages.ts`, ops `find-copy` with `pages: true`, a `find-copy` job on
+ `platform:archive.org`): `page` citations (grouped by URL) → `checkOriginalUrl` → gone (`deleted` |
+ `account_unavailable`) → the channel named or `channelsCovering` (a target's exact/prefix/host/domain over the
+ URL, `targetCoversUrl`) → held (the channel already has a record of the URL: no fetch) or `closestCapture(url,
+ captureAtOf(citation))` (its `date`, else its archiveUrl's timestamp, else today) → `importPage` inline (the run is
+ on the archive.org queue). `post` citations of a pages channel's record whose availability is gone: held when
+ `hasStoredCapture`, else its capture imported again. Each item carries `pointTo {channel, id}` (the record whose
+ text holds the quote, else the first) and `as` (the page citation as a `post` citation: `pageCitationAsPost`).
+ **The report is never rewritten here** (lane D's Import-this-capture owns rewriting with a fallback). `max`
+ default 10, at most 100.
+- **The fake** (`testing/web/fakeWayback.mjs`, lane E block): `POST /save` (keys `FAKE_SPN_ACCESS` /
+ `FAKE_SPN_SECRET`, `spn.busyTimes` 429s, `spn.refuseUrls`), `GET /save/status/<id>` (`spn.pendingPolls`, then
+ success at `SPN_CAPTURE_TS`, or `spn.failUrls` → error:not-found); a saved page is then served raw like a page
+ capture; `wb.spnForms`, `wb.spnCaptures`; `requests[].method`.
+- New ops: `check-post-availability {slug, mode?, limit?}` (any posts channel), `save-page-now {url, slug?,
+ dryRun?}`. UI: `components/WaybackLivePanel.tsx` under the pages panel (Check originals, the gone table, Save Page
+ Now field + per-live-record Capture now; off with `spnOffSentence` when no keys).
diff --git a/plans/release-37/live.md b/plans/release-37/live.md
@@ -0,0 +1,128 @@
+# Release 37 lane E — `r37/live`: liveness and saving what is still up (as shipped)
+
+The plan of record is [`wayback-pages.md`](wayback-pages.md) ("S5"). A page record (lane A) is a capture of a page;
+this lane answers whether the page's ORIGINAL is still up — when it is not, the Wayback copy is the only copy — asks
+the Wayback Machine to capture a page that is still up (Save Page Now), and teaches find-copy to find a copy of a
+gone page a report cites. Rulings followed: no model anywhere; every operation has a button (Check originals, Ask the
+Wayback Machine to capture this now, Capture now per live record) and an ops action; every archive.org request goes
+through the polite Wayback client on the `platform:archive.org` queue, every original-site request through the
+editor's web pacer — never a burst, never the Wayback Machine for liveness; synthetic fixtures only (the fake
+Wayback's new SPN block, stub original sites); the S3 keys are never a setting value, never logged; commits end with
+the one Co-Authored-By trailer.
+
+## What
+
+1. **Availability of a page record = its original URL's** (`controller/checkPageAvailability.ts`, reached from
+ `checkPostAvailability` for a Wayback pages channel). One request per distinct original URL (a split capture's
+ records and a page's versions share it), every record of it gets the verdict; `limit` counts URLs; `stale` orders
+ by the oldest check among a URL's records. The request (`lib/waybackPages/liveness-server.ts`
+ `checkOriginalUrl`): through `webPacer`, the web fetch's fence on every hop, HEAD with redirects followed by hand
+ (≤ 5), a GET when the HEAD is refused (403/405/501) or the platform has a "gone" page (body to 256 KB). The verdict
+ (`lib/waybackPages/liveness.ts`): `deleted` (404/410, or a `PAGE_GONE_MARKERS` row — X's "This account doesn't
+ exist" / "this page doesn't exist", Tumblr's "There's nothing here", Google Docs' "Sorry, the file you have
+ requested does not exist", YouTube's "This channel does not exist"), `account_unavailable` (X suspended, a Doc
+ not shared, a terminated YouTube account), `available` (2xx after redirects on the same site), `error` otherwise
+ with the status. Stored in `posts-availability.json` with the answer's `status` and `reason` (additive fields);
+ the index's `isDeleted` follows as for any post. The channel page's **Originals** (Check originals, "N of M
+ original URLs checked · K gone", the gone table with "the only copy" → the Wayback copy); ops
+ `check-post-availability` (new door, any posts channel); the CLI `archilyzer posts check` reaches the same branch.
+2. **Save Page Now** (`controller/savePageNow.ts`, `lib/waybackPages/savePageNow{,-server}.ts`): job kind
+ `save-page-now` on `platform:archive.org`: SPN2 `POST /save` (`url`, `capture_outlinks=0`, `Authorization: LOW
+ <access>:<secret>`), status polled every 10 s (≤ 30), then with a slug an `import-page` job of the capture
+ (`startImportPageJob`). Keys: `ARCHIVE_ORG_S3_ACCESS` + `ARCHIVE_ORG_S3_SECRET` in the environment, else the
+ mode-600 file the new setting `archiveOrg.s3KeyFile` names (default `~/.config/archilyzer/archive-org.env`);
+ refused when others can read it; a settings value that is not a path is refused (also by `/api/ops/settings`,
+ without echoing it); `redactSpnKeys` over every log line and error. Refused before any request: no keys (the
+ button is off with that sentence), not http(s), a Wayback URL, not a pages channel, a video, X while private.
+ Requests through `WaybackClient.send` → `ArchiveOrgClient.send` (new: any method, same chain, gap and retry; a
+ non-retryable status handed back with its body). UI: the channel page's **Save Page Now** field ("Ask the Wayback
+ Machine to capture this now", also the plain field for a scan target's URL) and **Capture now** on each record
+ whose original answered. Ops `save-page-now {url, slug?, dryRun?}`. Lane B's door: `startSavePageNowJob({url,
+ slug?})`.
+3. **find-copy, page mode** (`publish/findCopyPages.ts`; ops `find-copy` with `"pages": true`, `channel?`, `max?`,
+ `dryRun?`; one `find-copy` job on `platform:archive.org`): every `page` citation (grouped by URL) whose original is
+ gone → the channel named or the one whose targets cover it (`targetCoversUrl`) → held (a record of the URL is
+ already there) or the capture nearest the citation's date (`captureAtOf`: its date, else its archiveUrl's
+ timestamp, else today) via ONE `closestCapture`, imported inline (`importPage`); a cited page record whose
+ original is gone: held when its capture is stored, else imported again. Live pages are left ("save it now"), an
+ uncovered page is `no-channel`, a never-captured one `none-found`, a check that failed `error`. Each item names
+ `pointTo` (the record whose text holds the quote, else the first) and `as` (the page citation as a post
+ citation). Dry run: the same paced questions, nothing imported.
+4. **The fake** (`testing/web/fakeWayback.mjs`, its own block): SPN `POST /save` and `GET /save/status/<id>`
+ (pending → success, 401 on wrong keys, 429s, refused and failed URLs), the saved page served raw afterwards,
+ `wb.spnForms` / `wb.spnCaptures`, `requests[].method`.
+
+## Interfaces
+
+- `lib/waybackPages/liveness.ts`: `PAGE_GONE_MARKERS`, `pageGoneMarker`, `hasGoneMarkers`, `foldPageText`,
+ `classifyOriginalAnswer`, `sameSite`, `siteOf`, `bareHost`, `groupByOriginalUrl`, `OriginalCheck`,
+ `PAGE_ORIGINAL_GONE_LABEL`. `liveness-server.ts`: `checkOriginalUrl(url, {pacer?, resolve?, allowPrivate?,
+ signal?})`, `LIVENESS_MAX_BODY_BYTES`.
+- `controller/checkPageAvailability.ts`: `checkPageAvailability`, `selectUrlsToCheck`.
+ `CheckPostAvailabilityOptions.pageCheck?` (tests).
+- `posts.ts` `PostAvailabilityRecord.status?` / `reason?`; `posts-server.ts` `mergePostAvailability(…, details?)`.
+- `lib/waybackPages/savePageNow.ts`: `SPN_SAVE_URL`, `spnStatusUrl`, `spnSaveBody`, `spnAuthorization`,
+ `parseSpnSubmit`, `parseSpnStatus`, `spnOffSentence`, `SpnKeys`. `savePageNow-server.ts`: `readSpnKeys`,
+ `redactSpnKeys`.
+- `controller/savePageNow.ts`: `planSavePageNow`, `savePageNow`, `queueSavePageNow`, **`startSavePageNowJob({url,
+ slug?, requestedBy?, paths?}) → {jobId}`** (throws `SavePageNowRefusal`), `savePageNowAvailability()`,
+ `SAVE_PAGE_NOW_JOB_KIND`, `SAVE_PAGE_NOW_RESULT_MARKER`, `SPN_POLL_MS`, `SPN_MAX_POLLS`.
+- `ArchiveOrgClient.send`, `WaybackClient.send`. `archiveOrgTorrent.ts`: `ArchiveOrgFetchSettings.s3KeyFile`,
+ `DEFAULT_ARCHIVE_ORG_S3_KEY_FILE`, `looksLikeS3Key`.
+- `publish/findCopyPages.ts`: `findPageCopies`, `citedPages`, `captureAtOf`, `targetCoversUrl`, `channelsCovering`,
+ `recordForQuote`, `pageCitationAsPost`, `defaultFindPageCopiesDeps`, `FIND_PAGE_COPY_DEFAULT_MAX`,
+ `FIND_PAGE_COPY_MAX_LIMIT`.
+- Routes `POST /api/ops/check-post-availability {slug, mode?, limit?}`, `POST /api/ops/save-page-now {url, slug?,
+ dryRun?}`, `POST /api/ops/find-copy {…, pages: true, channel?, max?, dryRun?}`. Actions
+ `editor/app/channels/[slug]/waybackLiveActions.ts`. Component `components/WaybackLivePanel.tsx` (state from
+ `waybackLiveState.ts`).
+
+## Files
+
+common: `lib/waybackPages/{liveness,liveness-server,savePageNow,savePageNow-server}.ts` (+ `liveness.test.ts`),
+`controller/{checkPageAvailability,savePageNow}.ts` (+ tests), `controller/checkPostAvailability.ts` (one branch),
+`publish/findCopyPages.ts` (+ test), `lib/posts.ts`, `lib/posts-server.ts`, `lib/archiveOrgClient.ts`,
+`lib/waybackClient.ts`, `lib/archiveOrgTorrent.ts`, `lib/settingsSchema.ts`, `lib/envVars.ts`, `jobs/jobKinds.ts`,
+`bin/archilyzer.ts` (one description), `testing/web/fakeWayback.{mjs,d.mts}`, `testing/README.md`. editor:
+`app/channels/[slug]/{page.tsx, waybackLiveActions.ts, waybackLiveState.ts, components/WaybackLivePanel.tsx}`,
+`app/api/ops/{check-post-availability,save-page-now}/route.ts`, `app/api/ops/find-copy/route.ts`,
+`app/api/ops/settings/route.ts`, `e2e/wayback-live.spec.ts`, `CHANGELOG.md`. scripts: `archilyzer-ops.mjs` (+
+test). Docs: OPERATING.md, COMMANDS.md, SETTINGS.md, ENVIRONMENT.md (regenerated), plans/FACTS.md.
+
+## Commits
+
+| sha | what |
+|---|---|
+| `442129c2` | the common half: liveness (markers, verdicts, the request), the pages branch of check-post-availability, Save Page Now (keys, client send, job), find-copy's page mode, the fake's SPN block, ops actions, generated docs |
+| `fbd569ae` | the editor half: the channel page's Originals and Save Page Now, the ops routes (check-post-availability, save-page-now, find-copy pages, the settings refusal), e2e spec |
+| (this) | the record, FACTS, OPERATING |
+
+Branched from main at d261ab33; main (14947e67, lane B) merged in before the first commit (three keep-both
+conflicts: OPERATING.md, fakeWayback.mjs/.d.mts).
+
+## Gates
+
+All through the session's locks, from the worktree root.
+
+- `pnpm -r --no-bail --workspace-concurrency=1 exec tsc --noEmit`: clean on the merged tree before the commits.
+- common: start (d261ab33) **4764 / 4762 pass / 0 fail / 2 skipped**; after (on 14947e67 + this lane) **4805 /
+ 4803 / 0 / 2** (+18 of this lane: liveness 7, checkPageAvailability 3, savePageNow 5, findCopyPages 3; the rest
+ lane B's).
+- editor unit: 356 → **357 / 357** (lane B's +1; none of this lane's).
+- test:scripts: 1316 (1312 + 4 skipped) → **1317: 1313 pass / 0 fail / 4 skipped** (+1: the ops actions' usage).
+- Docs: `docs env --check`, `docs files --check`, `docs cli --check`, `settings example --check`: all 0
+ (COMMANDS.md, ENVIRONMENT.md, SETTINGS.md, settings.json.example regenerated).
+- e2e (editor, start mode, stamp `131742a50d76` at `fbd569ae`; the build 1116 s in the heavy slot):
+ `wayback-live.spec.ts` + `wayback-pages.spec.ts` **2 / 2 passed** (58.5 s; 25.6 s + 14.2 s).
+
+## Rulings followed / decisions
+
+- Liveness never asks the Wayback Machine, and an `error` is never a deletion (a 403 wall, a 5xx, a redirect to
+ another site, a DNS failure, the fence).
+- A suspended account / an unshared document is `account_unavailable` (the enum's "may reverse"), not `deleted`.
+- The S3 keys follow the Claude API key's pattern: environment first, else a mode-600 file whose PATH is the setting.
+- SPN captures the page alone (`capture_outlinks=0`); the import is its own `import-page` job queued behind.
+- find-copy's page mode imports inline (its job is on the archive.org queue) and does NOT rewrite the report: it
+ answers `pointTo` / `as`; rewriting a citation (with its fallback) is the report editor's (lane D).
+- The availability check of a pages channel runs on the channel's own queue (`platform:webpage`), not archive.org's
+ (it never asks archive.org).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -124,6 +124,11 @@
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait
// pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait
+// pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait
+// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'
+// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait
+// pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait
+// pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait
// pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'
@@ -455,6 +460,13 @@ const ACTIONS = [
// re-derived from its stored captures ({slug, dryRun?}), offline, as a job.
"import-page",
"reextract-pages",
+ // WAYBACK PAGES, LIVE (release 37 S5): a posts channel's availability check
+ // ({slug, mode?, limit?}; a Wayback pages channel: each record's ORIGINAL
+ // URL at its own site), as a job; and Save Page Now ({url, slug?, dryRun?}):
+ // the Wayback Machine asked to capture a live page now (archive.org's S3
+ // keys), the capture imported into slug, as a save-page-now job.
+ "check-post-availability",
+ "save-page-now",
// ARCHIVE SOURCES (release 37 lane F): the copies of a page across archive
// sources — the Wayback Machine and archive.today — read only and paced
// ({url, source?, limit?}).
@@ -1466,6 +1478,20 @@ export function usage() {
" with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped,",
" looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,",
" copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.",
+ ' The page mode (release 37): {"article"} | {"articles": true} |',
+ ' {"siteId"}, "pages": true, "channel"?, "max"? (10, at most 100),',
+ ' "dryRun"? -> {jobId}. Every page a report cites ("page" citations) whose',
+ " original is gone at its own site gets the Wayback capture nearest the",
+ " citation's date (one CDX lookup) imported into the Wayback pages channel",
+ " named, else the one whose targets cover the page; a cited page record",
+ " whose original is gone has its capture imported again when it is not",
+ " stored. A live page is left (save-page-now it). The answer names the",
+ " record each citation should cite (pointTo) and the citation as a post",
+ " citation of it (as); the report is not rewritten. A find-copy job on the",
+ " archive.org queue; dryRun asks the same paced questions and imports",
+ " nothing. The log ends with @@find-copy {host, dryRun, max, pages, posts,",
+ " items: [{citedBy, url, original, channel?, capture?, outcome, detail,",
+ " pointTo?, as?, records?}], left, stopped?}.",
"",
'wayback-scan lists the Wayback Machine\'s captures of a Wayback pages',
' channel\'s targets (config wayback.targets) into its wayback-scan.json,',
@@ -1554,6 +1580,32 @@ export function usage() {
" {captures, stale, records: {added, changed, removed, unchanged, kept},",
" written}.",
"",
+ "check-post-availability checks which of a posts channel's archived posts",
+ ' are gone at their source: {"slug", "mode"?: "stale" (default) |',
+ ' "unchecked" | "all", "limit"?: 200}, as a check-post-availability job.',
+ " A Wayback pages channel's records are checked by their ORIGINAL URL at",
+ " its own site (never the Wayback Machine), one request per distinct URL",
+ " through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD",
+ " is refused or the platform has a \"gone\" page; available (2xx on the",
+ " same site), deleted (404/410, or X's, Tumblr's, Google Docs' or",
+ ' YouTube\'s "does not exist" page), account_unavailable (suspended, not',
+ " shared), error otherwise — with the status. A deleted original means the",
+ " Wayback copy is the only copy. Verdicts go to posts-availability.json.",
+ "",
+ "save-page-now asks the Wayback Machine to capture a live page now (Save",
+ ' Page Now, with archive.org\'s S3 keys): {"url", "slug"?, "dryRun"?}. A',
+ " save-page-now job on the archive.org queue: the capture asked (the page",
+ " alone, no outlinks), its status polled until it is made, then — with",
+ " slug, a Wayback pages channel — an import-page job of the new capture.",
+ " Refused, before any job: no keys (ARCHIVE_ORG_S3_ACCESS and",
+ " ARCHIVE_ORG_S3_SECRET in the editor's environment, or the mode-600 file",
+ " settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page",
+ " on the Wayback Machine, not a Wayback pages channel, a video, an X page",
+ " outside an X channel while X is private. The keys are never logged.",
+ ' "dryRun" answers what it would ask and starts nothing. The log ends with',
+ " @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl,",
+ " waybackUrl, importJobId?, importError?, polls, error?}.",
+ "",
'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,',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -911,6 +911,24 @@ test("import-page and reextract-pages are POSTs to their routes, named in the us
assert.match(usage(), /import-page imports ONE Wayback Machine capture/);
});
+// Release 37 S5: a posts channel's availability check, Save Page Now and
+// find-copy's page mode are POSTs to their routes, named in the usage.
+test("check-post-availability, save-page-now and find-copy's page mode are POSTs, named in the usage", () => {
+ const c = parseArgs(["check-post-availability", "--json", '{"slug":"old-blog","mode":"unchecked"}', "--wait"]);
+ assert.equal(c.method, "POST");
+ assert.equal(c.path, "/api/ops/check-post-availability");
+ assert.deepEqual(c.body, { slug: "old-blog", mode: "unchecked" });
+ const s = parseArgs(["save-page-now", "--json", '{"url":"https://blog.example/a.html","slug":"old-blog","dryRun":true}']);
+ assert.equal(s.path, "/api/ops/save-page-now");
+ assert.deepEqual(s.body, { url: "https://blog.example/a.html", slug: "old-blog", dryRun: true });
+ const f = parseArgs(["find-copy", "--json", '{"siteId":"demo-site","pages":true,"channel":"old-blog"}', "--wait"]);
+ assert.equal(f.path, "/api/ops/find-copy");
+ assert.deepEqual(f.body, { siteId: "demo-site", pages: true, channel: "old-blog" });
+ assert.match(usage(), /Actions:.*reextract-pages, check-post-availability, save-page-now/);
+ assert.match(usage(), /save-page-now asks the Wayback Machine to capture a live page now/);
+ assert.match(usage(), /The page mode \(release 37\)/);
+});
+
// Release 37 lane F: the copies of a page across archive sources, and an
// archive.today copy's import, are POSTs to their routes.
test("archive-lookup is a POST to its route; import-page passes source through; both named in the usage", () => {
@@ -920,7 +938,7 @@ test("archive-lookup is a POST to its route; import-page passes source through;
assert.deepEqual(p.body, { url: "https://blog.example/a.html", source: "archive.today", limit: 5 });
const i = parseArgs(["import-page", "--json", '{"slug":"old-blog","url":"https://blog.example/a.html","at":"2019","source":"archive.today"}']);
assert.deepEqual(i.body, { slug: "old-blog", url: "https://blog.example/a.html", at: "2019", source: "archive.today" });
- assert.match(usage(), /Actions:.*reextract-pages, archive-lookup/);
+ assert.match(usage(), /Actions:.*save-page-now, archive-lookup/);
assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/);
assert.match(usage(), /excluded from the Wayback Machine \(cause/);
});
diff --git a/settings.json.example b/settings.json.example
@@ -195,7 +195,8 @@
"stallMinutes": 5,
"maxPeers": 30,
"maxDownloadKiBps": 0,
- "maxUploadKiBps": 0
+ "maxUploadKiBps": 0,
+ "s3KeyFile": "~/.config/archilyzer/archive-org.env"
},
"archives": {
"archiveTodayHost": "archive.ph",