Archilyzer · Source

archilyzer

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

commit 2bafcae9645c763c94b58b2c0e90337323bec8c1
parent 918aa0c7836312601a225c2c15105acfc4b176ef
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 02:00:58 -0500

Merge branch 'main' into lane/rev9-fixes

Diffstat:
MCOMMANDS.md | 7++++---
MENVIRONMENT.md | 1+
MOPERATING.md | 14+++++++++++++-
Mcommon/bin/archilyzer.ts | 4++--
Mcommon/bin/evidence-pack.ts | 11++++++++---
Mcommon/bin/fetch-posts.ts | 13+++++++++++--
Mcommon/controller/fetchOlderPosts.test.ts | 6++++--
Mcommon/controller/fetchPosts.test.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/controller/fetchPosts.ts | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/archiveOrgClient.ts | 16++++++++++++----
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/posts-server.ts | 21+++++++++++++++------
Acommon/lib/timelineWalk.test.ts | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/timelineWalk.ts | 235+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/web/pacer.ts | 16++++++++++++----
Mcommon/social/blueskyFetcher.ts | 11++++++-----
Mcommon/social/fetchers.ts | 12+++++++-----
Mcommon/social/postCapture.test.ts | 29++++++++++++++++++++++++++++-
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/_door.test.ts | 1+
Meditor/app/api/ops/browser-lookup/route.test.ts | 7++++++-
Meditor/app/api/ops/fetch-posts/route.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/fetch-posts/route.ts | 10++++++++--
Aeditor/app/api/ops/resume-backfill/route.ts | 37+++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/SocialChannelPanel.tsx | 73++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Meditor/app/channels/[slug]/page.tsx | 17+++++++++++++++++
Meditor/app/channels/[slug]/socialActions.ts | 27+++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 2++
Meditor/e2e/social-channel.spec.ts | 71++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mmcp/src/archivalTools.test.ts | 8++++++++
Mmcp/src/archivalTools.ts | 14++++++++++----
Mplans/FACTS.md | 14+++++++++++++-
Mscripts/archilyzer-ops.mjs | 31++++++++++++++++++++++++++-----
Mscripts/archilyzer-ops.test.mjs | 14+++++++++++++-
34 files changed, 1064 insertions(+), 98 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -66,10 +66,10 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer seed` | | the home seeder of last resort: seed the playable torrents of settings.seeder.sites, each only while no other seeder has it (standby otherwise, with hysteresis), TCP + WebRTC, no DHT; runs until interrupted — behind the VPN (docker compose profile `seeder`, docker-compose.seeder.yml) | | `archilyzer tracker` | `[--host 127.0.0.1] [--port 8000]` | the self-hosted tracker (HTTP + WebSocket, no UDP) for the seeder's torrents only — any other infohash is refused; runs until interrupted | | `archilyzer duplicates` | `[--threshold N] [--all-durations] [--blocking title\|duration\|both] [--near F] [--tolerance N] …` | on-demand duplicate detection (after index + stats) *(passthrough)* | -| `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again) *(passthrough)* | +| `archilyzer posts fetch` | `--slug <channel> [--backfill \| --full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again) *(passthrough)* | | `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched | | `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* | -| `archilyzer evidence pack` | `<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media\|--no-media] [--stamp\|--no-stamp] [--dry-run] [--json]` | package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/&lt;postId&gt;/ (the files in posts-media/, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/&lt;handle\|channel&gt;-&lt;YYYY-MM-DD&gt;/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later) | +| `archilyzer evidence pack` | `<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media\|--no-media] [--stamp\|--no-stamp] [--dry-run] [--json]` | package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/&lt;postId&gt;/ (the post's captured files, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/&lt;handle\|channel&gt;-&lt;YYYY-MM-DD&gt;/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later) | | `archilyzer evidence stamp` | `<dir> [--json]` | OpenTimestamps-stamp an evidence package's SHA256SUMS (one with --no-stamp, or whose stamp failed): SHA256SUMS.ots, one request to each of the client's calendars; refused when it is stamped already | | `archilyzer evidence upgrade` | `<dir> [--json]` | upgrade an evidence package's pending SHA256SUMS.ots to its Bitcoin attestation (`ots upgrade`; the calendars attest a few hours after the stamp; the pending proof is kept as SHA256SUMS.ots.bak); exit 0 pending or attested, and says which | | `archilyzer evidence verify` | `<dir> [--json]` | check an evidence package: every file against SHA256SUMS (missing, changed, and files it does not list), then the stamp's state (`ots info`: pending calendars or the Bitcoin block); exit 1 on any difference | @@ -150,7 +150,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | -| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | +| `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"} is SYNC NEW — from the top of the timeline down to the newest archived post (a sync that stopped part-way continues down to the watermark it began with). It never reads or clears an unfinished backfill's resume point. "backfill": true is RESUME BACKFILL instead (the same as resume-backfill). "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full", "older" and "backfill" are one at a time. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run of the same walk resumes there. | `pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait` | +| `resume-backfill` | resume-backfill continues a social channel's unfinished full-history timeline walk (X, Bluesky) from its saved resume point, with no watermark: {"slug"} ("limit"? caps the posts this run reads). The walk is left part-way by a first fetch, a full re-walk or a backfill that stopped; the channel page then says "backfill unfinished — N archived" and shows Resume backfill. Nothing resumes it but this (or fetch-posts "backfill": true): a plain fetch-posts, Sync and the scheduler sync new posts and keep its place. Refused when none is part-way, on a forum thread (every fetch catches up, then continues its history) and on an X search channel. | `pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait` | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -63,6 +63,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `ARCHIVE_ORG_S3_ACCESS` | unset (the S3 key file is read instead) | archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why. | common/lib/waybackPages/savePageNow-server.ts | | `ARCHIVE_ORG_S3_SECRET` | unset (the S3 key file is read instead) | archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above). | common/lib/waybackPages/savePageNow-server.ts | | `SYNC_HEARTBEAT_SECONDS` | `settings.syncScheduler.heartbeatSeconds` | Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead). | editor/app/scheduler/heartbeat.ts | +| `ARCHILYZER_OTS_BIN` | `ots` on PATH, then `~/.local/bin/ots` | The OpenTimestamps `ots` binary that `archilyzer evidence stamp\|upgrade\|verify` (and `evidence pack`'s stamp) run. Without one, the stamp fails and the package is left unstamped (`evidence stamp` it later). | common/bin/evidence-pack.ts | | `SYNC_TICK_URL` | `http://127.0.0.1:3001/api/scheduler/tick` | Where `archilyzer sync tick` (cron's heartbeat) posts. | common/bin/sync-tick.ts | | `SYNC_TICK_TOKEN` | unset (no auth) | Bearer token for the tick endpoint; set on both the editor and the cron job. | common/bin/sync-tick.ts, editor/app/scheduler/auth.ts | | `R2_ACCESS_KEY_ID` | — | R2 S3 credentials for uploading oversize archives at deploy time (with `R2_SECRET_ACCESS_KEY` and `CLOUDFLARE_ACCOUNT_ID`), needed only when `archiveStorage.bucket` is set. In Docker they come from `.env`. See [PUBLISH.md](PUBLISH.md). | common/publish/build.ts, common/bin/doctor.ts (set or not) | diff --git a/OPERATING.md b/OPERATING.md @@ -445,7 +445,8 @@ pnpm ops capture-posts --json '{"slug":"old-blog","ids":["<recordId>"],"media":f ```sh pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}' -pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait +pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait # sync new +pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait # = fetch-posts "backfill": true pnpm ops fetch-posts --json '{"slug":"example-x","older":true}' --wait pnpm ops fetch-posts --json '{"slug":"example-forum-thread","pages":20,"retryOnBlock":true}' --wait pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait @@ -453,6 +454,17 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait - An X, Bluesky or XenForo URL makes a social channel (its handle derived from the URL). `"older": true` walks back below the oldest archived post and resumes from its saved place; `"full": true` re-walks the timeline. +- **Sync new and resume backfill are two actions** for an X or Bluesky timeline (`common/lib/timelineWalk.ts`). A + plain `fetch-posts` — and Sync, the scheduler, the channel page's **Sync new** — is SYNC NEW: from the top down to + the newest archived post. It never reads or clears an unfinished backfill's place (`posts-state.json` `backfill`). + A sync that stopped part-way keeps its own place (`sync`) and the next sync continues it down to the watermark + it began with. **Resume backfill** (`pnpm ops resume-backfill`, or `fetch-posts "backfill": true`; the channel + page's button, shown only when one is part-way) continues the full-history walk from its saved place, with no + watermark. A first fetch, an unfinished `"full"` and a stopped backfill leave one; the channel page then says + `backfill unfinished — N archived; Resume backfill continues it`, and nothing resumes it unasked. A + `posts-state.json` from before the split has one `cursor`. It is read as the backfill's place and rewritten on + the next fetch. The job log's first line names the mode (`— sync new, since …` / `— resume backfill, from its + saved resume point`). - **Pacing is enforced, not advised** (plans/pacing-guard.md). Every job that asks a platform waits its platform queue's gap after the previous one there ended — `pacing.jobGapSeconds`: X 300 s, forums and Bluesky 60 s, everything else 20 s (set on /settings) — and its /jobs row and log say so (`waiting 4m12s: X diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -856,7 +856,7 @@ export const COMMANDS: Command[] = [ script(["duplicates"], "duplicate-shorts.ts", "[--threshold N] [--all-durations] [--blocking title|duration|both] [--near F] [--tolerance N] … on-demand duplicate detection (after index + stats)", 8192), script(["posts", "fetch"], "fetch-posts.ts", - "--slug <channel> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), + "--slug <channel> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M] fetch a social channel's posts into its posts corpus (plain: sync new — from the top down to the newest archived post, never the backfill; --backfill: resume the timeline's unfinished full-history walk from its saved point; --older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-*: wait out a challenge or refusal page and run again)"), { path: ["posts", "import-html"], usage: @@ -882,7 +882,7 @@ export const COMMANDS: Command[] = [ { path: ["evidence", "pack"], usage: - "<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media|--no-media] [--stamp|--no-stamp] [--dry-run] [--json] package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/<postId>/ (the files in posts-media/, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/<handle|channel>-<YYYY-MM-DD>/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later)", + "<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media|--no-media] [--stamp|--no-stamp] [--dry-run] [--json] package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/<postId>/ (the post's captured files, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/<handle|channel>-<YYYY-MM-DD>/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later)", flags: { handle: "string", since: "string", diff --git a/common/bin/evidence-pack.ts b/common/bin/evidence-pack.ts @@ -48,6 +48,11 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import type { FlagValue } from "./_parseFlags"; +// The capture layout's one definition (posts-media/<id>/capture.json). This +// module is the second reader of captures the export guard allows +// (social/postCapture.test.ts): a private package, written outside the +// corpus, that nothing in the export or publish layer imports. +import { CAPTURE_FILENAME, postsMediaDir } from "../social/postCapture"; export const SUMS_FILE = "SHA256SUMS"; export const OTS_FILE = "SHA256SUMS.ots"; @@ -443,7 +448,7 @@ async function planMedia( const out: PlannedCopy[] = []; const seen = new Set<string>(); for (const ch of channels) { - const dir = path.join(channelsDir, ch, "posts-media", id); + const dir = path.join(postsMediaDir(path.join(channelsDir, ch)), id); if (!(await isDir(dir))) continue; const capture = captures.get(ch) ?? null; const named = new Map<string, { sha256?: string; url?: string }>(); @@ -493,7 +498,7 @@ export async function pack(opts: PackOptions): Promise<PackResult> { const forbidden = [opts.transcriptsDir, opts.channelsDir]; for (const s of opts.slugs) { forbidden.push(path.join(opts.channelsDir, s)); - forbidden.push(path.join(opts.channelsDir, s, "posts-media")); + forbidden.push(postsMediaDir(path.join(opts.channelsDir, s))); forbidden.push(path.join(opts.channelsDir, s, "media")); } for (const f of forbidden) { @@ -547,7 +552,7 @@ export async function pack(opts: PackOptions): Promise<PackResult> { const channels = list.map((l) => l.channel); const captures = new Map<string, Record<string, unknown> | null>(); for (const ch of channels) { - captures.set(ch, obj(await readJson(path.join(opts.channelsDir, ch, "posts-media", id, "capture.json"))) ?? null); + captures.set(ch, obj(await readJson(path.join(postsMediaDir(path.join(opts.channelsDir, ch)), id, CAPTURE_FILENAME))) ?? null); } const capture = channels.map((c) => captures.get(c)).find((c) => c) ?? null; const avail = channels.map((c) => obj(availability.get(c)?.[id])).find((a) => a) ?? null; diff --git a/common/bin/fetch-posts.ts b/common/bin/fetch-posts.ts @@ -2,7 +2,7 @@ // Fetch social posts for one channel into its on-disk posts corpus. // // pnpm --filter yt-dlp-transcript-common exec tsx bin/fetch-posts.ts \ -// --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] +// --slug <channel-slug> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] // [--retry-on-block | --retry-minutes N --retry-tries M] // // --pages caps how many pages one run reads, for a source read page by page (a @@ -16,6 +16,14 @@ // walk; wait N minutes and run again, M tries in all. --retry-on-block uses // settings.social.xenforo.retryOnBlock (nothing when unset). // +// A plain run is SYNC NEW: from the top of the timeline down to the newest +// archived post (an unfinished sync continues down to the watermark it began +// with). It never reads or clears the backfill's resume point. +// +// --backfill is RESUME BACKFILL: the timeline's unfinished full-history walk +// continued from its saved resume point, with no watermark (refused when none +// is part-way). lib/timelineWalk.ts. +// // --full re-walks the account's whole history instead of stopping at the // stored watermark. New posts are still deduped against the posts-archive, so // it repairs a gap rather than creating duplicates. @@ -39,7 +47,7 @@ const flags = parseFlags(process.argv.slice(2)); const slug = flags.slug; if (!slug) { console.error( - "Usage: fetch-posts.ts --slug <channel-slug> [--full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]", + "Usage: fetch-posts.ts --slug <channel-slug> [--backfill | --full | --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block | --retry-minutes N --retry-tries M]", ); process.exit(2); } @@ -74,6 +82,7 @@ fetchPosts({ slug, settings: getSettings(), full: flags.full === "true", + backfill: flags.backfill === "true", older: flags.older === "true", floor: flags.floor, from: flags.from, diff --git a/common/controller/fetchOlderPosts.test.ts b/common/controller/fetchOlderPosts.test.ts @@ -212,12 +212,14 @@ test("an older fetch walks back window by window and stops after four empty wind assert.ok(again.some((l) => /already complete/.test(l)), again.join("\n")); }); -test("a normal fetch ignores the older walk's state, resumes the TIMELINE, and keeps the older state", async () => { +test("resume backfill ignores the older walk's state, resumes the TIMELINE's backfill, and keeps the older state", async () => { const slug = "older-walk"; const channelRoot = path.join(channelsDir, slug); const olderBefore = (await readPostFetchState(channelRoot))?.older; assert.ok(olderBefore); - const result = await fetchPosts({ paths: getPaths(), slug, settings: LOGIN }); + // The seeded legacy `cursor` is the backfill's (lib/timelineWalk.ts): a + // plain fetch would sync new from the top; `backfill` resumes it. + const result = await fetchPosts({ paths: getPaths(), slug, settings: LOGIN, backfill: true }); assert.equal(result.ok, true); const argv = (await argvLines()).at(-1)!; assert.equal(argv[argv.length - 1], `https://x.com/${HANDLE}/timeline`); diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -1,7 +1,10 @@ // fetchPosts over the gallery-dl X fetcher, end to end against a fake binary: // a run that is cancelled (or times out) part-way keeps what it read and the -// resume point, and the next run continues from there. A drained run stops at -// a page boundary, keeps that resume point, and is not a failure. +// resume point, and the next run of the same walk continues from there. A +// drained run stops at a page boundary, keeps that resume point, and is not a +// failure. The timeline's two walks (lib/timelineWalk.ts): a plain fetch is +// SYNC NEW and never reads or clears the backfill's point; RESUME BACKFILL +// (`backfill`) continues it. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchPosts.test.ts @@ -121,7 +124,7 @@ async function lastArgv(): Promise<string[]> { return JSON.parse(lines[lines.length - 1]) as string[]; } -test("a cancelled backfill keeps what it read and where it stopped", async () => { +test("a cancelled first walk keeps what it read, and where it stopped as the BACKFILL's point", async () => { const controller = new AbortController(); const log: string[] = []; const result = await fetchPosts({ @@ -140,26 +143,71 @@ test("a cancelled backfill keeps what it read and where it stopped", async () => assert.equal(result.complete, false); assert.equal((await readSeenPostIds(channelRoot)).size, 6); const state = await readPostFetchState(channelRoot); - assert.equal(state?.cursor, "1/AFTER-P2"); + assert.equal(state?.backfill?.cursor, "1/AFTER-P2"); + assert.equal(state?.cursor, undefined); + assert.equal(state?.sync, undefined); assert.ok(log.some((l) => /Cancelled; the next run resumes/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /sync new — nothing archived yet, so this is the first full-history walk/.test(l)), log.join("\n")); const argv = await lastArgv(); assert.ok(argv.includes("output.jsonl=true")); assert.ok(argv.includes("--verbose")); }); -test("the next run resumes from the saved cursor and finishes the history", async () => { +test("a plain fetch is SYNC NEW: from the top down to the watermark, never reading the backfill's point, and keeping it", async () => { + process.env.FAKE_MODE = "known"; + const log: string[] = []; + let result; + try { + result = await fetchPosts({ + paths: (await import("../lib/paths")).getPaths(), + slug: SLUG, + settings: {}, + onLog: (l) => log.push(l), + }); + } finally { + delete process.env.FAKE_MODE; + } + assert.equal(result.ok, true, log.join("\n")); + assert.equal(result.complete, true); + // From the top: no resume point handed to gallery-dl. + assert.equal((await lastArgv()).some((a) => a.startsWith("extractor.twitter.cursor=")), false); + assert.ok(log.some((l) => /— sync new, since 2026-06-28/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /A backfill is unfinished \(6 archived; its resume point is kept\)/.test(l)), log.join("\n")); + // Caught up — and the backfill's point is exactly where it was. + assert.equal((await readPostFetchState(channelRoot))?.backfill?.cursor, "1/AFTER-P2"); +}); + +test("RESUME BACKFILL continues from the saved point and finishes the history; the point is then cleared", async () => { + const log: string[] = []; const result = await fetchPosts({ paths: (await import("../lib/paths")).getPaths(), slug: SLUG, settings: {}, + backfill: true, + onLog: (l) => log.push(l), }); assert.equal(result.ok, true); assert.equal(result.written, 3); assert.equal(result.complete, true); assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/AFTER-P2")); + assert.ok(log.some((l) => /— resume backfill, from its saved resume point/.test(l)), log.join("\n")); assert.equal((await readSeenPostIds(channelRoot)).size, 9); // Caught up: no resume point left behind. - assert.equal((await readPostFetchState(channelRoot))?.cursor, undefined); + const state = await readPostFetchState(channelRoot); + assert.equal(state?.backfill, undefined); + assert.equal(state?.cursor, undefined); +}); + +test("RESUME BACKFILL with none part-way, or with full or older, is refused and spawns nothing", async () => { + const before = (await readFile(ARGS_LOG, "utf8")).trim().split("\n").length; + const paths = (await import("../lib/paths")).getPaths(); + const { NO_BACKFILL_TO_RESUME, BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL } = await import("./fetchPosts"); + const none = await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true }); + assert.equal(none.ok, false); + assert.equal(none.error, NO_BACKFILL_TO_RESUME); + assert.equal((await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true, full: true })).error, BACKFILL_AND_FULL_REFUSAL); + assert.equal((await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true, older: true })).error, BACKFILL_AND_OLDER_REFUSAL); + assert.equal((await readFile(ARGS_LOG, "utf8")).trim().split("\n").length, before); }); test("an incremental run stops itself once it is past everything new", async () => { @@ -179,6 +227,36 @@ test("an incremental run stops itself once it is past everything new", async () assert.equal((await readdir(channelRoot)).includes("posts-state.json"), true); }); +test("MIGRATION: a legacy single `cursor` is the backfill's — a plain fetch syncs new past it and keeps it; backfill resumes it", async () => { + // The madamsavvy-x shape (2026-11-06): an unfinished backfill's cursor, from + // before the walks split. A plain fetch used to resume it and miss the new + // posts above the archive. + await writeFile( + path.join(channelRoot, "posts-state.json"), + JSON.stringify({ lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/AFTER-P2" }), + ); + const paths = (await import("../lib/paths")).getPaths(); + process.env.FAKE_MODE = "known"; + const log: string[] = []; + try { + const sync = await fetchPosts({ paths, slug: SLUG, settings: {}, onLog: (l) => log.push(l) }); + assert.equal(sync.ok, true, log.join("\n")); + } finally { + delete process.env.FAKE_MODE; + } + assert.equal((await lastArgv()).some((a) => a.startsWith("extractor.twitter.cursor=")), false); + assert.ok(log.some((l) => /Read the old single resume point/.test(l)), log.join("\n")); + assert.ok(log.some((l) => /— sync new, since /.test(l)), log.join("\n")); + const raw = JSON.parse(await readFile(path.join(channelRoot, "posts-state.json"), "utf8")) as Record<string, unknown>; + assert.equal("cursor" in raw, false); + assert.equal((raw.backfill as { cursor?: string } | undefined)?.cursor, "1/AFTER-P2"); + + const resumed = await fetchPosts({ paths, slug: SLUG, settings: {}, backfill: true }); + assert.equal(resumed.ok, true); + assert.ok((await lastArgv()).includes("extractor.twitter.cursor=1/AFTER-P2")); + assert.equal((await readPostFetchState(channelRoot))?.backfill, undefined); +}); + test("a run that dies part-way fails the job but keeps its posts and resume point", async () => { process.env.FAKE_MODE = "crash"; const result = await fetchPosts({ @@ -191,7 +269,11 @@ test("a run that dies part-way fails the job but keeps its posts and resume poin assert.match(result.error ?? "", /exited 4: .*404 Not Found/); assert.equal(result.written, 3); const state = await readPostFetchState(channelRoot); - assert.equal(state?.cursor, "1/CRASH-P1"); + // A SYNC that stopped: its own point, with the watermark it began with — + // not the backfill's. + assert.equal(state?.sync?.cursor, "1/CRASH-P1"); + assert.equal(state?.sync?.since, "2026-06-28T12:00:00.000Z"); + assert.equal(state?.backfill, undefined); assert.match(state?.lastError ?? "", /404 Not Found/); }); @@ -211,7 +293,7 @@ test("an auth failure that read nothing keeps the resume point it had, and inven // The crash above left a resume point: an auth failure must not drop it. const kept = await run(); assert.equal(kept.needsCookies, true); - assert.equal((await readPostFetchState(channelRoot))?.cursor, "1/CRASH-P1"); + assert.equal((await readPostFetchState(channelRoot))?.sync?.cursor, "1/CRASH-P1"); // From a caught-up state it must not invent one either: the watermark stands. await writeFile(path.join(channelRoot, "posts-state.json"), "{}"); @@ -224,6 +306,8 @@ test("an auth failure that read nothing keeps the resume point it had, and inven const state = await readPostFetchState(channelRoot); assert.equal(state?.needsCookies, true); assert.equal(state?.cursor, undefined); + assert.equal(state?.sync, undefined); + assert.equal(state?.backfill, undefined); }); async function makeChannel(slug: string): Promise<string> { @@ -286,7 +370,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th assert.equal(result.written, 6); assert.equal((await readSeenPostIds(root)).size, 6); const state = await readPostFetchState(root); - assert.equal(state?.cursor, "1/PAGES-P1"); + assert.equal(state?.backfill?.cursor, "1/PAGES-P1"); assert.equal(state?.lastError, undefined); assert.equal(log.some((l) => /page 2 read/.test(l)), false, log.join("\n")); assert.ok(log.some((l) => /Drained; the next run resumes from the last page read/.test(l)), log.join("\n")); @@ -300,6 +384,7 @@ test("a drain mid-page waits for the page's cursor, stops there and keeps it; th paths: (await import("../lib/paths")).getPaths(), slug, settings: {}, + backfill: true, signal: cancel.signal, onLog: (line) => { if (!/^Running /.test(line)) return; @@ -337,7 +422,7 @@ test("a drain while gallery-dl waits out a rate limit stops it at once, keeping assert.equal(result.written, 6); // Not left asleep for its 60 s. assert.ok(Date.now() - started < 15_000, `took ${Date.now() - started} ms`); - assert.equal((await readPostFetchState(root))?.cursor, "1/AFTER-P2"); + assert.equal((await readPostFetchState(root))?.backfill?.cursor, "1/AFTER-P2"); }); test("a drain before the fetch starts reads nothing and spawns nothing", async () => { diff --git a/common/controller/fetchPosts.ts b/common/controller/fetchPosts.ts @@ -53,6 +53,21 @@ import { isUtcDay, olderFloorDay, } from "../social/olderBackfill"; +import { + BACKFILL_AND_FULL_REFUSAL, + BACKFILL_AND_OLDER_REFUSAL, + hasTimelineResumePoint, + NO_BACKFILL_TO_RESUME, + planTimelineRun, + settleTimelineRun, + timelineRunLine, + timelineWalkFields, + timelineWalks, + withResumePoint, + type TimelineMode, + type TimelineRunPlan, + type TimelineWalks, +} from "../lib/timelineWalk"; // Registering the built-in fetchers is a side effect of importing them. Keep // this list here (rather than inside fetchers.ts) so the registry module stays // free of imports from the heavier fetchers. @@ -85,6 +100,13 @@ export type FetchPostsOptions = { // posts are still deduped against the archive, so this is a safe repair // operation rather than a duplicate-maker. full?: boolean; + // RESUME BACKFILL (lib/timelineWalk.ts): continue the timeline's unfinished + // full-history walk from its saved resume point (posts-state.json's + // `backfill`), with no watermark. Without it a fetch is SYNC NEW: from the + // top down to the newest archived post, never reading or clearing the + // backfill's position. Refused when no backfill is part-way, with `full` or + // `older`, on a forum thread and on an X search channel. + backfill?: boolean; // Walk the account's history BACKWARDS from the oldest archived post, with // the fetcher's `fetchOlder` (X: search windows), instead of fetching new // posts. Its position is kept in posts-state.json's `older`, apart from the @@ -139,6 +161,24 @@ export const RETRY_AND_OLDER_REFUSAL = "Retry on a block applies to a new-posts export const FULL_AND_OLDER_REFUSAL = "A full re-fetch and an older-posts fetch are different walks — run one at a time."; +export { BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL, NO_BACKFILL_TO_RESUME }; + +// A forum thread's every fetch catches up from the last page first, then +// continues its history (lib/forumWalk.ts): there is no separate backfill. +export const FORUM_BACKFILL_REFUSAL = + "A forum thread has no separate backfill: every Fetch posts catches up from the last page, then continues the history where it stopped."; + +export const X_SEARCH_BACKFILL_REFUSAL = + "An X search channel has one walk, its search windows: there is no timeline backfill to resume."; + +// Why `backfill` cannot run on this channel's state, or null. Shared with the +// server action, so a refusal comes before any job exists. +export function resumeBackfillProblem( + state: Parameters<typeof timelineWalks>[0], +): string | null { + return timelineWalks(state).backfill ? null : NO_BACKFILL_TO_RESUME; +} + // Why this fetcher cannot fetch older posts, or null when it can. export function olderPostsProblem( fetcher: Pick<SocialFetcher, "label" | "fetchOlder"> | undefined, @@ -160,11 +200,11 @@ export const EMPTY_ACCOUNT_OLDER_REFUSAL = export function emptyAccountOlderProblem( archived: number, - state: Pick<PostFetchState, "lastFetchedCount" | "cursor" | "lastError" | "needsCookies"> | null, + state: Pick<PostFetchState, "lastFetchedCount" | "cursor" | "backfill" | "sync" | "lastError" | "needsCookies"> | null, ): string | null { if (archived > 0 || !state) return null; if (state.lastFetchedCount !== 0) return null; - if (state.cursor || state.lastError || state.needsCookies) return null; + if (hasTimelineResumePoint(state) || state.lastError || state.needsCookies) return null; return EMPTY_ACCOUNT_OLDER_REFUSAL; } @@ -194,6 +234,12 @@ export async function fetchPosts( if (opts.full && opts.older) { return { ok: false, written: 0, skipped: 0, complete: false, error: FULL_AND_OLDER_REFUSAL }; } + if (opts.backfill && opts.full) { + return { ok: false, written: 0, skipped: 0, complete: false, error: BACKFILL_AND_FULL_REFUSAL }; + } + if (opts.backfill && opts.older) { + return { ok: false, written: 0, skipped: 0, complete: false, error: BACKFILL_AND_OLDER_REFUSAL }; + } for (const [name, day] of [["from", opts.from]] as const) { if (day !== undefined && !isUtcDay(day)) { return { ok: false, written: 0, skipped: 0, complete: false, error: `"${day}" is not a date (YYYY-MM-DD) for "${name}"` }; @@ -250,6 +296,9 @@ export async function fetchPosts( if (opts.older) { return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_OLDER_REFUSAL }; } + if (opts.backfill) { + return { ok: false, written: 0, skipped: 0, complete: false, error: X_SEARCH_BACKFILL_REFUSAL }; + } if (opts.drain?.aborted) { log("Drained before the fetch started; nothing was read."); return { ok: true, written: 0, skipped: 0, complete: false, drained: true }; @@ -290,8 +339,16 @@ export async function fetchPosts( return { ok: true, written: 0, skipped: 0, complete: false, drained: true }; } + if (opts.backfill && fetcher.platform === "xenforo") { + return { ok: false, written: 0, skipped: 0, complete: false, error: FORUM_BACKFILL_REFUSAL }; + } + const seenIds = await readSeenPostIds(channelRoot); const priorState = await readPostFetchState(channelRoot); + if (opts.backfill) { + const problem = resumeBackfillProblem(priorState); + if (problem) return { ok: false, written: 0, skipped: 0, complete: false, error: problem }; + } if (opts.older) { const problem = olderPostsProblem(fetcher); @@ -415,22 +472,35 @@ async function fetchTimeline(ctx: { // A FORUM THREAD keeps two positions (lib/forumWalk.ts), re-derived from the // archived posts' pages every run; its walk needs neither a cursor nor a - // watermark. Every other fetcher: a stored cursor means the previous run - // stopped early (hit its limit, or was cancelled) — resume the backfill from - // there rather than applying the watermark, which would otherwise leave that - // history permanently missing. --full discards the cursor and re-walks from - // the top. + // watermark. Every other fetcher keeps the timeline's two walks + // (lib/timelineWalk.ts): SYNC NEW (the default) walks from the top down to + // the newest archived post — or continues its own unfinished sync down to + // the watermark that sync began with — and never reads or clears the + // backfill's resume point; RESUME BACKFILL (`backfill`) continues the + // full-history walk from that point, with no watermark; --full re-walks + // from the top. let forumWalk: ForumWalkState | undefined; if (forum) { const derived = deriveForumWalk(priorState?.forum, priorState?.cursor, await heldForumPages(channelRoot)); forumWalk = derived.walk; for (const note of derived.notes) log(note); } - const resumeCursor = opts.full || forum ? undefined : priorState?.cursor; - const since = - opts.full || resumeCursor || forum - ? undefined - : ((await latestPostCreatedAt(channelRoot)) ?? undefined); + const mode: TimelineMode = opts.full ? "full" : opts.backfill ? "backfill" : "sync"; + let walks: TimelineWalks = forum ? {} : timelineWalks(priorState); + let plan: TimelineRunPlan | undefined; + if (!forum) { + const watermark = mode === "sync" ? await latestPostCreatedAt(channelRoot) : undefined; + const planned = planTimelineRun(mode, walks, watermark); + if ("error" in planned) { + return { ok: false, written: 0, skipped: 0, complete: false, error: planned.error }; + } + plan = planned; + if (walks.migrated) { + log("Read the old single resume point (posts-state.json's `cursor`) as the backfill's."); + } + } + const resumeCursor = plan?.cursor; + const since = plan?.since; const policy = resolveCookiePolicy(settings, config); const cookies = alwaysCookies(policy); // An X fetcher's login source (social.x.cookieSource, xCookieSource.ts), @@ -447,13 +517,15 @@ async function fetchTimeline(ctx: { ? opts.full ? " — a full re-walk" : ` — ${forumWalkStartLine(forumWalk ?? {})}` - : resumeCursor - ? " — resuming an unfinished backfill" - : since - ? ` since ${since}` - : " — full history") + + : ` — ${timelineRunLine(plan!)}`) + `; ${seenIds.size} already archived.`, ); + if (plan?.mode === "sync" && walks.backfill) { + log( + `A backfill is unfinished (${seenIds.size} archived; its resume point is kept): this run syncs new posts only. ` + + 'Resume backfill (fetch-posts "backfill": true, or the ops action resume-backfill) continues it.', + ); + } // A managed job's cancel/drain arrives as an AbortSignal; the fetcher // interface requires one, so synthesize a never-aborting signal when the @@ -495,11 +567,13 @@ async function fetchTimeline(ctx: { checkpointSkipped += w.skipped; for (const shard of w.shards) shards.add(shard); if (forum && cp.forumWalk) state.forum = cp.forumWalk; + const next = plan ? withResumePoint(plan, walks, cp.cursor, new Date().toISOString()) : walks; await writePostFetchState(channelRoot, { ...state, - ...(forum ? {} : { cursor: cp.cursor }), + ...timelineWalkFields(next), lastFetchedCount: checkpointWritten, }); + walks = next; if (w.written > 0) { log(`Saved ${w.written} new post(s) (${checkpointWritten} so far this run); resume point recorded.`); } @@ -534,9 +608,10 @@ async function fetchTimeline(ctx: { log(`[error] ${message}`); state.lastError = message; // Whatever was checkpointed is on disk; keep the resume point that covers - // it rather than dropping back to the watermark. - const prior = await readPostFetchState(channelRoot); - if (!forum && prior?.cursor) state.cursor = prior.cursor; + // it (and the other walk's, untouched) rather than dropping back to the + // watermark. + if (!forum) Object.assign(state, timelineWalkFields(walks)); + const prior = forum ? await readPostFetchState(channelRoot) : null; if (forum && prior?.forum) state.forum = prior.forum; if (checkpointWritten > 0) state.lastFetchedCount = checkpointWritten; await writePostFetchState(channelRoot, state); @@ -559,7 +634,11 @@ async function fetchTimeline(ctx: { `Wrote ${written.written} new post(s), skipped ${written.skipped} already archived` + (upsert ? `, updated ${updated} edited` : "") + (shards.size > 0 ? ` (shards: ${[...shards].join(", ")})` : "") + - (result.complete ? "." : " — more history remains."), + (result.complete + ? "." + : plan?.saveTo === "sync" + ? " — the sync stopped part-way; the next Sync new continues it." + : " — more history remains."), ); if (result.notSeen?.length) { log( @@ -573,8 +652,9 @@ async function fetchTimeline(ctx: { state.lastFetchedCount = written.written; if (forum) { if (result.forumWalk) state.forum = result.forumWalk; - } else if (result.cursor && !result.complete) { - state.cursor = result.cursor; + } else if (plan) { + walks = settleTimelineRun(plan, walks, result, new Date().toISOString()); + Object.assign(state, timelineWalkFields(walks)); } if (result.needsCookies) state.needsCookies = true; // A FORUM's browser check or login wall is the forum session's cookies: the diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -135,7 +135,7 @@ export function parseRetryAfterMs(value: string | null, nowMs: number): number | export class ArchiveOrgClient { private readonly deps: Required<ArchiveOrgClientDeps>; - private readonly opts: Required<ArchiveOrgClientOpts>; + private readonly opts: Required<Omit<ArchiveOrgClientOpts, "jitter">> & { jitter?: number }; private chain: Promise<unknown> = Promise.resolve(); private lastDoneAt = -Infinity; private readonly cache = new Map<string, { at: number; value: ArchiveOrgItemMetadata }>(); @@ -158,10 +158,18 @@ export class ArchiveOrgClient { cacheTtlMs: opts.cacheTtlMs ?? 6 * 60 * 60 * 1000, timeoutMs: opts.timeoutMs ?? 60_000, idleTimeoutMs: opts.idleTimeoutMs ?? 120_000, - jitter: opts.jitter ?? pacingJitter(), + // Read at each wait, not here: THE process's client below is built at + // import time, and reading settings then would fix getPaths() to + // whatever TRANSCRIPTS_DIR was set before any caller set its own (and + // the jitter to the settings of that moment). + ...(opts.jitter !== undefined ? { jitter: opts.jitter } : {}), }; } + private jitterShare(): number { + return this.opts.jitter ?? pacingJitter(); + } + // Run `fn` after every earlier request (and its gap) has finished. private serial<T>(fn: () => Promise<T>): Promise<T> { const run = this.chain.then(fn, fn); @@ -173,13 +181,13 @@ export class ArchiveOrgClient { // doubling — upward only: it used to land as much as 20 % short of it. private backoffMs(attempt: number): number { const exp = Math.min(this.opts.maxBackoffMs, this.opts.baseBackoffMs * 2 ** (attempt - 1)); - return Math.ceil(jitterUp(exp, Math.max(0.2, this.opts.jitter), this.deps.random)); + return Math.ceil(jitterUp(exp, Math.max(0.2, this.jitterShare()), this.deps.random)); } // The gap before one request: minGapMs stretched by up to pacing.jitter, a // fresh draw per request (lib/jitter.mjs — never shorter than minGapMs). private gapMs(): number { - return Math.ceil(jitterUp(this.opts.minGapMs, this.opts.jitter, this.deps.random)); + return Math.ceil(jitterUp(this.opts.minGapMs, this.jitterShare(), this.deps.random)); } // One GET, with the gap before it and the retry policy around it. With diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -99,6 +99,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHIVE_ORG_S3_ACCESS", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 access key for Save Page Now (release 37): read first, with `ARCHIVE_ORG_S3_SECRET`, before the mode-600 file `settings.archiveOrg.s3KeyFile` names. Both or neither. Sent only to web.archive.org/save in the `Authorization: LOW <access>:<secret>` header; never logged, and never in an error, a job record or a result. Without keys Save Page Now is off and says why." }, { name: "ARCHIVE_ORG_S3_SECRET", audience: "runtime", default: "unset (the S3 key file is read instead)", readBy: "common/lib/waybackPages/savePageNow-server.ts", doc: "archive.org's S3 secret key for Save Page Now, with `ARCHIVE_ORG_S3_ACCESS` (above)." }, { name: "SYNC_HEARTBEAT_SECONDS", audience: "runtime", default: "`settings.syncScheduler.heartbeatSeconds`", readBy: "editor/app/scheduler/heartbeat.ts", doc: "Overrides the editor's in-process sync heartbeat. `0` = no internal timer (tick from cron instead)." }, + { name: "ARCHILYZER_OTS_BIN", audience: "runtime", default: "`ots` on PATH, then `~/.local/bin/ots`", readBy: "common/bin/evidence-pack.ts", doc: "The OpenTimestamps `ots` binary that `archilyzer evidence stamp|upgrade|verify` (and `evidence pack`'s stamp) run. Without one, the stamp fails and the package is left unstamped (`evidence stamp` it later)." }, { name: "SYNC_TICK_URL", audience: "runtime", default: "`http://127.0.0.1:3001/api/scheduler/tick`", readBy: "common/bin/sync-tick.ts", doc: "Where `archilyzer sync tick` (cron's heartbeat) posts." }, { name: "SYNC_TICK_TOKEN", audience: "runtime", default: "unset (no auth)", readBy: "common/bin/sync-tick.ts, editor/app/scheduler/auth.ts", doc: "Bearer token for the tick endpoint; set on both the editor and the cron job." }, { name: "R2_ACCESS_KEY_ID", audience: "runtime", default: "—", readBy: "common/publish/build.ts, common/bin/doctor.ts (set or not)", doc: "R2 S3 credentials for uploading oversize archives at deploy time (with `R2_SECRET_ACCESS_KEY` and `CLOUDFLARE_ACCOUNT_ID`), needed only when `archiveStorage.bucket` is set. In Docker they come from `.env`. See [PUBLISH.md](PUBLISH.md)." }, diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -14,6 +14,7 @@ import { writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; import type { ForumWalkState } from "./forumWalk"; +import type { TimelineBackfillState, TimelineSyncState } from "./timelineWalk"; import { readdir, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { appendFile } from "node:fs/promises"; import { mergePageRecord } from "./waybackPages/toPost"; @@ -495,13 +496,21 @@ export type PostFetchState = { // the post-corpus analogue of the video pipeline's needs_auth outcome. needsCookies?: boolean; lastFetchedCount?: number; - // The TIMELINE walk's resume point (gallery-dl's cursor). Only a normal fetch - // reads it; the older-posts backfill keeps its own position in `older`. + // LEGACY (before 2026-11-06): the one TIMELINE resume point a sync and the + // history backfill shared. Read as `backfill`'s (lib/timelineWalk.ts) and + // dropped on the next timeline write; still read by a forum thread's walk + // as its pre-release-37 history position (lib/forumWalk.ts). cursor?: string; - // The older-posts backfill (a fetcher's `fetchOlder`), which walks the - // account's history backwards through search windows. Kept apart from - // `cursor` so a normal fetch never resumes backwards, and carried through - // every write a normal fetch makes. + // The timeline's two walks (lib/timelineWalk.ts): the full-history + // backfill's resume point — continued only by Resume backfill — and an + // unfinished sync's, with the watermark it walks down to. A sync never + // reads or clears `backfill`; a backfill never touches `sync`. + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; + // The older-posts walk (a fetcher's `fetchOlder`), which walks the + // account's history backwards through search windows. Kept apart from the + // timeline's positions so a normal fetch never resumes backwards, and + // carried through every write a normal fetch makes. older?: OlderBackfillState; // A FORUM THREAD's two walks (release 37 lane G, lib/forumWalk.ts): the // catch-up's mark and resume point, and the history walk's position — in diff --git a/common/lib/timelineWalk.test.ts b/common/lib/timelineWalk.test.ts @@ -0,0 +1,159 @@ +// The timeline's two walks — sync new and resume backfill — as pure +// decisions, and the read of a posts-state.json written before they split. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/timelineWalk.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + describeTimelineBackfill, + describeTimelineSync, + hasTimelineResumePoint, + NO_BACKFILL_TO_RESUME, + planTimelineRun, + settleTimelineRun, + timelineRunLine, + timelineWalkFields, + timelineWalks, + withResumePoint, + type TimelineRunPlan, +} from "./timelineWalk"; + +const NOW = "2026-11-06T12:00:00.000Z"; +const WATERMARK = "2026-11-01T08:00:00.000Z"; + +test("MIGRATION: a legacy `cursor` is read as the backfill's position, and never written back", () => { + // The madamsavvy-x shape: a state from before the split, an unfinished + // backfill's cursor beside the rest. + const legacy = { lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/LEGACY" }; + const walks = timelineWalks(legacy); + assert.deepEqual(walks, { backfill: { cursor: "1/LEGACY" }, migrated: true }); + assert.equal(hasTimelineResumePoint(legacy), true); + // What is written: the backfill, no `cursor`, no `migrated` marker. + assert.deepEqual(timelineWalkFields(walks), { backfill: { cursor: "1/LEGACY" } }); + // And read back, it is the same position — not migrated again. + assert.deepEqual(timelineWalks(timelineWalkFields(walks)), { backfill: { cursor: "1/LEGACY" } }); +}); + +test("MIGRATION: a `backfill` already present wins over a stray legacy `cursor`; empty values are nothing", () => { + assert.deepEqual(timelineWalks({ cursor: "1/OLD", backfill: { cursor: "1/NEW" } }), { + backfill: { cursor: "1/NEW" }, + }); + assert.deepEqual(timelineWalks({ cursor: "" }), {}); + assert.deepEqual(timelineWalks({ backfill: { cursor: "" }, sync: { cursor: "" } }), {}); + assert.deepEqual(timelineWalks(null), {}); + assert.deepEqual(timelineWalks({}), {}); + assert.equal(hasTimelineResumePoint({}), false); + assert.equal(hasTimelineResumePoint({ sync: { cursor: "1/S", since: WATERMARK } }), true); +}); + +test("SYNC NEW walks from the top down to the watermark, past an unfinished backfill it does not read", () => { + const walks = timelineWalks({ cursor: "1/LEGACY" }); + const plan = planTimelineRun("sync", walks, WATERMARK); + assert.deepEqual(plan, { mode: "sync", since: WATERMARK, saveTo: "sync" }); + // It finishes ("caught up"): the backfill's position is exactly as it was. + const after = settleTimelineRun(plan as TimelineRunPlan, walks, { complete: true }, NOW); + assert.deepEqual(after.backfill, { cursor: "1/LEGACY" }); + assert.equal(after.sync, undefined); +}); + +test("SYNC NEW that stops part-way keeps its own resume point with the watermark it began with", () => { + const walks = timelineWalks({ backfill: { cursor: "1/BF" } }); + const plan = planTimelineRun("sync", walks, WATERMARK) as TimelineRunPlan; + const stopped = settleTimelineRun(plan, walks, { complete: false, cursor: "1/S-P3" }, NOW); + assert.deepEqual(stopped, { + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/S-P3", since: WATERMARK, savedAt: NOW }, + }); + // The next sync continues it, down to THAT watermark — not the newer one + // the posts it just wrote would make. + const next = planTimelineRun("sync", stopped, "2026-11-06T09:00:00.000Z"); + assert.deepEqual(next, { mode: "sync", cursor: "1/S-P3", since: WATERMARK, saveTo: "sync" }); + assert.match(timelineRunLine(next as TimelineRunPlan), /continuing the unfinished sync down to 2026-11-01/); + // Finished, the sync's slot clears; the backfill's stays. + assert.deepEqual(settleTimelineRun(next as TimelineRunPlan, stopped, { complete: true }, NOW), { + backfill: { cursor: "1/BF" }, + }); +}); + +test("SYNC NEW with nothing archived is the first full-history walk: an unfinished one leaves a BACKFILL", () => { + const plan = planTimelineRun("sync", {}, null) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "sync", saveTo: "backfill" }); + assert.match(timelineRunLine(plan), /first full-history walk/); + const after = settleTimelineRun(plan, {}, { complete: false, cursor: "1/FIRST-P2" }, NOW); + assert.deepEqual(after, { backfill: { cursor: "1/FIRST-P2", savedAt: NOW } }); + // The next plain fetch (posts now archived) syncs new; it does not resume it. + assert.deepEqual(planTimelineRun("sync", after, WATERMARK), { mode: "sync", since: WATERMARK, saveTo: "sync" }); +}); + +test("SYNC NEW on an empty archive never moves or clears a backfill that is part-way", () => { + const walks = timelineWalks({ cursor: "1/LEGACY" }); + const plan = planTimelineRun("sync", walks, null) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "sync", saveTo: "sync" }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), { backfill: { cursor: "1/LEGACY" } }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false, cursor: "1/S" }, NOW), { + backfill: { cursor: "1/LEGACY" }, + sync: { cursor: "1/S", savedAt: NOW }, + }); + assert.deepEqual(withResumePoint(plan, walks, "1/CP", NOW).backfill, { cursor: "1/LEGACY" }); +}); + +test("RESUME BACKFILL continues the saved point with no watermark, and never touches the sync's", () => { + const walks = timelineWalks({ + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/S", since: WATERMARK }, + }); + const plan = planTimelineRun("backfill", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "backfill", cursor: "1/BF", saveTo: "backfill" }); + assert.match(timelineRunLine(plan), /^resume backfill/); + const further = settleTimelineRun(plan, walks, { complete: false, cursor: "1/BF-2" }, NOW); + assert.deepEqual(further.sync, { cursor: "1/S", since: WATERMARK }); + assert.deepEqual(further.backfill, { cursor: "1/BF-2", savedAt: NOW }); + const done = settleTimelineRun(plan, further, { complete: true }, NOW); + assert.deepEqual(done, { sync: { cursor: "1/S", since: WATERMARK } }); +}); + +test("RESUME BACKFILL with no backfill part-way is refused", () => { + assert.deepEqual(planTimelineRun("backfill", {}, WATERMARK), { error: NO_BACKFILL_TO_RESUME }); + assert.deepEqual(planTimelineRun("backfill", { sync: { cursor: "1/S", since: WATERMARK } }, WATERMARK), { + error: NO_BACKFILL_TO_RESUME, + }); +}); + +test("a run that stops with no resume point keeps the one it had", () => { + const walks = { backfill: { cursor: "1/BF" } }; + const plan = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false }, NOW), walks); +}); + +test("FULL re-walks from the top; unfinished it replaces the backfill's point, finished it clears both", () => { + const walks = { backfill: { cursor: "1/BF" }, sync: { cursor: "1/S", since: WATERMARK } }; + const plan = planTimelineRun("full", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(plan, { mode: "full", saveTo: "backfill" }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: false, cursor: "1/F" }, NOW), { + backfill: { cursor: "1/F", savedAt: NOW }, + sync: { cursor: "1/S", since: WATERMARK }, + }); + assert.deepEqual(settleTimelineRun(plan, walks, { complete: true }, NOW), {}); +}); + +test("a checkpoint saves into the run's own slot", () => { + const walks = { backfill: { cursor: "1/BF" } }; + const sync = planTimelineRun("sync", walks, WATERMARK) as TimelineRunPlan; + assert.deepEqual(withResumePoint(sync, walks, "1/CP", NOW), { + backfill: { cursor: "1/BF" }, + sync: { cursor: "1/CP", since: WATERMARK, savedAt: NOW }, + }); + const bf = planTimelineRun("backfill", walks, null) as TimelineRunPlan; + assert.deepEqual(withResumePoint(bf, walks, "1/CP", NOW), { backfill: { cursor: "1/CP", savedAt: NOW } }); +}); + +test("the status lines say a backfill is unfinished, and what continues a stopped sync", () => { + assert.equal( + describeTimelineBackfill({ backfill: { cursor: "1/BF" } }, 9936), + "backfill unfinished — 9936 archived; Resume backfill continues it", + ); + assert.equal(describeTimelineBackfill({}, 10), "no backfill part-way"); + assert.equal(describeTimelineSync({}), null); + assert.match(describeTimelineSync({ sync: { cursor: "1/S", since: WATERMARK } }) ?? "", /down to 2026-11-01/); +}); diff --git a/common/lib/timelineWalk.ts b/common/lib/timelineWalk.ts @@ -0,0 +1,235 @@ +// WHERE A SOCIAL TIMELINE'S TWO WALKS STAND (X, Bluesky, Nitter) — +// `posts-state.json`'s `backfill` and `sync`. Pure: no fs, client-safe (the +// channel page's status line reads it). +// +// Two actions, for two purposes (operator, 6 Nov 2026: "We should have +// distinct 'sync new' and 'resume backfill' actions, they are different +// actions for different purposes"): +// +// SYNC NEW — from the top of the timeline down to the newest archived post +// (the `since` watermark). What a plain fetch-posts, the scheduler and the +// Sync button run. It never reads the backfill's resume point and never +// clears it. A sync that stops part-way (its budget, a cancel, a drain, a +// cap) keeps ITS OWN resume point in `sync`, with the watermark it was +// walking down to: the next sync continues there, down to that same +// watermark, rather than stopping at the posts it just wrote and leaving +// the gap between them and the archive unread. +// +// RESUME BACKFILL — the full-history walk continued from its saved resume +// point (`backfill.cursor`), with no watermark. Run only when asked +// (fetch-posts "backfill": true, the ops action resume-backfill, the channel +// page's Resume backfill). It never touches the sync's position. +// +// The backfill's resume point is written by a FULL-HISTORY walk that did not +// finish: a channel's first fetch (nothing archived, so no watermark), a +// --full re-walk, or a resumed backfill. +// +// One field, `cursor`, used to serve both: a stored cursor made the next +// plain fetch resume the backfill and skip the watermark — so a fetch meant +// for new posts walked old history, missed the new ones, and on finishing +// cleared the cursor (2026-11-06, madamsavvy-x: "resuming an unfinished +// backfill; 9936 already archived … 0 new", 85 newer posts missed). A state +// written before the split has only `cursor`; it is read as the BACKFILL's +// position (timelineWalks), which is what it most often was, and is dropped +// from the file on the next timeline write. Read so, nothing is lost: were it +// really an unfinished sync's, resuming the backfill from it walks the same +// gap down to the archive. +// +// The older-posts walk (`older`, search windows below the oldest archived +// post) and a forum thread's two walks (`forum`, lib/forumWalk.ts) are their +// own and untouched by this. + +// The full-history walk's resume point. +export type TimelineBackfillState = { + // The fetcher's opaque resume point (gallery-dl's extractor cursor, a + // Bluesky feed cursor, a Nitter "Load more" cursor). + cursor: string; + // When the point was saved. + savedAt?: string; +}; + +// An unfinished sync's resume point, and the watermark it walks down to. +export type TimelineSyncState = { + cursor: string; + // The newest archived post's time when the sync started (ISO): the walk + // ends there. Absent only for a state no sync wrote. + since?: string; + savedAt?: string; +}; + +export type TimelineWalkFields = { + // LEGACY (before 2026-11-06): the one resume point both walks shared. + cursor?: string; + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; +}; + +export type TimelineWalks = { + backfill?: TimelineBackfillState; + sync?: TimelineSyncState; + // The backfill came from the legacy `cursor`. + migrated?: boolean; +}; + +const cursorOf = (v: unknown): string | undefined => + typeof v === "string" && v.length > 0 ? v : undefined; + +// The two positions a state holds, with a legacy `cursor` read as the +// backfill's. A `backfill` already present wins over a stray `cursor` (only an +// older build, run after this one, would write both). +export function timelineWalks(state: TimelineWalkFields | null | undefined): TimelineWalks { + if (!state) return {}; + const out: TimelineWalks = {}; + const backfill = state.backfill && cursorOf(state.backfill.cursor) ? state.backfill : undefined; + if (backfill) out.backfill = { ...backfill }; + else { + const legacy = cursorOf(state.cursor); + if (legacy) { + out.backfill = { cursor: legacy }; + out.migrated = true; + } + } + if (state.sync && cursorOf(state.sync.cursor)) out.sync = { ...state.sync }; + return out; +} + +// The two positions as fields to write: `cursor` is never written again. +export function timelineWalkFields(walks: TimelineWalks): Pick<TimelineWalkFields, "backfill" | "sync"> { + return { + ...(walks.backfill ? { backfill: walks.backfill } : {}), + ...(walks.sync ? { sync: walks.sync } : {}), + }; +} + +// Whether a state holds any timeline resume point (either walk's, or the +// legacy one). +export function hasTimelineResumePoint(state: TimelineWalkFields | null | undefined): boolean { + const w = timelineWalks(state); + return Boolean(w.backfill || w.sync); +} + +export type TimelineMode = "sync" | "backfill" | "full"; + +export const NO_BACKFILL_TO_RESUME = + "There is no unfinished backfill to resume: the timeline's full-history walk is not part-way. " + + 'A plain fetch-posts syncs new posts; "full": true re-walks the whole timeline; "older": true walks back below the oldest archived post.'; + +export const BACKFILL_AND_FULL_REFUSAL = + 'Resume backfill continues the saved history walk; a full re-walk ("full") starts it over — run one.'; + +export const BACKFILL_AND_OLDER_REFUSAL = + 'Resume backfill continues the timeline\'s history walk; "older" is the search walk below the oldest archived post — run one at a time.'; + +// What one run reads from and where an unfinished run's resume point goes. +export type TimelineRunPlan = { + mode: TimelineMode; + // The resume point handed to the fetcher (none: from the top). + cursor?: string; + // The watermark handed to the fetcher (none: no stop below). + since?: string; + // Where this run's resume point is saved when it stops part-way. + saveTo: "sync" | "backfill"; +}; + +// The run a mode makes, given the positions and the newest archived post's +// time (`watermark`; null/undefined when nothing is archived). +export function planTimelineRun( + mode: TimelineMode, + walks: TimelineWalks, + watermark: string | null | undefined, +): TimelineRunPlan | { error: string } { + if (mode === "full") return { mode, saveTo: "backfill" }; + if (mode === "backfill") { + if (!walks.backfill) return { error: NO_BACKFILL_TO_RESUME }; + return { mode, cursor: walks.backfill.cursor, saveTo: "backfill" }; + } + // SYNC NEW: an unfinished sync continues down to the watermark it began + // with; else from the top down to the newest archived post. Nothing + // archived and no backfill part-way: the walk is the channel's first + // full-history walk, and its resume point is the backfill's. With a backfill + // part-way a sync keeps to its own slot whatever the archive holds, so it + // can never move or clear the backfill's place. + const since = walks.sync?.since ?? watermark ?? undefined; + const cursor = walks.sync?.cursor; + return { + mode, + ...(cursor ? { cursor } : {}), + ...(since ? { since } : {}), + saveTo: since || walks.backfill ? "sync" : "backfill", + }; +} + +// The positions after a run, from the fetcher's outcome. A run that finished +// clears its own slot (a full re-walk that finished clears both: it read +// everything); one that stopped part-way saves its resume point there, or +// keeps the one it had when it learned none. The other slot is never touched. +export function settleTimelineRun( + plan: TimelineRunPlan, + prior: TimelineWalks, + outcome: { complete: boolean; cursor?: string }, + now: string, +): TimelineWalks { + const next: TimelineWalks = { + ...(prior.backfill ? { backfill: prior.backfill } : {}), + ...(prior.sync ? { sync: prior.sync } : {}), + }; + if (outcome.complete) { + if (plan.mode === "full") return {}; + if (plan.saveTo === "sync") delete next.sync; + else delete next.backfill; + // A sync that had no watermark (nothing archived) and finished walked the + // whole timeline: an old sync position under it is spent too. + if (plan.mode === "sync" && plan.saveTo === "backfill") delete next.sync; + return next; + } + const cursor = cursorOf(outcome.cursor); + if (!cursor) return next; + return withResumePoint(plan, next, cursor, now); +} + +// A resume point saved mid-run (a checkpoint) or at its end. +export function withResumePoint( + plan: TimelineRunPlan, + walks: TimelineWalks, + cursor: string, + now: string, +): TimelineWalks { + const next: TimelineWalks = { + ...(walks.backfill ? { backfill: walks.backfill } : {}), + ...(walks.sync ? { sync: walks.sync } : {}), + }; + if (plan.saveTo === "sync") next.sync = { cursor, ...(plan.since ? { since: plan.since } : {}), savedAt: now }; + else { + next.backfill = { cursor, savedAt: now }; + // A first walk (sync with no watermark) that left a backfill behind has + // no sync of its own to continue. + if (plan.mode === "sync") delete next.sync; + } + return next; +} + +// The job log's opening words for a run: the mode, named. +export function timelineRunLine(plan: TimelineRunPlan): string { + if (plan.mode === "full") return "full re-walk of the timeline, from the top"; + if (plan.mode === "backfill") return "resume backfill, from its saved resume point"; + if (plan.cursor && plan.since) return `sync new, continuing the unfinished sync down to ${plan.since}`; + if (plan.since) return `sync new, since ${plan.since}`; + if (plan.saveTo === "sync") return "sync new — nothing archived yet, from the top"; + return "sync new — nothing archived yet, so this is the first full-history walk"; +} + +// The channel page's status line for the timeline's history walk. +export function describeTimelineBackfill(walks: TimelineWalks, archived: number): string { + if (walks.backfill) { + return `backfill unfinished — ${archived} archived; Resume backfill continues it`; + } + return "no backfill part-way"; +} + +// The channel page's line for an unfinished sync, or null. +export function describeTimelineSync(walks: TimelineWalks): string | null { + if (!walks.sync) return null; + return walks.sync.since + ? `a sync stopped part-way; the next Sync new continues it down to ${walks.sync.since}` + : "a sync stopped part-way; the next Sync new continues it"; +} diff --git a/common/lib/web/pacer.ts b/common/lib/web/pacer.ts @@ -80,7 +80,7 @@ function retryAfterMs(value: string | null, nowMs: number): number | null { export class WebPacer { private readonly deps: Required<WebPacerDeps>; - private readonly opts: Required<WebPacerOpts>; + private readonly opts: Required<Omit<WebPacerOpts, "jitter">> & { jitter?: number }; private chain: Promise<unknown> = Promise.resolve(); private lastDoneAt = -Infinity; // Every attempt sent, with when it started (tests and logs). @@ -99,10 +99,18 @@ export class WebPacer { backoffMaxMs: opts.backoffMaxMs ?? WEB_BACKOFF_MAX_MS, maxAttempts: opts.maxAttempts ?? WEB_MAX_ATTEMPTS, timeoutMs: opts.timeoutMs ?? WEB_TIMEOUT_MS, - jitter: opts.jitter ?? pacingJitter(), + // Read at each wait, not here: THE process's pacer below is built at + // import time, and reading settings then would fix getPaths() to + // whatever TRANSCRIPTS_DIR was set before any caller set its own (and + // the jitter to the settings of that moment). + ...(opts.jitter !== undefined ? { jitter: opts.jitter } : {}), }; } + private jitterShare(): number { + return this.opts.jitter ?? pacingJitter(); + } + // Run `fn` after every earlier request (and its gap) has finished. private serial<T>(fn: () => Promise<T>): Promise<T> { const run = this.chain.then(fn, fn); @@ -120,7 +128,7 @@ export class WebPacer { ): Promise<T> { return this.serial(async () => { for (let attempt = 1; ; attempt++) { - const gap = Math.ceil(jitterUp(this.opts.minGapMs, this.opts.jitter, this.deps.random)); + const gap = Math.ceil(jitterUp(this.opts.minGapMs, this.jitterShare(), this.deps.random)); const wait = this.lastDoneAt + gap - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, init.signal); this.sent.push({ url, at: this.deps.now() }); @@ -149,7 +157,7 @@ export class WebPacer { const told = retryAfterMs(res.headers.get("retry-after"), this.deps.now()); const backoff = Math.min(this.opts.backoffMaxMs, told ?? this.opts.backoffBaseMs * 2 ** (attempt - 1)); await this.deps.sleep( - Math.ceil(jitterUp(backoff, this.opts.jitter, this.deps.random)), + Math.ceil(jitterUp(backoff, this.jitterShare(), this.deps.random)), init.signal, ); continue; diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts @@ -411,15 +411,16 @@ export const blueskyFetcher: SocialFetcher = { async fetch(input: PostFetchInput): Promise<PostFetchResult> { const { handle, channelSlug, since, seenIds, limit, signal, onLog } = input; const posts: Post[] = []; - // Resuming an unfinished backfill: continue from the stored cursor and - // ignore the watermark, otherwise the first page (all already-archived) - // would stop the run before it reached the missing history. + // A saved resume point: continue from it. The controller decides the + // watermark (lib/timelineWalk.ts): RESUME BACKFILL passes none, so only an + // already-archived post stops it; an unfinished SYNC NEW passes the + // watermark it began with, so it stops there and not before. let cursor: string | undefined = input.cursor; const resuming = Boolean(input.cursor); - const watermark = resuming ? undefined : since; + const watermark = since; let complete = false; if (resuming) { - onLog?.(`Resuming backfill from cursor ${cursor}`); + onLog?.(`Continuing from the saved resume point (cursor ${cursor})`); } for (let page = 0; page < MAX_PAGES; page++) { diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -29,13 +29,15 @@ export type PostFetchInput = { // The channel slug the produced posts belong to. channelSlug: string; // ISO watermark: stop once posts older than this are reached. Absent on a - // first (full-backfill) run AND whenever a previous run stopped early — see - // `cursor`, which resumes the backfill instead. + // full-history walk: a first run, a --full re-walk, and RESUME BACKFILL. + // Given WITH `cursor` on an unfinished sync that continues: it walks on down + // to the watermark it began with (lib/timelineWalk.ts). since?: string; // Opaque resume point from a previous run that did not finish (hit its - // limit, or was cancelled). When set, the fetcher continues paging from here - // rather than from the top of the timeline, so a capped first run does not - // leave a permanent hole in the archived history. + // limit, or was cancelled) — the backfill's, or an unfinished sync's; the + // controller picks which by the run's mode. When set, the fetcher continues + // paging from here rather than from the top of the timeline, so a capped + // run does not leave a permanent hole in the archived history. cursor?: string; // Post ids already on disk. Paging stops at the first page containing one, // mirroring how sync() stops at the first already-archived video. diff --git a/common/social/postCapture.test.ts b/common/social/postCapture.test.ts @@ -205,7 +205,19 @@ test("article files are named by the layout, images numbered from 1", () => { // publish layer or the export app names the directory, except EXACTLY the one // that copies a report site's CITED captures (publish/citedPostCaptures.ts, // whose own test proves it copies nothing else). +// +// One reader in common/bin is not an export path and is named here: the +// evidence package (bin/evidence-pack.ts, `archilyzer evidence pack`), which +// copies an account's captures into a PRIVATE package outside the corpus +// (~/reports/evidence/…; it refuses an --out inside the corpus or a channel). +// It is allowed by name, with its test, and only while no export or publish +// module imports it — checked below — so it can never carry posts-media/ +// into a build. const CITED_CAPTURE_COPIER = path.join("common", "publish", "citedPostCaptures.ts"); +const EVIDENCE_PACK = [ + path.join("common", "bin", "evidence-pack.ts"), + path.join("common", "bin", "evidence-pack.test.ts"), +]; test("no export or publish source names posts-media/ but the cited-capture copier", async () => { const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -218,6 +230,8 @@ test("no export or publish source names posts-media/ but the cited-capture copie ]; const offenders: string[] = []; const allowed: string[] = []; + const evidence: string[] = []; + const importsEvidencePack: string[] = []; const walk = async (dir: string): Promise<void> => { let entries; try { @@ -231,11 +245,20 @@ test("no export or publish source names posts-media/ but the cited-capture copie if (e.isDirectory()) await walk(p); else if (/\.(ts|tsx|mjs|js)$/.test(e.name)) { const text = await readFile(p, "utf8"); + const rel = path.relative(repo, p); if (text.includes(POSTS_MEDIA_DIRNAME) || text.includes("POSTS_MEDIA_DIRNAME") || text.includes("social/postCapture")) { - const rel = path.relative(repo, p); if (rel === CITED_CAPTURE_COPIER) allowed.push(rel); + else if (EVIDENCE_PACK.includes(rel)) evidence.push(rel); else offenders.push(rel); } + // The CLI's lazy `import("./evidence-pack")` is its one importer. + if ( + /["']\.{1,2}\/(?:[^"']*\/)?evidence-pack["']/.test(text) && + !EVIDENCE_PACK.includes(rel) && + rel !== path.join("common", "bin", "archilyzer.ts") + ) { + importsEvidencePack.push(rel); + } } } }; @@ -243,4 +266,8 @@ test("no export or publish source names posts-media/ but the cited-capture copie assert.deepEqual(offenders, []); // The exception exists and is the only one: if it moves, this moves with it. assert.deepEqual(allowed, [CITED_CAPTURE_COPIER]); + // The evidence package is where it is said to be, and nothing in the export + // or publish layer reaches it. + assert.deepEqual(evidence.sort(), [...EVIDENCE_PACK].sort()); + assert.deepEqual(importsEvidencePack, []); }); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Sync new and Resume backfill are separate actions for an X or Bluesky channel.** A fetch meant to get new posts could walk old history instead. If an account's full-history walk had stopped part-way, the next plain fetch, from Sync or the schedule too, resumed that walk and skipped the newest posts. On 6 Nov one such fetch read 100 posts the archive already held, stopped as "caught up" with 0 new, and missed 85 newer posts. It then cleared the walk's saved place, so the place was lost as well. The operator: "We should have distinct 'sync new' and 'resume backfill' actions, they are different actions for different purposes". **Sync new** (the channel page's first button; a plain `fetch-posts`, Sync and the scheduler) now always reads from the newest post down to the newest one archived, and never moves or clears the backfill's place. A sync that stops part-way keeps its own place and finishes on the next sync. **Resume backfill** (the button, shown only when a full-history walk is unfinished; `pnpm ops resume-backfill`, or `fetch-posts "backfill": true`; `--backfill` on `archilyzer posts fetch`; `backfill` on the MCP enqueue tool) continues that walk and does nothing else. When one is unfinished, the channel page says so: "backfill unfinished — N archived; Resume backfill continues it". The job log's first line names the mode. Resume backfill is refused when no walk is unfinished, and on a forum thread, which already reads its newest pages before its history. An X search channel has one walk and refuses it too. Re-fetch full history and Fetch older posts are unchanged. **Upgrading:** a `posts-state.json` from before this keeps one `cursor`. It is read as the unfinished backfill's place, so nothing is lost, and the next fetch rewrites it. Needs a restart of the editor. - **Archived posts can be packaged as timestamped evidence.** The operator wanted public evidence that Mr. Obvious's X posts existed, and Save Page Now refuses x.com as a site (HTTP 523); he chose "the timestamped evidence package". `archilyzer evidence pack <channel>[,<channel>…] [--handle <h>] [--since/--until YYYY-MM-DD] [--out <dir>] [--no-media] [--no-stamp] [--dry-run] [--json]` writes, read only over the corpus, a self-contained folder (default `~/reports/evidence/<handle>-<date>/`): `posts.jsonl` (one record a post, deduped across the channels, every archived field kept under `raw`, the capture record and availability check, and the archived record of a post it answers or quotes as `context`), `posts.csv`, the post media copied byte for byte from `posts-media/` (each hash checked against its `capture.json`), `pack.json`, a README saying how to verify, `SHA256SUMS` over every file, and an OpenTimestamps proof of it (`SHA256SUMS.ots`, the official `ots` client, one request to each calendar). `evidence upgrade <dir>` fetches the Bitcoin attestation a few hours later, `evidence verify <dir>` checks every file and the stamp, `evidence stamp <dir>` stamps an unstamped one. Refused inside the corpus or a channel's media, over a non-empty dir, and for a channel whose text is unreadable. OPERATING.md, "Package posts as timestamped evidence". - **Save Page Now works without archive.org keys, and a whole list of pages can be archived politely, with an evidence file.** The operator wanted every Mr. Obvious post on a public archive ("I'm just trying to make sure evidence of the pages exist"), and Save Page Now refused without S3 keys. With no keys configured it now asks archive.org's public endpoint anonymously (`"mode": "anonymous"` in the log and result; with keys, SPN2 as before, `"mode": "keys"`), and the channel page's Save Page Now panel says which. Every save in the editor takes turns through one pacer: one at a time, at least 60 s apart anonymous (10 s with keys), and a 429/503 or archive.org's "slow down" rests it (Retry-After, else 2 min doubling to 1 h). `pnpm ops save-page-now-batch --json '{"file":"/abs/urls.json"}'` runs ONE resumable job over a list: each URL looked up first (the Wayback CDX and archive.today's timemap, paced) and skipped when a copy shows it, else saved; at most 150 saves a day without keys (archive.org allows 200); progress and an ETA on /jobs; cancel, a restart or `{"batch": "<id>"}` continue from the first pending URL. Its evidence JSON + CSV (default `<transcripts>/.spn-batches/<batch>.evidence.*`, or `evidence`) names, per URL, the status, the Wayback and archive.today copy URLs, the capture time and the HTTP status the archive recorded. archive.today and Ghostarchive are looked up only, never asked to save (their forms put a CAPTCHA in front). Save Page Now refuses x.com as a site today (HTTP 523, "limitations when it comes to archiving this site"): a batch asks such a site once, then only looks its other URLs up and records them as not asked. OPERATING.md, "Archive a list of pages politely (evidence)". - **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before. The Trailer page has **end on the outro card** and its fields beside **open on the brand intro**. Shorts get both too: `umtool vertical … --intro` opens a short on the brand intro re-laid 9:16 (the drawing centred between the Shorts overlays: the top 8 %, the bottom 20 %, 12 % either side), a reel's `intro` on does the same, and a reel's outro card is laid out 9:16 inside that safe area (`--no-intro`, `--no-outro`). A landscape intro is unchanged. diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts @@ -106,6 +106,7 @@ test("a traversing slug is refused at the door, on every route that takes one", ["relocate", { slugs: ["../../escape"], root: "/tmp/ops-api-never" }], ["relocate-back", { slugs: ["../../escape"] }], ["fetch-posts", { slug: "../../escape", older: true }], + ["resume-backfill", { slug: "../../escape" }], ["capture-posts", { slug: "../../escape", ids: ["1"] }], ["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }], ["fetch-chat", { slug: "../../escape", id: "abc123" }], diff --git a/editor/app/api/ops/browser-lookup/route.test.ts b/editor/app/api/ops/browser-lookup/route.test.ts @@ -31,7 +31,12 @@ process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = ROOT; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.E2E_ODYSEE_PAGE_FIXTURE = FIXTURE; -await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +// No queue gap: the listing job is the second on the odysee queue, and the +// default 20 s gap (stretched by pacing.jitter) outlasts settle()'s 20 s. +await writeFile( + process.env.SETTINGS_FILE, + JSON.stringify({ minFreeDiskGB: 0, pacing: { jobGapSeconds: { odysee: 0, default: 0 } } }), +); await writeFile( FIXTURE, JSON.stringify({ diff --git a/editor/app/api/ops/fetch-posts/route.test.ts b/editor/app/api/ops/fetch-posts/route.test.ts @@ -137,3 +137,49 @@ test("fetch-posts refuses a channel that is not social, full with older, and an assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); + +test("resume backfill — fetch-posts \"backfill\": true or the resume-backfill action — is refused before any job when none is part-way", async () => { + const { NO_BACKFILL_TO_RESUME, BACKFILL_AND_FULL_REFUSAL, BACKFILL_AND_OLDER_REFUSAL, FORUM_BACKFILL_REFUSAL } = + await import("yt-dlp-transcript-common/controller/fetchPosts"); + const { POST: RESUME } = await import("../resume-backfill/route"); + // demo-x's state holds no resume point of either walk. + const none = await post({ slug: SLUG, backfill: true }); + assert.equal(none.status, 400); + assert.equal(none.error, NO_BACKFILL_TO_RESUME); + const res = await RESUME( + new Request("http://localhost/api/ops/resume-backfill", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ slug: SLUG }), + }), + ); + assert.equal(res.status, 400); + assert.equal(((await res.json()) as { error?: string }).error, NO_BACKFILL_TO_RESUME); + // It takes no walk options of its own. + const stray = await RESUME( + new Request("http://localhost/api/ops/resume-backfill", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify({ slug: SLUG, full: true }), + }), + ); + assert.equal(stray.status, 400); + + assert.equal((await post({ slug: SLUG, backfill: true, full: true })).error, BACKFILL_AND_FULL_REFUSAL); + assert.equal((await post({ slug: SLUG, backfill: true, older: true })).error, BACKFILL_AND_OLDER_REFUSAL); + const bad = await post({ slug: SLUG, backfill: "yes" }); + assert.equal(bad.status, 400); + assert.match(bad.error, /"backfill" must be a boolean/); + + // A forum thread has no separate backfill. + await channel("demo-forum", { + handling: "transcribe", + sourceKind: "social", + platform: "xenforo", + name: "Demo thread", + url: "https://forum.example.invalid/threads/demo.1/", + }); + assert.equal((await post({ slug: "demo-forum", backfill: true })).error, FORUM_BACKFILL_REFUSAL); + + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); diff --git a/editor/app/api/ops/fetch-posts/route.ts b/editor/app/api/ops/fetch-posts/route.ts @@ -26,7 +26,12 @@ function optRetryOnBlock(body: OpsBody): RetryOnBlock | "settings" | undefined { export const dynamic = "force-dynamic"; -// POST { slug, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId } +// POST { slug, backfill?, full?, older?, floor?, from?, force?, limit?, pages?, retryOnBlock?, queueKey? } -> { ok: true, jobId } +// +// Plain, it is SYNC NEW (lib/timelineWalk.ts): from the top of the timeline +// down to the newest archived post, never reading or clearing an unfinished +// backfill's resume point. `backfill: true` is RESUME BACKFILL — the same as +// the ops action resume-backfill — refused when no backfill is part-way. // // `pages` caps how many pages a run reads, for a channel read page by page (a // forum thread: its latest N pages). `retryOnBlock` ({minutes, max}, or true @@ -47,7 +52,7 @@ export const dynamic = "force-dynamic"; export async function POST(request: Request) { return ops( request, - ["slug", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"], + ["slug", "backfill", "full", "older", "floor", "from", "force", "limit", "pages", "retryOnBlock", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -62,6 +67,7 @@ export async function POST(request: Request) { optPositiveInt(body, "pages"), optString(body, "from"), optRetryOnBlock(body), + optBool(body, "backfill"), ), ); }, diff --git a/editor/app/api/ops/resume-backfill/route.ts b/editor/app/api/ops/resume-backfill/route.ts @@ -0,0 +1,37 @@ +import { fetchPostsAction } from "../../../channels/[slug]/socialActions"; +import { jobResponse, ops, optPositiveInt, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, limit?, queueKey? } -> { ok: true, jobId } +// +// RESUME BACKFILL (lib/timelineWalk.ts): a social channel's unfinished +// full-history timeline walk, continued from its saved resume point +// (posts-state.json's `backfill`) with no watermark — the channel page's +// Resume backfill button, and fetch-posts `"backfill": true` by its own name. +// Its counterpart, SYNC NEW, is a plain fetch-posts: from the top down to the +// newest archived post, never touching this point. +// +// Refused before any job: no backfill part-way, a forum thread (its catch-up +// always comes first, then its history), an X search channel (one walk), a +// channel that is not a social one. On the platform's queue, as fetch-posts. +export async function POST(request: Request) { + return ops(request, ["slug", "limit", "queueKey"], async (body) => { + const slug = reqSlug(body, "slug"); + return jobResponse( + await fetchPostsAction( + slug, + optString(body, "queueKey"), + undefined, + optPositiveInt(body, "limit"), + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + true, + ), + ); + }); +} diff --git a/editor/app/channels/[slug]/components/SocialChannelPanel.tsx b/editor/app/channels/[slug]/components/SocialChannelPanel.tsx @@ -54,6 +54,11 @@ export type SocialChannelState = { forumSession?: ForumSessionStatus; // An X search channel (release 38): its query and where its walk stands. search?: { query: string; walk: string }; + // A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new, and + // Resume backfill when the full-history walk is part-way (`backfill`, its + // status line); `sync`, the line for a sync that stopped part-way. Absent on + // a forum thread and an X search channel, which keep Fetch posts. + timeline?: { backfill: string | null; sync: string | null }; // A forum thread's two walks (lib/forumWalk.ts): the status line, the // thread's last page as last seen, the mean seconds a page takes at the // channel's pace, and the Fetch posts button's retry after a block. @@ -135,7 +140,8 @@ export function SocialChannelPanel({ const [fetchNote, setFetchNote] = useState<string | null>(null); const [fetchErr, setFetchErr] = useState<string | null>(null); - const run = (full: boolean, older = false) => + const timeline = state.timeline; + const run = (full: boolean, older = false, backfill = false) => startTransition(async () => { setFetchNote(null); setFetchErr(null); @@ -153,13 +159,21 @@ export function SocialChannelPanel({ undefined, // A forum thread's Fetch posts waits out a block as settings say. forum && !full ? "settings" : undefined, + backfill || undefined, ); // The job streams to the jobs page; nothing to consume here, but the // stream must be released or its buffered chunks leak. if (res.ok) { void res.stream.cancel(); if (forum) setFetchNote(full ? "Full re-walk queued — its log is on the jobs page." : "Fetch queued — its log is on the jobs page."); - } else if (forum) { + else if (timeline && !full && !older) { + setFetchNote( + backfill + ? "Resume backfill queued — its log is on the jobs page." + : "Sync new queued — its log is on the jobs page.", + ); + } + } else if (forum || timeline) { setFetchErr(res.error); } }); @@ -296,15 +310,42 @@ export function SocialChannelPanel({ <span>pages</span> </label> )} - <button - type="button" - onClick={() => run(false)} - disabled={pending} - aria-label="fetch posts" - className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" - > - {pending ? "Fetching…" : "Fetch posts"} - </button> + {timeline ? ( + <> + <button + type="button" + onClick={() => run(false)} + disabled={pending} + aria-label="sync new posts" + title="Fetch the posts newer than the newest archived one: from the top of the timeline down to it. It never resumes an unfinished backfill, and never moves its place." + className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" + > + {pending ? "Fetching…" : "Sync new"} + </button> + {timeline.backfill && ( + <button + type="button" + onClick={() => run(false, false, true)} + disabled={pending} + aria-label="resume posts backfill" + title="Continue the account's unfinished full-history walk from where it stopped, down through older posts. It does not look for new posts — Sync new does that." + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Resume backfill + </button> + )} + </> + ) : ( + <button + type="button" + onClick={() => run(false)} + disabled={pending} + aria-label="fetch posts" + className="rounded-md bg-primary px-3 py-1 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50" + > + {pending ? "Fetching…" : "Fetch posts"} + </button> + )} <button type="button" onClick={checkDeleted} @@ -395,6 +436,16 @@ export function SocialChannelPanel({ {walk.status} </p> )} + {timeline?.backfill && ( + <p aria-label="timeline backfill" className="mt-3 text-xs text-warning"> + {timeline.backfill} + </p> + )} + {timeline?.sync && ( + <p aria-label="timeline sync" className="mt-2 text-xs text-muted-foreground"> + {timeline.sync} + </p> + )} {fetchNote && ( <p role="status" className="mt-2 text-xs text-success"> {fetchNote} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -13,6 +13,11 @@ import { import { isPostGone, type Post, type PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts"; import { resolveSocialFetcher } from "yt-dlp-transcript-common/social/fetchers"; import { describeOlderBackfill } from "yt-dlp-transcript-common/social/olderBackfill"; +import { + describeTimelineBackfill, + describeTimelineSync, + timelineWalks, +} from "yt-dlp-transcript-common/lib/timelineWalk"; import "yt-dlp-transcript-common/social/blueskyFetcher"; import "yt-dlp-transcript-common/social/xGalleryDlFetcher"; import "yt-dlp-transcript-common/social/xPlaywrightFetcher"; @@ -234,6 +239,10 @@ export default async function ChannelDetailPage({ // An X SEARCH channel (release 38): its query, its walk and its leads. const xSearch = isXSearchChannel(config) && config.xSearch ? config.xSearch : null; const leads = xSearch ? await readXSearchLeads(paths, slug) : null; + // A TIMELINE's two walks (X, Bluesky; lib/timelineWalk.ts): Sync new and, + // when the full-history walk is part-way, Resume backfill — never a forum + // thread's (its own two walks) or an X search's (one walk). + const timeline = !forumThread && !xSearch ? timelineWalks(fetchState) : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -276,6 +285,14 @@ export default async function ChannelDetailPage({ typeof fetcher?.checkAvailability === "function", canFetchOlder: typeof fetcher?.fetchOlder === "function", olderStatus: describeOlderBackfill(fetchState?.older), + ...(timeline + ? { + timeline: { + backfill: timeline.backfill ? describeTimelineBackfill(timeline, postCount) : null, + sync: describeTimelineSync(timeline), + }, + } + : {}), handle: config.socialHandle ?? slug, accountUrl: config.url, platform: config.platform, diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -26,11 +26,16 @@ import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetc import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts"; import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage"; import { + BACKFILL_AND_FULL_REFUSAL, + BACKFILL_AND_OLDER_REFUSAL, emptyAccountOlderProblem, fetchPosts, + FORUM_BACKFILL_REFUSAL, FULL_AND_OLDER_REFUSAL, OLDER_FROM_REFUSAL, olderPostsProblem, + resumeBackfillProblem, RETRY_AND_OLDER_REFUSAL, + X_SEARCH_BACKFILL_REFUSAL, } from "yt-dlp-transcript-common/controller/fetchPosts"; import { retryOnBlockProblem, @@ -167,6 +172,14 @@ export async function checkPostAvailabilityAction( }); } +// With none of `full`, `older`, `backfill` it is SYNC NEW (lib/timelineWalk.ts): +// from the top of the timeline down to the newest archived post — what the +// scheduler, the Sync button and a plain ops fetch-posts run. It never reads or +// clears an unfinished backfill's resume point. `backfill` is RESUME +// BACKFILL: that point continued, with no watermark — refused here, before a +// job exists, when no backfill is part-way, with `full` or `older`, on a forum +// thread or an X search channel. +// // `older` walks the account's history backwards from the oldest archived post // (the fetcher's `fetchOlder` — X: search windows) instead of fetching new // posts; `floor` (YYYY-MM-DD) is the date that walk stops at. Both are refused @@ -189,8 +202,12 @@ export async function fetchPostsAction( // `{minutes, max}`, or "settings" for `settings.social.xenforo.retryOnBlock` // (a forum thread's Fetch posts button; nothing when it is unset). retryOnBlock?: RetryOnBlock | "settings", + // RESUME BACKFILL in place of sync new (FetchPostsOptions.backfill). + backfill?: boolean, ): Promise<StreamActionResult> { if (full && older) return { ok: false, error: FULL_AND_OLDER_REFUSAL }; + if (backfill && full) return { ok: false, error: BACKFILL_AND_FULL_REFUSAL }; + if (backfill && older) return { ok: false, error: BACKFILL_AND_OLDER_REFUSAL }; if (retryOnBlock && older) return { ok: false, error: RETRY_AND_OLDER_REFUSAL }; const retry = retryOnBlock === "settings" ? getSettings().social.xenforo?.retryOnBlock : retryOnBlock; @@ -223,6 +240,14 @@ export async function fetchPostsAction( if (isWaybackPagesChannel(config)) return { ok: false, info: true, error: WAYBACK_PAGES_NOT_FETCHED }; // An X search channel's one walk is its search windows (release 38). if (older && isXSearchChannel(config)) return { ok: false, error: X_SEARCH_OLDER_REFUSAL }; + if (backfill) { + if (isXSearchChannel(config)) return { ok: false, error: X_SEARCH_BACKFILL_REFUSAL }; + if (config.platform === "xenforo") return { ok: false, error: FORUM_BACKFILL_REFUSAL }; + const problem = resumeBackfillProblem( + await readPostFetchState(path.join(paths.channelsDir, slug)), + ); + if (problem) return { ok: false, error: problem }; + } if (older) { await registerBuiltinSocialFetchers(); const problem = olderPostsProblem( @@ -262,6 +287,7 @@ export async function fetchPostsAction( older, floor, force, + ...(backfill ? { backfill: true } : {}), ...(pages ? { pages } : {}), ...(from ? { from } : {}), ...(retry ? { retryOnBlock: retry } : {}), @@ -273,6 +299,7 @@ export async function fetchPostsAction( slug, settings: getSettings(), full, + ...(backfill ? { backfill: true } : {}), older, floor, from, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -426,6 +426,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { p.retryOnBlock && typeof p.retryOnBlock === "object" ? (p.retryOnBlock as { minutes: number; max: number }) : undefined, + // A resume-backfill job replays as one; any other as sync new. + bool(p.backfill), ); }, // Lane spn-batch: the batch's state file holds the list and each URL's diff --git a/editor/e2e/social-channel.spec.ts b/editor/e2e/social-channel.spec.ts @@ -173,7 +173,8 @@ test("fetch-posts writes month-sharded JSONL + a posts-archive, and re-running i // the archive must dedupe all of them rather than doubling the corpus. await generateReport(page, "faketester"); await page.goto("/channels/faketester"); - await page.getByRole("button", { name: /fetch posts/i }).first().click(); + // An X timeline's Fetch posts is Sync new (lib/timelineWalk.ts). + await page.getByRole("button", { name: "sync new posts" }).click(); await expect .poll( @@ -265,6 +266,74 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in .toEqual(["xenforo 21", "xenforo 22", "xenforo 23"]); }); +// SYNC NEW AND RESUME BACKFILL are two buttons for two walks (operator, 6 Nov +// 2026): an unfinished backfill is said, not silently resumed — Sync new walks +// from the top down to the watermark and keeps the backfill's place; Resume +// backfill continues it. The state is a posts-state.json from before the split +// (one `cursor`), which reads as the backfill's. +test("an X channel: Sync new keeps an unfinished backfill's place; Resume backfill continues it and the button goes", async ({ + page, +}) => { + await resetData("empty"); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/faketester`); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + socialHandle: "faketester", + name: "Fake Tester", + url: X_URL, + }), + ); + const statePath = path.join(dir, "posts-state.json"); + await writeFile(statePath, JSON.stringify({ lastFetchedAt: "2026-11-05T00:00:00.000Z", lastFetchedCount: 0, cursor: "1/LEGACY-BACKFILL" })); + await generateReport(page, "faketester"); + await page.goto("/channels/faketester"); + + const panel = page.locator("[data-social-panel]"); + await expect(panel.getByLabel("timeline backfill")).toHaveText("backfill unfinished — 0 archived; Resume backfill continues it"); + await expect(panel.getByRole("button", { name: "resume posts backfill" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "fetch posts" })).toHaveCount(0); + await expect(panel.getByRole("button", { name: "refetch full history" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "fetch older posts" })).toBeVisible(); + + // SYNC NEW: the fake's three tweets land; the backfill's place is kept. + await panel.getByRole("button", { name: "sync new posts" }).click(); + await expect(panel.getByRole("status")).toHaveText("Sync new queued — its log is on the jobs page."); + const archive = `${testPaths().transcriptsDir}/channels/faketester/posts-archive`; + const archived = async () => + (await pathExists(archive)) ? (await readFile(resolvePath(archive), "utf8")).split("\n").filter(Boolean).length : 0; + await expect.poll(archived, { timeout: 30_000 }).toBe(3); + const config = `${testPaths().transcriptsDir}/channels/faketester/config.json`; + await expect + .poll(async () => (await readJson<{ lastSyncedAt?: string }>(config)).lastSyncedAt ?? null, { timeout: 30_000 }) + .not.toBeNull(); + const afterSync = JSON.parse(await readFile(statePath, "utf8")) as Record<string, unknown>; + expect(afterSync.backfill).toMatchObject({ cursor: "1/LEGACY-BACKFILL" }); + expect("cursor" in afterSync).toBe(false); + await page.reload(); + await expect(panel.getByLabel("timeline backfill")).toHaveText("backfill unfinished — 3 archived; Resume backfill continues it"); + + // RESUME BACKFILL: the fake walks to the end and exits cleanly — the walk + // is finished, its place cleared, and the button goes. + await panel.getByRole("button", { name: "resume posts backfill" }).click(); + await expect(panel.getByRole("status")).toHaveText("Resume backfill queued — its log is on the jobs page."); + await expect + .poll(async () => (JSON.parse(await readFile(statePath, "utf8")) as Record<string, unknown>).backfill ?? null, { + timeout: 30_000, + }) + .toBeNull(); + await page.reload(); + await expect(panel.getByRole("button", { name: "sync new posts" })).toBeVisible(); + await expect(panel.getByRole("button", { name: "resume posts backfill" })).toHaveCount(0); + await expect(panel.getByLabel("timeline backfill")).toHaveCount(0); + expect(await archived()).toBe(3); +}); + // A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): the // Sync button on the /channels rack ran yt-dlp's listing against an X profile // and failed. It runs fetch-posts now (the fake gallery-dl here), and a diff --git a/mcp/src/archivalTools.test.ts b/mcp/src/archivalTools.test.ts @@ -29,7 +29,15 @@ test("enqueue: each kind posts to its own route with only the keys it takes", () route: "/api/ops/import-video", body: { slug: "demo", url: "https://example.invalid/v/1" }, }); + // Sync new is a plain fetch-posts; resume backfill is asked for by name. + assert.deepEqual(enqueueBody({ kind: "fetch-posts", channel: "demo", backfill: true }), { + ok: true, + kind: "fetch-posts", + route: "/api/ops/fetch-posts", + body: { slug: "demo", backfill: true }, + }); const refusals: [Record<string, unknown>, RegExp][] = [ + [{ kind: "sync", channel: "demo", backfill: true }, /sync does not take backfill/], [{ kind: "delete-channel", channel: "demo" }, /kind must be one of sync, download-missing/], [{ kind: "sync" }, /channel is required/], [{ kind: "sync", channel: "../x" }, /channel is required/], diff --git a/mcp/src/archivalTools.ts b/mcp/src/archivalTools.ts @@ -119,10 +119,10 @@ const KIND_ARGS: Record<EnqueueKind, readonly string[]> = { "download-missing": [], "retry-bucket": ["bucket", "ids"], "transcribe-bucket": ["ids"], - "fetch-posts": ["full", "older"], + "fetch-posts": ["full", "older", "backfill"], "import-video": ["url"], }; -const ALL_ARGS = ["full", "older", "bucket", "ids", "url"]; +const ALL_ARGS = ["full", "older", "backfill", "bucket", "ids", "url"]; export function enqueueBody( args: Record<string, unknown>, @@ -142,7 +142,7 @@ export function enqueueBody( }; } const body: Record<string, unknown> = { slug: channel }; - for (const k of ["full", "older"] as const) { + for (const k of ["full", "older", "backfill"] as const) { if (args[k] === undefined) continue; if (typeof args[k] !== "boolean") return { ok: false, error: `enqueue: ${k} must be true or false` }; if (args[k]) body[k] = true; @@ -479,7 +479,8 @@ export const ARCHIVAL_TOOLS = [ "the whole listing), download-missing (every listed video not held), retry-bucket " + "(one bucket of the channel's report, or ids within it — the way to download chosen " + "videos), transcribe-bucket (the downloaded, untranscribed videos, or ids among them), " + - "fetch-posts (a social channel's new posts; full / older walks), import-video (one " + + "fetch-posts (a social channel's new posts — sync new; backfill: true resumes its unfinished " + + "history walk instead; full / older walks), import-video (one " + "video by URL into the channel). The editor runs it on its own queues at each " + "platform's pace and answers a job id — follow it with get_job. Only when the " + "operator asks for it. Settings, storage and deletes are not reachable from here. " + @@ -491,6 +492,11 @@ export const ARCHIVAL_TOOLS = [ channel: { type: "string", description: "The channel slug (the editor's)." }, full: { type: "boolean", description: "sync: sweep the whole listing now; fetch-posts: re-walk the timeline." }, older: { type: "boolean", description: "fetch-posts: walk back below the oldest archived post." }, + backfill: { + type: "boolean", + description: + "fetch-posts: resume the timeline's unfinished full-history walk from its saved point (without it, fetch-posts syncs new posts only).", + }, bucket: { type: "string", description: "retry-bucket: the bucket name (e.g. noTranscript, partialDownloads)." }, ids: { type: "array", diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -8639,11 +8639,23 @@ phase deletes from the destination. ending the day after the oldest archived post; one gallery-dl run per window, a random 45–120 s apart (every X request itself waits a random 4–10 s: `sleep-request=4.0-10.0`, `ratelimit=wait`), one 3-hour budget across them. Its resume point is its own: the oldest post id read in the window, sent back as `max_id:<id>` (inclusive; gallery-dl's rewrite replaces it). State is - `posts-state.json` `older` (`OlderBackfillState`), apart from the timeline `cursor`; a normal fetch + `posts-state.json` `older` (`OlderBackfillState`), apart from the timeline's positions; a normal fetch copies `older` through untouched and an older run copies every other field through. Ends at the later of the `floor` and the account's creation day, or after 4 empty windows in a row; then `older.complete` and a re-run fetches nothing. No login = refused before spawning (`needsCookies`). It does not stamp `lastSyncedAt`. +- **A timeline's two walks are SYNC NEW and RESUME BACKFILL** (2026-11-06, `common/lib/timelineWalk.ts`, + pure; X, Bluesky, Nitter — not a forum thread's `forum`, not an X search's `search`). A plain + `fetch-posts` (Sync, the scheduler, the channel page's **Sync new**, aria `sync new posts`) walks + from the top with `since` = the newest archived post, and NEVER reads or clears `backfill`. A sync + stopped part-way saves `sync: {cursor, since}` (the watermark it began with) and the next sync + continues to it. **Resume backfill** = `fetch-posts "backfill": true` = `pnpm ops resume-backfill` + = `--backfill` (button aria `resume posts backfill`; `resume backfill` is the backfill LANE's pause) + continues `backfill.cursor` with no `since`, never touching `sync`. It is refused before any job + when none is part-way, with `full`/`older`, on a forum thread or an X search channel. A first walk + (nothing archived, no backfill) and an unfinished `full` save to `backfill`; a finished `full` + clears both. A legacy single `cursor` is read as `backfill` and not written again (a forum still + reads it as its pre-37 history position). The old rule "resume = a plain fetch-posts" is gone. - **`node:sqlite`** (Node 22.23 here; unflagged since 22.13, an ExperimentalWarning once per process) is loaded at run time through an assembled specifier with `webpackIgnore` (`common/social/nodeSqlite.ts`), like `playwrightRuntime.ts`: the editor's Turbopack build has diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -40,6 +40,8 @@ // EXAMPLES // // pnpm ops sync --json '{"slug":"the-quartering"}' --wait +// pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait +// pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait @@ -435,9 +437,12 @@ const ACTIONS = [ // The TRANSCRIBE half of a channel's "downloaded, not transcribed" bucket // (retry-bucket is the download retry and skips audio already on disk). "transcribe-bucket", - // A social channel's post fetch: new posts, the full re-walk ("full"), or - // the walk back below the oldest archived post ("older"). + // A social channel's post fetch: SYNC NEW (plain), RESUME BACKFILL + // ("backfill": true), the full re-walk ("full"), or the walk back below the + // oldest archived post ("older"). "fetch-posts", + // RESUME BACKFILL by its own name: fetch-posts "backfill": true. + "resume-backfill", // A screenshot and the attached media of specific archived posts. "capture-posts", // Publishing as stages (release 18): {"verb": "index" | "build" | "deploy" | @@ -1519,7 +1524,11 @@ export function usage() { ' bucket on the transcription queue, as the channel page\'s Transcribe button', ' does: {"slug"}. "ids": [...] narrows it the same way as on retry-bucket.', "", - 'fetch-posts fetches a social channel\'s new posts: {"slug"}. "full": true', + 'fetch-posts fetches a social channel\'s new posts: {"slug"} is SYNC NEW —', + ' from the top of the timeline down to the newest archived post (a sync that', + ' stopped part-way continues down to the watermark it began with). It never', + ' reads or clears an unfinished backfill\'s resume point. "backfill": true', + ' is RESUME BACKFILL instead (the same as resume-backfill). "full": true', ' re-walks the whole timeline; "older": true walks back from the oldest', " archived post through search (X; needs a login), saving its place for", ' the next run, down to "floor": "YYYY-MM-DD" when given; "from":', @@ -1531,10 +1540,22 @@ export function usage() { ' "full": true is its full re-walk (every page, edits updated).', ' "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default', ' in settings) waits out a challenge or refusal page and runs again, max', - ' tries in all. "full" and "older" together are refused. An', + ' tries in all. "full", "older" and "backfill" are one at a time. An', ' older walk over an account that shows no posts (nothing archived, and', ' the last timeline fetch read none) is refused unless "force": true. A', - " drained fetch stops at its next resume point and the next run resumes.", + " drained fetch stops at its next resume point and the next run of the", + " same walk resumes there.", + "", + 'resume-backfill continues a social channel\'s unfinished full-history', + ' timeline walk (X, Bluesky) from its saved resume point, with no', + ' watermark: {"slug"} ("limit"? caps the posts this run reads). The walk', + " is left part-way by a first fetch, a full re-walk or a backfill that", + " stopped; the channel page then says \"backfill unfinished — N archived\"", + " and shows Resume backfill. Nothing resumes it but this (or fetch-posts", + ' "backfill": true): a plain fetch-posts, Sync and the scheduler sync new', + " posts and keep its place. Refused when none is part-way, on a forum", + " thread (every fetch catches up, then continues its history) and on an X", + " search channel.", "", 'capture-posts captures archived posts of a social channel (X, forum,', ' Bluesky): a screenshot of each through the connected X profile (a forum', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -607,6 +607,18 @@ test("fetch-posts is a POST to its route, named in the usage", () => { assert.match(usage(), /read none\) is refused unless "force": true/); }); +// SYNC NEW and RESUME BACKFILL are two named actions (operator, 6 Nov 2026): +// a plain fetch-posts syncs new posts; resume-backfill is its own POST. +test("resume-backfill is a POST to its own route, and the usage says a plain fetch-posts is sync new", () => { + const p = parseArgs(["resume-backfill", "--json", '{"slug":"example-x"}']); + assert.equal(p.method, "POST"); + assert.equal(p.path, "/api/ops/resume-backfill"); + assert.deepEqual(p.body, { slug: "example-x" }); + assert.match(usage(), /fetch-posts fetches a social channel's new posts: \{"slug"\} is SYNC NEW/); + assert.match(usage(), /"backfill": true\s+is RESUME BACKFILL instead/); + assert.match(usage(), /resume-backfill continues a social channel's unfinished full-history/); +}); + // A post capture: a POST to its route, the body passed through untouched — the // route and the action judge it (ids in the archive, both halves off). test("capture-posts is a POST to its route, named in the usage", () => { @@ -618,7 +630,7 @@ test("capture-posts is a POST to its route, named in the usage", () => { assert.equal(p.method, "POST"); assert.equal(p.path, "/api/ops/capture-posts"); assert.deepEqual(p.body, { slug: "example-x", ids: ["123"], media: false }); - assert.match(usage(), /Actions:.*fetch-posts, capture-posts/); + assert.match(usage(), /Actions:.*fetch-posts, resume-backfill, capture-posts/); assert.match(usage(), /Every id must be in the channel's posts archive/); assert.match(usage(), /unless\s+"articles": false/); });