Archilyzer · Source

archilyzer

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

commit bbe4aa30be3520b652e42492882b549720a97c2a
parent 7ebc4df24e999bb868f801a7dc9c8002175c8bac
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 15:36:26 -0400

Merge main (lane B: wayback-scan, the Captures tab, wayback.auto) into r37/archive-sources

Conflicts: the fake Wayback's opts (excluded beside scanRefuseFrom), the targets field
(sources beside keep), the wayback key's doc. Also: nearest by time for archive.today,
cdxPage maps a 403 to the exclusion, B's form-save test keeps sources, docs regenerated.

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

Diffstat:
MCHANNEL.md | 2+-
MCOMMANDS.md | 11++++++++---
MENVIRONMENT.md | 1+
MOPERATING.md | 22++++++++++++++++++++++
MSETTINGS.md | 25+++++++++++++++++++++++++
Mcommon/bin/archilyzer.ts | 20++++++++++++++++++++
Acommon/bin/wayback-scan.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/autoRunner.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneWaybackAuto.test.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneWaybackAuto.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackImport.test.ts | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackImport.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackScan.test.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackScan.ts | 380+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 5++++-
Mcommon/jobs/jobKinds.ts | 15+++++++++++++++
Mcommon/lib/archives/archiveToday.ts | 14+++++++++++---
Mcommon/lib/channelConfig.ts | 2+-
Mcommon/lib/waybackClient.ts | 20++++++++++++++++++++
Mcommon/lib/waybackPages/config.ts | 4++++
Acommon/lib/waybackPages/imported.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scan.test.ts | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanCdx.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanFile-server.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanFile.ts | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanView.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/targets.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/web/fakeArchiveToday.mjs | 9+++++++--
Mcommon/testing/web/fakeWayback.d.mts | 15++++++++++++++-
Mcommon/testing/web/fakeWayback.mjs | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/wayback-import/route.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/wayback-scan/route.ts | 39+++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/actions.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/components/CapturesPanel.tsx | 357+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/captures/page.tsx | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/ChannelTabs.tsx | 21+++++++++++++++++++--
Meditor/app/channels/[slug]/components/WaybackPagesPanel.tsx | 3+++
Meditor/app/channels/[slug]/layout.tsx | 11++++++++++-
Meditor/app/channels/components/ChannelForm.tsx | 1+
Meditor/app/channels/components/WaybackTargetsField.tsx | 29+++++++++++++++++++++++++++--
Meditor/app/channels/components/channelConfigToForm.ts | 3+++
Meditor/app/channels/components/parseChannelForm.test.ts | 26++++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 2+-
Aeditor/e2e/wayback-captures.spec.ts | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-37/scan.md | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/release-38/research-cases-and-assist.md | 8++++++++
Mscripts/archilyzer-ops.mjs | 39+++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 6++++++
50 files changed, 3463 insertions(+), 19 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -50,7 +50,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `browserLookup` | config | `true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: "browser"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says. | | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | | `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | -| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. | +| `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". | #### `downloadFilter` diff --git a/COMMANDS.md b/COMMANDS.md @@ -56,7 +56,9 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer run` | `<operation> <channel> [ids…] [--lane local\|remote]` | run one catalogued operation over a channel offline, as the editor's job does (sync, downloads and transcription are refused: they run in the editor; it does not see the editor's lanes, so not beside one on the same channel) | | `archilyzer archive-org refresh` | `<slug> [--dry-run]` | bring a channel's archive.org file records up to their provenance: a name-only mirror's title (where the item gives the file none) and upload date from its file name; offline, through the metadata history; prints old → new | | `archilyzer wayback refresh` | `<slug> [--titles <json>] [--dry-run]` | bring a channel's Wayback Machine copies up to the Wayback rules: wayback.json (original URL, capture time), the dir renamed to its canonical id through the snapshot's reconcile (roster moved with it), and with --titles (a file of id → {title, upload\_date}) a raw file's title and date; offline, skips a record a live job holds; prints old → new | -| `archilyzer wayback pages import` | `<slug> <url> [--at YYYYMMDD] [--dry-run]` | import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page` | +| `archilyzer wayback scan` | `<slug> [--dry-run] [--max-rows N] [--full]` | list the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json: the CDX API per target, paged with a resume key, collapse=digest, status 200, at most N rows (50000) a run, no bodies; a cut run continues next time, a complete one starts a new pass (--full: from each target's start); paced as archive.org asks, in this process — with the editor running use `pnpm ops wayback-scan`; --dry-run asks nothing and prints the next request per target | +| `archilyzer wayback pages import` | `<slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run]` | import ONE Wayback Machine capture (or archive.today copy) of a page that is not a video into a Wayback pages channel: a capture's replay URL, an archive.today copy's URL (archive.ph/&lt;id&gt;), or the page's URL and --at for the capture nearest that date (--source archive.today: its archive.today copy); the body stored under pages/, its records in the channel's posts. In-process, through this process's own paced clients — while an editor runs, prefer `pnpm ops import-page` | +| `archilyzer archive lookup` | `<url> [--source wayback\|archive.today] [--limit N]` | the copies of a page each archive source holds (the Wayback Machine's CDX, archive.today's timemap), oldest first, at most N per source (50): read only, each source through its own paced client. A source that refuses says why (excluded from the Wayback Machine, a check, a 429). While an editor runs, `pnpm ops archive-lookup` shares its clients | | `archilyzer wayback pages reextract` | `<slug> [--dry-run]` | re-derive a Wayback pages channel's records from the raw captures it stores (no request): every capture read by the extractor it goes to now, the records replaced when anything differs; --dry-run counts. Writes the channel's posts — with the editor stopped, or use `pnpm ops reextract-pages` | | `archilyzer feeds backfill-metadata` | `<slug> [--feed <url>] [--dry-run]` | complete a podcast channel's records (title, date, description, duration) from its RSS feed: one fetch of the feed (default: the channel's url), no media; --dry-run counts matched / unmatched / already complete and writes nothing | | `archilyzer media attach` | `<slug> <source> [--items <json\|@file>] [--match <regex>] [--create-records] [--replace] [--dry-run]` | give a channel's held videos their media from a LOCAL archive (a directory, a .zip read in place, a .7z) into the saved-video store, provenance recorded (archive, entry, sha256); the id from the folder's "(&lt;id&gt;)" or the file's yt-dlp suffix; --create-records writes a record for a video not held; --dry-run lists each folder's class and writes nothing; offline, nothing fetched | @@ -157,10 +159,13 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -&gt; {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | -| `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/&lt;timestamp&gt;/&lt;page&gt;) — or {"slug", "url": &lt;the page&gt;, "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?}. | `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` | +| `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/&lt;timestamp&gt;/&lt;page&gt;) — or {"slug", "url": &lt;the page&gt;, "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/&lt;id&gt;, /&lt;timestamp&gt;/&lt;page&gt;, /newest/&lt;page&gt;), 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` | -| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` | +| `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) -&gt; {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) -&gt; {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. 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"? -&gt; {jobId}. Per YouTube recording, one at a time: the Wayback Machine when it holds the video (the check yt-dlp makes, not a capture of the page), then archive.org (a mirror of the upload: its identifier, a file name or its original URL names the id, and the file has the recording's length). A copy a fetch failed from at its source (404, 410, 403, unreachable; never our own format selector) is not picked again, unless "retryFailed": true. A copy's windows are cut with a lenient selector (a direct file of unknown height: then the best single file). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". The log ends with @@find-copy {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, failedBefore, tried, copy?, outcome}\], items, stopped?, fetchJobId?, refused?}. dryRun looks and starts no fetch; a cancelled job starts none. The scope mode (release 31): {"slug"} \| {"siteId"}, "gone": "no-transcript" \| "all", "dryRun"?, "max"? (10, at most 200), "retryFailed"? -&gt; {jobId}. Every gone (deleted or private) video of the channel, or of the site's channels, that holds no audio or video ("no-transcript": and no transcript; "all": the transcribed ones too, after) is looked for the same way, at most max per run; a video whose last copy attempt found none or failed in the last 30 days is left out unless "retryFailed". Each copy's WHOLE audio is fetched into the video's own record (audio.&lt;fmt&gt;; its metadata stays the original's, the copy is in wayback.json or archiveorg.json and copy-attempts.json) by ONE fetch-copies job on archive.org's download queue, one at a time; the transcription lane then transcribes it like any downloaded audio. A video neither source holds is recorded none-found. dryRun asks the same (paced) questions and records and fetches nothing. The log ends with @@find-copy {scope, gone, dryRun, max, channels, eligible, skipped, looked: \[{slug, id, gone, noTranscript, watchUrl, youtubeId, tried, copy?, via?, outcome}\], left, items, stopped?, fetchJobId?, refused?}. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait`<br>`pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait`<br>`pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait`<br>`pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait` | +| `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"?} -&gt; {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"?: \["&lt;digest&gt; &lt;url&gt;", ...\]} or a range — "year"? (first seen), "prefix"? ("host/path/"), "q"? (text in the URL), "show"? (all \| new \| not-imported \| imported) — and "dryRun"? -&gt; {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", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -&gt; {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -235,6 +235,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `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_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 @@ -146,6 +146,28 @@ pnpm archilyzer archive lookup https://blog.example/a-post.html --source archive button per copy; a source that refuses says why in its own line. - Adding another archive service is one module: `plans/release-37/archive-sources.md`, "Adding an archive source". +### Wayback pages: scan, then choose + +```sh +pnpm ops wayback-scan --json '{"slug":"example-pages","dryRun":true}' --wait +pnpm ops wayback-scan --json '{"slug":"example-pages"}' --wait +pnpm ops wayback-import --json '{"slug":"example-pages","year":"2014","show":"not-imported","dryRun":true}' +pnpm ops wayback-import --json '{"slug":"example-pages","year":"2014","show":"not-imported"}' +``` + +- A Wayback pages channel names its scope in `config.wayback.targets` (`{url, match: exact | prefix | host | + domain, from?, to?, mime?, include?, exclude?}`). `wayback-scan` lists what the Wayback Machine holds of them + (its CDX API, no page bodies) into `channels/<slug>/wayback-scan.json`: one row per distinct content of a page, + first and last seen. At most 50,000 rows a run (`maxRows`); a cut run continues from where it stopped, a + complete one starts a new pass that marks what it adds as new (`full: true` rescans from the start). Dry run + first: it asks nothing and logs the next request per target. +- The channel page's **Captures** tab is the scan as a table: filter by year, path and text, then **Import + selected** or **Import all in range** — one `import-page` job per row, one at a time at archive.org's pace. + `wayback-import` is the same over HTTP (`keys` or a range; at most 500 a call). +- `wayback.auto: true` (the Captures tab's **Import new captures automatically**, or the channel form's) lets the download lane import rows a later scan adds, at the + 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`. + ## Fetch and capture posts ```sh diff --git a/SETTINGS.md b/SETTINGS.md @@ -47,6 +47,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`backfill`](#backfill) | object — see below | | [`attribution`](#attribution) | object — see below | | [`archiveOrg`](#archiveorg) | object — see below | +| [`archives`](#archives) | object — see below | | [`publish`](#publish) | object — see below | | [`reportSchedule`](#reportschedule) | object — see below | | [`seeder`](#seeder) | object — see below | @@ -827,6 +828,30 @@ Default: } ``` +## `archives` + +The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings. + +#### `archives` + +| Key | Default | Description | +|---|---|---| +| `archiveTodayHost` | `"archive.ph"` | The archive.today name every request goes to (archive.ph, archive.today, archive.is, archive.li, archive.vn, archive.fo or archive.md — one service). A copy's URL on any of them is read from this one. Anything else falls back to archive.ph. | +| `archiveTodayGapSeconds` | `8` | The least time between two archive.today requests, seconds, from the end of one to the start of the next, with up to a quarter more at random. One request at a time, always. Clamped to [4, 120]; default 8. | +| `archiveTodayCooldownMinutes` | `30` | After archive.today answers HTTP 429 (too many requests) the run stops, and no request goes to it for this long (or its Retry-After, when longer). Clamped to [5, 1440]; default 30. | +| `archiveTodayBrowser` | `true` | When archive.today answers with a check (a CAPTCHA, a browser check) instead of a copy, read the copy once more through the headless browser on the archive session's profile (Connect archive session keeps a cleared check there). Nothing is ever solved by code: a check the browser cannot pass is refused with a sentence. False = refuse at the check. | + +Default: + +```json +{ + "archiveTodayHost": "archive.ph", + "archiveTodayGapSeconds": 8, + "archiveTodayCooldownMinutes": 30, + "archiveTodayBrowser": true +} +``` + ## `publish` The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts. diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -677,6 +677,26 @@ export const COMMANDS: Command[] = [ }, }, { + path: ["wayback", "scan"], + usage: + "<slug> [--dry-run] [--max-rows N] [--full] list the Wayback Machine's captures of a Wayback pages channel's targets (config wayback.targets) into its wayback-scan.json: the CDX API per target, paged with a resume key, collapse=digest, status 200, at most N rows (50000) a run, no bodies; a cut run continues next time, a complete one starts a new pass (--full: from each target's start); paced as archive.org asks, in this process — with the editor running use `pnpm ops wayback-scan`; --dry-run asks nothing and prints the next request per target", + flags: { "dry-run": "boolean", "max-rows": "string", full: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => { + const [slug] = positionals; + if (!slug) { + console.error("wayback scan: which channel? Pass its slug."); + return 2; + } + return (await import("./wayback-scan")).main({ + slug, + dryRun: flags["dry-run"] === true, + full: flags.full === true, + ...(typeof flags["max-rows"] === "string" ? { maxRows: Number(flags["max-rows"]) } : {}), + }); + }, + }, + { path: ["wayback", "pages", "import"], usage: "<slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run] import ONE Wayback Machine capture (or archive.today copy) of a page that is not a video into a Wayback pages channel: a capture's replay URL, an archive.today copy's URL (archive.ph/<id>), or the page's URL and --at for the capture nearest that date (--source archive.today: its archive.today copy); the body stored under pages/, its records in the channel's posts. In-process, through this process's own paced clients — while an editor runs, prefer `pnpm ops import-page`", diff --git a/common/bin/wayback-scan.ts b/common/bin/wayback-scan.ts @@ -0,0 +1,54 @@ +// `archilyzer wayback scan <slug> [--dry-run] [--max-rows N] [--full]` — a +// Wayback pages channel's CDX scan into its wayback-scan.json +// (controller/waybackScan.ts), in this process: no editor needed. The same +// paced client the editor uses (one request at a time, 2 s apart, 429/503 +// waited out) — its own instance, so with the editor running, scan through +// `pnpm ops wayback-scan` instead and keep archive.org on one queue. No bodies +// are fetched. Prints the run's summary; exit 1 when archive.org refused. + +import { isValidChannelSlug } from "../controller/channels"; +import { readWaybackChannelConfig, runWaybackScan } from "../controller/waybackScan"; +import { SCAN_MAX_ROWS_LIMIT } from "../lib/waybackPages/scanCdx"; +import { getPaths, type Paths } from "../lib/paths"; + +export async function main(opts: { + slug: string; + dryRun: boolean; + full: boolean; + maxRows?: number; + paths?: Paths; +}): Promise<number> { + if (!isValidChannelSlug(opts.slug)) { + console.error(`wayback scan: "${opts.slug}" is not a channel slug`); + return 2; + } + if (opts.maxRows !== undefined && (!Number.isInteger(opts.maxRows) || opts.maxRows < 1 || opts.maxRows > SCAN_MAX_ROWS_LIMIT)) { + console.error(`wayback scan: --max-rows must be a whole number from 1 to ${SCAN_MAX_ROWS_LIMIT}`); + return 2; + } + const paths = opts.paths ?? getPaths(); + const wayback = await readWaybackChannelConfig(paths, opts.slug); + if (!wayback) { + console.error(`wayback scan: ${opts.slug} is not a Wayback pages channel (its config names no wayback.targets)`); + return 2; + } + const r = await runWaybackScan({ + paths, + slug: opts.slug, + wayback, + dryRun: opts.dryRun, + full: opts.full, + ...(opts.maxRows !== undefined ? { maxRows: opts.maxRows } : {}), + onLog: (line) => console.log(line), + }); + console.log( + `${r.dryRun ? "dry run: " : ""}pass ${r.pass}${r.newPass ? " (new)" : ""}: ${r.requests} requests, ${r.rowsRead} rows read, ` + + `${r.added} new, ${r.totalRows} in the scan` + + (r.complete ? " — every target complete" : r.stopped ? ` — stopped: ${r.stopped}` : ""), + ); + if (!r.ok) { + console.error(`wayback scan: ${r.error}`); + return 1; + } + return 0; +} diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -95,6 +95,13 @@ import { type StoredUrlAttempt, } from "../lib/downloadOutcome"; import { downloadQueueKey } from "../lib/queueKeys"; +import { + launchWaybackAutoImport, + WAYBACK_AUTO_LEAF_ID, + WAYBACK_AUTO_PLATFORM, + WaybackAutoPicker, + type WaybackAutoPick, +} from "./laneWaybackAuto"; import { isGateHeld } from "../lib/pauseGates"; import { inspectChannelMedia, @@ -1176,6 +1183,10 @@ type Picked = { // past a cooling or held platform because its record stores a media URL; it // downloads as `only`, `held` on a held platform. storedOnly?: { held: boolean }; + // THE WAYBACK IMPORT UNIT (release 37 S2, controller/laneWaybackAuto.ts): a + // `wayback.auto` channel's next new scan row, imported by one import-page + // job. Channel-scoped like `scan`: no node's active count moves for it. + waybackImport?: WaybackAutoPick; }; async function runLoop( @@ -1290,6 +1301,9 @@ async function runLoop( // Channels this runner has already scanned (or tried to). See the pre-pick in // next() for why a scan is never retried inside one runner's lifetime. const scannedThisRun = new Set<string>(); + // `wayback.auto` channels' new scan rows (release 37 S2): read once a minute + // per channel, each row offered once in this runner's life. + const waybackAuto = WaybackAutoPicker.forPaths(paths); // Platforms this tick may not touch — busy or cooling down. Hoisted out of the // download branch because the metadata-scan pre-pick honours it too: a // platform in a 429 cooldown must not be asked for 1,800 titles either. @@ -1847,6 +1861,42 @@ async function runLoop( } } + // ── A WAYBACK PAGES CHANNEL'S NEW CAPTURES (release 37 S2) ───────────── + // + // Only a channel whose `wayback.auto` is on: the lane never crawls a host + // nobody opted in. One import-page job per unit, on the `archive.org` + // platform slot (one at a time, the lane's gap and back-off for it), after + // the scans and before the downloads; honours the focus hold. + if (kind === "download") { + const wb = await waybackAuto.pick(metaCache, { + platformSkip, + ...(focus ? { focus: { slugs: new Set(ctx.focusSlugs), holding: focus.holding } } : {}), + }); + if (wb) { + const unitPlatform = WAYBACK_AUTO_PLATFORM; + const videoId = wb.unitId; + const note = `importing a Wayback capture for ${wb.slug}: ${wb.row.replayUrl}`; + live.idleReason = null; + live.inFlight.set(videoId, { + videoId, + leafId: WAYBACK_AUTO_LEAF_ID, + channelSlug: wb.slug, + startedAt: Date.now(), + note, + }); + platformInFlight.set(unitPlatform, (platformInFlight.get(unitPlatform) ?? 0) + 1); + recordPick(kindState, { at: Date.now(), leafId: WAYBACK_AUTO_LEAF_ID, videoId, channelSlug: wb.slug }); + persist(); + onLog(`Auto-download: ${note}.`); + return { + pick: { leafId: WAYBACK_AUTO_LEAF_ID, videoId, path: [] }, + channelSlug: wb.slug, + unitPlatform, + waybackImport: wb, + }; + } + } + const pick = selectNextWork(root, pending, runtime, live.active); if (!pick) { // Attribute the idleness. Nothing pending at all is a different situation @@ -2024,6 +2074,14 @@ async function runLoop( result = { outcome: "skipped" }; return; } + if (picked.waybackImport) { + result = await launchWaybackAutoImport({ + pick: picked.waybackImport, + onLog, + onChildJob: (jid) => { childJobIds.set(pick.videoId, jid); const u = live.inFlight.get(pick.videoId); if (u) u.jobId = jid; }, + }); + return; + } if (picked.scan) { result = await launchMetadataScan({ paths, diff --git a/common/controller/laneWaybackAuto.test.ts b/common/controller/laneWaybackAuto.test.ts @@ -0,0 +1,101 @@ +// `wayback.auto` in the download lane (release 37 S2): which channel's row a +// unit takes (opted in only, the lane's order, the focus hold, the platform +// slot), each row once per runner, the minute-long cache; and a unit's +// import-page job waited on to its end. Synthetic rows; the starter is the +// seam. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/laneWaybackAuto.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "lane-wayback-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); + +const { WaybackAutoPicker, waybackAutoOn, awaitJobEnd, launchWaybackAutoImport, WAYBACK_AUTO_PLATFORM } = await import("./laneWaybackAuto"); +const { setImportPageStarterForTest } = await import("./waybackImport"); +const { runManagedFunction } = await import("../jobs/streamCommand"); +const { getPaths } = await import("../lib/paths"); + +const row = (key: string) => + ({ key, originalUrl: key, path: key, digest: "D", firstTs: "20160101000000", lastTs: "20160101000000", count: 1, version: 1, versions: 1, isNew: true, imported: null, replayUrl: `https://web.archive.org/web/20160101000000/${key}` }) as const; + +const on = (targets = [{ url: "a.example", match: "host" }]) => ({ handling: "transcribe", wayback: { targets, auto: true } }); + +test("only opted-in channels, in the lane's order; each row once; none while the platform is skipped or outside a holding focus", async () => { + let reads = 0; + let clock = 0; + const picker = new WaybackAutoPicker({ + pending: async (slug) => { + reads++; + return slug === "b" ? [row("https://b.example/1"), row("https://b.example/2")] : slug === "c" ? [row("https://c.example/1")] : []; + }, + now: () => clock, + ttlMs: 1000, + }); + assert.equal(waybackAutoOn(on()), true); + assert.equal(waybackAutoOn({ wayback: { targets: [{ url: "x" }] } }), false); + assert.equal(waybackAutoOn({}), false); + const channels = [ + { slug: "a", config: { handling: "transcribe", wayback: { targets: [{ url: "a.example" }] } } }, + { slug: "b", config: on() }, + { slug: "c", config: on() }, + ]; + const none = new Set<string>(); + assert.equal(await picker.pick(channels, { platformSkip: new Set([WAYBACK_AUTO_PLATFORM]) }), null); + const p1 = await picker.pick(channels, { platformSkip: none }); + assert.equal(p1?.slug, "b"); + assert.equal(p1?.row.key, "https://b.example/1"); + assert.equal(p1?.unitId, "wayback-import b https://b.example/1"); + assert.equal((await picker.pick(channels, { platformSkip: none }))?.row.key, "https://b.example/2"); + assert.equal((await picker.pick(channels, { platformSkip: none }))?.slug, "c"); + assert.equal(await picker.pick(channels, { platformSkip: none }), null, "each row once in a runner's life"); + const readsBefore = reads; + await picker.pick(channels, { platformSkip: none }); + assert.equal(reads, readsBefore, "cached inside the TTL"); + clock = 5000; + await picker.pick(channels, { platformSkip: none }); + assert.ok(reads > readsBefore, "re-read after the TTL"); + const focused = new WaybackAutoPicker({ pending: async (slug) => [row(`https://${slug}.example/1`)] }); + assert.equal((await focused.pick(channels, { platformSkip: none, focus: { slugs: new Set(["c"]), holding: true } }))?.slug, "c"); + assert.equal((await focused.pick(channels, { platformSkip: none, focus: { slugs: new Set(["c"]), holding: false } }))?.slug, "b"); +}); + +test("a unit: the row's import-page job, waited on to its end; a refusal is a skip", async () => { + const paths = getPaths(); + const pick = { slug: "b", row: row("https://b.example/1"), unitId: "u" }; + for (const [fail, outcome] of [[false, "transcribed"], [true, "failed"]] as const) { + setImportPageStarterForTest(async () => { + const r = await runManagedFunction({ + kind: "import-page-test", + queueKey: "", + paths, + fn: async () => { + await new Promise((res) => setTimeout(res, 20)); + if (fail) throw new Error("no"); + }, + }); + if (!r.ok) throw new Error(r.error); + void r.stream.cancel(); + return { jobId: r.jobId }; + }); + let child = ""; + const lines: string[] = []; + const out = await launchWaybackAutoImport({ pick, onLog: (l) => lines.push(l), onChildJob: (j) => (child = j) }); + assert.equal(out.outcome, outcome); + assert.ok(child); + assert.ok(["done", "failed"].includes(await awaitJobEnd(child)), "an ended job answers at once"); + } + setImportPageStarterForTest(async () => { + throw new Error("held"); + }); + const lines: string[] = []; + assert.deepEqual(await launchWaybackAutoImport({ pick, onLog: (l) => lines.push(l) }), { outcome: "skipped" }); + assert.match(lines[0], /could not queue the Wayback import .*: held/); + setImportPageStarterForTest(async () => ({ jobId: "seam-1" })); + assert.deepEqual(await launchWaybackAutoImport({ pick, onLog: () => {} }), { outcome: "skipped" }, "an id the registry does not hold"); + setImportPageStarterForTest(null); +}); diff --git a/common/controller/laneWaybackAuto.ts b/common/controller/laneWaybackAuto.ts @@ -0,0 +1,123 @@ +// `wayback.auto` IN THE DOWNLOAD LANE (release 37 S2): a Wayback pages channel +// that opts in has its new scan rows imported by the lane — one row per unit, +// one `import-page` job per row (controller/waybackImport.ts), on archive.org's +// queue, waited on like the metadata scan's child job, at the lane's pace for +// the `archive.org` platform (one unit at a time; the gap and back-off its +// outcomes earn). Default off: no unattended crawling of a host unless the +// channel opts in. +// +// What a unit takes is `pendingAutoImports`: rows first listed after the +// channel's first pass that no record holds yet, oldest first. A channel's list +// is read at most once a minute (the scan file and the channel's posts), and a +// row the runner has tried is not offered again in its lifetime — a failed +// import waits for the operator or a restart, never a re-hammer. + +import type { Paths } from "../lib/paths"; +import { onJobEnd, getRegistry, type JobStatus } from "../jobs/registry"; +import { waybackConfigOf } from "../lib/waybackPages/targets"; +import type { CaptureRowView } from "../lib/waybackPages/scanView"; +import { pendingAutoImports, startCaptureImport } from "./waybackImport"; + +export const WAYBACK_AUTO_LEAF_ID = "wayback-auto"; +export const WAYBACK_AUTO_UNIT_PREFIX = "wayback-import "; +// The platform key a unit holds: one Wayback import at a time in the lane. +export const WAYBACK_AUTO_PLATFORM = "archive.org"; +export const WAYBACK_AUTO_TTL_MS = 60_000; + +export function waybackAutoOn(config: unknown): boolean { + return waybackConfigOf(config)?.auto === true; +} + +export type WaybackAutoPick = { slug: string; row: CaptureRowView; unitId: string }; + +export class WaybackAutoPicker { + private readonly cache = new Map<string, { at: number; rows: CaptureRowView[] }>(); + private readonly tried = new Set<string>(); + constructor( + private readonly deps: { + pending: (slug: string) => Promise<CaptureRowView[]>; + now?: () => number; + ttlMs?: number; + }, + ) {} + + static forPaths(paths: Paths): WaybackAutoPicker { + return new WaybackAutoPicker({ pending: (slug) => pendingAutoImports(paths, slug) }); + } + + private async rowsOf(slug: string): Promise<CaptureRowView[]> { + const now = (this.deps.now ?? Date.now)(); + const hit = this.cache.get(slug); + if (hit && now - hit.at < (this.deps.ttlMs ?? WAYBACK_AUTO_TTL_MS)) return hit.rows; + const rows = await this.deps.pending(slug).catch(() => [] as CaptureRowView[]); + this.cache.set(slug, { at: now, rows }); + return rows; + } + + // The next row to import: the first opted-in channel (in the lane's order) + // with a row not tried yet. None while the platform is skipped (busy, + // cooling, held, paced) or, under a holding focus, outside it. + async pick( + channels: ReadonlyArray<{ slug: string; config: unknown }>, + opts: { platformSkip: ReadonlySet<string>; focus?: { slugs: ReadonlySet<string>; holding: boolean } }, + ): Promise<WaybackAutoPick | null> { + if (opts.platformSkip.has(WAYBACK_AUTO_PLATFORM)) return null; + for (const c of channels) { + if (!waybackAutoOn(c.config)) continue; + if (opts.focus?.holding && !opts.focus.slugs.has(c.slug)) continue; + for (const row of await this.rowsOf(c.slug)) { + const unitId = `${WAYBACK_AUTO_UNIT_PREFIX}${c.slug} ${row.key}`; + if (this.tried.has(unitId)) continue; + this.tried.add(unitId); + return { slug: c.slug, row, unitId }; + } + } + return null; + } +} + +// A job's end: its terminal status, or "unknown" for an id the registry does +// not hold. +export function awaitJobEnd(jobId: string): Promise<JobStatus | "unknown"> { + const terminal = (s: JobStatus | undefined) => s === "done" || s === "failed" || s === "cancelled"; + const now = getRegistry().get(jobId); + if (!now) return Promise.resolve("unknown"); + if (terminal(now.status)) return Promise.resolve(now.status); + return new Promise((resolve) => { + const stop = onJobEnd((j) => { + if (j.id !== jobId) return; + stop(); + resolve(j.status); + }); + // The end may have landed between the read above and the listener. + const again = getRegistry().get(jobId); + if (again && terminal(again.status)) { + stop(); + resolve(again.status); + } + }); +} + +// ONE UNIT: the row's import-page job, waited on. "transcribed" (the lane's +// word for done), "failed", or "skipped" (refused before a job, or cancelled). +export async function launchWaybackAutoImport(args: { + pick: WaybackAutoPick; + onLog: (line: string) => void; + onChildJob?: (jobId: string) => void; +}): Promise<{ outcome: "transcribed" | "failed" | "skipped" }> { + let jobId: string; + try { + ({ jobId } = await startCaptureImport(args.pick.slug, args.pick.row, "auto-download")); + } catch (e) { + args.onLog(`Auto-download: could not queue the Wayback import of ${args.pick.row.replayUrl}: ${(e as Error).message}`); + return { outcome: "skipped" }; + } + args.onChildJob?.(jobId); + const end = await awaitJobEnd(jobId); + if (end === "done") return { outcome: "transcribed" }; + if (end === "failed") { + args.onLog(`Auto-download: the Wayback import of ${args.pick.row.replayUrl} failed.`); + return { outcome: "failed" }; + } + return { outcome: "skipped" }; +} diff --git a/common/controller/waybackImport.test.ts b/common/controller/waybackImport.test.ts @@ -0,0 +1,186 @@ +// Queueing imports of chosen scan rows (release 37 S2): by key, by the +// table's filter, a dry run, the batch cap, a refusal, and what wayback.auto +// would take — one import-page request per row (the starter swapped for a +// recorder, and S1's own door once), and the imported derivation over real +// webpage records. Synthetic scan files and records only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/waybackImport.test.ts + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "wayback-import-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +after(() => rm(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { emptyScanFile, mergeCdxRows, summarizeScan } = await import("../lib/waybackPages/scanFile"); +const { writeWaybackScan } = await import("../lib/waybackPages/scanFile-server"); +const { + IMPORT_BATCH_MAX, + pendingAutoImports, + queueCaptureImports, + setImportPageStarterForTest, +} = await import("./waybackImport"); + +const row = (originalUrl: string, timestamp: string, digest: string) => ({ originalUrl, timestamp, digest, mimetype: "text/html", status: 200 }); + +async function scan(slug: string, pass1: ReturnType<typeof row>[], pass2: ReturnType<typeof row>[] = []) { + await mkdir(path.join(getPaths().channelsDir, slug), { recursive: true }); + const file = emptyScanFile(slug, "2026-01-01T00:00:00.000Z"); + mergeCdxRows(file, pass1); + if (pass2.length) { + file.pass = 2; + mergeCdxRows(file, pass2); + } + file.summary = summarizeScan(file.rows); + await writeWaybackScan(getPaths().channelsDir, file); +} + +const asked: unknown[] = []; +setImportPageStarterForTest(async (req) => { + const { paths: _p, ...rest } = req; + asked.push(rest); + return { jobId: `job-${asked.length}` }; +}); + +await scan( + "blog", + [ + row("https://blog.example/", "20140102030405", "HOMEA"), + row("https://blog.example/post/1", "20140203000000", "P1A"), + row("https://blog.example/post/1", "20150203000000", "P1B"), + row("https://blog.example/post/2", "20150506000000", "P2A"), + ], + [row("https://blog.example/post/3", "20160101000000", "P3A")], +); + +test("by key: one import-page request per row, the capture it was first listed at; an unknown key is skipped", async () => { + asked.length = 0; + const r = await queueCaptureImports({ + paths: getPaths(), + slug: "blog", + keys: ["P1B https://blog.example/post/1", "NOPE https://blog.example/x", "P1B https://blog.example/post/1"], + requestedBy: "captures", + }); + assert.equal(r.ok, true); + assert.equal(r.chosen, 1); + assert.deepEqual(asked, [{ slug: "blog", url: "https://web.archive.org/web/20150203000000/https://blog.example/post/1", requestedBy: "captures" }]); + assert.deepEqual(r.queued, [{ key: "P1B https://blog.example/post/1", url: "https://web.archive.org/web/20150203000000/https://blog.example/post/1", jobId: "job-1" }]); + assert.deepEqual(r.skipped, [{ key: "NOPE https://blog.example/x", why: "not in the scan" }]); +}); + +test("by filter (Import all in range): year, prefix, text, new; a dry run queues nothing", async () => { + asked.length = 0; + const y = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { year: "2015" } }); + assert.deepEqual(y.queued.map((q) => q.key), ["P1B https://blog.example/post/1", "P2A https://blog.example/post/2"]); + const p = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { prefix: "blog.example/post/" }, dryRun: true }); + assert.equal(p.queued.length, 4); + assert.equal(p.queued.every((q) => q.jobId === undefined), true); + const n = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { show: "new" }, dryRun: true }); + assert.deepEqual(n.queued.map((q) => q.key), ["P3A https://blog.example/post/3"]); + const q = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: { q: "POST/2" }, dryRun: true }); + assert.deepEqual(q.queued.map((x) => x.key), ["P2A https://blog.example/post/2"]); + assert.equal(asked.length, 2, "only the real run asked"); +}); + +test("no scan is a refusal; a starter's refusal stops the batch with its sentence", async () => { + const none = await queueCaptureImports({ paths: getPaths(), slug: "nothing", filter: {} }); + assert.equal(none.ok, false); + assert.match(none.error ?? "", /no Wayback scan yet/); + setImportPageStarterForTest(async () => { + throw new Error("the platform is held"); + }); + try { + const r = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: {} }); + assert.equal(r.ok, false); + assert.equal(r.error, "the platform is held"); + assert.equal(r.queued.length, 0); + } finally { + setImportPageStarterForTest(async (req) => { + const { paths: _p, ...rest } = req; + asked.push(rest); + return { jobId: `job-${asked.length}` }; + }); + } +}); + +test("at most IMPORT_BATCH_MAX a call; the rest are left for the next", async () => { + const many = Array.from({ length: IMPORT_BATCH_MAX + 7 }, (_, i) => row(`https://many.example/p/${i}`, `2014010100${String(i).padStart(4, "0")}`, `D${i}`)); + await scan("many", many); + const r = await queueCaptureImports({ paths: getPaths(), slug: "many", filter: {}, dryRun: true }); + assert.equal(r.chosen, IMPORT_BATCH_MAX + 7); + assert.equal(r.queued.length, IMPORT_BATCH_MAX); + assert.equal(r.left, 7); +}); + +test("wayback.auto takes the rows listed after the first pass, oldest first", async () => { + const pending = await pendingAutoImports(getPaths(), "blog"); + assert.deepEqual(pending.map((r) => r.key), ["P3A https://blog.example/post/3"]); + assert.deepEqual(await pendingAutoImports(getPaths(), "nothing"), []); +}); + +test("the default door is S1's import-page: refused with its sentence for a channel that is not a Wayback pages channel", async () => { + setImportPageStarterForTest(null); + const r = await queueCaptureImports({ paths: getPaths(), slug: "blog", keys: ["HOMEA https://blog.example/"] }); + assert.equal(r.ok, false); + assert.ok(r.error && r.error.length > 0); + assert.equal(r.queued.length, 0); +}); + +test("imported: a webpage record of a row's content is marked and skipped, through the posts store's reader", async () => { + setImportPageStarterForTest(async (req) => { + const { paths: _p, ...rest } = req; + asked.push(rest); + return { jobId: `job-${asked.length}` }; + }); + const { writePosts } = await import("../lib/posts-server"); + const { readImportedIndex } = await import("../lib/waybackPages/scanFile-server"); + const root = path.join(getPaths().channelsDir, "blog"); + const page = (originalUrl: string, captureTs: string, digest?: string) => ({ + originalUrl, + captureTs, + waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`, + rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`, + kind: "generic" as const, + extractor: "generic", + extractorVersion: 1, + ...(digest ? { digest } : {}), + }); + const post = (id: string, p: ReturnType<typeof page>) => ({ + id, + slug: `blog/${id}`, + channelSlug: "blog", + author: "blog.example", + createdAt: "2015-02-03T00:00:00.000Z", + uploadDate: "20150203", + text: "A post.", + url: p.originalUrl, + platform: "webpage" as const, + isReply: false, + isRepost: false, + links: [], + threadId: "page-x", + page: p, + }); + await writePosts(root, [ + post("20150203000000-aaaaaaaaaaaa", page("https://blog.example/post/1", "20150203000000", "P1B")), + post("20140102030405-bbbbbbbbbbbb", page("http://www.blog.example/", "20140102030405")), + ]); + const index = await readImportedIndex(getPaths().channelsDir, "blog"); + assert.equal(index.size, 2); + asked.length = 0; + const r = await queueCaptureImports({ paths: getPaths(), slug: "blog", filter: {} }); + assert.equal(r.ok, true); + assert.deepEqual( + r.skipped.map((x) => x.key).sort(), + ["HOMEA https://blog.example/", "P1B https://blog.example/post/1"], + ); + assert.equal(r.skipped.every((x) => x.why.startsWith("imported as ")), true); + assert.deepEqual(r.queued.map((q) => q.key), ["P1A https://blog.example/post/1", "P2A https://blog.example/post/2", "P3A https://blog.example/post/3"]); + const auto = await pendingAutoImports(getPaths(), "blog"); + assert.deepEqual(auto.map((x) => x.key), ["P3A https://blog.example/post/3"]); +}); diff --git a/common/controller/waybackImport.ts b/common/controller/waybackImport.ts @@ -0,0 +1,122 @@ +// IMPORTING CHOSEN SCAN ROWS (release 37 S2): the Captures tab's Import selected +// and Import all in range, `pnpm ops wayback-import`, and the download lane's +// `wayback.auto` pick all end here — one `import-page` job per row (S1's job, +// controller/importPage.ts), queued on archive.org's queue, so they run one at +// a time at its pace. A row already imported (a webpage record holds its +// content, imported.ts) is skipped; at most IMPORT_BATCH_MAX are queued per +// call. Each job takes the capture the row was first listed at — exactly that +// content. + +import type { Paths } from "../lib/paths"; +import { startImportPageJob } from "./importPage"; +import { readImportedIndex, readWaybackScan } from "../lib/waybackPages/scanFile-server"; +import { + captureRows, + filterCaptureRows, + type CaptureFilter, + type CaptureRowView, +} from "../lib/waybackPages/scanView"; + +export type ImportPageRequest = { slug: string; url: string; at?: string; requestedBy?: string; paths?: Paths }; +export type ImportPageStarter = (req: ImportPageRequest) => Promise<{ jobId: string }>; + +// At most this many jobs per call: a 50,000-row range is queued a batch at a +// time, never as 50,000 records at once. +export const IMPORT_BATCH_MAX = 500; + +export const WAYBACK_IMPORT_BODY_KEYS = ["slug", "keys", "year", "prefix", "q", "show", "dryRun"] as const; + +// THE DOOR to `import-page`: S1's job (controller/importPage.ts), one per row. +// Its refusal (ImportPageRefusal) carries the plan's sentence. +async function defaultStarter(req: ImportPageRequest): Promise<{ jobId: string }> { + return startImportPageJob(req); +} + +let starter: ImportPageStarter = defaultStarter; + +// Tests (and nothing else) swap the starter. +export function setImportPageStarterForTest(fn: ImportPageStarter | null): void { + starter = fn ?? defaultStarter; +} + +export type CaptureImportResult = { + ok: boolean; + error?: string; + slug: string; + dryRun: boolean; + // Rows the selection or the range named. + chosen: number; + queued: { key: string; url: string; jobId?: string }[]; + skipped: { key: string; why: string }[]; + // Rows left for another call (over IMPORT_BATCH_MAX). + left: number; +}; + +export type QueueCaptureImportsOpts = { + paths: Paths; + slug: string; + // The rows by key (`<digest> <originalUrl>`), or every row the filter keeps. + keys?: ReadonlyArray<string>; + filter?: CaptureFilter; + dryRun?: boolean; + requestedBy?: string; +}; + +export async function queueCaptureImports(opts: QueueCaptureImportsOpts): Promise<CaptureImportResult> { + const base = { slug: opts.slug, dryRun: opts.dryRun === true, chosen: 0, queued: [], skipped: [], left: 0 }; + const file = await readWaybackScan(opts.paths.channelsDir, opts.slug); + if (!file) return { ...base, ok: false, error: `${opts.slug} has no Wayback scan yet: scan it first.` }; + const rows = captureRows(file, await readImportedIndex(opts.paths.channelsDir, opts.slug)); + const out: CaptureImportResult = { ...base, ok: true, queued: [], skipped: [] }; + let chosen: CaptureRowView[]; + if (opts.keys) { + const byKey = new Map(rows.map((r) => [r.key, r])); + chosen = []; + for (const key of new Set(opts.keys)) { + const r = byKey.get(key); + if (r) chosen.push(r); + else out.skipped.push({ key, why: "not in the scan" }); + } + } else { + chosen = filterCaptureRows(rows, opts.filter ?? {}); + } + out.chosen = chosen.length; + const todo: CaptureRowView[] = []; + for (const r of chosen) { + if (r.imported) out.skipped.push({ key: r.key, why: `imported as ${r.imported.id}` }); + else todo.push(r); + } + out.left = Math.max(0, todo.length - IMPORT_BATCH_MAX); + for (const r of todo.slice(0, IMPORT_BATCH_MAX)) { + if (opts.dryRun) { + out.queued.push({ key: r.key, url: r.replayUrl }); + continue; + } + try { + const { jobId } = await starter({ slug: opts.slug, url: r.replayUrl, paths: opts.paths, ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}) }); + out.queued.push({ key: r.key, url: r.replayUrl, jobId }); + } catch (e) { + // A refusal of the first is a refusal of all (the same channel, the same job). + return { ...out, ok: false, error: (e as Error).message }; + } + } + return out; +} + +// ONE ROW, for the download lane's `wayback.auto` unit. +export async function startCaptureImport(slug: string, row: Pick<CaptureRowView, "replayUrl">, requestedBy: string, paths?: Paths): Promise<{ jobId: string }> { + return starter({ slug, url: row.replayUrl, requestedBy, ...(paths ? { paths } : {}) }); +} + +// What `wayback.auto` imports: rows first listed after the channel's first +// pass (a capture the Wayback Machine took, or indexed, since the channel's +// scope was first listed) that no record holds yet, oldest first. The first +// pass's rows are the operator's to choose. +export async function pendingAutoImports(paths: Paths, slug: string): Promise<CaptureRowView[]> { + const file = await readWaybackScan(paths.channelsDir, slug); + if (!file) return []; + const pass1 = new Set(file.rows.filter((r) => r.pass <= 1).map((r) => `${r.digest} ${r.originalUrl}`)); + return captureRows(file, await readImportedIndex(paths.channelsDir, slug)) + .filter((r) => !r.imported && !pass1.has(r.key)) + .sort((a, b) => a.firstTs.localeCompare(b.firstTs) || a.key.localeCompare(b.key)); +} diff --git a/common/controller/waybackScan.test.ts b/common/controller/waybackScan.test.ts @@ -0,0 +1,207 @@ +// The Wayback pages scan end to end over a temp corpus and the fake Wayback +// (common/testing/web/fakeWayback.mjs, its scan listing): paged with the +// resume key across two runs, the row cap, collapse by digest, the filters, +// a second pass that asks only from before the first began and marks what it +// added, a refusal that keeps the resume key, the dry run that asks nothing, +// and the refusals before any job. No real archive.org. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/waybackScan.test.ts + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "wayback-scan-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); + +const { getPaths } = await import("../lib/paths"); +const { WaybackClient } = await import("../lib/waybackClient"); +const { startFakeWayback, SCAN_CAPTURES } = await import("../testing/web/fakeWayback.mjs"); +const { runWaybackScan, startWaybackScanJob, parseWaybackScanBody, WAYBACK_QUEUE } = await import("./waybackScan"); +const { readWaybackScan } = await import("../lib/waybackPages/scanFile-server"); +const { isNewRow } = await import("../lib/waybackPages/scanFile"); +const { getRegistry } = await import("../jobs/registry"); + +const wb = await startFakeWayback({ captures: SCAN_CAPTURES }); +after(async () => { + await wb.close(); + await rm(ROOT, { recursive: true, force: true }); +}); + +const client = () => new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 1 }); + +async function channel(slug: string, wayback: unknown) { + const dir = path.join(getPaths().channelsDir, slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", name: slug, url: "https://web.archive.org/web/*/blog.example*", wayback }), + ); +} + +const scanRequests = () => wb.requests.filter((r: { path: string }) => r.path.includes("showResumeKey=true")); + +test("paged with the resume key across two runs under a row cap; collapsed by digest; assets, 404s and images left out", async () => { + await channel("blog", { targets: [{ url: "blog.example", match: "host" }] }); + const paths = getPaths(); + const wayback = { targets: [{ url: "blog.example", match: "host" as const }], collapse: "digest" as const, auto: false }; + const before = scanRequests().length; + const first = await runWaybackScan({ paths, slug: "blog", wayback, maxRows: 4, client: client() }); + assert.equal(first.ok, true); + assert.equal(first.complete, false); + assert.equal(first.stopped, "row cap"); + assert.equal(first.rowsRead, 4); + assert.equal(first.requests, 1); + const file1 = (await readWaybackScan(paths.channelsDir, "blog"))!; + assert.equal(file1.targets[0].resumeKey, "fake-4"); + assert.equal(file1.targets[0].complete, false); + const second = await runWaybackScan({ paths, slug: "blog", wayback, maxRows: 100, client: client() }); + assert.equal(second.complete, true); + assert.equal(second.newPass, false, "the same pass, continued"); + const asked = scanRequests().slice(before).map((r: { path: string }) => new URL(r.path, "http://x").searchParams); + assert.equal(asked.length, 2); + assert.equal(asked[0].get("resumeKey"), null); + assert.equal(asked[0].get("limit"), "4"); + assert.equal(asked[1].get("resumeKey"), "fake-4"); + assert.equal(asked[1].get("matchType"), "host"); + const file = (await readWaybackScan(paths.channelsDir, "blog"))!; + const keys = file.rows.map((r) => `${r.originalUrl} ${r.digest}`); + assert.deepEqual(keys, [ + "https://blog.example/ HOMEA", + "https://blog.example/ HOMEB", + "https://blog.example/post/101/first-post P101A", + "https://blog.example/post/101/first-post P101B", + "https://blog.example/post/102/second-post P102A", + "https://blog.example/post/103/third-post P103A", + "https://blog.example/tagged/bread TAGA", + ], "the css (served as text/html) dropped by extension, the png by mime, the 404 by status, about. by host"); + const home = file.rows.find((r) => r.digest === "HOMEA")!; + assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140102030405", "20140102030405", 1], "the June capture of the same content collapsed away"); + assert.equal(file.summary.pages, 5); + assert.deepEqual(file.summary.byYear, { "2014": 3, "2015": 4 }); + assert.equal(file.targets[0].complete, true); + assert.equal(file.targets[0].resumeKey, undefined); + assert.ok(file.lastScanAt); + assert.equal(file.rows.some((r) => isNewRow(file, r)), false, "nothing is new on the first pass"); +}); + +test("a later pass asks from 30 days before the last began, merges, and marks only what it added", async () => { + const paths = getPaths(); + const wayback = { targets: [{ url: "blog.example", match: "host" as const }], collapse: "digest" as const, auto: false }; + const firstPassStart = (await readWaybackScan(paths.channelsDir, "blog"))!.passStartedAt; + // A new capture of a new post appears. + SCAN_CAPTURES.push({ original: "https://blog.example/post/104/fourth", timestamp: "20991231000000", statuscode: "200", mimetype: "text/html", digest: "P104A" }); + try { + const before = scanRequests().length; + const run = await runWaybackScan({ paths, slug: "blog", wayback, client: client(), now: () => new Date(Date.parse(firstPassStart) + 86_400_000) }); + assert.equal(run.newPass, true); + assert.equal(run.pass, 2); + assert.equal(run.added, 1); + const asked = new URL(scanRequests().slice(before)[0].path, "http://x").searchParams; + const from = asked.get("from")!; + assert.match(from, /^\d{14}$/); + assert.ok(Date.parse(firstPassStart) - Date.UTC(+from.slice(0, 4), +from.slice(4, 6) - 1, +from.slice(6, 8)) >= 29 * 86_400_000); + const file = (await readWaybackScan(paths.channelsDir, "blog"))!; + assert.equal(file.previousPassStartedAt, firstPassStart); + const fresh = file.rows.filter((r) => isNewRow(file, r)).map((r) => r.digest); + assert.deepEqual(fresh, ["P104A"]); + assert.equal(file.rows.length, 8); + } finally { + SCAN_CAPTURES.pop(); + } +}); + +test("include/exclude per target; a domain target; several targets in one run", async () => { + const paths = getPaths(); + const targets = [ + { url: "blog.example", match: "domain" as const, include: "/post/|about\\.", exclude: "/post/102/" }, + { url: "https://blog.example/tagged/", match: "prefix" as const }, + ]; + await channel("blog-two", { targets }); + const run = await runWaybackScan({ paths, slug: "blog-two", wayback: { targets, collapse: "digest", auto: false }, client: client() }); + assert.equal(run.complete, true); + assert.equal(run.targets.length, 2); + const file = (await readWaybackScan(paths.channelsDir, "blog-two"))!; + assert.deepEqual( + file.rows.map((r) => r.digest).sort(), + ["ABOUTA", "P101A", "P101B", "P103A", "TAGA"], + ); +}); + +test("a refusal stops the run, keeps the resume key and what it had; the next run continues", async () => { + const paths = getPaths(); + const targets = [{ url: "blog.example", match: "host" as const }]; + const wayback = { targets, collapse: "digest" as const, auto: false }; + await channel("blog-refused", { targets }); + // Pages of 3 rows, so the listing takes several requests. + const paged = (c: InstanceType<typeof WaybackClient>) => ({ + cdxPage: (u: string, o?: { signal?: AbortSignal }) => c.cdxPage(u.replace(/limit=\d+/, "limit=3"), o), + }); + const refusing = await startFakeWayback({ captures: SCAN_CAPTURES, scanRefuseFrom: 2 }); + try { + const c = new WaybackClient({ fetch: refusing.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }); + const cut = await runWaybackScan({ paths, slug: "blog-refused", wayback, client: paged(c) }); + assert.equal(cut.ok, false); + assert.match(cut.error ?? "", /did not answer .* after 2 attempts/); + assert.equal(cut.stopped, cut.error); + assert.equal(cut.rowsRead, 3); + const file = (await readWaybackScan(paths.channelsDir, "blog-refused"))!; + assert.equal(file.rows.length, 3, "the first page kept"); + assert.equal(file.targets[0].resumeKey, "fake-3"); + assert.equal(file.targets[0].complete, false); + } finally { + await refusing.close(); + } + const before = scanRequests().length; + const next = await runWaybackScan({ paths, slug: "blog-refused", wayback, client: paged(client()) }); + assert.equal(next.ok, true); + assert.equal(next.complete, true); + assert.equal(new URL(scanRequests()[before].path, "http://x").searchParams.get("resumeKey"), "fake-3"); + assert.equal((await readWaybackScan(paths.channelsDir, "blog-refused"))!.rows.length, 7); +}); + +test("a dry run asks nothing and writes nothing, and says what the next run would ask", async () => { + const paths = getPaths(); + const targets = [{ url: "dry.example", match: "prefix" as const, from: "2014" }]; + await channel("dry", { targets }); + const before = wb.requests.length; + const run = await runWaybackScan({ paths, slug: "dry", wayback: { targets, collapse: "digest", auto: false }, client: client(), dryRun: true }); + assert.equal(wb.requests.length, before); + assert.equal(run.dryRun, true); + assert.equal(run.requests, 0); + assert.match(run.targets[0].next ?? "", /^https:\/\/web\.archive\.org\/cdx\/search\/cdx\?url=dry\.example&matchType=prefix/); + assert.equal(await readWaybackScan(paths.channelsDir, "dry"), null); +}); + +test("the body and the job: refused before any job for a channel that is not a Wayback pages channel; the job runs on archive.org's queue", async () => { + assert.throws(() => parseWaybackScanBody({}), /slug/); + assert.throws(() => parseWaybackScanBody({ slug: "../x" }), /not a channel slug/); + assert.throws(() => parseWaybackScanBody({ slug: "x", maxRows: 0 }), /maxRows/); + assert.throws(() => parseWaybackScanBody({ slug: "x", dryRun: "yes" }), /dryRun/); + assert.deepEqual(parseWaybackScanBody({ slug: "x" }), { slug: "x", dryRun: false, maxRows: 50000, full: false }); + const paths = getPaths(); + const none = await startWaybackScanJob({ slug: "no-such" }, { paths }); + assert.equal(none.ok, false); + const dir = path.join(paths.channelsDir, "plain"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@plain" })); + const plain = await startWaybackScanJob({ slug: "plain" }, { paths }); + assert.equal(plain.ok, false); + assert.match(!plain.ok ? plain.error : "", /not a Wayback pages channel/); + let done = ""; + const job = await startWaybackScanJob({ slug: "blog", full: true }, { paths, client: client(), onDone: (s) => (done = s) }); + assert.equal(job.ok, true); + if (!job.ok) return; + assert.equal(getRegistry().get(job.jobId)?.queueKey, WAYBACK_QUEUE); + assert.equal(getRegistry().get(job.jobId)?.kind, "wayback-scan"); + const end = await job.done; + assert.equal(end.status, "done"); + assert.equal(done, "blog"); + const log = await readFile(getRegistry().get(job.jobId)!.logPath, "utf8"); + const marker = log.split("\n").find((l) => l.startsWith("@@wayback-scan "))!; + const result = JSON.parse(marker.slice("@@wayback-scan ".length)); + assert.equal(result.pass, 3, "a full pass is a new pass"); + assert.equal(result.complete, true); +}); diff --git a/common/controller/waybackScan.ts b/common/controller/waybackScan.ts @@ -0,0 +1,380 @@ +// THE WAYBACK PAGES SCAN (release 37 S2): which captures the Wayback Machine +// holds of a Wayback pages channel's targets (`config.wayback.targets`), as +// `channels/<slug>/wayback-scan.json` (lib/waybackPages/scanFile.ts) — a +// `wayback-scan` job, `pnpm ops wayback-scan {slug, dryRun?, maxRows?, full?}`, +// `archilyzer wayback scan <slug>`, the channel page's Captures tab. +// +// LISTINGS ONLY. A scan asks the CDX API and never fetches a capture's body; +// `import-page` does that, one capture per job. Every request goes through the +// Wayback client's paced ArchiveOrgClient (one at a time, a 2 s gap, 429/503 +// waited out), on the `platform:archive.org` queue, and a run reads at most +// `maxRows` CDX rows (50,000) in pages of 5,000. A run that stops before a +// target's end (the cap, a refusal, a drain, a cancel) keeps the target's +// resume key, and the next run continues from it. Once every target is complete +// the next run starts a new pass, which asks only from 30 days before the +// previous pass began (scanFile.ts). `full` starts a new pass from each target's +// own start. +// +// A refusal (archive.org kept answering 429/503, or answered an error) stops the +// run with what it had written, and the job fails with the reason. +// +// A dry run asks nothing and writes nothing: it says, per target, what the next +// run would ask for. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { isSafeChannelSegment } from "../lib/citations/moments"; +import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; +import { WAYBACK_ORIGIN, waybackClient } from "../lib/waybackClient"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { + keepCaptureUrl, + waybackConfigOf, + waybackTargetKey, + type WaybackChannelConfig, + type WaybackTarget, +} from "../lib/waybackPages/targets"; +import { + CDX_PAGE_ROWS, + DEFAULT_SCAN_MAX_ROWS, + parseScanCdxPage, + SCAN_MAX_ROWS_LIMIT, + scanCdxUrl, +} from "../lib/waybackPages/scanCdx"; +import { + cdxTsBefore, + emptyScanFile, + indexScanRows, + mergeCdxRows, + PASS_OVERLAP_DAYS, + sortScanRows, + summarizeScan, + type WaybackScanFile, + type WaybackScanTarget, +} from "../lib/waybackPages/scanFile"; +import { readWaybackScan, writeWaybackScan } from "../lib/waybackPages/scanFile-server"; +import { readChannelConfig } from "./channels"; +import { WAYBACK_PAGES_QUEUE } from "./importPage"; + +export const WAYBACK_SCAN_JOB_KIND = "wayback-scan"; +// archive.org's own queue for Wayback work: a scan, and every `import-page`, +// run one at a time on it. +export const WAYBACK_QUEUE = WAYBACK_PAGES_QUEUE; +export const WAYBACK_SCAN_RESULT_MARKER = "@@wayback-scan "; +export const WAYBACK_SCAN_BODY_KEYS = ["slug", "dryRun", "maxRows", "full"] as const; + +// A run never sends more CDX requests than this, whatever the pages hold (a +// listing that answers resume keys with no rows must not spin). +export const SCAN_MAX_REQUESTS = 100; + +export type CdxPager = { cdxPage(url: string, o?: { signal?: AbortSignal }): Promise<string> }; + +export type WaybackScanBody = { + slug: string; + dryRun: boolean; + maxRows: number; + full: boolean; +}; + +export function parseWaybackScanBody(raw: Record<string, unknown>): WaybackScanBody { + const slug = typeof raw.slug === "string" ? raw.slug.trim() : ""; + if (!slug) throw new Error('"slug" is required: the Wayback pages channel'); + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + for (const k of ["dryRun", "full"] as const) { + if (raw[k] !== undefined && typeof raw[k] !== "boolean") throw new Error(`"${k}" must be true or false`); + } + let maxRows = DEFAULT_SCAN_MAX_ROWS; + if (raw.maxRows !== undefined) { + if (typeof raw.maxRows !== "number" || !Number.isInteger(raw.maxRows) || raw.maxRows < 1 || raw.maxRows > SCAN_MAX_ROWS_LIMIT) { + throw new Error(`"maxRows" must be a whole number from 1 to ${SCAN_MAX_ROWS_LIMIT}`); + } + maxRows = raw.maxRows; + } + return { slug, dryRun: raw.dryRun === true, maxRows, full: raw.full === true }; +} + +// The channel's `config.wayback`, through the channel config's schema. +export async function readWaybackChannelConfig(paths: Paths, slug: string): Promise<WaybackChannelConfig | null> { + return waybackConfigOf(await readChannelConfig(paths, slug)); +} + +// Why a channel cannot be scanned, or null. +export async function waybackScanRefusal(paths: Paths, slug: string): Promise<string | null> { + const config = await readChannelConfig(paths, slug); + if (!config) return `No channel "${slug}".`; + if (!waybackConfigOf(config)) { + return `${slug} is not a Wayback pages channel: its config names no wayback.targets.`; + } + return null; +} + +export type WaybackScanTargetReport = { + url: string; + match: string; + requests: number; + rows: number; + added: number; + complete: boolean; + resumeKey?: string; + // A dry run: what the next request for this target would be. + next?: string; +}; + +export type WaybackScanResult = { + ok: boolean; + slug: string; + dryRun: boolean; + pass: number; + newPass: boolean; + targets: WaybackScanTargetReport[]; + requests: number; + rowsRead: number; + added: number; + totalRows: number; + complete: boolean; + // Why the run stopped before every target's end: "row cap", "drained", + // "cancelled", "request cap", or the refusal. + stopped?: string; + error?: string; + path?: string; +}; + +export type RunWaybackScanOpts = { + paths: Paths; + slug: string; + wayback: WaybackChannelConfig; + dryRun?: boolean; + maxRows?: number; + full?: boolean; + client?: CdxPager; + origin?: string; + now?: () => Date; + jobId?: string; + onLog?: (line: string) => void; + signal?: AbortSignal; + drainSignal?: AbortSignal; +}; + +// Line the file's targets up with the config's: a known target keeps its +// state, a new one starts incomplete, one the config no longer names is +// dropped (its rows stay). +export function reconcileTargets(file: WaybackScanFile, targets: ReadonlyArray<WaybackTarget>): void { + const byKey = new Map(file.targets.map((t) => [t.key, t])); + file.targets = targets.map((t) => { + const key = waybackTargetKey(t); + return ( + byKey.get(key) ?? { + key, + url: t.url, + match: t.match, + ...(t.from ? { from: t.from } : {}), + ...(t.to ? { to: t.to } : {}), + complete: false, + rows: 0, + } + ); + }); +} + +// Start a new pass (mutates): every target from its start — or, `incremental`, +// from PASS_OVERLAP_DAYS before the pass that just ended began. +export function startPass(file: WaybackScanFile, nowIso: string, incremental: boolean): void { + const previous = file.passStartedAt; + const fresh = file.rows.length === 0 && file.targets.every((t) => t.rows === 0 && !t.complete); + if (!fresh) { + file.pass += 1; + file.previousPassStartedAt = previous; + } + file.passStartedAt = nowIso; + const passFrom = incremental && !fresh ? cdxTsBefore(previous, PASS_OVERLAP_DAYS) : undefined; + file.targets = file.targets.map((t): WaybackScanTarget => { + const { resumeKey: _r, completedAt: _c, passFrom: _p, ...rest } = t; + return { ...rest, complete: false, rows: 0, ...(passFrom ? { passFrom } : {}) }; + }); +} + +export async function runWaybackScan(opts: RunWaybackScanOpts): Promise<WaybackScanResult> { + const log = (l: string) => opts.onLog?.(l); + const now = opts.now ?? (() => new Date()); + const client = opts.client ?? waybackClient; + // The process client sends web.archive.org to the e2e fake when one is named + // (waybackClient.ts, E2E_WAYBACK_ORIGIN_FILE). + const origin = opts.origin ?? WAYBACK_ORIGIN; + const maxRows = Math.max(1, Math.min(opts.maxRows ?? DEFAULT_SCAN_MAX_ROWS, SCAN_MAX_ROWS_LIMIT)); + const channelsDir = opts.paths.channelsDir; + + const file = (await readWaybackScan(channelsDir, opts.slug)) ?? emptyScanFile(opts.slug, now().toISOString()); + reconcileTargets(file, opts.wayback.targets); + let newPass = false; + if (opts.full) { + startPass(file, now().toISOString(), false); + newPass = true; + } else if (file.targets.length > 0 && file.targets.every((t) => t.complete)) { + startPass(file, now().toISOString(), true); + newPass = true; + } + const configByKey = new Map(opts.wayback.targets.map((t) => [waybackTargetKey(t), t])); + const reports = new Map<string, WaybackScanTargetReport>( + file.targets.map((t) => [ + t.key, + { url: t.url, match: t.match, requests: 0, rows: 0, added: 0, complete: t.complete, ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}) }, + ]), + ); + const result = (extra: Partial<WaybackScanResult> = {}): WaybackScanResult => ({ + ok: true, + slug: opts.slug, + dryRun: opts.dryRun === true, + pass: file.pass, + newPass, + targets: [...reports.values()], + requests: [...reports.values()].reduce((n, r) => n + r.requests, 0), + rowsRead: [...reports.values()].reduce((n, r) => n + r.rows, 0), + added: [...reports.values()].reduce((n, r) => n + r.added, 0), + totalRows: file.rows.length, + complete: file.targets.every((t) => t.complete), + ...extra, + }); + + if (opts.dryRun) { + for (const t of file.targets) { + const target = configByKey.get(t.key)!; + const r = reports.get(t.key)!; + if (!t.complete) { + r.next = scanCdxUrl({ target, limit: Math.min(CDX_PAGE_ROWS, maxRows), ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}), ...(t.passFrom ? { from: t.passFrom } : {}) }, origin); + } + log(`${t.match} ${t.url}: ${t.complete ? "complete this pass" : `would ask ${r.next}`}`); + } + return result(); + } + + const index = indexScanRows(file); + let remaining = maxRows; + let requests = 0; + let stopped: string | undefined; + let error: string | undefined; + let written: string | undefined; + const flush = async () => { + const at = now().toISOString(); + file.lastScanAt = at; + if (opts.jobId) file.jobId = opts.jobId; + sortScanRows(file.rows); + file.summary = summarizeScan(file.rows); + written = await writeWaybackScan(channelsDir, file); + }; + + outer: for (const t of file.targets) { + if (t.complete) continue; + const target = configByKey.get(t.key)!; + const r = reports.get(t.key)!; + log(`${t.match} ${t.url}${t.resumeKey ? " (continuing from its resume key)" : ""}${t.passFrom ? ` — captures from ${t.passFrom.slice(0, 8)}` : ""}`); + while (!t.complete) { + if (opts.signal?.aborted) { stopped = "cancelled"; break outer; } + if (opts.drainSignal?.aborted) { stopped = "drained"; break outer; } + if (remaining <= 0) { stopped = "row cap"; break outer; } + if (requests >= SCAN_MAX_REQUESTS) { stopped = "request cap"; break outer; } + const url = scanCdxUrl({ target, limit: Math.min(CDX_PAGE_ROWS, remaining), ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}), ...(t.passFrom ? { from: t.passFrom } : {}) }, origin); + let body: string; + requests++; + r.requests++; + try { + body = await client.cdxPage(url, opts.signal ? { signal: opts.signal } : {}); + } catch (e) { + if (opts.signal?.aborted) { stopped = "cancelled"; break outer; } + error = e instanceof ArchiveOrgRequestError ? e.message : `the CDX request failed: ${(e as Error).message}`; + stopped = error; + break outer; + } + let page; + try { + page = parseScanCdxPage(body); + } catch (e) { + error = `${(e as Error).message} for ${t.url}`; + stopped = error; + break outer; + } + const kept = page.rows.filter((row) => keepCaptureUrl(target, row.originalUrl)); + const added = mergeCdxRows(file, kept, index); + r.rows += page.rows.length; + r.added += added; + t.rows += page.rows.length; + remaining -= page.rows.length; + t.lastScanAt = now().toISOString(); + const stalled = page.rows.length === 0 && page.resumeKey !== undefined && page.resumeKey === t.resumeKey; + if (page.resumeKey && !stalled) { + t.resumeKey = page.resumeKey; + } else { + delete t.resumeKey; + t.complete = true; + t.completedAt = t.lastScanAt; + } + r.complete = t.complete; + if (t.resumeKey) r.resumeKey = t.resumeKey; + else delete r.resumeKey; + log(` ${page.rows.length} rows, ${kept.length} kept, ${added} new${t.complete ? " — complete" : " — continues"}`); + await flush(); + } + } + if (!written) await flush(); + const out = result({ ...(stopped ? { stopped } : {}), ...(written ? { path: written } : {}) }); + if (error) return { ...out, ok: false, error }; + return out; +} + +// What the `@@wayback-scan` line says (the targets without dry-run URLs only +// when there are many). +export function waybackScanSummary(r: WaybackScanResult): WaybackScanResult { + const { path: _p, ...rest } = r; + return rest; +} + +// Enqueue a `wayback-scan` job (refused before any job for a channel that is +// not a Wayback pages channel). `onDone` runs after a run that wrote its file +// (the editor revalidates the channel page there). +export async function startWaybackScanJob( + raw: Record<string, unknown>, + deps: { paths: Paths; onDone?: (slug: string) => void; client?: CdxPager; now?: () => Date; background?: boolean }, +): Promise<StreamActionResult> { + let body: WaybackScanBody; + try { + body = parseWaybackScanBody(raw); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const refusal = await waybackScanRefusal(deps.paths, body.slug); + if (refusal) return { ok: false, error: refusal }; + return runManagedFunction({ + kind: WAYBACK_SCAN_JOB_KIND, + queueKey: WAYBACK_QUEUE, + paths: deps.paths, + channelSlug: body.slug, + ...(deps.background ? { background: true } : {}), + fn: async (onLog, signal, _setProgress, ctx) => { + const wayback = await readWaybackChannelConfig(deps.paths, body.slug); + if (!wayback) throw new Error(`${body.slug} is not a Wayback pages channel: its config names no wayback.targets.`); + onLog(`Wayback scan of ${body.slug}${body.dryRun ? " (dry run: nothing is asked or written)" : ""}${body.full ? " (a full pass)" : ""}`); + const out = await runWaybackScan({ + paths: deps.paths, + slug: body.slug, + wayback, + dryRun: body.dryRun, + maxRows: body.maxRows, + full: body.full, + jobId: ctx.jobId, + onLog, + signal, + drainSignal: ctx.drainSignal, + ...(deps.client ? { client: deps.client } : {}), + ...(deps.now ? { now: deps.now } : {}), + }); + onLog( + `pass ${out.pass}${out.newPass ? " (new)" : ""}: ${out.requests} request${out.requests === 1 ? "" : "s"}, ` + + `${out.rowsRead} rows read, ${out.added} new, ${out.totalRows} in the scan` + + (out.complete ? " — every target complete" : out.stopped ? ` — stopped: ${out.stopped}` : ""), + ); + if (out.path) onLog(`wrote ${path.relative(deps.paths.transcriptsDir, out.path)}`); + onLog(`${WAYBACK_SCAN_RESULT_MARKER}${JSON.stringify(waybackScanSummary(out))}`); + if (out.path) deps.onDone?.(body.slug); + if (!out.ok) throw new Error(out.error ?? "the Wayback scan stopped"); + }, + }); +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -109,6 +109,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "fetch-copies": { label: "Fetch copies", drainable: true }, // An article's own video (release 32): one remux or encode. "attach-report-video": { label: "Attach article video", drainable: false }, + // A Wayback pages channel's CDX scan (release 37 S2). + "wayback-scan": { label: "Wayback scan", drainable: true }, }; test("added kinds carry their pinned label and drainability", () => { @@ -290,7 +292,8 @@ test("release 18: the kinds no longer created keep their labels (seven of them n test("release 18: every drainable kind but the lane runners and the clip-window batch is an ingest kind", () => { const runners = new Set(["auto-transcribe", "auto-download", "auto-digest", "auto-backfill", "auto-publish"]); // fetch-windows writes only `data/<id>/clips/`, a cache the index never reads. - const notIngest = new Set(["fetch-windows"]); + // wayback-scan writes only `wayback-scan.json`, which the index never reads. + const notIngest = new Set(["fetch-windows", "wayback-scan"]); for (const kind of jobKindIds()) { if (!isDrainableKind(kind) || runners.has(kind) || notIngest.has(kind)) continue; assert.equal(isIngestKind(kind), true, `${kind} is drainable and per channel: an ingest kind`); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -632,6 +632,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", }, + // A WAYBACK PAGES CHANNEL'S SCAN (release 37 S2, controller/waybackScan.ts): + // the CDX listings of its targets into `wayback-scan.json`, no bodies, on + // archive.org's queue (`platform:archive.org`) beside every `import-page`. + // Drainable (it stops between pages and keeps the resume key); not an + // ingest kind — the index never reads the scan. Reads only the channel's + // own files, so the text guard covers it. + "wayback-scan": { + kind: "wayback-scan", + label: "Wayback scan", + drainable: true, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: false, + needsText: true, + }, // The posts analogue of the video availability check: which archived posts // have since been deleted at the source. "check-post-availability": { diff --git a/common/lib/archives/archiveToday.ts b/common/lib/archives/archiveToday.ts @@ -70,13 +70,21 @@ export function withinCaptureRange(ts: string, from?: string, to?: string): bool return true; } -// The row nearest `at` (4–14 digits), the earlier of two as near. +// A 4–14 digit timestamp as epoch ms (the missing units the start of the +// period); NaN for one that is not a time. +function tsMs(ts: string): number { + const p = ts.padEnd(14, "0"); + return Date.UTC(+p.slice(0, 4), Math.max(0, +p.slice(4, 6) - 1), Math.max(1, +p.slice(6, 8)), +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14)); +} + +// The row nearest `at` (4–14 digits) IN TIME — not by the digits, where +// 20191201 is "nearer" 20190512 than 20200101 — the earlier of two as near. export function nearestCapture<T extends { captureTs: string }>(rows: readonly T[], at: string): T | null { - const want = Number(at.padEnd(14, "0")); + const want = tsMs(at); let best: T | null = null; let bestD = Infinity; for (const r of rows) { - const d = Math.abs(Number(r.captureTs.padEnd(14, "0")) - want); + const d = Math.abs(tsMs(r.captureTs) - want); if (d < bestD || (d === bestD && best && r.captureTs < best.captureTs)) { best = r; bestD = d; diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -227,7 +227,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { mirror: "For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped.", wayback: - 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".', + 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org\'s pace; absent, nothing is imported unasked. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".', }; // Every key a config.json may carry, in emission order. The unknown-key oracle: diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -421,6 +421,26 @@ export class WaybackClient { throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); } } + + // ONE PAGE OF A CDX LISTING the caller built (release 37 S2, the Wayback + // pages scan — lib/waybackPages/scanCdx.ts builds the URL and parses the + // answer): the body as text, through the same chain, gap and back-off. + // Throws ArchiveOrgRequestError when the API kept refusing or answered an + // error. + async cdxPage(cdxUrl: string, o: { signal?: AbortSignal } = {}): Promise<string> { + try { + return await this.http.getText(cdxUrl, "application/json", o.signal); + } catch (e) { + // Release 37 lane F: a 403 for the scanned URL is its exclusion. + let url = cdxUrl; + try { + url = new URL(cdxUrl).searchParams.get("url") ?? cdxUrl; + } catch { + // keep the request URL + } + throw waybackExcludedOf(e, url); + } + } } // TEST-ONLY: E2E_WAYBACK_ORIGIN_FILE names a file holding ONE loopback origin diff --git a/common/lib/waybackPages/config.ts b/common/lib/waybackPages/config.ts @@ -47,6 +47,9 @@ export type WaybackPagesConfig = { targets: WaybackTarget[]; // How a scan folds repeated captures: "digest" = one row per distinct body. collapse?: "digest"; + // The download lane imports the captures a later scan adds (release 37 S2, + // controller/laneWaybackAuto.ts). Off unless true. + auto?: boolean; }; const TS_PREFIX_RE = /^\d{4,14}$/; @@ -96,6 +99,7 @@ export function coerceWaybackPagesConfig(v: unknown): WaybackPagesConfig | undef if (targets.length === 0) return undefined; const out: WaybackPagesConfig = { targets }; if (r.collapse === "digest") out.collapse = "digest"; + if (r.auto === true) out.auto = true; return out; } diff --git a/common/lib/waybackPages/imported.ts b/common/lib/waybackPages/imported.ts @@ -0,0 +1,69 @@ +// WHICH SCAN ROWS ARE ALREADY IMPORTED (release 37 S2). Derived, never stored +// twice: a row of wayback-scan.json is imported when the channel holds a +// webpage record (a Post with `page`) of the same original URL whose capture is +// that content — the same digest, or, for a record that names no digest, a +// capture time inside the row's first..last seen. Pure, client-safe. + +import { normalHost, type WaybackScanRow } from "./scanFile"; + +// The `page` facts this needs (PagePostInfo's provenance half + digest). +export type ImportedPageFacts = { + originalUrl: string; + captureTs: string; + digest?: string; + waybackUrl?: string; +}; + +export type ImportedRecordRef = { + id: string; + captureTs: string; + waybackUrl?: string; +}; + +export type ImportedIndex = Map<string, Array<ImportedRecordRef & { digest?: string }>>; + +// One spelling per page the Wayback Machine treats as one: no scheme, the host +// lowercased without www. or a default port, path and query as captured. +export function pageUrlKey(url: string): string { + try { + const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `http://${url}`); + return `${normalHost(u.host)}${u.pathname}${u.search}`; + } catch { + return url; + } +} + +export function buildImportedIndex( + posts: ReadonlyArray<{ id: string; page?: ImportedPageFacts | null }>, +): ImportedIndex { + const index: ImportedIndex = new Map(); + for (const p of posts) { + const page = p.page; + if (!page || typeof page.originalUrl !== "string" || typeof page.captureTs !== "string") continue; + const key = pageUrlKey(page.originalUrl); + const list = index.get(key) ?? []; + list.push({ + id: p.id, + captureTs: page.captureTs, + ...(page.digest ? { digest: page.digest } : {}), + ...(page.waybackUrl ? { waybackUrl: page.waybackUrl } : {}), + }); + index.set(key, list); + } + for (const list of index.values()) list.sort((a, b) => a.captureTs.localeCompare(b.captureTs) || a.id.localeCompare(b.id)); + return index; +} + +// The first record that holds this row's content, or null. +export function importedRecordOf( + row: Pick<WaybackScanRow, "originalUrl" | "digest" | "firstTs" | "lastTs">, + index: ImportedIndex, +): ImportedRecordRef | null { + const list = index.get(pageUrlKey(row.originalUrl)); + if (!list) return null; + for (const r of list) { + const hit = r.digest ? r.digest === row.digest : r.captureTs >= row.firstTs && r.captureTs <= row.lastTs; + if (hit) return { id: r.id, captureTs: r.captureTs, ...(r.waybackUrl ? { waybackUrl: r.waybackUrl } : {}) }; + } + return null; +} diff --git a/common/lib/waybackPages/scan.test.ts b/common/lib/waybackPages/scan.test.ts @@ -0,0 +1,199 @@ +// The Wayback pages scan's pure half (release 37 S2): the targets reader, the +// CDX URL per match type, the page parse with its resume key, the merge by +// (URL, digest), the asset/include/exclude filters, the summaries, and which +// rows are already imported. Synthetic URLs only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/scan.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + cdxUrlParam, + isAssetUrl, + keepCaptureUrl, + waybackConfigOf, + waybackTargetKey, + type WaybackTarget, +} from "./targets"; +import { parseScanCdxPage, scanCdxUrl } from "./scanCdx"; +import { + cdxTsBefore, + displayPathOf, + emptyScanFile, + isNewRow, + mergeCdxRows, + pathPrefixOf, + summarizeScan, +} from "./scanFile"; +import { buildImportedIndex, importedRecordOf, pageUrlKey } from "./imported"; + +test("the targets reader is the schema's: bad targets dropped, regexes that do not compile dropped, auto read", () => { + assert.equal(waybackConfigOf({}), null); + assert.equal(waybackConfigOf({ wayback: { targets: [] } }), null); + assert.equal(waybackConfigOf({ wayback: { targets: [{ match: "host" }] } }), null); + const w = waybackConfigOf({ + handling: "transcribe", + wayback: { + targets: [ + { url: " blog.example ", match: "host", from: "2014", to: "20151231", mime: ["text/html"], include: "/post/", exclude: "(", other: 1 }, + { url: "https://example.org/a", match: "sideways" }, + { url: "https://example.org/b", match: "exact", from: "14" }, + ], + collapse: "none", + auto: "yes", + extra: true, + }, + }); + assert.deepEqual(w, { + targets: [ + { url: "blog.example", match: "host", from: "2014", to: "20151231", mime: ["text/html"], include: "/post/" }, + { url: "https://example.org/b", match: "exact" }, + ], + collapse: "digest", + auto: false, + }); + assert.equal(waybackConfigOf({ wayback: { targets: [{ url: "x.example", match: "host" }], auto: true } })?.auto, true); +}); + +test("a target's key changes with what it asks, not with its filters", () => { + const a: WaybackTarget = { url: "blog.example", match: "host" }; + assert.equal(waybackTargetKey(a), waybackTargetKey({ ...a, include: "/post/" })); + assert.notEqual(waybackTargetKey(a), waybackTargetKey({ ...a, from: "2014" })); + assert.notEqual(waybackTargetKey(a), waybackTargetKey({ ...a, match: "domain" })); +}); + +test("the CDX URL per match type: url, matchType, the 200 and mime filters, collapse, bounds, paging", () => { + const params = (t: WaybackTarget, extra: Partial<Parameters<typeof scanCdxUrl>[0]> = {}) => + new URL(scanCdxUrl({ target: t, limit: 5000, ...extra })).searchParams; + for (const match of ["exact", "prefix", "host", "domain"] as const) { + const url = match === "host" || match === "domain" ? "https://www.blog.example/whatever" : "https://blog.example/post/"; + const p = params({ url, match }); + assert.equal(p.get("matchType"), match); + assert.equal(p.get("url"), match === "host" || match === "domain" ? "www.blog.example" : url); + assert.deepEqual(p.getAll("filter"), ["statuscode:200", "mimetype:text\\/html"]); + assert.equal(p.get("collapse"), "digest"); + assert.equal(p.get("showResumeKey"), "true"); + assert.equal(p.get("output"), "json"); + assert.equal(p.get("limit"), "5000"); + assert.equal(p.get("resumeKey"), null); + } + assert.equal(cdxUrlParam({ url: "blog.example", match: "domain" }), "blog.example"); + const p = params( + { url: "blog.example", match: "host", from: "2014", to: "2015", mime: ["text/html", "text/plain", "application/json"] }, + { resumeKey: "abc 123", from: "20140601000000" }, + ); + assert.equal(p.getAll("filter")[1], "mimetype:text\\/html|text\\/plain|application\\/json"); + assert.equal(p.get("from"), "20140601000000", "the later of the target's from and the pass's"); + assert.equal(p.get("to"), "2015"); + assert.equal(p.get("resumeKey"), "abc 123"); + assert.equal(params({ url: "blog.example", match: "host", from: "2016" }, { from: "20140601000000" }).get("from"), "2016"); + assert.ok(scanCdxUrl({ target: { url: "a.example", match: "host" }, limit: 1 }).startsWith("https://web.archive.org/cdx/search/cdx?")); +}); + +test("a CDX page: rows by the header's columns, the resume key after an empty row, [] as none", () => { + assert.deepEqual(parseScanCdxPage(""), { rows: [] }); + assert.deepEqual(parseScanCdxPage("[]"), { rows: [] }); + const page = parseScanCdxPage( + JSON.stringify([ + ["original", "timestamp", "digest", "mimetype", "statuscode"], + ["https://blog.example/", "20140102030405", "HOMEA", "text/html", "200"], + ["https://blog.example/x", "bad", "X", "text/html", "200"], + ["https://blog.example/y", "20140102030406", "", "text/html", "200"], + [], + ["key-2"], + ]), + ); + assert.equal(page.resumeKey, "key-2"); + assert.deepEqual(page.rows, [ + { originalUrl: "https://blog.example/", timestamp: "20140102030405", digest: "HOMEA", mimetype: "text/html", status: 200 }, + { originalUrl: "https://blog.example/y", timestamp: "20140102030406", digest: "ts-20140102030406", mimetype: "text/html", status: 200 }, + ]); + assert.equal(parseScanCdxPage(JSON.stringify([["original", "timestamp"], ["https://a.example/", "20140102030405"]])).resumeKey, undefined); + assert.throws(() => parseScanCdxPage("<html>"), /did not answer JSON/); + assert.throws(() => parseScanCdxPage("{}"), /not a list/); +}); + +test("assets are dropped by extension unless include names them; exclude always wins", () => { + for (const u of ["https://blog.example/style.css", "https://blog.example/a/logo.PNG?v=2", "https://blog.example/f.woff2", "https://blog.example/app.js"]) { + assert.equal(isAssetUrl(u), true, u); + } + for (const u of ["https://blog.example/", "https://blog.example/post/1", "https://blog.example/page.html", "https://blog.example/x?f=a.css"]) { + assert.equal(isAssetUrl(u), false, u); + } + const t: WaybackTarget = { url: "blog.example", match: "host" }; + assert.equal(keepCaptureUrl(t, "https://blog.example/post/1"), true); + assert.equal(keepCaptureUrl(t, "https://blog.example/style.css"), false); + assert.equal(keepCaptureUrl({ ...t, include: "\\.css$" }, "https://blog.example/style.css"), true); + assert.equal(keepCaptureUrl({ ...t, include: "/post/" }, "https://blog.example/tagged/x"), false); + assert.equal(keepCaptureUrl({ ...t, exclude: "/post/1$" }, "https://blog.example/post/1"), false); + assert.equal(keepCaptureUrl({ ...t, include: "/post/", exclude: "/post/1$" }, "https://blog.example/post/1"), false); +}); + +const row = (originalUrl: string, timestamp: string, digest: string) => ({ originalUrl, timestamp, digest, mimetype: "text/html", status: 200 }); + +test("the merge: one row per (URL, digest); a later sighting widens first/last and counts; a second pass marks what it added", () => { + const file = emptyScanFile("blog", "2026-01-01T00:00:00.000Z"); + const added = mergeCdxRows(file, [ + row("https://blog.example/", "20140601000000", "HOMEA"), + row("https://blog.example/", "20150101000000", "HOMEB"), + row("https://blog.example/", "20160101000000", "HOMEA"), + row("https://blog.example/post/1", "20140203000000", "P1A"), + ]); + assert.equal(added, 3); + const home = file.rows.find((r) => r.digest === "HOMEA")!; + assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140601000000", "20160101000000", 2]); + // The same capture again (an overlapping later pass) is not counted twice. + file.pass = 2; + assert.equal(mergeCdxRows(file, [row("https://blog.example/", "20160101000000", "HOMEA"), row("https://blog.example/", "20140102000000", "HOMEA")]), 0); + assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140102000000", "20160101000000", 3]); + assert.equal(mergeCdxRows(file, [row("https://blog.example/post/2", "20170101000000", "P2A")]), 1); + const p2 = file.rows.find((r) => r.digest === "P2A")!; + assert.equal(isNewRow(file, p2), true); + assert.equal(isNewRow(file, home), false); + assert.equal(isNewRow({ pass: 1 }, { pass: 1 }), false, "nothing is new on the first pass"); +}); + +test("summaries: pages, versions, rows by first-seen year and by one- and two-segment prefix", () => { + const file = emptyScanFile("blog", "2026-01-01T00:00:00.000Z"); + mergeCdxRows(file, [ + row("https://blog.example/", "20140601000000", "H"), + row("https://www.blog.example/post/1/first", "20140203000000", "P1A"), + row("https://blog.example/post/1/first", "20150203000000", "P1B"), + row("https://blog.example/post/2/second", "20150203000000", "P2A"), + row("https://blog.example/tagged/bread", "20150203000000", "T"), + ]); + const s = summarizeScan(file.rows); + assert.equal(s.versions, 5); + assert.equal(s.pages, 5, "www. and bare are two original URLs"); + assert.deepEqual(s.byYear, { "2014": 2, "2015": 3 }); + assert.deepEqual(s.byPrefix, { + "blog.example/": 1, + "blog.example/post/": 3, + "blog.example/post/1/": 2, + "blog.example/tagged/": 1, + }); + assert.equal(pathPrefixOf("https://blog.example/post/1/first", 1), "blog.example/post/"); + assert.equal(pathPrefixOf("https://blog.example/post/1/", 2), "blog.example/post/1/"); + assert.equal(displayPathOf("https://blog.example/post/1?x=2", false), "/post/1?x=2"); + assert.equal(displayPathOf("https://www.blog.example/post/1", true), "blog.example/post/1"); + assert.equal(cdxTsBefore("2026-02-01T12:00:00.000Z", 31), "20260101120000"); +}); + +test("imported: a record of the same page with the row's digest, or with no digest a capture inside its range", () => { + const index = buildImportedIndex([ + { id: "20140203000000-aaa", page: { originalUrl: "http://www.blog.example/post/1", captureTs: "20140203000000", digest: "P1A", waybackUrl: "https://web.archive.org/web/20140203000000/http://www.blog.example/post/1" } }, + { id: "20150301000000-bbb", page: { originalUrl: "https://blog.example/", captureTs: "20150301000000" } }, + { id: "a-post-with-no-page" }, + ]); + assert.equal(pageUrlKey("http://www.Blog.example:80/post/1"), "blog.example/post/1"); + const r = (originalUrl: string, digest: string, firstTs: string, lastTs: string) => ({ originalUrl, digest, firstTs, lastTs }); + assert.deepEqual(importedRecordOf(r("https://blog.example/post/1", "P1A", "20140203000000", "20140304000000"), index), { + id: "20140203000000-aaa", + captureTs: "20140203000000", + waybackUrl: "https://web.archive.org/web/20140203000000/http://www.blog.example/post/1", + }); + assert.equal(importedRecordOf(r("https://blog.example/post/1", "P1B", "20150405000000", "20150405000000"), index), null, "another version is not imported"); + assert.equal(importedRecordOf(r("https://blog.example/", "HOMEB", "20150101000000", "20150601000000"), index)?.id, "20150301000000-bbb"); + assert.equal(importedRecordOf(r("https://blog.example/", "HOMEA", "20140101000000", "20140601000000"), index), null); + assert.equal(importedRecordOf(r("https://blog.example/post/9", "X", "2014", "2015"), index), null); +}); diff --git a/common/lib/waybackPages/scanCdx.ts b/common/lib/waybackPages/scanCdx.ts @@ -0,0 +1,117 @@ +// THE CDX LISTING A WAYBACK PAGES SCAN ASKS FOR (release 37 S2): one target's +// captures, paged with the API's resume key, one row per distinct content +// (`collapse=digest`), only those that recorded a 200, only the target's +// mimetypes, inside its date bounds. Pure: the URL and the parse; the request +// is the Wayback client's (lib/waybackClient.ts `cdxPage`), paced. +// +// The CDX server's JSON answer with `showResumeKey=true`: a header row, the +// rows, and — when more remain — an empty row then `[<resumeKey>]`. + +import { WAYBACK_ORIGIN } from "../waybackClient"; +import { cdxMimeFilter, cdxUrlParam, type WaybackTarget } from "./targets"; + +// Rows asked for per request. +export const CDX_PAGE_ROWS = 5_000; +// Rows read per run, all targets together, unless the run asks for fewer. +export const DEFAULT_SCAN_MAX_ROWS = 50_000; +// The hard ceiling on a run's `maxRows`. +export const SCAN_MAX_ROWS_LIMIT = 200_000; + +// The columns asked for, in this order. +export const CDX_FIELDS = ["original", "timestamp", "digest", "mimetype", "statuscode"] as const; + +export type CdxQuery = { + target: WaybackTarget; + limit: number; + resumeKey?: string; + // A later pass's lower bound (YYYYMMDDhhmmss), when later than the target's + // own `from`. + from?: string; +}; + +export function scanCdxUrl(q: CdxQuery, origin: string = WAYBACK_ORIGIN): string { + const t = q.target; + const p = new URLSearchParams(); + p.set("url", cdxUrlParam(t)); + p.set("matchType", t.match); + p.set("output", "json"); + p.set("fl", CDX_FIELDS.join(",")); + p.append("filter", "statuscode:200"); + p.append("filter", cdxMimeFilter(t)); + p.set("collapse", "digest"); + const from = laterTs(t.from, q.from); + if (from) p.set("from", from); + if (t.to) p.set("to", t.to); + p.set("limit", String(q.limit)); + p.set("showResumeKey", "true"); + if (q.resumeKey) p.set("resumeKey", q.resumeKey); + return `${origin}/cdx/search/cdx?${p.toString()}`; +} + +// The later of two CDX bounds (prefix timestamps compare by padding). +function laterTs(a: string | undefined, b: string | undefined): string | undefined { + if (!a) return b; + if (!b) return a; + return a.padEnd(14, "0") >= b.padEnd(14, "0") ? a : b; +} + +export type CdxScanRow = { + originalUrl: string; + timestamp: string; + digest: string; + mimetype: string; + status: number; +}; + +export type CdxScanPage = { + rows: CdxScanRow[]; + // Present when the listing continues. + resumeKey?: string; +}; + +// One page of the answer. An empty body or `[]` is no rows; anything that is +// not the JSON list shape is an error (the API changed, or answered a page). +export function parseScanCdxPage(body: string): CdxScanPage { + const text = body.trim(); + if (!text) return { rows: [] }; + let raw: unknown; + try { + raw = JSON.parse(text); + } catch { + throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`); + } + if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list"); + if (raw.length === 0) return { rows: [] }; + const list = raw as unknown[]; + let resumeKey: string | undefined; + // The tail: [] then [key]. + const last = list[list.length - 1]; + const beforeLast = list[list.length - 2]; + let end = list.length; + if (Array.isArray(last) && last.length === 1 && typeof last[0] === "string" && Array.isArray(beforeLast) && beforeLast.length === 0) { + resumeKey = last[0] || undefined; + end -= 2; + } + const header = list[0]; + if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row"); + const col = (name: string) => (header as unknown[]).indexOf(name); + const ci = { original: col("original"), timestamp: col("timestamp"), digest: col("digest"), mimetype: col("mimetype"), statuscode: col("statuscode") }; + if (ci.original < 0 || ci.timestamp < 0) throw new Error("the CDX API's header names no timestamp or original"); + const rows: CdxScanRow[] = []; + for (const row of list.slice(1, end)) { + if (!Array.isArray(row) || row.length === 0) continue; + const timestamp = String(row[ci.timestamp] ?? ""); + const originalUrl = String(row[ci.original] ?? ""); + if (!/^\d{14}$/.test(timestamp) || !originalUrl) continue; + const digest = ci.digest >= 0 ? String(row[ci.digest] ?? "") : ""; + const status = ci.statuscode >= 0 ? Number(row[ci.statuscode]) : 200; + rows.push({ + originalUrl, + timestamp, + digest: digest || `ts-${timestamp}`, + mimetype: ci.mimetype >= 0 ? String(row[ci.mimetype] ?? "") : "", + status: Number.isFinite(status) ? status : 0, + }); + } + return { rows, ...(resumeKey ? { resumeKey } : {}) }; +} diff --git a/common/lib/waybackPages/scanFile-server.ts b/common/lib/waybackPages/scanFile-server.ts @@ -0,0 +1,43 @@ +// The disk half of lib/waybackPages/scanFile.ts: +// `channels/<slug>/wayback-scan.json`, read and written (atomic), and the +// channel's imported-record index read through the posts store's reader. +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { writeJsonAtomic } from "../jsonFile-server"; +import { readAllPosts } from "../posts-server"; +import { isSafeChannelSegment } from "../citations/moments"; +import { buildImportedIndex, type ImportedIndex, type ImportedPageFacts } from "./imported"; +import { isWaybackScanFile, WAYBACK_SCAN_FILENAME, type WaybackScanFile } from "./scanFile"; + +export function waybackScanPath(channelsDir: string, slug: string): string { + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + return path.join(channelsDir, slug, WAYBACK_SCAN_FILENAME); +} + +// The channel's scan, or null (none yet, unreadable, or another format). +export async function readWaybackScan(channelsDir: string, slug: string): Promise<WaybackScanFile | null> { + try { + const v = JSON.parse(await readFile(waybackScanPath(channelsDir, slug), "utf8")) as unknown; + return isWaybackScanFile(v) ? v : null; + } catch { + return null; + } +} + +// Compact: a 50,000-row scan is ~8 MB of JSON as it is. +export async function writeWaybackScan(channelsDir: string, file: WaybackScanFile): Promise<string> { + const p = waybackScanPath(channelsDir, file.slug); + await writeJsonAtomic(p, file, { indent: 0 }); + return p; +} + +// The channel's webpage records, by page (imported.ts). Every record through +// the posts store's own reader; a record without `page` is not a capture. +export async function readImportedIndex(channelsDir: string, slug: string): Promise<ImportedIndex> { + const posts = await readAllPosts(path.join(channelsDir, slug)); + return buildImportedIndex( + posts.map((p) => ({ id: p.id, page: (p as { page?: ImportedPageFacts }).page ?? null })), + ); +} diff --git a/common/lib/waybackPages/scanFile.ts b/common/lib/waybackPages/scanFile.ts @@ -0,0 +1,260 @@ +// `channels/<slug>/wayback-scan.json` — what a Wayback pages channel's scan +// found (release 37 S2; written by controller/waybackScan.ts, read by the +// channel page's Captures tab and the download lane's `wayback.auto` pick). +// Every distinct (original URL, digest) the CDX API listed for the channel's +// targets — no bodies: a scan never fetches one, only `import-page` does. +// +// Shape: `{format: "archilyzer-wayback-scan", version: 1, slug, pass, +// passStartedAt, previousPassStartedAt?, lastScanAt?, jobId?, targets, rows, +// summary}`. +// targets[] per target: {key, url, match, from?, to?, resumeKey?, complete, +// rows (CDX rows read this pass), lastScanAt?, completedAt?, +// passFrom?} +// rows[] {originalUrl, digest, firstTs, lastTs, count, mimetype, status, +// pass (the pass that first listed it)} +// summary {pages, versions, byYear (first seen), byPrefix (first one and +// two path segments, host first)} +// +// A PASS is one walk of every target to its end. A pass that is cut (the row +// cap, a refusal, a drain) keeps each target's resume key and the next run +// continues it; once every target is complete the next run starts a new pass, +// asking only for captures from 30 days before the previous pass started (the +// CDX index lags the crawl). A row is NEW when a pass after the first listed it +// in the current pass. Imported state is NOT stored here — it is derived from +// the channel's posts (imported.ts). +// +// Pure, client-safe (types, merge, summaries). + +import type { WaybackMatchType } from "./targets"; +import type { CdxScanRow } from "./scanCdx"; + +export const WAYBACK_SCAN_FORMAT = "archilyzer-wayback-scan"; +export const WAYBACK_SCAN_VERSION = 1; +export const WAYBACK_SCAN_FILENAME = "wayback-scan.json"; + +// How far before the previous pass's start a later pass asks from. +export const PASS_OVERLAP_DAYS = 30; + +export type WaybackScanTarget = { + key: string; + url: string; + match: WaybackMatchType; + from?: string; + to?: string; + resumeKey?: string; + complete: boolean; + // CDX rows read for this target in the current pass. + rows: number; + lastScanAt?: string; + completedAt?: string; + // The lower bound this pass asks from (a later pass only). + passFrom?: string; +}; + +export type WaybackScanRow = { + originalUrl: string; + digest: string; + // YYYYMMDDhhmmss: the earliest and latest capture of this content listed. + // With collapse=digest a run of identical captures is listed once, at its + // first; `count` counts the listed captures, not every crawl. + firstTs: string; + lastTs: string; + count: number; + mimetype: string; + status: number; + pass: number; +}; + +export type WaybackScanSummary = { + // Distinct original URLs, and distinct (URL, digest). + pages: number; + versions: number; + byYear: Record<string, number>; + byPrefix: Record<string, number>; +}; + +export type WaybackScanFile = { + format: typeof WAYBACK_SCAN_FORMAT; + version: typeof WAYBACK_SCAN_VERSION; + slug: string; + pass: number; + passStartedAt: string; + previousPassStartedAt?: string; + lastScanAt?: string; + jobId?: string; + targets: WaybackScanTarget[]; + rows: WaybackScanRow[]; + summary: WaybackScanSummary; +}; + +export function isWaybackScanFile(v: unknown): v is WaybackScanFile { + const f = v as WaybackScanFile | null; + return ( + !!f && + typeof f === "object" && + f.format === WAYBACK_SCAN_FORMAT && + f.version === WAYBACK_SCAN_VERSION && + typeof f.slug === "string" && + typeof f.pass === "number" && + Array.isArray(f.targets) && + Array.isArray(f.rows) + ); +} + +export function emptyScanFile(slug: string, now: string): WaybackScanFile { + return { + format: WAYBACK_SCAN_FORMAT, + version: WAYBACK_SCAN_VERSION, + slug, + pass: 1, + passStartedAt: now, + targets: [], + rows: [], + summary: { pages: 0, versions: 0, byYear: {}, byPrefix: {} }, + }; +} + +export function scanRowKey(r: Pick<WaybackScanRow, "originalUrl" | "digest">): string { + return `${r.originalUrl}\u0000${r.digest}`; +} + +// Fold one page of CDX rows into `file.rows` (mutated): a new (URL, digest) +// is added under the current pass; a known one widens its first/last seen and +// counts the capture when it lies outside what was already seen. Answers how +// many rows were added. `index` is the caller's key → row map, kept across +// pages so a 50,000-row file is not rescanned per page. +export function mergeCdxRows( + file: WaybackScanFile, + rows: ReadonlyArray<CdxScanRow>, + index: Map<string, WaybackScanRow> = indexScanRows(file), +): number { + let added = 0; + for (const r of rows) { + const key = scanRowKey(r); + const have = index.get(key); + if (!have) { + const row: WaybackScanRow = { + originalUrl: r.originalUrl, + digest: r.digest, + firstTs: r.timestamp, + lastTs: r.timestamp, + count: 1, + mimetype: r.mimetype, + status: r.status, + pass: file.pass, + }; + file.rows.push(row); + index.set(key, row); + added++; + continue; + } + if (r.timestamp < have.firstTs) { + have.firstTs = r.timestamp; + have.count++; + } else if (r.timestamp > have.lastTs) { + have.lastTs = r.timestamp; + have.count++; + } + } + return added; +} + +export function indexScanRows(file: Pick<WaybackScanFile, "rows">): Map<string, WaybackScanRow> { + return new Map(file.rows.map((r) => [scanRowKey(r), r])); +} + +// A row is new when a pass after the first listed it in the current pass. +export function isNewRow(file: Pick<WaybackScanFile, "pass">, row: Pick<WaybackScanRow, "pass">): boolean { + return file.pass > 1 && row.pass === file.pass; +} + +// "example.org" for every www./port spelling of one host. +export function normalHost(host: string): string { + return host.toLowerCase().replace(/^www\./, "").replace(/:(80|443)$/, ""); +} + +function parseUrl(u: string): URL | null { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(u) ? u : `http://${u}`); + } catch { + return null; + } +} + +// The first `depth` path segments of a URL, host first: "example.org/blog/", +// "example.org/blog/2014/". A URL with fewer segments is its own path's +// directory ("example.org/"). +export function pathPrefixOf(originalUrl: string, depth: 1 | 2): string { + const u = parseUrl(originalUrl); + if (!u) return originalUrl; + const segs = u.pathname.split("/").filter(Boolean); + // The last segment of a path that does not end in "/" is a page, not a dir. + const dirs = u.pathname.endsWith("/") ? segs : segs.slice(0, -1); + const take = dirs.slice(0, depth); + return `${normalHost(u.host)}/${take.map((s) => `${s}/`).join("")}`; +} + +// What the table shows for a URL: its path and query, with the host first +// when the scan spans hosts. +export function displayPathOf(originalUrl: string, withHost: boolean): string { + const u = parseUrl(originalUrl); + if (!u) return originalUrl; + const p = `${u.pathname}${u.search}`; + return withHost ? `${normalHost(u.host)}${p}` : p; +} + +export function hostsOf(rows: ReadonlyArray<Pick<WaybackScanRow, "originalUrl">>): Set<string> { + const out = new Set<string>(); + for (const r of rows) { + const u = parseUrl(r.originalUrl); + if (u) out.add(normalHost(u.host)); + } + return out; +} + +// Prefixes kept in the summary: every one-segment prefix, and the two-segment +// ones that hold more than one row (a two-segment prefix per post would be a +// copy of the rows), at most this many of each, most rows first. +export const SUMMARY_PREFIXES_MAX = 200; + +export function summarizeScan(rows: ReadonlyArray<WaybackScanRow>): WaybackScanSummary { + const pages = new Set<string>(); + const byYear: Record<string, number> = {}; + const one = new Map<string, number>(); + const two = new Map<string, number>(); + for (const r of rows) { + pages.add(r.originalUrl); + const y = r.firstTs.slice(0, 4); + byYear[y] = (byYear[y] ?? 0) + 1; + const p1 = pathPrefixOf(r.originalUrl, 1); + const p2 = pathPrefixOf(r.originalUrl, 2); + one.set(p1, (one.get(p1) ?? 0) + 1); + if (p2 !== p1) two.set(p2, (two.get(p2) ?? 0) + 1); + } + const top = (m: Map<string, number>, min: number) => + [...m.entries()] + .filter(([, n]) => n >= min) + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .slice(0, SUMMARY_PREFIXES_MAX); + const byPrefix: Record<string, number> = {}; + for (const [k, n] of [...top(one, 1), ...top(two, 2)].sort((a, b) => a[0].localeCompare(b[0]))) byPrefix[k] = n; + return { pages: pages.size, versions: rows.length, byYear, byPrefix }; +} + +// Rows in table order: by URL, then by first seen. +export function sortScanRows(rows: WaybackScanRow[]): WaybackScanRow[] { + return rows.sort((a, b) => a.originalUrl.localeCompare(b.originalUrl) || a.firstTs.localeCompare(b.firstTs)); +} + +// YYYYMMDDhhmmss of an ISO time, minus `days`. +export function cdxTsBefore(iso: string, days: number): string { + const ms = Date.parse(iso) - days * 86_400_000; + const d = new Date(Number.isFinite(ms) ? ms : 0); + const p = (n: number, w = 2) => String(n).padStart(w, "0"); + return `${p(d.getUTCFullYear(), 4)}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`; +} + +// "2014-05-06" of a CDX timestamp. +export function cdxTsDate(ts: string): string { + return ts.length >= 8 ? `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : ts; +} diff --git a/common/lib/waybackPages/scanView.ts b/common/lib/waybackPages/scanView.ts @@ -0,0 +1,124 @@ +// THE CAPTURES TABLE (release 37 S2): a Wayback pages channel's scan rows as +// the channel page's Captures tab shows them, and the filter the tab, Import +// all in range and the download lane's `wayback.auto` pick share. Pure, +// client-safe. + +import { importedRecordOf, type ImportedIndex, type ImportedRecordRef } from "./imported"; +import { displayPathOf, hostsOf, isNewRow, type WaybackScanFile, type WaybackScanRow } from "./scanFile"; + +// The replay URL of a capture (waybackClient.ts's waybackReplayUrl, spelled +// here so this module stays client-safe: that one pulls in node:fs). +function replayUrl(timestamp: string, original: string): string { + return `https://web.archive.org/web/${timestamp}/${original}`; +} + +export type CaptureRowView = { + // `<digest> <originalUrl>`: what a selection names. + key: string; + originalUrl: string; + path: string; + digest: string; + firstTs: string; + lastTs: string; + count: number; + // This content's place among the URL's versions (1 = the earliest), of + // `versions`. + version: number; + versions: number; + isNew: boolean; + imported: ImportedRecordRef | null; + // The capture an import of this row takes: the content's first listing. + replayUrl: string; +}; + +export type CaptureShow = "all" | "new" | "not-imported" | "imported"; +export const CAPTURE_SHOW_VALUES: readonly CaptureShow[] = ["all", "new", "not-imported", "imported"]; + +export type CaptureFilter = { + // YYYY of first seen. + year?: string; + // A path prefix as the summary names it ("blog.example/post/"): host first, + // no scheme, no www. + prefix?: string; + // Free text, over the original URL (case-insensitive). + q?: string; + show?: CaptureShow; +}; + +export function captureRowKey(r: Pick<WaybackScanRow, "digest" | "originalUrl">): string { + return `${r.digest} ${r.originalUrl}`; +} + +// Every row, in table order (by URL, then first seen), with its version +// ordinal, new mark and imported record. +export function captureRows(file: WaybackScanFile, index: ImportedIndex): CaptureRowView[] { + const withHost = hostsOf(file.rows).size > 1; + const byUrl = new Map<string, WaybackScanRow[]>(); + for (const r of file.rows) { + const list = byUrl.get(r.originalUrl) ?? []; + list.push(r); + byUrl.set(r.originalUrl, list); + } + const out: CaptureRowView[] = []; + for (const url of [...byUrl.keys()].sort()) { + const list = byUrl.get(url)!.sort((a, b) => a.firstTs.localeCompare(b.firstTs)); + list.forEach((r, i) => { + out.push({ + key: captureRowKey(r), + originalUrl: r.originalUrl, + path: displayPathOf(r.originalUrl, withHost), + digest: r.digest, + firstTs: r.firstTs, + lastTs: r.lastTs, + count: r.count, + version: i + 1, + versions: list.length, + isNew: isNewRow(file, r), + imported: importedRecordOf(r, index), + replayUrl: replayUrl(r.firstTs, r.originalUrl), + }); + }); + } + return out; +} + +export function filterCaptureRows(rows: ReadonlyArray<CaptureRowView>, f: CaptureFilter): CaptureRowView[] { + const q = f.q?.trim().toLowerCase(); + return rows.filter((r) => { + if (f.year && r.firstTs.slice(0, 4) !== f.year) return false; + if (f.prefix && !displayPathOf(r.originalUrl, true).startsWith(f.prefix)) return false; + if (q && !r.originalUrl.toLowerCase().includes(q)) return false; + switch (f.show ?? "all") { + case "new": + return r.isNew; + case "not-imported": + return !r.imported; + case "imported": + return !!r.imported; + default: + return true; + } + }); +} + +// A filter from a URL's search params (the tab's own links). +export function captureFilterFrom(sp: Record<string, string | string[] | undefined>): CaptureFilter { + const one = (k: string) => { + const v = sp[k]; + const s = Array.isArray(v) ? v[0] : v; + return typeof s === "string" && s.trim() ? s.trim() : undefined; + }; + const year = one("year"); + const show = one("show"); + return { + ...(year && /^\d{4}$/.test(year) ? { year } : {}), + ...(one("prefix") ? { prefix: one("prefix") } : {}), + ...(one("q") ? { q: one("q") } : {}), + ...(show && (CAPTURE_SHOW_VALUES as readonly string[]).includes(show) ? { show: show as CaptureShow } : {}), + }; +} + +// Rows per page of the table. +export const CAPTURES_PAGE_SIZE = 100; +// Import all in range asks for a confirmation above this many. +export const IMPORT_CONFIRM_ABOVE = 50; diff --git a/common/lib/waybackPages/targets.ts b/common/lib/waybackPages/targets.ts @@ -0,0 +1,124 @@ +// A WAYBACK PAGES CHANNEL'S SCOPE (release 37 S2): `config.wayback` — the +// targets whose captures the channel is about, and whether the download lane +// imports new ones by itself. Pure and client-safe: no I/O. +// +// config.wayback = { +// targets: [{url, match: "exact"|"prefix"|"host"|"domain", from?, to?, +// mime?: ["text/html"], include?, exclude?}], +// collapse?: "digest", +// auto?: boolean, +// } +// +// The reader is the schema's (lib/waybackPages/config.ts coerceWaybackPagesConfig): +// a target without a usable `url` or `match` is dropped, a date that is not +// 4–14 digits is dropped; here also a regex that does not compile. A channel +// with no usable target is not a Wayback pages channel. + +import { coerceWaybackPagesConfig, WAYBACK_TARGET_MATCHES, type WaybackTarget, type WaybackTargetMatch } from "./config"; + +// The schema's own target (lib/waybackPages/config.ts, `config.wayback`). +export type { WaybackTarget }; +export const WAYBACK_MATCH_TYPES = WAYBACK_TARGET_MATCHES; +export type WaybackMatchType = WaybackTargetMatch; + +// The mimetypes a target asks for when it names none. +export const DEFAULT_WAYBACK_MIMES: readonly string[] = ["text/html"]; + +// What a scan needs of `config.wayback`: the targets (the schema's), and +// whether the download lane imports new rows. +export type WaybackChannelConfig = { + targets: WaybackTarget[]; + collapse: "digest"; + // The download lane imports new scan rows for this channel (default off: no + // unattended crawling of a host unless the channel opts in). + auto: boolean; +}; + +function regexOk(src: string | undefined): string | undefined { + if (!src) return undefined; + try { + new RegExp(src); + return src; + } catch { + return undefined; + } +} + +// One target through the schema's coercion, its include/exclude kept only +// when they compile (a regex that does not is no filter at all). +export function parseWaybackTarget(raw: unknown): WaybackTarget | null { + const c = coerceWaybackPagesConfig({ targets: [raw] }); + const t = c?.targets[0]; + if (!t) return null; + const { include, exclude, ...rest } = t; + const inc = regexOk(include); + const exc = regexOk(exclude); + return { ...rest, ...(inc ? { include: inc } : {}), ...(exc ? { exclude: exc } : {}) }; +} + +// `config.wayback` of a channel config (or a raw config.json object), or null +// when the channel names no usable target. +export function waybackConfigOf(config: unknown): WaybackChannelConfig | null { + if (!config || typeof config !== "object") return null; + const w = (config as { wayback?: unknown }).wayback; + const c = coerceWaybackPagesConfig(w); + if (!c) return null; + const targets = c.targets.map(parseWaybackTarget).filter((t): t is WaybackTarget => t !== null); + if (targets.length === 0) return null; + return { targets, collapse: "digest", auto: c.auto === true }; +} + +export function isWaybackPagesConfig(config: unknown): boolean { + return waybackConfigOf(config) !== null; +} + +// The identity of a target in the scan file: what it ASKS the CDX API. A +// target whose url, match, bounds or mimes change is a new target (scanned from +// its start); include/exclude only filter what is kept. +export function waybackTargetKey(t: WaybackTarget): string { + return JSON.stringify([t.match, t.url, t.from ?? "", t.to ?? "", (t.mime ?? DEFAULT_WAYBACK_MIMES).join(",")]); +} + +// The `url` the CDX API takes for a target: a host or a domain without its +// scheme or path. +export function cdxUrlParam(t: WaybackTarget): string { + if (t.match === "host" || t.match === "domain") { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t.url) ? t.url : `http://${t.url}`).hostname; + } catch { + return t.url; + } + } + return t.url; +} + +function escapeRegex(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); +} + +// The CDX `filter=mimetype:` regex for a target's mimes. +export function cdxMimeFilter(t: WaybackTarget): string { + return `mimetype:${(t.mime ?? DEFAULT_WAYBACK_MIMES).map(escapeRegex).join("|")}`; +} + +// Obvious non-page assets, by the path's extension: dropped from a scan unless +// the target's `include` names them. +const ASSET_EXT_RE = + /\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|woff2?|ttf|otf|eot|mp4|m4v|webm|mov|mp3|m4a|ogg|wav|flac|zip|gz|tgz|rar|7z|pdf|swf|flv|exe|dmg|iso)$/i; + +export function isAssetUrl(originalUrl: string): boolean { + let p = originalUrl; + try { + p = new URL(originalUrl).pathname; + } catch { + p = originalUrl.split(/[?#]/)[0] ?? originalUrl; + } + return ASSET_EXT_RE.test(p); +} + +// Whether a capture of `originalUrl` belongs in the target's scan. +export function keepCaptureUrl(t: WaybackTarget, originalUrl: string): boolean { + if (t.exclude && new RegExp(t.exclude).test(originalUrl)) return false; + if (t.include) return new RegExp(t.include).test(originalUrl); + return !isAssetUrl(originalUrl); +} diff --git a/common/testing/web/fakeArchiveToday.mjs b/common/testing/web/fakeArchiveToday.mjs @@ -208,8 +208,13 @@ export async function startFakeArchiveToday(opts = {}) { if (near) { const list = of(near[2]); if (list.length === 0) return send(404, "text/plain", "not found"); - const want = Number(near[1].replace(/[.-]/g, "").padEnd(14, "0")); - const c = [...list].sort((a, b) => Math.abs(Number(a.timestamp) - want) - Math.abs(Number(b.timestamp) - want))[0]; + // Nearest in time, as archive.today answers. + const ms = (ts) => { + const p = ts.padEnd(14, "0"); + return Date.UTC(+p.slice(0, 4), Math.max(0, +p.slice(4, 6) - 1), Math.max(1, +p.slice(6, 8)), +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14)); + }; + const want = ms(near[1].replace(/[.-]/g, "")); + const c = [...list].sort((a, b) => Math.abs(ms(a.timestamp) - want) - Math.abs(ms(b.timestamp) - want))[0]; return send(302, "text/html", "", { location: `https://${host}/${c.id}` }); } const one = /^([A-Za-z0-9]{4,6})$/.exec(rest); diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -1,4 +1,11 @@ -export type FakeWaybackCapture = { original: string; timestamp: string; statuscode: string; mimetype?: string }; +export type FakeWaybackCapture = { + original: string; + timestamp: string; + statuscode: string; + mimetype?: string; + // (release 37 S2) the content digest the scan listing answers (default DIGEST<timestamp>). + digest?: string; +}; export const CAPTURES: FakeWaybackCapture[]; @@ -39,4 +46,10 @@ export function startFakeWayback(opts?: { pageCaptures?: FakePageCapture[]; // (release 37 lane F) originals CDX and their captures answer 403 for. excluded?: string[]; + // (release 37 S2) the Nth scan listing request and every one after answer 503. + scanRefuseFrom?: number; }): Promise<FakeWayback>; + +// (release 37 S2) the scan listing: a blog with posts, assets, a 404, a second host. +export const SCAN_CAPTURES: FakeWaybackCapture[]; +export function scanListing(captures: FakeWaybackCapture[], q: URLSearchParams): unknown[]; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -26,6 +26,14 @@ // or opts.pageCaptures) with its own mimetype; a timestamp with no capture of a // known page answers 302 to the nearest one; a capture with `offsite` answers 302 there // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. +// ── THE SCAN LISTING (release 37 S2, lib/waybackPages/scanCdx.ts) ── +// GET /cdx/search/cdx?…&showResumeKey=true the paged listing a Wayback pages scan asks: +// matchType exact|prefix|host|domain, from/to (timestamp prefixes), every `filter=` +// (`[!]field:regex`, a whole-field match, over statuscode and mimetype), collapse=digest +// (adjacent rows of one URL with one digest listed once), fl (the columns, in order), +// limit, and resumeKey — the answer ends with [] and [<resumeKey>] when rows remain. +// A capture's `digest` is its own when it names one, else DIGEST<timestamp>. +// opts.scanRefuseFrom: the Nth scan request (1-based) and every one after answer 503. // opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1). // opts.excluded: (release 37 lane F) originals the archive answers 403 for — CDX and // their captures — while every other URL answers as usual. @@ -183,6 +191,7 @@ export async function startFakeWayback(opts = {}) { let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; const excluded = opts.excluded ?? []; + let scanRequests = 0; const server = http.createServer((req, res) => { const u = new URL(req.url ?? "/", "http://fake"); requests.push({ path: u.pathname + u.search, at: Date.now() }); @@ -208,6 +217,11 @@ export async function startFakeWayback(opts = {}) { down--; return send(503, "text/plain", "Service Unavailable"); } + if (u.searchParams.get("showResumeKey") === "true") { + scanRequests++; + if (opts.scanRefuseFrom && scanRequests >= opts.scanRefuseFrom) return send(503, "text/plain", "Service Unavailable"); + return send(200, "application/json", JSON.stringify(scanListing(captures, u.searchParams))); + } const want = u.searchParams.get("url") ?? ""; const prefix = u.searchParams.get("matchType") === "prefix"; const status = /^statuscode:(\d+)$/.exec(u.searchParams.get("filter") ?? "")?.[1]; @@ -220,7 +234,7 @@ export async function startFakeWayback(opts = {}) { .filter((c) => !status || c.statuscode === status) .sort((a, b) => (closest ? near(a) - near(b) : 0) || a.timestamp.localeCompare(b.timestamp)) .slice(0, limit) - .map((c) => [urlkey(c.original), c.timestamp, c.original, c.mimetype ?? "text/html", c.statuscode, `DIGEST${c.timestamp}`, "1234"]); + .map((c) => [urlkey(c.original), c.timestamp, c.original, c.mimetype ?? "text/html", c.statuscode, c.digest ?? `DIGEST${c.timestamp}`, "1234"]); if (u.searchParams.get("output") === "json") return send(200, "application/json", JSON.stringify(rows.length ? [HEADER, ...rows] : [])); return send(200, "text/plain", rows.map((r) => r.join(" ")).join("\n") + (rows.length ? "\n" : "")); } @@ -266,3 +280,88 @@ export async function startFakeWayback(opts = {}) { close: () => new Promise((r) => server.close(() => r())), }; } + +// ── THE SCAN LISTING (release 37 S2) ───────────────────────────────────────── +// Its own block: the paged, filtered, collapsed listing a Wayback pages scan +// asks for. Nothing above calls it unless the request carries showResumeKey. + +// Invented page captures for a scan: a blog on blog.example with posts across +// 2014–2015 (one post captured three times, twice with the same content), its +// stylesheet and a logo (assets), a 404, and an about page on a second host of +// the same domain. +export const SCAN_CAPTURES = [ + { original: "https://blog.example/", timestamp: "20140102030405", statuscode: "200", mimetype: "text/html", digest: "HOMEA" }, + { original: "https://blog.example/", timestamp: "20140601000000", statuscode: "200", mimetype: "text/html", digest: "HOMEA" }, + { original: "https://blog.example/", timestamp: "20150101000000", statuscode: "200", mimetype: "text/html", digest: "HOMEB" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20140203000000", statuscode: "200", mimetype: "text/html", digest: "P101A" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20140304000000", statuscode: "200", mimetype: "text/html", digest: "P101A" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20150405000000", statuscode: "200", mimetype: "text/html", digest: "P101B" }, + { original: "https://blog.example/post/102/second-post", timestamp: "20140506000000", statuscode: "200", mimetype: "text/html", digest: "P102A" }, + { original: "https://blog.example/post/103/third-post", timestamp: "20150607000000", statuscode: "200", mimetype: "text/html", digest: "P103A" }, + { original: "https://blog.example/tagged/bread", timestamp: "20150708000000", statuscode: "200", mimetype: "text/html", digest: "TAGA" }, + { original: "https://blog.example/style.css", timestamp: "20140102030406", statuscode: "200", mimetype: "text/html", digest: "CSSA" }, + { original: "https://blog.example/logo.png", timestamp: "20140102030407", statuscode: "200", mimetype: "image/png", digest: "PNGA" }, + { original: "https://blog.example/post/999/gone", timestamp: "20150809000000", statuscode: "404", mimetype: "text/html", digest: "GONEA" }, + { original: "https://about.blog.example/", timestamp: "20140910000000", statuscode: "200", mimetype: "text/html", digest: "ABOUTA" }, +]; + +const SCAN_FIELDS = ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"]; + +function hostOf(u) { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(u) ? u : `http://${u}`).hostname.toLowerCase(); + } catch { + return ""; + } +} + +const noScheme = (u) => u.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").replace(/^www\./, ""); + +function matchesTarget(original, want, matchType) { + if (matchType === "prefix") return noScheme(original).startsWith(noScheme(want)); + if (matchType === "host") return hostOf(original).replace(/^www\./, "") === hostOf(want).replace(/^www\./, ""); + if (matchType === "domain") { + const h = hostOf(original); + const d = hostOf(want).replace(/^www\./, ""); + return h === d || h.endsWith(`.${d}`); + } + return noScheme(original) === noScheme(want); +} + +export function scanListing(captures, q) { + const want = q.get("url") ?? ""; + const matchType = q.get("matchType") ?? "exact"; + const from = (q.get("from") ?? "").padEnd(14, "0"); + const to = (q.get("to") ?? "").padEnd(14, "9"); + const filters = q.getAll("filter").map((f) => { + const neg = f.startsWith("!"); + const body = neg ? f.slice(1) : f; + const i = body.indexOf(":"); + return { neg, field: body.slice(0, i), re: new RegExp(`^(?:${body.slice(i + 1)})$`) }; + }); + const fl = (q.get("fl") ?? SCAN_FIELDS.join(",")).split(","); + const limit = Number(q.get("limit") ?? 0) || Infinity; + const offset = Number(/^fake-(\d+)$/.exec(q.get("resumeKey") ?? "")?.[1] ?? 0); + const all = captures + .map((c) => ({ + urlkey: urlkey(c.original), + timestamp: c.timestamp, + original: c.original, + mimetype: c.mimetype ?? "text/html", + statuscode: c.statuscode, + digest: c.digest ?? `DIGEST${c.timestamp}`, + length: "1234", + })) + .filter((c) => matchesTarget(c.original, want, matchType)) + .filter((c) => (!q.get("from") || c.timestamp >= from) && (!q.get("to") || c.timestamp <= to)) + .filter((c) => filters.every((f) => f.re.test(String(c[f.field] ?? "")) !== f.neg)) + .sort((a, b) => a.urlkey.localeCompare(b.urlkey) || a.timestamp.localeCompare(b.timestamp)); + const collapsed = q.get("collapse") === "digest" + ? all.filter((c, i) => i === 0 || !(all[i - 1].urlkey === c.urlkey && all[i - 1].digest === c.digest)) + : all; + const page = collapsed.slice(offset, offset + limit); + const rows = page.map((c) => fl.map((f) => c[f] ?? "")); + const more = offset + page.length < collapsed.length; + if (rows.length === 0 && !more) return []; + return [fl, ...rows, ...(more ? [[], [`fake-${offset + page.length}`]] : [])]; +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -4,6 +4,7 @@ - **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. - **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. - **Focus the queues on a site, or on some channels, from a terminal.** `pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"<id>"}}'` does what the /channels focus bar's **Focus site** does: that site's channels lead every lane, and the focus follows the site's membership. `{"kind":"channels","slugs":[…]}` focuses a list and `{"kind":"none"}` ends the focus. `focus` goes alone in the body. Needs a restart of the editor. - **The clip editor can ask an assistant to label and rank the clip finder's proposals — optionally.** A **Suggest** button in the clip editor's side column asks the model your generation settings choose (the local model, the Claude API, or a Claude Code session through `/gen`) to name each proposal in at most six words, say in one line what makes it land, and rank them; the labels show on every clip and unused proposal, and **Sort by the assistant's rank** orders both lists by them. Labels made before the clips were proposed again are marked stale, not hidden. Nothing in the cut changes: the labels are suggestions. Without a model, or with no labels, the clip editor works as before. From a shell: `pnpm ops report-draft '{"task":"clips-suggest","project":"<dir>","dryRun":true}'` shows how many proposals and what it would cost first. diff --git a/editor/app/api/ops/wayback-import/route.ts b/editor/app/api/ops/wayback-import/route.ts @@ -0,0 +1,50 @@ +import { NextResponse } from "next/server"; +import { WAYBACK_IMPORT_BODY_KEYS } from "yt-dlp-transcript-common/controller/waybackImport"; +import { CAPTURE_SHOW_VALUES, type CaptureShow } from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import { importCapturesAction } from "../../../channels/[slug]/captures/actions"; +import { OpsInputError, ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, keys? | year?, prefix?, q?, show?, dryRun? } -> { ok, slug, +// dryRun, chosen, queued: [{key, url, jobId?}], skipped: [{key, why}], left } +// +// Imports chosen rows of a Wayback pages channel's scan (release 37 S2): one +// `import-page` job per row, each the capture the row's content was first +// listed at, queued on archive.org's queue (they run one at a time at its +// pace). `keys` names rows as the Captures tab does (`<digest> <originalUrl>`); +// without it, every row the tab's filter keeps — `year` (first seen), `prefix` +// ("blog.example/post/": host first, no scheme), `q` (text in the URL), `show` +// (all | new | not-imported | imported) — is Import all in range. A row already +// imported is skipped; at most 500 are queued a call (`left` says how many +// remain). `dryRun` says what would be queued and queues nothing. +// +// AN ADAPTER: the refusals are the controller's (controller/waybackImport.ts). +export async function POST(request: Request) { + return ops(request, WAYBACK_IMPORT_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const keys = body.keys; + if (keys !== undefined && (!Array.isArray(keys) || keys.some((k) => typeof k !== "string" || !k.trim()))) { + throw new OpsInputError('"keys" must be a list of row keys ("<digest> <originalUrl>")'); + } + const show = optString(body, "show"); + if (show !== undefined && !(CAPTURE_SHOW_VALUES as readonly string[]).includes(show)) { + throw new OpsInputError(`"show" must be one of ${CAPTURE_SHOW_VALUES.join(", ")}`); + } + const year = optString(body, "year"); + if (year !== undefined && !/^\d{4}$/.test(year)) throw new OpsInputError('"year" must be YYYY'); + const filterKeys = ["year", "prefix", "q", "show"].filter((k) => body[k] !== undefined); + if (keys !== undefined && filterKeys.length) throw new OpsInputError(`send "keys" or a range (${filterKeys.join(", ")}), not both`); + const prefix = optString(body, "prefix"); + const q = optString(body, "q"); + const r = await importCapturesAction( + slug, + keys !== undefined + ? { keys: keys as string[] } + : { filter: { ...(year ? { year } : {}), ...(prefix ? { prefix } : {}), ...(q ? { q } : {}), ...(show ? { show: show as CaptureShow } : {}) } }, + { dryRun: optBool(body, "dryRun") === true, requestedBy: "ops" }, + ); + if (!r.ok) return opsFail(r.error ?? "the import was refused", 409, { queued: r.queued, skipped: r.skipped }); + return NextResponse.json(r); + }); +} diff --git a/editor/app/api/ops/wayback-scan/route.ts b/editor/app/api/ops/wayback-scan/route.ts @@ -0,0 +1,39 @@ +import { WAYBACK_SCAN_BODY_KEYS } from "yt-dlp-transcript-common/controller/waybackScan"; +import { waybackScanAction } from "../../../channels/[slug]/captures/actions"; +import { jobResponse, ops, optBool, optPositiveInt, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?, maxRows?, full? } -> { ok: true, jobId } +// +// A Wayback pages channel's scan (release 37 S2), as a `wayback-scan` job on +// archive.org's queue: the CDX listing of every target in its +// `config.wayback.targets` (matchType per target, status 200, its mimes, +// collapse=digest, its date bounds), in pages of 5,000, at most `maxRows` +// (50,000, at most 200,000) a run, into `channels/<slug>/wayback-scan.json` — +// one row per distinct (URL, digest) with first/last seen. No bodies. A run cut +// short 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); `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 and keeps the resume key). `dryRun` asks nothing and writes +// nothing: it logs what the next run would ask. Refused before any job for a +// channel with no `wayback.targets`. The log ends `@@wayback-scan {slug, +// dryRun, pass, newPass, targets: [{url, match, requests, rows, added, +// complete, resumeKey?, next?}], requests, rowsRead, added, totalRows, +// complete, stopped?, error?}`. +// +// AN ADAPTER: the refusals are the controller's (controller/waybackScan.ts). +export async function POST(request: Request) { + return ops(request, WAYBACK_SCAN_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const maxRows = optPositiveInt(body, "maxRows"); + return jobResponse( + await waybackScanAction(slug, { + dryRun: optBool(body, "dryRun") === true, + full: optBool(body, "full") === true, + ...(maxRows !== undefined ? { maxRows } : {}), + }), + ); + }); +} diff --git a/editor/app/channels/[slug]/captures/actions.ts b/editor/app/channels/[slug]/captures/actions.ts @@ -0,0 +1,75 @@ +"use server"; + +// THE CAPTURES TAB'S ACTIONS (release 37 S2), and `pnpm ops wayback-scan` / +// `wayback-import` over HTTP: one code path for the button and the agent. +// +// waybackScanAction a `wayback-scan` job on archive.org's queue +// (controller/waybackScan.ts) — Scan now / Continue scan. +// importCapturesAction one `import-page` job per chosen row +// (controller/waybackImport.ts) — Import selected (keys) +// and Import all in range (the table's filter). +// +// Refusals are the controllers' sentences. A scan or an import that wrote +// anything revalidates the tab. + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { startWaybackScanJob } from "yt-dlp-transcript-common/controller/waybackScan"; +import { queueCaptureImports, type CaptureImportResult } from "yt-dlp-transcript-common/controller/waybackImport"; +import type { CaptureFilter } from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../../lib/safeRevalidate"; +import { patchChannelConfig, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; + +const revalidate = (slug: string) => safeRevalidate([`/channels/${slug}`, `/channels/${slug}/captures`]); + +export async function waybackScanAction( + slug: string, + opts: { dryRun?: boolean; maxRows?: number; full?: boolean } = {}, +): Promise<StreamActionResult> { + return startWaybackScanJob( + { + slug, + ...(opts.dryRun ? { dryRun: true } : {}), + ...(opts.maxRows !== undefined ? { maxRows: opts.maxRows } : {}), + ...(opts.full ? { full: true } : {}), + }, + { paths: getPaths(), onDone: revalidate }, + ); +} + +// The button's form: a job id, or the refusal. +export async function startWaybackScanFromTab(slug: string, full: boolean): Promise<{ ok: true; jobId: string } | { ok: false; error: string }> { + const r = await waybackScanAction(slug, full ? { full: true } : {}); + if (!r.ok) return { ok: false, error: r.error }; + // Nobody reads the stream: the log is on disk, the tab polls nothing. + void r.stream.cancel().catch(() => {}); + return { ok: true, jobId: r.jobId }; +} + +export async function importCapturesAction( + slug: string, + choice: { keys: string[] } | { filter: CaptureFilter }, + opts: { dryRun?: boolean; requestedBy?: string } = {}, +): Promise<CaptureImportResult> { + const r = await queueCaptureImports({ + paths: getPaths(), + slug, + ...("keys" in choice ? { keys: choice.keys } : { filter: choice.filter }), + ...(opts.dryRun ? { dryRun: true } : {}), + requestedBy: opts.requestedBy ?? "captures", + }); + if (r.queued.length > 0 && !r.dryRun) revalidate(slug); + return r; +} + +// The Captures tab's toggle: `wayback.auto` on or off, through the one channel +// config writer (the rest of `wayback` kept as it is). +export async function setWaybackAutoAction(slug: string, auto: boolean): Promise<{ ok: boolean; error?: string }> { + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config?.wayback) return { ok: false, error: `${slug} is not a Wayback pages channel.` }; + const { auto: _was, ...rest } = config.wayback; + await patchChannelConfig(paths, slug, { wayback: { ...rest, ...(auto ? { auto: true } : {}) } }); + revalidate(slug); + return { ok: true }; +} diff --git a/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx b/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx @@ -0,0 +1,357 @@ +"use client"; + +import Link from "next/link"; +import Form from "next/form"; +import { useRouter } from "next/navigation"; +import { useState, useTransition } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cdxTsDate } from "yt-dlp-transcript-common/lib/waybackPages/scanFile"; +import { + IMPORT_CONFIRM_ABOVE, + type CaptureFilter, + type CaptureRowView, +} from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import type { CaptureImportResult } from "yt-dlp-transcript-common/controller/waybackImport"; +import { importCapturesAction, setWaybackAutoAction, waybackScanAction } from "../actions"; +import { cancelJobAction } from "../../../../jobs/actions"; + +// THE CAPTURES TAB'S PANEL (release 37 S2). The server hands it one page of +// already-filtered rows; the filter is the URL's (a GET form), so a 50,000-row +// scan never reaches the browser. Selection is per page; Import all in range +// is the filter, sent back and re-applied on the server. + +export type CapturesStatus = { + scanned: boolean; + versions: number; + pages: number; + imported: number; + newRows: number; + lastScanAt?: string; + lastScanJobId?: string; + pass: number; + complete: boolean; + targets: { url: string; match: string; complete: boolean; rows: number; resumable: boolean }[]; + auto: boolean; + liveScanJobId?: string; +}; + +type Props = { + slug: string; + status: CapturesStatus; + rows: CaptureRowView[]; + matching: number; + matchingToImport: number; + page: number; + pages: number; + filter: CaptureFilter; + years: string[]; + prefixes: string[]; +}; + +const n = (x: number) => x.toLocaleString("en-US"); +const plural = (x: number, one: string, many = `${one}s`) => `${n(x)} ${x === 1 ? one : many}`; +const when = (iso: string) => `${iso.slice(0, 16).replace("T", " ")} UTC`; + +function hrefWith(slug: string, filter: CaptureFilter, page?: number): string { + const q = new URLSearchParams(); + if (filter.year) q.set("year", filter.year); + if (filter.prefix) q.set("prefix", filter.prefix); + if (filter.q) q.set("q", filter.q); + if (filter.show && filter.show !== "all") q.set("show", filter.show); + if (page && page > 1) q.set("page", String(page)); + const s = q.toString(); + return `/channels/${slug}/captures${s ? `?${s}` : ""}`; +} + +function importLine(r: CaptureImportResult): string { + if (!r.ok) return r.error ?? "The import was refused."; + const parts = [`Queued ${plural(r.queued.length, "import job")}`]; + const imported = r.skipped.filter((s) => s.why.startsWith("imported")).length; + if (imported) parts.push(`${n(imported)} already imported`); + const gone = r.skipped.length - imported; + if (gone) parts.push(`${n(gone)} no longer in the scan`); + if (r.left) parts.push(`${n(r.left)} left: import the range again for the rest`); + return `${parts.join("; ")}.`; +} + +export function CapturesPanel({ slug, status, rows, matching, matchingToImport, page, pages, filter, years, prefixes }: Props) { + const router = useRouter(); + const [selected, setSelected] = useState<Set<string>>(new Set()); + const [confirming, setConfirming] = useState(false); + const [result, setResult] = useState<CaptureImportResult | null>(null); + const [pending, startTransition] = useTransition(); + // Shown at once; the server's answer arrives with the refresh. + const [auto, setAuto] = useState(status.auto); + const selectable = rows.filter((r) => !r.imported); + const allOnPage = selectable.length > 0 && selectable.every((r) => selected.has(r.key)); + + const toggle = (key: string) => + setSelected((s) => { + const next = new Set(s); + if (next.has(key)) next.delete(key); + else next.add(key); + return next; + }); + + const run = (choice: { keys: string[] } | { filter: CaptureFilter }) => + startTransition(async () => { + const r = await importCapturesAction(slug, choice); + setResult(r); + setConfirming(false); + if (r.ok) setSelected(new Set()); + router.refresh(); + }); + + const scanLabel = !status.scanned || status.complete ? "Scan now" : "Continue scan"; + const statusLine = !status.scanned + ? "Not scanned yet" + : [ + `${plural(status.versions, "version")} of ${plural(status.pages, "page")}`, + `${n(status.imported)} imported`, + ...(status.newRows ? [`${n(status.newRows)} new since the last scan`] : []), + ...(status.lastScanAt ? [`last scan ${when(status.lastScanAt)}`] : []), + status.complete ? "complete" : `continues where it stopped (${status.targets.filter((t) => !t.complete).length} of ${status.targets.length} targets left)`, + ].join(" · "); + + return ( + <div className="flex flex-col gap-5" aria-label="captures"> + <section className="rounded-lg border border-border bg-card p-4 flex flex-col gap-3" aria-label="wayback scan"> + <p className="text-sm text-muted-foreground" aria-label="captures status line"> + {statusLine} + </p> + <ul className="text-xs text-muted-foreground flex flex-col gap-0.5" aria-label="scan targets"> + {status.targets.map((t) => ( + <li key={`${t.match} ${t.url}`}> + <span className="font-mono">{t.url}</span> ({t.match}) — {t.complete ? "complete" : t.resumable ? `${n(t.rows)} rows read, continues` : "not scanned this pass"} + </li> + ))} + </ul> + {status.liveScanJobId ? ( + <p className="text-sm" aria-label="scan running"> + A scan is queued or running:{" "} + <Link href={`/jobs/${status.liveScanJobId}`} className="underline font-mono"> + {status.liveScanJobId} + </Link> + </p> + ) : ( + <StreamActionLog + trigger={() => waybackScanAction(slug)} + cancelAction={cancelJobAction} + buttonLabel={scanLabel} + runningLabel="Scanning…" + label="Wayback scan" + onSettled={() => router.refresh()} + /> + )} + {status.lastScanJobId ? ( + <p className="text-xs text-muted-foreground"> + Last scan:{" "} + <Link href={`/jobs/${status.lastScanJobId}`} className="underline font-mono" aria-label="last scan job"> + {status.lastScanJobId} + </Link> + </p> + ) : null} + <label className="flex items-center gap-2 text-sm" aria-label="automatic import"> + <input + type="checkbox" + checked={auto} + disabled={pending} + aria-label="Import new captures automatically" + onChange={(e) => { + const on = e.target.checked; + setAuto(on); + startTransition(async () => { + await setWaybackAutoAction(slug, on); + router.refresh(); + }); + }} + /> + Import new captures automatically + <span className="text-xs text-muted-foreground">(the download lane, one at a time at archive.org&apos;s pace)</span> + </label> + </section> + + {status.scanned ? ( + <section className="flex flex-col gap-3" aria-label="capture table"> + <Form action={`/channels/${slug}/captures`} className="flex flex-wrap items-end gap-2 text-sm" aria-label="capture filters"> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Year</span> + <select name="year" defaultValue={filter.year ?? ""} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Year"> + <option value="">All years</option> + {years.map((y) => ( + <option key={y} value={y}> + {y} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Path</span> + <select name="prefix" defaultValue={filter.prefix ?? ""} className="rounded-md border border-border bg-card px-2 py-1 max-w-72" aria-label="Path prefix"> + <option value="">All paths</option> + {prefixes.map((p) => ( + <option key={p} value={p}> + {p} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Contains</span> + <input name="q" defaultValue={filter.q ?? ""} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Filter text" /> + </label> + <label className="flex flex-col gap-1"> + <span className="text-xs text-muted-foreground">Show</span> + <select name="show" defaultValue={filter.show ?? "all"} className="rounded-md border border-border bg-card px-2 py-1" aria-label="Show"> + <option value="all">All</option> + <option value="not-imported">Not imported</option> + <option value="new">New since the last scan</option> + <option value="imported">Imported</option> + </select> + </label> + <button type="submit" className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted"> + Filter + </button> + <Link href={`/channels/${slug}/captures`} className="text-xs underline text-muted-foreground"> + Clear + </Link> + </Form> + + <div className="flex flex-wrap items-center gap-2 text-sm"> + <span aria-label="capture count" className="text-muted-foreground"> + {plural(matching, "row")} match{matching === 1 ? "es" : ""} + {matching !== matchingToImport ? ` (${n(matchingToImport)} not imported)` : ""} + </span> + <button + type="button" + disabled={pending || selected.size === 0} + onClick={() => run({ keys: [...selected] })} + className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted disabled:opacity-50" + > + Import selected ({n(selected.size)}) + </button> + {confirming ? ( + <span className="flex items-center gap-2" aria-label="confirm import range"> + <span>Import {plural(matchingToImport, "capture")}, one job each, at archive.org&apos;s pace?</span> + <button type="button" disabled={pending} onClick={() => run({ filter })} className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted"> + Confirm + </button> + <button type="button" onClick={() => setConfirming(false)} className="text-xs underline"> + Cancel + </button> + </span> + ) : ( + <button + type="button" + disabled={pending || matchingToImport === 0} + onClick={() => (matchingToImport > IMPORT_CONFIRM_ABOVE ? setConfirming(true) : run({ filter }))} + className="rounded-md border border-border bg-card px-3 py-1 hover:bg-muted disabled:opacity-50" + > + Import all in range ({n(matchingToImport)}) + </button> + )} + </div> + {result ? ( + <p className={`text-sm ${result.ok ? "" : "text-destructive"}`} aria-label="import result"> + {importLine(result)}{" "} + {result.ok && result.queued.length > 0 ? ( + <Link href="/jobs" className="underline"> + Jobs + </Link> + ) : null} + </p> + ) : null} + + <div className="overflow-x-auto"> + <table className="text-sm border-collapse w-full" aria-label="captures table"> + <thead> + <tr className="text-left text-muted-foreground"> + <th className="py-1 pr-2 font-medium"> + <input + type="checkbox" + aria-label="Select every row on this page" + checked={allOnPage} + disabled={selectable.length === 0} + onChange={() => + setSelected((s) => { + const next = new Set(s); + for (const r of selectable) { + if (allOnPage) next.delete(r.key); + else next.add(r.key); + } + return next; + }) + } + /> + </th> + <th className="py-1 pr-4 font-medium">Path</th> + <th className="py-1 pr-4 font-medium">First seen</th> + <th className="py-1 pr-4 font-medium">Last seen</th> + <th className="py-1 pr-4 font-medium">Version</th> + <th className="py-1 pr-4 font-medium">Imported</th> + <th className="py-1 font-medium">New</th> + </tr> + </thead> + <tbody> + {rows.map((r) => ( + <tr key={r.key} className="border-t border-border align-top" aria-label={`capture ${r.path} ${r.digest}`} data-key={r.key}> + <td className="py-1 pr-2"> + <input + type="checkbox" + aria-label={`Select ${r.path} (${cdxTsDate(r.firstTs)})`} + checked={selected.has(r.key)} + disabled={!!r.imported} + onChange={() => toggle(r.key)} + /> + </td> + <td className="py-1 pr-4 break-all"> + <a href={r.replayUrl} target="_blank" rel="noreferrer" className="underline hover:no-underline font-mono" title={r.originalUrl}> + {r.path || "/"} + </a> + </td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{cdxTsDate(r.firstTs)}</td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums">{cdxTsDate(r.lastTs)}</td> + <td className="py-1 pr-4 whitespace-nowrap tabular-nums" title={`${plural(r.count, "listed capture")} of this content`}> + {r.version} of {r.versions} + </td> + <td className="py-1 pr-4 whitespace-nowrap"> + {r.imported ? ( + r.imported.waybackUrl ? ( + <a href={r.imported.waybackUrl} target="_blank" rel="noreferrer" className="underline" title={`record ${r.imported.id}`} aria-label={`imported as ${r.imported.id}`}> + ✓ {r.imported.id} + </a> + ) : ( + <span aria-label={`imported as ${r.imported.id}`}>✓ {r.imported.id}</span> + ) + ) : ( + <span className="text-muted-foreground">—</span> + )} + </td> + <td className="py-1 whitespace-nowrap">{r.isNew ? <span className="text-xs rounded-full border border-info/30 bg-info-soft text-info px-2 py-0.5">new</span> : null}</td> + </tr> + ))} + </tbody> + </table> + </div> + {pages > 1 ? ( + <nav className="flex items-center gap-3 text-sm" aria-label="capture pages"> + {page > 1 ? ( + <Link href={hrefWith(slug, filter, page - 1)} className="underline"> + Previous + </Link> + ) : null} + <span className="text-muted-foreground"> + Page {page} of {pages} + </span> + {page < pages ? ( + <Link href={hrefWith(slug, filter, page + 1)} className="underline"> + Next + </Link> + ) : null} + </nav> + ) : null} + </section> + ) : null} + </div> + ); +} diff --git a/editor/app/channels/[slug]/captures/page.tsx b/editor/app/channels/[slug]/captures/page.tsx @@ -0,0 +1,89 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readWaybackChannelConfig, WAYBACK_SCAN_JOB_KIND } from "yt-dlp-transcript-common/controller/waybackScan"; +import { readImportedIndex, readWaybackScan } from "yt-dlp-transcript-common/lib/waybackPages/scanFile-server"; +import { + captureFilterFrom, + captureRows, + CAPTURES_PAGE_SIZE, + filterCaptureRows, +} from "yt-dlp-transcript-common/lib/waybackPages/scanView"; +import { waybackTargetKey } from "yt-dlp-transcript-common/lib/waybackPages/targets"; +import { readChannelConfigCached } from "../lib/channelConfigCache"; +import { CapturesPanel, type CapturesStatus } from "./components/CapturesPanel"; + +export const dynamic = "force-dynamic"; + +export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> { + const { slug } = await params; + const config = await readChannelConfigCached(slug); + return { title: `${config?.name ?? slug} — Captures` }; +} + +// THE CAPTURES TAB (release 37 S2): a Wayback pages channel's scan +// (wayback-scan.json, controller/waybackScan.ts) as a table — one row per +// distinct content of a page — filtered on the server by year, path prefix, +// text and what to show, a page of rows at a time (a 50,000-row scan never +// reaches the browser whole). Import selected / Import all in range queue one +// import-page job per row (controller/waybackImport.ts). +export default async function CapturesPage({ + params, + searchParams, +}: { + params: Promise<{ slug: string }>; + searchParams?: Promise<Record<string, string | string[] | undefined>>; +}) { + const { slug } = await params; + const sp = (await searchParams) ?? {}; + const config = await readChannelConfigCached(slug); + if (!config) notFound(); + const paths = getPaths(); + const wayback = await readWaybackChannelConfig(paths, slug); + if (!wayback) notFound(); + const scan = await readWaybackScan(paths.channelsDir, slug); + const all = scan ? captureRows(scan, await readImportedIndex(paths.channelsDir, slug)) : []; + const filter = captureFilterFrom(sp); + const matching = filterCaptureRows(all, filter); + const pages = Math.max(1, Math.ceil(matching.length / CAPTURES_PAGE_SIZE)); + const pageRaw = Number(Array.isArray(sp.page) ? sp.page[0] : sp.page); + const page = Number.isInteger(pageRaw) && pageRaw >= 1 ? Math.min(pageRaw, pages) : 1; + const shown = matching.slice((page - 1) * CAPTURES_PAGE_SIZE, page * CAPTURES_PAGE_SIZE); + const liveScan = getRegistry() + .list() + .find((j) => j.kind === WAYBACK_SCAN_JOB_KIND && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); + const status: CapturesStatus = { + scanned: scan !== null, + versions: all.length, + pages: scan?.summary.pages ?? 0, + imported: all.filter((r) => r.imported).length, + newRows: all.filter((r) => r.isNew).length, + ...(scan?.lastScanAt ? { lastScanAt: scan.lastScanAt } : {}), + ...(scan?.jobId ? { lastScanJobId: scan.jobId } : {}), + pass: scan?.pass ?? 0, + complete: scan ? wayback.targets.every((t) => scan.targets.some((s) => s.key === waybackTargetKey(t) && s.complete)) : false, + targets: wayback.targets.map((t) => { + const st = scan?.targets.find((s) => s.key === waybackTargetKey(t)); + return { url: t.url, match: t.match, complete: st?.complete ?? false, rows: st?.rows ?? 0, resumable: !!st?.resumeKey }; + }), + auto: wayback.auto, + ...(liveScan ? { liveScanJobId: liveScan.id } : {}), + }; + const years = scan ? Object.keys(scan.summary.byYear).sort() : []; + const prefixes = scan ? Object.keys(scan.summary.byPrefix).sort() : []; + return ( + <CapturesPanel + slug={slug} + status={status} + rows={shown} + matching={matching.length} + matchingToImport={matching.filter((r) => !r.imported).length} + page={page} + pages={pages} + filter={filter} + years={years} + prefixes={prefixes} + /> + ); +} diff --git a/editor/app/channels/[slug]/components/ChannelTabs.tsx b/editor/app/channels/[slug]/components/ChannelTabs.tsx @@ -3,7 +3,7 @@ import Link from "next/link"; import { useSelectedLayoutSegment } from "next/navigation"; -// Overview | Videos. +// Overview | Videos (a Wayback pages channel: Overview | Captures). // // A CLIENT component on purpose. Next 16 layouts are cached during navigation // and DO NOT RERENDER — they cannot read searchParams and would not re-evaluate @@ -11,8 +11,25 @@ import { useSelectedLayoutSegment } from "next/navigation"; // useSelectedLayoutSegment is the supported way to ask "which child segment is // rendered", and it re-renders because this component does. -export function ChannelTabs({ slug }: { slug: string }) { +export function ChannelTabs({ + slug, + captures = false, +}: { + slug: string; + // A Wayback pages channel (release 37 S2): Overview | Captures — its + // records are captures, not videos. + captures?: boolean; +}) { const segment = useSelectedLayoutSegment(); + if (captures) { + const onCaptures = segment === "captures"; + return ( + <nav aria-label="channel sections" className="flex items-center gap-1"> + <Tab href={`/channels/${slug}`} active={!onCaptures} label="Overview" /> + <Tab href={`/channels/${slug}/captures`} active={onCaptures} label="Captures" /> + </nav> + ); + } const onVideos = segment === "videos"; return ( <nav aria-label="channel sections" className="flex items-center gap-1"> diff --git a/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx b/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx @@ -64,6 +64,9 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac <section data-wayback-pages="" aria-label="Wayback pages" className="rounded-lg border border-border bg-card p-4"> <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1"> <h2 className="text-sm font-medium">Pages</h2> + <Link href={`/channels/${slug}/captures`} className="text-sm underline" aria-label="open captures"> + Captures: scan and choose + </Link> <span role="status" aria-label="pages held" className="text-sm text-muted-foreground"> {state.recordCount} record{state.recordCount === 1 ? "" : "s"} from {state.captureCount} capture {state.captureCount === 1 ? "" : "s"} diff --git a/editor/app/channels/[slug]/layout.tsx b/editor/app/channels/[slug]/layout.tsx @@ -5,6 +5,7 @@ import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { ChannelTabs } from "./components/ChannelTabs"; import { RefreshSnapshotButton } from "./components/RefreshSnapshotButton"; import { readChannelConfigCached } from "./lib/channelConfigCache"; +import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; // Shared chrome for every channel route: the breadcrumb, the name, the refresh // control and the Overview | Videos switch. This is what StatusHeader used to @@ -35,6 +36,10 @@ export default async function ChannelLayout({ // Deduped with page.tsx's read of the same file via React cache(). const config = await readChannelConfigCached(slug); if (!config) notFound(); + // A Wayback pages channel (release 37 S2) is a posts channel whose records + // are captures: unlike every other posts channel it has tabs, Overview | + // Captures (the Wayback pages panel links the tab too). + const wayback = isWaybackPagesChannel(config); return ( <div className="flex flex-col gap-6"> @@ -59,7 +64,11 @@ export default async function ChannelLayout({ the video workspace would be an empty room, and there is no video report to refresh. Both controls stay off it — which is also what the header did before this layout existed. */} - {!isSocialChannel(config) && ( + {wayback ? ( + <div className="flex items-center gap-3"> + <ChannelTabs slug={slug} captures /> + </div> + ) : !isSocialChannel(config) && ( <div className="flex items-center gap-3"> <ChannelTabs slug={slug} /> <RefreshSnapshotButton slug={slug} /> diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -609,6 +609,7 @@ export function ChannelForm({ <input type="hidden" name="socialHandle" value={isEdit ? (c?.socialHandle ?? "") : waybackHandle} /> <WaybackTargetsField {...(isEdit ? { initial: c?.wayback?.targets ?? [] } : { derivedFrom: url })} + auto={isEdit ? c?.wayback?.auto === true : false} /> </> )} diff --git a/editor/app/channels/components/WaybackTargetsField.tsx b/editor/app/channels/components/WaybackTargetsField.tsx @@ -13,7 +13,16 @@ import { // `sources` (release 37 lane F): "wayback", "archive.today" or "both" — // where the target's copies are looked for. -type Row = { url: string; match: string; from: string; to: string; sources?: string }; +// `keep`: what the rows do not edit (mime, include, exclude), carried through a +// save so the scan's filters survive an edit of the form (release 37 S2). +type Row = { + url: string; + match: string; + from: string; + to: string; + sources?: string; + keep?: Pick<WaybackTarget, "mime" | "include" | "exclude">; +}; const SOURCE_LABELS: Record<string, string> = { wayback: "Wayback Machine", @@ -38,12 +47,23 @@ const LABELS: Record<string, string> = { domain: "Domain (and subdomains)", }; -const toRow = (t: WaybackTarget): Row => ({ url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "", sources: sourcesOf(t) }); +const toRow = (t: WaybackTarget): Row => { + const keep = { + ...(t.mime?.length ? { mime: t.mime } : {}), + ...(t.include ? { include: t.include } : {}), + ...(t.exclude ? { exclude: t.exclude } : {}), + }; + return { url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "", sources: sourcesOf(t), ...(Object.keys(keep).length ? { keep } : {}) }; +}; export function WaybackTargetsField({ initial, derivedFrom, + auto, }: { + // `wayback.auto` (release 37 S2): the download lane imports the captures a + // later scan adds. Posted as the `waybackAuto` checkbox. + auto?: boolean; // The stored targets (edit mode). initial?: WaybackTarget[]; // Create mode: the URL typed above, a first row is derived from until a row @@ -70,6 +90,7 @@ export function WaybackTargetsField({ ...(r.from.trim() ? { from: r.from.trim() } : {}), ...(r.to.trim() ? { to: r.to.trim() } : {}), ...(sourcesList(r.sources) ? { sources: sourcesList(r.sources) } : {}), + ...(r.keep ?? {}), })), ); const input = "rounded border border-border bg-card px-2 py-1 text-sm"; @@ -149,6 +170,10 @@ export function WaybackTargetsField({ Add target </button> </div> + <label className="flex items-center gap-2 text-sm"> + <input type="checkbox" name="waybackAuto" defaultChecked={auto === true} aria-label="Import new captures automatically" /> + Import new captures automatically (the download lane, at archive.org&apos;s pace) + </label> <span className="text-xs text-muted-foreground"> Which captures are in scope, and on which archive. Dates are capture timestamps or their start (2014, 201403, 20140305). </span> diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -27,6 +27,8 @@ export const CHANNEL_FORM_FLAGS = [ "downloadFilterIncludeLivestreams", "audioCheckEnabled", "audioCheckResumeDuringProbe", + // A Wayback pages channel's `wayback.auto` (release 37 S2). + "waybackAuto", ] as const; // The value-shaped fields. A patch may set any of these to "" to clear it. @@ -128,6 +130,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "recordedDateTitlePattern", config.recordedDate?.titlePattern); put(fd, "mirrorOf", config.mirror?.of.join(", ")); if (config.wayback?.targets.length) fd.set("waybackTargets", JSON.stringify(config.wayback.targets)); + if (config.wayback?.auto) fd.set("waybackAuto", "on"); // Ticked when the check is on: said so, or the platform's default (an // Odysee channel with no `audioCheck`; lib/audioCheckPolicy.ts) — so a patch // that does not name it keeps what the channel has. diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -206,3 +206,29 @@ test("the ops patch round-trips a pages channel's targets (an array or its JSON) applyChannelFormPatch(fd, { waybackTargets: [{ url: "blog.example/about", match: "exact" }] }); assert.deepEqual(parseChannelForm(fd).config.wayback?.targets, [{ url: "blog.example/about", match: "exact" }]); }); + +// Release 37 S2: a save of the form keeps `wayback.auto` and each target's +// mime/include/exclude (the form rewrites `config.wayback` whole); the +// `waybackAuto` checkbox and the ops patch turn it on and off. +test("a form save keeps wayback.auto and the targets' filters and sources; the checkbox and the ops patch set and clear auto", () => { + // Release 37 lane F: and each target's archive sources. + const targets = [ + { url: "blog.example", match: "host" as const, mime: ["text/html", "text/plain"], include: "/post/", exclude: "/post/9/", sources: ["wayback" as const, "archive.today" as const] }, + ]; + const fd = channelConfigToFormData({ + handling: "transcribe", + name: "Old blog", + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + url: "https://web.archive.org/web/*/blog.example*", + wayback: { targets, auto: true }, + }); + assert.equal(fd.get("waybackAuto"), "on"); + assert.deepEqual(parseChannelForm(fd).config.wayback, { targets, auto: true }); + validateChannelFormPatch({ waybackAuto: false }); + applyChannelFormPatch(fd, { waybackAuto: false }); + assert.deepEqual(parseChannelForm(fd).config.wayback, { targets }); + applyChannelFormPatch(fd, { waybackAuto: true }); + assert.equal(parseChannelForm(fd).config.wayback?.auto, true); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -469,7 +469,7 @@ function parseWaybackTargets(formData: FormData, url: string | undefined): Wayba const derived = waybackTargetFromUrl(url); if (derived) rows = [derived]; } - const config = coerceWaybackPagesConfig({ targets: rows }); + const config = coerceWaybackPagesConfig({ targets: rows, ...(formData.get("waybackAuto") === "on" ? { auto: true } : {}) }); if (!config) { throw new Error( "A Wayback pages channel needs a target: a URL that scopes its captures " + diff --git a/editor/e2e/wayback-captures.spec.ts b/editor/e2e/wayback-captures.spec.ts @@ -0,0 +1,158 @@ +// The Captures tab of a Wayback pages channel (release 37 S2), end to end over +// the fake Wayback (common/testing/web/fakeWayback.mjs, its scan listing), +// named to the test server through E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). +// The real Wayback Machine is never contacted. +// +// Scan now runs a wayback-scan job (the CDX listing, no bodies) → the table → +// filter by year → Import selected and Import all in range queue one +// import-page job per row (S1's job: the capture fetched raw, a page record +// written) → the rows read as imported and Import all in range skips them → +// the automatic-import toggle writes wayback.auto. + +import { test, expect } from "@playwright/test"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import type { APIRequestContext } from "@playwright/test"; +import path from "node:path"; +import { startFakeWayback, SCAN_CAPTURES } from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs"; +import { baseUrl } from "./baseUrl"; +import { resetData, resolvePath, testPaths } from "./helpers"; +import { waybackOriginFile } from "./servers"; + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "synth-pages"; + +type JobRow = { id: string; status: string }; + +// Every import-page job of the channel, once `n` exist and all have ended. +async function importJobs(request: APIRequestContext, n: number): Promise<JobRow[]> { + let rows: JobRow[] = []; + await expect + .poll( + async () => { + const res = await request.get(`${baseUrl}/api/ops/jobs?kind=import-page&slug=${SLUG}&limit=50`, { headers: AUTH }); + rows = ((await res.json()) as { jobs: JobRow[] }).jobs; + return rows.length === n && rows.every((r) => r.status === "done" || r.status === "failed"); + }, + { timeout: 90_000, intervals: [1_000] }, + ) + .toBe(true); + return rows; +} + +test("Captures: scan on the fake → the table → filter by year → Import selected and Import all in range queue one import each", async ({ + page, + request, +}) => { + test.setTimeout(180_000); + await resetData("empty"); + const transcripts = resolvePath(testPaths().transcriptsDir); + const channelRoot = path.join(transcripts, "channels", SLUG); + await mkdir(channelRoot, { recursive: true }); + await writeFile( + path.join(channelRoot, "config.json"), + JSON.stringify( + { + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + name: "Synth Blog (Wayback)", + url: "https://web.archive.org/web/*/blog.example*", + wayback: { targets: [{ url: "blog.example", match: "host" }] }, + }, + null, + 2, + ), + ); + const wb = await startFakeWayback({ captures: SCAN_CAPTURES }); + const originFile = waybackOriginFile(transcripts); + await writeFile(originFile, wb.base); + try { + await page.goto(`/channels/${SLUG}/captures`); + await expect(page.getByRole("link", { name: "Captures tab" })).toHaveAttribute("aria-current", "page"); + await expect(page.getByLabel("captures status line")).toHaveText("Not scanned yet"); + + await page.getByRole("button", { name: "Scan now" }).click(); + const status = page.getByLabel("captures status line"); + await expect(status).toContainText("7 versions of 5 pages", { timeout: 30_000 }); + await expect(status).toContainText("0 imported"); + await expect(status).toContainText("complete"); + + // One listing, no bodies: matchType host, collapsed by digest, paged. + const cdx = wb.requests.filter((r) => r.path.startsWith("/cdx/")); + expect(cdx.length).toBe(1); + const q = new URL(cdx[0].path, "http://x").searchParams; + expect(q.get("matchType")).toBe("host"); + expect(q.get("collapse")).toBe("digest"); + expect(q.get("showResumeKey")).toBe("true"); + expect(wb.requests.some((r) => r.path.startsWith("/web/"))).toBe(false); + + const table = page.getByRole("table", { name: "captures table" }); + await expect(table.locator("tbody tr")).toHaveCount(7); + const p101b = page.getByRole("row", { name: "capture /post/101/first-post P101B" }); + await expect(p101b).toContainText("2015-04-05"); + await expect(p101b).toContainText("2 of 2"); + + // Filter: the 2015 rows. + await page.getByLabel("Year").selectOption("2015"); + await page.getByRole("button", { name: "Filter" }).click(); + await expect(page).toHaveURL(/year=2015/); + await expect(table.locator("tbody tr")).toHaveCount(4); + await expect(page.getByLabel("capture count")).toHaveText("4 rows match"); + + // Import selected: two rows → two import-page jobs, each the capture the + // content was first listed at. + await page.getByLabel("Select /post/101/first-post (2015-04-05)").check(); + await page.getByLabel("Select /tagged/bread (2015-07-08)").check(); + await page.getByRole("button", { name: "Import selected (2)" }).click(); + await expect(page.getByLabel("import result")).toContainText("Queued 2 import jobs."); + const first = await importJobs(request, 2); + expect(first.map((j) => j.status)).toEqual(["done", "done"]); + const fetched = wb.requests.filter((r) => /^\/web\/\d{14}id_\//.test(r.path)).map((r) => r.path).sort(); + expect(fetched).toEqual([ + "/web/20150405000000id_/https://blog.example/post/101/first-post", + "/web/20150708000000id_/https://blog.example/tagged/bread", + ]); + + // The two rows now read as imported; Import all in range takes the other two. + await page.reload(); + await expect(page.getByLabel("captures status line")).toContainText("2 imported"); + await expect(page.getByRole("row", { name: "capture /post/101/first-post P101B" }).getByLabel(/^imported as /)).toBeVisible(); + await expect(page.getByLabel("capture count")).toHaveText("4 rows match (2 not imported)"); + await page.getByRole("button", { name: "Import all in range (2)" }).click(); + await expect(page.getByLabel("import result")).toContainText("Queued 2 import jobs; 2 already imported."); + expect((await importJobs(request, 4)).every((j) => j.status === "done")).toBe(true); + await page.reload(); + await expect(page.getByLabel("captures status line")).toContainText("4 imported"); + await expect(page.getByRole("button", { name: "Import all in range (0)" })).toBeDisabled(); + + // The automatic-import toggle writes wayback.auto (and keeps the targets). + const toggle = page.getByLabel("Import new captures automatically"); + await expect(toggle).not.toBeChecked(); + await toggle.check(); + await expect + .poll(async () => JSON.parse(await readFile(path.join(channelRoot, "config.json"), "utf8")).wayback) + .toEqual({ targets: [{ url: "blog.example", match: "host" }], auto: true }); + await page.reload(); + await expect(page.getByLabel("Import new captures automatically")).toBeChecked(); + + // The same over HTTP, as a dry run: nothing queued. + const res = await request.post(`${baseUrl}/api/ops/wayback-import`, { + headers: AUTH, + data: { slug: SLUG, prefix: "blog.example/post/", dryRun: true }, + }); + const body = (await res.json()) as { ok: boolean; chosen: number; queued: { url: string; jobId?: string }[]; skipped: unknown[] }; + expect(res.status()).toBe(200); + expect(body.chosen).toBe(4); + expect(body.queued.map((x) => x.url)).toEqual([ + "https://web.archive.org/web/20140203000000/https://blog.example/post/101/first-post", + "https://web.archive.org/web/20140506000000/https://blog.example/post/102/second-post", + ]); + expect(body.queued.every((x) => x.jobId === undefined)).toBe(true); + expect(body.skipped.length).toBe(2); + await importJobs(request, 4); + } finally { + await rm(originFile, { force: true }); + await wb.close(); + } +}); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11092,6 +11092,54 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri url) is on x.com / twitter.com / mobile.twitter.com, so `publishedMemberSlugs` leaves it out of a public site while X is private. +## Release 37 S2 — Wayback pages: the scan (`wayback-scan.json`) and the Captures tab + +- **`channels/<slug>/wayback-scan.json`** (lib/waybackPages/scanFile.ts, written compact and atomic by + controller/waybackScan.ts; read by the Captures tab and the lane): `{format: "archilyzer-wayback-scan", version: 1, + slug, pass, passStartedAt, previousPassStartedAt?, lastScanAt?, jobId?, targets: [{key, url, match, from?, to?, + resumeKey?, complete, rows, lastScanAt?, completedAt?, passFrom?}], rows: [{originalUrl, digest, firstTs, lastTs, + count, mimetype, status, pass}], summary: {pages, versions, byYear, byPrefix}}`. One row per distinct (original URL, + digest). Text tier, never published; moves with the channel dir (rename) and goes with it (delete); a media + relocation does not touch it. **Imported state is not in it**: `imported.ts` derives it from the channel's posts + (`page.originalUrl` by `pageUrlKey` — no scheme, host without www./default port — plus `page.digest`, or for a record + with no digest a `captureTs` in the row's first..last). +- **A target's key** (`waybackTargetKey`) is `[match, url, from, to, mimes]`; include/exclude only filter. A changed + key is a new target scanned from its start; a target the config drops loses its state, its rows stay. +- **The CDX request** (`scanCdxUrl`): `url` (host/domain targets: the hostname), `matchType`, `output=json`, + `fl=original,timestamp,digest,mimetype,statuscode`, `filter=statuscode:200`, `filter=mimetype:<escaped mimes joined + by |>` (default text/html), `collapse=digest`, `from` (the later of the target's and the pass's), `to`, `limit` + (≤ 5,000), `showResumeKey=true`, `resumeKey`. The JSON answer ends `[]`, `[<key>]` when rows remain. Through + `WaybackClient.cdxPage` (the `waybackClient` singleton's paced chain). A run reads ≤ `maxRows` (50,000; ≤ 200,000) + rows and ≤ 100 requests; the file is written after every page. +- **Passes**: a run continues incomplete targets from their resume keys; when every target is complete the next run + is pass n+1 asking `from` = previous pass start − 30 days (`PASS_OVERLAP_DAYS`), `full` = pass n+1 from each + target's start. A row is **new** iff `file.pass > 1 && row.pass === file.pass`. With collapse, `count` = listed + captures (a later sighting counts only outside [firstTs, lastTs]). +- **Assets** (css/js/images/fonts/media/archives by extension, `isAssetUrl`) are dropped unless the target's + `include` matches; `exclude` always wins. +- **Queue**: `wayback-scan` and every `import-page` run on `platform:archive.org` (`WAYBACK_QUEUE`). The job kind is + drainable, `needsText`, not an ingest kind (jobKinds.test's notIngest). +- **Imports from the scan** (controller/waybackImport.ts): one `import-page` request per row + `{slug, url: https://web.archive.org/web/<firstTs>/<originalUrl>, requestedBy}`; row key `<digest> <originalUrl>`; + imported rows skipped; ≤ 500 a call (`left`). The starter is S1's `startImportPageJob` (its `ImportPageRefusal` + sentence stops the batch); tests swap it with `setImportPageStarterForTest`. +- **`wayback.auto`** (controller/laneWaybackAuto.ts): the download lane's channel-scoped unit after the metadata-scan + pre-pick — an opted-in channel's rows with `pass > 1` not imported, oldest first, one per unit on the `archive.org` + platform slot (`platformInFlight`/gap/back-off like any platform), the child job awaited through `onJobEnd`; the + pending list cached 60 s per channel, each row offered once per runner. +- **The Captures tab** (`/channels/<slug>/captures`; ChannelTabs shows Overview | Captures for a channel whose raw + config names `wayback.targets`): filtered server-side by `?year=&prefix=&q=&show=&page=` (100 rows a page). Labels + the spec uses: "captures status line", "captures table", rows `capture <path> <digest>`, checkboxes + `Select <path> (<YYYY-MM-DD>)`, buttons "Scan now" / "Continue scan", "Import selected (N)", "Import all in range + (N)" (inline confirm above 50, "confirm import range"), "import result", "capture count". +- **`wayback.auto`** is a key of `config.wayback` in the schema (lib/waybackPages/config.ts, `auto?: true`); the + channel form carries it as the `waybackAuto` checkbox (CHANNEL_FORM_FLAGS), and its target rows carry each target's + mime/include/exclude through a save. The Captures tab's toggle writes it through `patchChannelConfig`. +- **E2E**: the scan's CDX URLs are built on `WAYBACK_ORIGIN`; the process `waybackClient` sends them to the spec's fake + (S1's `E2E_WAYBACK_ORIGIN_FILE`). The fake's scan listing (`scanListing`, `SCAN_CAPTURES`, `scanRefuseFrom`) answers + only requests with `showResumeKey=true`; its plain CDX answer carries a capture's own `digest` when it names one. +- **Where the tab lives**: Wayback pages channels are the one kind of posts channel with ChannelTabs (Overview | + Captures, `isWaybackPagesChannel`); S1's Wayback pages panel links "Captures: scan and choose". ## Release 37 lane C: the page extractors (verified 2026-10-20, branch `r37/extractors`) - **Where**: `common/lib/waybackPages/extractors/{gdoc,ytAbout,x,xenforo,tumblr}.ts`, each a `PageExtractor` diff --git a/plans/release-37/scan.md b/plans/release-37/scan.md @@ -0,0 +1,83 @@ +# Release 37 lane B `r37/scan` (S2: scan and choose) — as shipped + +Plan of record: `plans/release-37/wayback-pages.md`, "What a channel is" and "S2". The brief's decisions held: a +scan never fetches a body; `collapse=digest` by default; no model anywhere. + +## What + +- **`wayback-scan {slug, dryRun?, maxRows?, full?}`** (`common/controller/waybackScan.ts`): every target of + `config.wayback.targets` listed through the CDX API — matchType per target, status 200, the target's mimes + (text/html by default), collapse=digest, the date bounds, `fl` of five columns, pages of 5,000 with + `showResumeKey`, at most `maxRows` (50,000; ceiling 200,000) rows and 100 requests a run — through the Wayback + client's paced chain (new `WaybackClient.cdxPage`). A run cut short (row cap, refusal, drain, cancel) keeps each + target's resume key; once all are complete the next run is a new pass asking from 30 days before the last pass + began; `full` is a new pass from each target's start. A refusal stops the job (failed, with the reason) and keeps + what it wrote. A dry run asks nothing and logs each target's next request. A job kind on `platform:archive.org` + (`WAYBACK_QUEUE`), drainable, `needsText`, not ingest. Ops action, `archilyzer wayback scan <slug>` CLI. +- **`channels/<slug>/wayback-scan.json`** (`common/lib/waybackPages/scanFile.ts` + `scanFile-server.ts`): per target + state, one row per distinct (URL, digest) with first/last seen, count, the pass that first listed it; summaries by + year and by one-/two-segment path prefix. Written compact and atomic after every page. Imported state derived + (`imported.ts`) from the channel's webpage records. +- **Targets reader** (`common/lib/waybackPages/targets.ts`): the brief's narrow, tolerant parser of `config.wayback` + (raw config.json until A's schema lands), the target key, the CDX `url`/mime filter, the asset/include/exclude + rules. +- **Captures tab** (`editor/app/channels/[slug]/captures/`): Overview | Captures on a Wayback pages channel + (`ChannelTabs captures`, the layout reads the raw config). Status line, targets, Scan now / Continue scan + (`StreamActionLog`), the last scan's job linked, the table (path, first/last seen, version i of n, imported mark + linking the record's capture, new), server-side filters (year, path prefix, text, show) and pagination (100 a page), + per-page selection, Import selected, Import all in range (inline confirm above 50), the result line. +- **Imports from the scan** (`common/controller/waybackImport.ts`): one `import-page` job per row through S1's + `startImportPageJob` (the capture the content was first listed at), imported rows skipped, ≤ 500 a call; + `wayback-import` ops action. (Before A merged, a seam stood in; removed at the merge.) +- **`wayback.auto`** (`common/controller/laneWaybackAuto.ts` + one pre-pick block and one run branch in + `autoRunner.ts`): the download lane's channel-scoped unit after the metadata scan — an opted-in channel's rows + listed after its first pass and not imported, one import-page job per unit on the `archive.org` platform slot, + waited on via `onJobEnd`. `auto` is a key of A's `wayback` schema entry (CHANNEL.md); the channel form carries it + (`waybackAuto`) and keeps each target's mime/include/exclude through a save; the Captures tab has the toggle. +- **Fake + e2e**: `fakeWayback.mjs` scan listing in its own block (matchType, from/to, filters, collapse, fl, limit, + resume keys, `scanRefuseFrom`, `SCAN_CAPTURES`; its plain CDX answer carries a capture's own digest); the scan's + URLs on `WAYBACK_ORIGIN`, sent to the fake by S1's process client (`E2E_WAYBACK_ORIGIN_FILE`); + `editor/e2e/wayback-captures.spec.ts` (real import-page jobs since the merge). +- **Where the tab lives**: Wayback pages channels are the one kind of posts channel with ChannelTabs (Overview | + Captures); S1's Wayback pages panel links "Captures: scan and choose". +- **Docs**: OPERATING.md "Wayback pages: scan, then choose", COMMANDS.md, ENVIRONMENT.md (two test env vars), FACTS + "Release 37 S2", CHANGELOG. + +## Commits + +| sha | what | +|---|---| +| `1f31f765` | the scan: CDX over the targets, paged and resumable, wayback-scan.json, the fake's scan listing, the job kind | +| `39877e0d` | the Captures tab, import selected / all in range (seam), wayback.auto in the download lane, ops + CLI | +| `47b54f68` | the e2e spec, its fake origin and seam, docs | +| `9082180c` | the two e2e variables in the editor's playwright config; this record (draft) | +| `b775e7c9` | merge main (lane C's extractors) | +| `c38da131` | scanView client-safe | +| `68f24a77` | record: commits and gates before A | +| `e88b5689` | merge main (lane A) + the post-A wiring: real import-page, schema `auto`, form field, toggle, panel link, tests | +| (next) | the toggle shows its state at once; this record | + +## Gates + +- tsc, the whole workspace: clean (after the merge of main). +- common: 4695 at the branch start (1 failure in a run that raced the lane's first edits, not reproduced) → 4717 + (+22, my one failure the playwright-config declaration, fixed) → 4751/4749 pass, 0 fail, 2 skipped after merging + main (lane C's tests included). +- editor unit: 353/353 → 353/353. +- test:scripts: 1315 (1311 pass, 4 skipped) → 1315 (1311, 4). +- docs: `docs env` regenerated (ENVIRONMENT.md), `docs cli` regenerated (COMMANDS.md); `docs env|files|cli --check` + and `settings example --check` clean. +- e2e before A: `wayback-captures.spec.ts` 1/1 (20.1 s wall, after an 87 s stamped build); `navigation.spec.ts` 5/5 + (17.0 s) as a neighbour check of the tab change. +- After merging lane A (main d261ab33): tsc clean; common 4787 / 4785 pass / 0 fail / 2 skipped; editor unit 357/357 + (+4: A's and the form test keeping `auto`); test:scripts 1316 (1312 + 4 skipped); docs env/files/cli and settings + `--check` clean (CHANNEL.md, ENVIRONMENT.md, COMMANDS.md regenerated); e2e `wayback-captures.spec.ts` + + `wayback-pages.spec.ts` 2/2 (35.0 s; the first run failed on the toggle — a controlled checkbox waiting for the + refresh — fixed with local state). A second neighbour run (navigation + channel-rename) never got the heavy slot in + two 10-minute tries and was not run; the full suite is the orchestrator's. + +## Rulings followed + +- Corpus read-only; synthetic fixtures only; no real network in any test. +- Every heavy step through the session lock. +- No Claude-Session trailer. diff --git a/plans/release-38/research-cases-and-assist.md b/plans/release-38/research-cases-and-assist.md @@ -128,3 +128,11 @@ Nik Drop: "make the joins 0.15 s with less smear" from the Ask box on local Qwen page (the content sits in blocks it drops). Raw captures are kept, so `reextract-pages` fixes held records. (Lane C.) - **Forum attachments as marked evidence**: `capture-posts` on a forum channel's posts → "forum attachment, post #N, unverified" wherever shown; a case export lists them in an Evidence section with the post link. (Lane C.) +- **Private names are stored as hashes** (`privateNames.sha256`: sha256 of each lowercased term), never as text: the + gate hashes every word and 2–3-word phrase of what it checks. A case's private terms then never sit in any file. + (Used live in `~/reports/oneylyzer/case/build_case.py`.) (Lane A.) +- **Quarantine as a finding status** (operator 2026-10-20: forum joke culture): `quarantined` for anything first seen + on a forum and not corroborated by an independent source; its own report section; attachments looked at before + being described. (Lanes B/C.) +- **An X search channel** (a saved query across accounts, leads ranked by author, Archive / Never archive) — lane S + `r38/x-search`, launched 2026-10-20. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -117,6 +117,9 @@ // pnpm ops find-copy --json '{"article":"demo-article","retryFailed":true}' --wait // pnpm ops find-copy --json '{"siteId":"demo-site","gone":"no-transcript","dryRun":true}' --wait // pnpm ops find-copy --json '{"slug":"demo-channel","gone":"all","max":5}' --wait +// pnpm ops wayback-scan --json '{"slug":"demo-pages","dryRun":true}' --wait +// pnpm ops wayback-scan --json '{"slug":"demo-pages"}' --wait +// pnpm ops wayback-import --json '{"slug":"demo-pages","year":"2014","show":"not-imported","dryRun":true}' // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait // 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 @@ -464,6 +467,12 @@ const ACTIONS = [ // brings every gone video's WHOLE audio home (a fetch-copies job). "wayback-lookup", "find-copy", + // WAYBACK PAGES, SCAN AND CHOOSE (release 37 S2): a Wayback pages channel's + // CDX scan into wayback-scan.json ({slug, dryRun?, maxRows?, full?}), as a + // job on archive.org's queue; and the chosen rows imported, one import-page + // job each ({slug, keys? | year?, prefix?, q?, show?, dryRun?}). + "wayback-scan", + "wayback-import", // GENERATION (release 27 S6): a sweep, a report or video revision, or a // narration step over an article's iteration ({task, article, iteration?, // model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?, @@ -1458,6 +1467,36 @@ export function usage() { " looked: [{slug, id, gone, noTranscript, watchUrl, youtubeId, tried,", " copy?, via?, outcome}], left, items, stopped?, fetchJobId?, refused?}.", "", + '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?}.", + "", + '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.", + "", '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', diff --git a/settings.json.example b/settings.json.example @@ -197,6 +197,12 @@ "maxDownloadKiBps": 0, "maxUploadKiBps": 0 }, + "archives": { + "archiveTodayHost": "archive.ph", + "archiveTodayGapSeconds": 8, + "archiveTodayCooldownMinutes": 30, + "archiveTodayBrowser": true + }, "publish": { "enabled": false, "held": false,