Archilyzer · Source

archilyzer

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

commit a8ca390467291c22f559665284e9c590afa05ce7
parent 3ba931c042ce5360ec1c6725207d8a984188b635
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 23 Oct 2026 11:54:01 -0400

Merge lane/pacing-guard: no burst on any site — a gap between jobs on every platform queue, no unqueued network job, X only on a fresh cookie jar, an X challenge fails the job and holds X

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

# Conflicts:
#	editor/CHANGELOG.md

Diffstat:
MCOMMANDS.md | 2+-
MENVIRONMENT.md | 2++
MOPERATING.md | 19+++++++++++++++++++
MSETTINGS.md | 7+++++--
Acommon/controller/feedTitlePrefilter.test.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/feedTitlePrefilter.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/fetchLiveChat.ts | 3+++
Mcommon/controller/fetchPosts.test.ts | 5++++-
Mcommon/controller/recheckServiceCookies.test.ts | 37+++++++++++++++++++++++++++++++++++++
Mcommon/controller/recheckServiceCookies.ts | 44++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Acommon/jobs/networkGuard.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/networkGuard.ts | 225+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/pacingGuard.test.ts | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/platformBackoff.test.ts | 5++++-
Acommon/jobs/queueGap.test.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/queueGap.ts | 281+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/queueGapText.ts | 27+++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 7+++++++
Mcommon/jobs/streamCommand.ts | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/envVars.ts | 2++
Acommon/lib/jobGap.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/serviceCookies-server.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/serviceCookies.test.ts | 16++++++++++++++++
Mcommon/lib/serviceCookies.ts | 23++++++++++++++++++++---
Mcommon/lib/settingsSchema.ts | 32+++++++++++++++++++++++++++++++-
Mcommon/social/xCookieSource.ts | 24++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/jobRowView.ts | 5+++++
Mcommon/views/jobRows.ts | 3+++
Mcommon/ytdlp/managedDownloadsSleep.test.ts | 15+++++++++++----
Mcommon/ytdlp/runYtdlp.ts | 38+++++++++++++++++++++++++++++++-------
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/recheck-service/route.ts | 5+++--
Meditor/app/api/test/invalidate-cache/route.ts | 6++++++
Meditor/app/channels/[slug]/socialActions.ts | 9++++++---
Meditor/app/components/QueueControl.tsx | 10++++++++--
Meditor/app/components/dashboard/CookieAlertsPanel.tsx | 2+-
Meditor/app/jobs/components/JobRow.tsx | 20++++++++++++++++++++
Meditor/app/settings/actions.ts | 38++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/components/SettingsForm.tsx | 37+++++++++++++++++++++++++++++++++++++
Meditor/app/settings/components/XSessionSection.tsx | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/page.tsx | 2++
Meditor/app/settings/xSessionActions.ts | 27+++++++++++++++++++++++++++
Meditor/e2e/cookie-alerts.spec.ts | 101++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Meditor/e2e/fixtures/bin/fake-gallery-dl.mjs | 8++++++++
Meditor/e2e/pacing.spec.ts | 36+++++++++++++++++++++++++++++++++++-
Meditor/e2e/queues.spec.ts | 40++++++++++++++--------------------------
Meditor/e2e/servers.ts | 7+++++++
Meditor/playwright.config.ts | 4++++
Aplans/pacing-guard.md | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 8+++++---
Msettings.json.example | 3++-
54 files changed, 2244 insertions(+), 64 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -151,7 +151,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | -| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'` | +| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'` | | `dismiss-service` | — | | | `rerun-service-jobs` | — | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -236,6 +236,8 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts | | `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | +| `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | +| `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | | `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_UMTOOL_ORIGIN_FILE` | unset (UMTOOL_URL) | A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored. | common/lib/umtoolUrl.ts | | `E2E_WAYBACK_ORIGIN_FILE` | unset (the real Wayback Machine) | A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored. | common/lib/waybackClient.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -73,6 +73,13 @@ pnpm ops dismiss-service --json '{"service":"rumble"}' Cloudflare's challenge words; no real sample yet) → open odysee.com. A forum's browser check, captcha or login wall, by host → Connect forum session on the thread's channel page. archive.today's check page → Connect archive session (Settings). A Connect that ends on a cleared page clears the banner too. +- **X** (`"service":"x"`): a Cloudflare challenge, a 401/403 or a login wall in gallery-dl's output — even + on a run that exits 0 — fails the fetch (posts read so far kept) and raises it; one is enough. **While it + is up, no X job starts**: every fetch, older walk, X search, capture or import on X is refused with its + sentence, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand (Connect X + account on /settings and clear it in the window; with the browser login, open x.com in that browser), + press **Refresh cookies**, then **Recheck** — which sends X *no* request: it clears when the login on disk + was renewed after the alert was raised. - The job it stopped says so in its log: `stopped: Rumble cookies look stale — open rumble.com in …, then Recheck on the dashboard.` `archilyzer doctor` lists it under "service cookies". - The state is `transcripts/.service-cookies.json` (`common/lib/serviceCookies.ts`); never hand-edit it. @@ -261,6 +268,18 @@ 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. +- **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 + jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)`). Thirteen fetches queued in one loop run five + minutes apart and stop at the first challenge. A queue override of `""` (immediate) is refused for any + such job. +- **X only on a fresh jar.** With the connected profile as the login source, a job aimed at X is refused — + at enqueue and again when its queue reaches it — unless the cookies were refreshed within + `social.x.maxCookieAgeMinutes` (60; 0 = off): `X cookies were last refreshed 16 days ago (limit 60 min): + press Refresh cookies (or Connect X account) on /settings, then fetch again.` Refreshing is a click on + /settings — it loads x.com — so the editor never refreshes on its own. With the browser login the age + cannot be read; the job logs that and proceeds. - `capture-posts` saves a screenshot and the attached media of named posts (and a linked X Article). - A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page to the newest held post, then continues the history from where it stopped, down to page 1 — `"pages": N` caps diff --git a/SETTINGS.md b/SETTINGS.md @@ -169,7 +169,7 @@ Default: `"when-required"` ## `social` -Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. +Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts. #### `social` @@ -184,6 +184,7 @@ Per-platform settings of the social posts: X's two, both chosen in the X account |---|---|---| | `cookieSource` | absent | Where the X fetchers' login comes from. `"browser"`: the operator's everyday browser, named by `cookiesFromBrowser` — gallery-dl is handed `--cookies-from-browser <spec>` and reads it on every run, and the Playwright fallback reads the same store (Firefox only; common/social/xBrowserLogin.ts), so the login lasts as long as the browser's. `"profile"`: the session broker's persistent profile ("Connect X account" on /settings) and the cookie jar it exports. ABSENT (the default) is resolved at read time, never stored: `"browser"` when `cookiesFromBrowser` is set and no profile is connected (no exported jar carrying an auth_token), else `"profile"`. The source, not `cookieMode`, governs the X fetchers. | | `visibility` | absent | Where X posts may appear. `"public"` (the default; absent): an X channel's posts are built into every site that has the channel. `"private"`: every X channel's posts (a channel with `sourceKind: "social"` and `platform: "twitter"`) are left out of every PUBLIC site build — the channel with them, since posts are all an X channel holds — and built only into PRIVATE sites (`site.json` `audience`). Nothing on disk changes and fetching does not; a site already published changes on its next build and deploy, and flipping back is a rebuild. Chosen in the X account session section of /settings; the rule is common/lib/postsVisibility.ts. | +| `maxCookieAgeMinutes` | absent | THE FRESH-JAR RULE: with the `"profile"` login source, a job that sends requests to X (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported cookie jar was written within this many minutes and carries a login (an auth_token). The refusal says what to do: press Refresh cookies (or Connect X account) on /settings, then fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so the editor never refreshes the jar to satisfy this. With the `"browser"` source the age cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most 10080 (a week). Set in the X account session section of /settings. common/jobs/networkGuard.ts. | #### `social.xenforo` @@ -219,6 +220,7 @@ How the download pace adapts to rate limits, per platform (release 17). Every yt | `decayAfterCleanUnits` | `5` | How many clean auto-download units on a platform halve its pace one step back toward the fixed value. Clamped 1–1000; default 5. | | `holdAfterFailsAtCap` | `3` | How many consecutive failures AT the 30-minute cooldown cap put a platform in a hold: the lane then runs one probe unit per holdProbeMinutes instead of one per cooldown, and a manual Sync or download on it is refused with the next probe's time. A clean probe clears the hold and the backoff. Clamped 1–100; default 3. | | `holdProbeMinutes` | `60` | Minutes between probes while a platform is held. Clamped 1–1440; default 60. | +| `jobGapSeconds` | `{}` | THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE, in seconds, keyed by platform (the `<p>` of a `platform:<p>` queue — `twitter`, `youtube`, `megaphone.fm` …) or `default`. A job that sends requests to a platform (a kind declaring `network` in common/jobs/jobKinds.ts) does not start until this long after the previous such job on its queue ended; while it waits its log and its /jobs row say so ("waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)"). The last end per queue survives a restart (`.jobs/queue-gaps.json`). Built in, for a key not set here: default 20, twitter 300, xenforo 60, bluesky 60 — only the keys set here are stored. 0 for a key: no gap on that platform. At most 86400. Set on /settings beside the download sleep. common/jobs/queueGap.ts. | Default: @@ -227,7 +229,8 @@ Default: "sleepRequestsCapSeconds": 16, "decayAfterCleanUnits": 5, "holdAfterFailsAtCap": 3, - "holdProbeMinutes": 60 + "holdProbeMinutes": 60, + "jobGapSeconds": {} } ``` diff --git a/common/controller/feedTitlePrefilter.test.ts b/common/controller/feedTitlePrefilter.test.ts @@ -0,0 +1,66 @@ +// A podcast feed channel's titles before any probe (plans/pacing-guard.md). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/feedTitlePrefilter.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { looksLikeFeedChannel, seedFeedTitles } from "./feedTitlePrefilter"; +import { loadMetadataScan, settledByTitleFilterIds } from "./metadataScanStore"; +import { extractVideoId } from "../lib/videoId"; + +const FEED = `<?xml version="1.0"?><rss><channel><title>Show</title> +<item><title>Episode 1: the topic</title><pubDate>Tue, 21 Oct 2026 10:00:00 GMT</pubDate> +<enclosure url="https://cdn.example.fm/ep1.mp3" type="audio/mpeg"/></item> +<item><title>Episode 2: something else</title><pubDate>Wed, 22 Oct 2026 10:00:00 GMT</pubDate> +<enclosure url="https://cdn.example.fm/ep2.mp3" type="audio/mpeg"/></item> +</channel></rss>`; + +const CONFIG = { + url: "https://feeds.example.fm/show", + downloadFilter: { include: "topic" }, +} as const; +const URLS = ["https://cdn.example.fm/ep1.mp3", "https://cdn.example.fm/ep2.mp3"]; + +test("which channels are read as a feed", () => { + assert.equal(looksLikeFeedChannel(CONFIG as never, URLS), true); + assert.equal(looksLikeFeedChannel({ url: CONFIG.url } as never, URLS), false, "no filter: nothing to settle"); + assert.equal( + looksLikeFeedChannel({ ...CONFIG, url: "https://www.youtube.com/@x" } as never, URLS), + false, + "a known platform is not a feed", + ); + assert.equal(looksLikeFeedChannel(CONFIG as never, ["https://example.fm/page/1", "https://example.fm/page/2"]), false); +}); + +test("one feed read titles the unscanned episodes; the filter then settles the unwanted one with no probe", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "feed-titles-")); + const paths = { channelsDir: path.join(root, "channels") } as Paths; + await mkdir(path.join(paths.channelsDir, "show"), { recursive: true }); + let reads = 0; + const lines: string[] = []; + const n = await seedFeedTitles({ + paths, + slug: "show", + config: CONFIG as never, + playlistUrls: URLS, + onLog: (l) => lines.push(l), + fetchFeed: async () => { + reads++; + return FEED; + }, + }); + assert.equal(reads, 1); + assert.equal(n, 2); + const scan = await loadMetadataScan(paths, "show"); + const ep2 = extractVideoId(URLS[1])!; + assert.equal(scan.entries[ep2]?.title, "Episode 2: something else"); + const settled = await settledByTitleFilterIds(paths, "show", CONFIG as never); + assert.deepEqual([...settled], [ep2]); + // Everything known: no second read. + await seedFeedTitles({ paths, slug: "show", config: CONFIG as never, playlistUrls: URLS, onLog: () => {}, fetchFeed: async () => { reads++; return FEED; } }); + assert.equal(reads, 1); +}); diff --git a/common/controller/feedTitlePrefilter.ts b/common/controller/feedTitlePrefilter.ts @@ -0,0 +1,89 @@ +// A PODCAST FEED CHANNEL'S TITLES, BEFORE ANY PROBE (plans/pacing-guard.md). +// +// A download-missing on a feed channel with a title filter (megaphone.fm, +// 2026-10-23) probed every listed episode with yt-dlp, ~1,150 of them back to +// back, only to learn each one's title and decline it. The feed already says +// every title. So, once per run and only where it can pay: ONE request for the +// channel's feed, each item's title, description and date written into the +// channel's metadata-scan store under the id its enclosure URL gives +// (`extractVideoId`, as the playlist's URLs are read) — and the batch's +// `settledByTitleFilterIds` then settles every filtered episode with no request +// at all. +// +// WHEN. The channel has a download filter, its platform is not one this app +// knows (a known platform's listing is not a feed), and the playlist's URLs +// are mostly direct media files (an RSS feed's enclosures). An item already in +// the store is left as it is: a probe's answer beats the feed's. +// +// Best effort: a feed that does not answer, or is not RSS, costs the run +// nothing but its log line. + +import { detectPlatform } from "../lib/platform"; +import { extractVideoId } from "../lib/videoId"; +import { compileDownloadFilter } from "../lib/downloadFilters"; +import { feedDateToUploadDate, parseRssFeed } from "../lib/rssFeed"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import { loadMetadataScan, upsertMetadataScan, type MetadataScanEntry } from "./metadataScanStore"; +import type { FetchFeed } from "./feedMetadataBackfill"; + +const MEDIA_FILE = /\.(mp3|m4a|m4b|aac|ogg|oga|opus|wav|flac|mp4|m4v)(?:$|[?#])/i; + +// Does this channel look like a podcast feed whose titles are worth one read? +export function looksLikeFeedChannel( + config: Pick<ChannelConfig, "url" | "platform" | "downloadFilter">, + playlistUrls: readonly string[], +): boolean { + if (!compileDownloadFilter(config.downloadFilter)) return false; + if (!config.url || !/^https?:\/\//i.test(config.url)) return false; + if (config.platform || detectPlatform(config.url)) return false; + if (playlistUrls.length === 0) return false; + const media = playlistUrls.filter((u) => MEDIA_FILE.test(u)).length; + return media * 2 >= playlistUrls.length; +} + +export async function seedFeedTitles(opts: { + paths: Paths; + slug: string; + config: Pick<ChannelConfig, "url" | "platform" | "downloadFilter">; + playlistUrls: readonly string[]; + onLog: (line: string) => void; + signal?: AbortSignal; + fetchFeed?: FetchFeed; + now?: string; +}): Promise<number> { + if (!looksLikeFeedChannel(opts.config, opts.playlistUrls)) return 0; + const wanted = new Set(opts.playlistUrls.map((u) => extractVideoId(u)).filter((id): id is string => Boolean(id))); + const scan = await loadMetadataScan(opts.paths, opts.slug); + const missing = [...wanted].filter((id) => !scan.entries[id]); + if (missing.length === 0) return 0; + let xml: string; + try { + opts.onLog(`Feed titles: reading the channel's feed once (${opts.config.url}) so filtered episodes cost no probe.\n`); + const fetchFeed = opts.fetchFeed ?? (await import("./feedMetadataBackfill")).fetchFeedText; + xml = await fetchFeed(opts.config.url!, opts.signal); + } catch (err) { + opts.onLog(`Feed titles: the feed could not be read (${(err as Error).message}); each episode is probed instead.\n`); + return 0; + } + const feed = parseRssFeed(xml); + const scannedAt = opts.now ?? new Date().toISOString(); + const entries: Record<string, MetadataScanEntry> = {}; + const missingSet = new Set(missing); + for (const item of feed.items) { + if (!item.enclosureUrl || !item.title) continue; + const id = extractVideoId(item.enclosureUrl); + if (!id || !missingSet.has(id) || entries[id]) continue; + entries[id] = { + title: item.title, + description: item.description ?? "", + uploadDate: feedDateToUploadDate(item.pubDate) ?? "", + ...(item.durationSeconds ? { duration: item.durationSeconds } : {}), + scannedAt, + }; + } + const n = Object.keys(entries).length; + if (n > 0) await upsertMetadataScan(opts.paths, opts.slug, { entries }, scannedAt); + opts.onLog(`Feed titles: ${n} of ${missing.length} unscanned episode(s) titled from the feed (${feed.items.length} item(s)).\n`); + return n; +} diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts @@ -297,6 +297,9 @@ export async function runFetchChatJob(opts: FetchChatJobOpts): Promise<StreamAct paths, channelSlug: slug, videoId, + // A replay already on disk is only normalized: no request, so no gap and + // no network guard (plans/pacing-guard.md). + ...(plan.kind === "normalize" ? { network: false as const } : {}), fn: async (onLog, signal) => { if (plan.kind === "normalize") { onLog(`The chat replay of ${videoId} is on disk; normalizing it (no network).`); diff --git a/common/controller/fetchPosts.test.ts b/common/controller/fetchPosts.test.ts @@ -216,7 +216,10 @@ test("an auth failure that read nothing keeps the resume point it had, and inven // From a caught-up state it must not invent one either: the watermark stands. await writeFile(path.join(channelRoot, "posts-state.json"), "{}"); const fresh = await run(); - assert.equal(fresh.ok, true); + // An auth failure STOPS X (plans/pacing-guard.md): the fetch fails — it + // used to end ok with only needsCookies set — and raises the X alert. + assert.equal(fresh.ok, false); + assert.match(fresh.error ?? "", /challenge or a login wall/); assert.equal(fresh.written, 0); const state = await readPostFetchState(channelRoot); assert.equal(state?.needsCookies, true); diff --git a/common/controller/recheckServiceCookies.test.ts b/common/controller/recheckServiceCookies.test.ts @@ -124,3 +124,40 @@ test("Recheck (archive.today): the request that met the check, again; a check st await rm(paths.transcriptsDir, { recursive: true, force: true }); } }); + +test("Recheck (X): no request to X — stale until the login is renewed after the alert, then clean", async () => { + const paths = await tmpPaths(); + try { + const { noteXServiceOutcome } = await import("../lib/serviceCookies-server"); + await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", url: "https://x.com/a", channel: "a" }); + const raisedAt = (await readServiceCookieState(paths)).services.x?.raisedAt; + assert.ok(raisedAt, "one challenge raises the X alert"); + const asked: string[] = []; + let login = { source: "profile" as const, renewedAt: new Date(Date.parse(raisedAt!) - 60_000).toISOString(), loggedIn: true }; + const deps = { + runYtdlp: async () => { + asked.push("yt-dlp"); + return { exitCode: 0, stderrTail: "", archiveLine: null }; + }, + loadForumPage: async () => { + asked.push("page"); + return { html: "" }; + }, + xLogin: async () => login, + }; + const stale = await recheckServiceCookies({ paths, service: "x", deps }); + assert.equal(stale.result, "stale"); + assert.match(stale.message, /Refresh cookies/); + assert.match(stale.message, /Recheck sends X no request/); + assert.equal(isAlertRaised((await readServiceCookieState(paths)).services.x), true); + + login = { source: "profile", renewedAt: new Date(Date.parse(raisedAt!) + 60_000).toISOString(), loggedIn: true }; + const clean = await recheckServiceCookies({ paths, service: "x", deps }); + assert.equal(clean.result, "clean"); + const after = (await readServiceCookieState(paths)).services.x; + assert.equal(after?.clearedBy, "recheck"); + assert.deepEqual(asked, [], "Recheck asked nothing of anyone"); + } finally { + await rm(paths.transcriptsDir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts @@ -14,6 +14,14 @@ // archive.today the request that met the check, again, through // the polite client (its observe hook records // the answer). +// x NO REQUEST (plans/pacing-guard.md): after a +// challenge the next request to X is the one +// that gets an account locked. Clean when the +// login was renewed AFTER the alert was raised — +// the profile's jar re-exported (Refresh cookies +// on /settings) with a login in it, or, with the +// browser source, the browser's x.com auth_token +// last sent since — read from disk only. // // A clean answer clears the alert (clearedBy "recheck") and, for a yt-dlp // service, settles the platform's backoff as any clean manual request does @@ -66,6 +74,9 @@ export type RecheckDeps = { readChannelConfig: (paths: Paths, slug: string) => Promise<ChannelConfig | null>; cookieSpec: (config: ChannelConfig | null) => string | undefined; recordPlatformClean: (platform: string, paths: Paths) => Promise<string | null>; + // X's login, read from disk (no request): the source in use, when it was + // last renewed, and whether it holds a login. + xLogin: (paths: Paths) => Promise<{ source: "browser" | "profile"; renewedAt?: string; loggedIn: boolean; browser?: string }>; }; const defaultDeps = (paths: Paths): RecheckDeps => ({ @@ -95,6 +106,16 @@ const defaultDeps = (paths: Paths): RecheckDeps => ({ } }, recordPlatformClean: (platform, p) => recordPlatformClean(platform, p), + xLogin: async (p) => { + const { readXLoginStatus } = await import("../social/xBrowserLogin"); + const login = await readXLoginStatus(p, getSettings()); + return { + source: login.source, + ...(login.lastSeenAt ? { renewedAt: login.lastSeenAt } : {}), + loggedIn: login.authTokenVisible === true, + ...(login.browserSpec ? { browser: login.browserSpec } : {}), + }; + }, }); // The probe's argv: metadata only, nothing written, the channel's own args @@ -193,6 +214,29 @@ export async function recheckServiceCookies(opts: { } return out("failed", `${label} answered the page with ${block.kind} (${block.detail}); the alert stays.`); } + case "x": { + const raisedAt = entry?.raisedAt ?? entry?.since; + let login: Awaited<ReturnType<RecheckDeps["xLogin"]>>; + try { + login = await deps.xLogin(paths); + } catch (e) { + return out("failed", `Could not read X's login: ${(e as Error).message}. The alert stays.`); + } + log(`Rechecking ${label}: the login on disk, no request to X (the ${login.source === "profile" ? "connected profile's cookie jar" : "browser's cookie store"}).`); + const renewed = !!login.renewedAt && (!raisedAt || Date.parse(login.renewedAt) > Date.parse(raisedAt)); + if (login.loggedIn && renewed) { + return clean(`login renewed ${login.renewedAt!.slice(11, 16)} UTC, after the challenge; no request sent`); + } + const at = raisedAt ? ` at ${raisedAt.slice(11, 16)} UTC` : ""; + return out( + "stale", + login.source === "profile" + ? `${label}'s cookie jar has not been re-exported with a login since the challenge${at}: pass X's check by hand ` + + "(Connect X account on /settings), press Refresh cookies there, then Recheck. Recheck sends X no request." + : `The browser's X login has not been used since the challenge${at}: open x.com in ` + + `${login.browser ?? "the browser cookiesFromBrowser names"}, pass its check, then Recheck. Recheck sends X no request.`, + ); + } case "archive": { const url = target?.url; if (!url) { diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -9,6 +9,8 @@ import { isIngestKind, isPublishStageJobKind, jobKindIds, + kindIsNetwork, + platformKindIds, } from "./jobKinds"; // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/jobKinds.test.ts @@ -335,3 +337,48 @@ test("release 21: prepare-playable is a drainable media ingest kind, not replaya assert.equal(kindNeedsMedia("prepare-playable"), true); assert.equal(isIngestKind("prepare-playable"), true); }); + +// plans/pacing-guard.md: a kind that asks a platform is never run unqueued, +// is spaced on its platform queue, and (aimed at X) needs a fresh jar. +test("pacing guard: every platform-queue kind declares whether it is a network kind", () => { + const undecided = platformKindIds().filter((k) => getJobKind(k)?.network === undefined); + assert.deepEqual(undecided, [], `declare network: true|false on ${undecided.join(", ")}`); +}); + +test("pacing guard: the kinds that make platform requests are network kinds", () => { + const required = [ + "fetch-posts", + "capture-posts", + "import-post", + "check-post-availability", + "import-one", + "import-archive-org", + "sync", + "download-missing", + "download-from-playlist", + "metadata-scan", + "store-playlist", + "refresh-metadata", + "fetch-windows", + "fetch-window", + "record-live", + "persist-videos", + "fetch-chat", + "auto-download-unit", + "check-availability", + "import-page", + "save-page-now", + "wayback-scan", + ]; + for (const k of required) { + assert.ok(getJobKind(k), `${k} is a registered kind`); + assert.equal(kindIsNetwork(k), true, `${k} must declare network: true`); + } + // The offline ones on a platform queue, and unknown kinds, are not. + assert.equal(kindIsNetwork("import-forum-pages"), false); + assert.equal(kindIsNetwork("reextract-pages"), false); + assert.equal(kindIsNetwork("no-such-kind"), false); + // Runners are not: their units are the jobs that ask. + assert.equal(kindIsNetwork("auto-download"), false); + for (const k of jobKindIds()) assert.equal(typeof kindIsNetwork(k), "boolean"); +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -71,6 +71,20 @@ export type JobKindMeta = { // availability checks and the metadata scan, read every downloaded video as // missing and re-request the whole channel. Absent means false. needsText?: boolean; + // Whether this kind SENDS REQUESTS TO A PLATFORM — a video site, X, a forum, + // archive.org, a feed host (plans/pacing-guard.md, operator 2026-10-23: "be + // very careful not to do that thing on any sort of site"). Declarative, and + // consumed by runManagedFunction (common/jobs/networkGuard.ts): + // - a queue override of "" (run immediately, unqueued) is REFUSED for it: + // a network job always waits its queue; + // - on a `platform:<p>` queue it starts only `pacing.jobGapSeconds[p]` + // after the previous network job there ended (jobs/queueGap.ts); + // - one aimed at X (platform:twitter, or an X channel) starts only on a + // fresh cookie jar and while no X cookie alert is raised. + // ABSENT MEANS FALSE (an unlisted kind keeps its behavior), but every kind on + // a platform queue says which it is — jobKinds.test.ts holds that, so a new + // platform kind cannot slip in unpaced. + network?: boolean; }; // One entry per kind known to the system. `label` is included only where the @@ -98,6 +112,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, // THE OPERATOR'S "Clear hold" on /operations/download (release 17 slice @@ -123,6 +138,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, }, // The two OPERATION lanes' runners. Same shape as the two above — one // long-lived job per lane on queueKey "", drainable, never replayable — with @@ -258,6 +274,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "download-from-playlist": { @@ -266,6 +283,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, "download-missing": { @@ -274,6 +292,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, "download-missing-subs": { @@ -282,6 +301,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -291,6 +311,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, // CHOSEN FILES OF ONE archive.org ITEM, imported one at a time on @@ -303,6 +324,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, // AN ODYSEE OR BITCHUTE CHANNEL'S LISTING, diffed against what is held @@ -315,6 +337,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -330,6 +353,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -348,6 +372,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -357,6 +382,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "retry-bucket": { @@ -365,6 +391,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, "clean-audio-transcribed": { @@ -433,6 +460,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "custom", + network: true, needsMedia: false, needsText: true, }, @@ -442,6 +470,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, // Persist an explicit list of videos (controller/persistVideos.ts): one job @@ -453,6 +482,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "backup-saved-videos": { @@ -569,15 +599,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { }, // Social-post ingest for a `sourceKind: "social"` channel. Drainable (the // fetcher stops paging on the drain signal and keeps what it already has) and - // replayable. queueKeyForUrl() routes x.com / bsky.app to - // `platform:x.com` / `platform:bsky.app`, so per-platform serialization and - // the existing 429 backoff come free. + // replayable. downloadQueueKey() puts an X channel on `platform:twitter` + // (detectPlatform maps x.com → twitter), Bluesky on `platform:bluesky`, a + // forum thread on `platform:xenforo`: serialized per platform, and spaced by + // `pacing.jobGapSeconds` (jobs/queueGap.ts). The video downloads' 429 + // backoff (jobs/platformBackoff.ts) does NOT apply to post fetchers; an X + // challenge raises the X cookie alert instead, which refuses every X job + // until it is cleared (plans/pacing-guard.md). "fetch-posts": { kind: "fetch-posts", label: "Fetch posts", drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, }, // Forum thread pages the operator saved from a browser, imported into a // forum-thread channel (controller/importForumPages.ts). Offline — nothing is @@ -591,6 +626,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: false, }, // ONE post by its URL into a posts channel of its platform (release 27 S3b, // social/importPost.ts): one read through the channel's fetcher. On the @@ -603,6 +639,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, }, // ONE Wayback Machine capture of a page that is not a video into a Wayback // pages channel (release 37 S1, controller/importPage.ts): the raw body @@ -616,6 +653,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsText: true, }, // A Wayback pages channel's records re-derived from its stored captures @@ -628,6 +666,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: false, needsText: true, }, // Save Page Now (release 37 S5, controller/savePageNow.ts): ask the Wayback @@ -642,6 +681,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, }, // A screenshot and the attached media of specific archived posts (and the X // Article a post links to), into the channel's `posts-media/` @@ -656,6 +696,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, }, // A WAYBACK PAGES CHANNEL'S SCAN (release 37 S2, controller/waybackScan.ts): // the CDX listings of its targets into `wayback-scan.json`, no bodies, on @@ -669,6 +710,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: false, needsText: true, }, @@ -680,6 +722,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, }, // needsMedia: syncPaged does not merely refresh a playlist — it reads the // channel's data dir to decide what is already there and downloads into @@ -691,6 +734,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, // The metadata scan (ytdlp/metadataScan.ts). On the platform download queue, @@ -709,6 +753,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -728,6 +773,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -744,6 +790,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -760,6 +807,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: true, }, // A FILE MADE A NORMAL TRANSCRIBED ITEM (controller/importMedia.ts — `pnpm @@ -776,6 +824,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, // A LIVE STREAM RECORDED (controller/recordLive.ts — `pnpm ops record-live`, @@ -792,6 +841,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, // FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's @@ -826,6 +876,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -1061,6 +1112,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "transcribe-one": { @@ -1068,6 +1120,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, // ONE ARBITRARY FILE (or a window of it) through a local worker, for a quote @@ -1134,6 +1187,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, }, // fetch-copies (release 31, lane C): the WHOLE audio of gone videos from the // copies find-copy's scope mode found (controller/fetchCopies.ts), each into @@ -1148,6 +1202,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: true, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "bench-verdicts": { @@ -1211,6 +1266,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "custom", + network: true, needsMedia: true, }, "transcode-audio": { @@ -1225,6 +1281,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -1233,6 +1290,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -1241,6 +1299,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: false, queueKeyStrategy: "platform", + network: true, needsMedia: false, needsText: true, }, @@ -1251,6 +1310,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { drainable: false, replayable: true, queueKeyStrategy: "custom", + network: true, }, "clear-failed-transcriptions": { kind: "clear-failed-transcriptions", @@ -1412,3 +1472,16 @@ export function kindNeedsMedia(kind: string): boolean { export function kindNeedsText(kind: string): boolean { return JOB_KINDS[kind]?.needsText ?? false; } + +// Whether a kind sends requests to a platform (see JobKindMeta.network). +// Absent = false. +export function kindIsNetwork(kind: string): boolean { + return JOB_KINDS[kind]?.network ?? false; +} + +// Every kind on a platform queue, for the test that holds each to a decision. +export function platformKindIds(): string[] { + return Object.values(JOB_KINDS) + .filter((k) => k.queueKeyStrategy === "platform") + .map((k) => k.kind); +} diff --git a/common/jobs/networkGuard.test.ts b/common/jobs/networkGuard.test.ts @@ -0,0 +1,63 @@ +// The network guard's pure rules (plans/pacing-guard.md); the job funnel +// end to end is pacingGuard.test.ts. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/networkGuard.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { ageText, emptyQueueRefusal, xJarVerdict } from "./networkGuard"; + +const NOW = Date.parse("2026-10-23T03:00:00Z"); +const at = (msAgo: number) => new Date(NOW - msAgo).toISOString(); + +test("the empty queue is refused for a network kind only", () => { + assert.match(emptyQueueRefusal("fetch-posts", "") ?? "", /^Fetch posts sends requests to a platform/); + assert.match(emptyQueueRefusal("sync", "") ?? "", /never runs unqueued/); + assert.equal(emptyQueueRefusal("fetch-posts", "platform:twitter"), null); + assert.equal(emptyQueueRefusal("evict-clips", ""), null); + assert.equal(emptyQueueRefusal("auto-download", ""), null); +}); + +test("the fresh-jar rule (profile source)", () => { + const v = (ageMs: number, authed = true, max = 60) => + xJarVerdict({ + source: "profile", + status: { hasCookies: true, cookiesUpdatedAt: at(ageMs), looksAuthenticated: authed }, + maxAgeMinutes: max, + now: NOW, + }); + assert.deepEqual(v(59 * 60_000), { ok: true }); + assert.deepEqual(v(16 * 24 * 3600_000), { + ok: false, + message: + "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.", + }); + assert.match((v(61 * 60_000) as { message: string }).message, /61 min ago/); + assert.match((v(60_000, false) as { message: string }).message, /holds no login/); + // 0 turns the rule off. + assert.deepEqual(v(16 * 24 * 3600_000, true, 0), { ok: true }); + const none = xJarVerdict({ + source: "profile", + status: { hasCookies: false, looksAuthenticated: false }, + maxAgeMinutes: 60, + now: NOW, + }); + assert.match((none as { message: string }).message, /No X cookie jar/); +}); + +test("the browser source cannot be checked: proceed, and say so", () => { + const v = xJarVerdict({ + source: "browser", + status: { hasCookies: false, looksAuthenticated: false }, + maxAgeMinutes: 60, + now: NOW, + }); + assert.equal(v.ok, true); + assert.match((v as { note?: string }).note ?? "", /cannot be read here/); +}); + +test("ageText", () => { + assert.equal(ageText(45 * 60_000), "45 min"); + assert.equal(ageText(3 * 3600_000), "3 h"); + assert.equal(ageText(16 * 24 * 3600_000), "16 days"); +}); diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -0,0 +1,225 @@ +// THE NETWORK GUARD (plans/pacing-guard.md): what runManagedFunction asks of a +// job whose kind SENDS REQUESTS TO A PLATFORM (`network` in jobs/jobKinds.ts), +// at enqueue and again when its queue starts it. +// +// 1. NO UNPACED NETWORK JOB. A queue override of "" runs a job at once, +// beside everything, outside its platform's queue and gap: refused. +// 2. X ONLY WHILE NO X ALERT IS UP. A challenge or login wall from X raises +// the X cookie alert (lib/serviceCookies.ts); until Recheck or Dismiss +// clears it, every job aimed at X is refused before it asks anything. +// 3. X ONLY ON A FRESH JAR. With the "profile" login source, a job aimed at X +// starts only when the exported cookie jar was written within +// `social.x.maxCookieAgeMinutes` (default 60; 0 = off) and carries a login. +// A refresh is a human click on /settings — refreshXCookies loads +// x.com/home, itself a request to X — so nothing here refreshes it. With +// the "browser" source the age cannot be read: the job logs that and +// proceeds. +// +// Operator, 2026-10-23: "only start X downloads with a recent cookie refresh", +// "be very careful not to do that thing on any sort of site", "This should be +// enforced in Archilyzer, not just an AI standing rule". + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile } from "../lib/jsonFile-server"; +import { channelConfigSchema } from "../lib/channelConfigSchema"; +import { downloadQueueKey } from "../lib/queueKeys"; +import { getSettings, type SiteSettings } from "../lib/settings"; +import { resolveCookiePolicy } from "../lib/cookiePolicy"; +import { serviceFixText, X_SERVICE } from "../lib/serviceCookies"; +import { + configuredCookieBrowser, + noteServiceStoppedJob, + raisedServiceAlert, +} from "../lib/serviceCookies-server"; +import { readXSessionStatus, type XSessionStatus } from "../social/xSessionBroker"; +import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource"; +import { jobKindLabel, kindIsNetwork } from "./jobKinds"; +import { queueGapPlatform } from "./queueGap"; + +export type NetworkJobOpts = { + kind: string; + queueKey: string; + paths: Paths; + channelSlug?: string; +}; + +// ── 1. the empty queue ───────────────────────────────────────────────────── + +export function emptyQueueRefusal(kind: string, queueKey: string): string | null { + if (queueKey !== "" || !kindIsNetwork(kind)) return null; + return ( + `${jobKindLabel(kind)} sends requests to a platform, so it never runs unqueued: ` + + `the queue override "" (immediate) is refused. Leave the queue at its default ` + + `(the platform's queue, which spaces its jobs) or name one.` + ); +} + +// ── which platform a job asks ────────────────────────────────────────────── + +async function channelPlatform(paths: Paths, slug: string): Promise<string | null> { + const read = await readJsonFile(path.join(paths.channelsDir, slug, "config.json")); + if (!read.ok) return null; + const config = channelConfigSchema.parse(read.value); + return config ? queueGapPlatform(downloadQueueKey(config)) : null; +} + +// The platform a network job asks: its `platform:<p>` queue's, else its +// channel's (a job moved to a named queue still asks its channel's platform). +export async function networkJobPlatform(opts: NetworkJobOpts): Promise<string | null> { + const fromQueue = queueGapPlatform(opts.queueKey); + if (fromQueue) return fromQueue; + if (!opts.channelSlug) return null; + try { + return await channelPlatform(opts.paths, opts.channelSlug); + } catch { + return null; + } +} + +// ── 2 + 3. X ─────────────────────────────────────────────────────────────── + +// "16 days", "3 h", "45 min". +export function ageText(ms: number): string { + const min = Math.max(0, Math.floor(ms / 60_000)); + if (min < 120) return `${min} min`; + const h = Math.floor(min / 60); + if (h < 48) return `${h} h`; + return `${Math.floor(h / 24)} days`; +} + +export type XJarVerdict = + | { ok: true; note?: string } + | { ok: false; message: string }; + +// The fresh-jar rule, pure: the source in use, the profile jar's status, the +// limit (minutes; 0 = off) and the time. +export function xJarVerdict(input: { + source: XCookieSource; + status: Pick<XSessionStatus, "hasCookies" | "cookiesUpdatedAt" | "looksAuthenticated">; + maxAgeMinutes: number; + now: number; +}): XJarVerdict { + if (input.source === "browser") { + return { + ok: true, + note: + "X login: the browser's (cookiesFromBrowser) — how fresh its cookies are cannot be read here, " + + "so social.x.maxCookieAgeMinutes is not checked; proceeding.", + }; + } + if (input.maxAgeMinutes <= 0) return { ok: true }; + const { status } = input; + if (!status.hasCookies || !status.cookiesUpdatedAt) { + return { + ok: false, + message: "No X cookie jar has been exported: press Connect X account on /settings, then fetch again.", + }; + } + if (!status.looksAuthenticated) { + return { + ok: false, + message: + "The X cookie jar holds no login (no auth_token): press Connect X account on /settings, then fetch again.", + }; + } + const age = input.now - Date.parse(status.cookiesUpdatedAt); + if (!(age <= input.maxAgeMinutes * 60_000)) { + return { + ok: false, + message: + `X cookies were last refreshed ${ageText(age)} ago (limit ${input.maxAgeMinutes} min): ` + + `press Refresh cookies (or Connect X account) on /settings, then fetch again.`, + }; + } + return { ok: true }; +} + +// TEST-ONLY: E2E_X_MAX_COOKIE_AGE_MINUTES replaces the BUILT-IN limit (the e2e +// server sets 0, so its fake X fetches need no jar); a limit a spec writes into +// settings.json still applies. Unset everywhere but the e2e test server. +function e2eDefaultMaxAge(): number | undefined { + const raw = process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; + if (raw === undefined || raw === "") return undefined; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined; +} + +function settingsNow(): SiteSettings | null { + try { + return getSettings(); + } catch { + return null; + } +} + +async function channelCookieSpec(paths: Paths, slug: string | undefined, settings: SiteSettings): Promise<string | undefined> { + let config = null; + if (slug) { + const read = await readJsonFile(path.join(paths.channelsDir, slug, "config.json")).catch(() => null); + config = read?.ok ? channelConfigSchema.parse(read.value) : null; + } + return resolveCookiePolicy(settings, config).cookies; +} + +export type XGuardResult = + | { ok: true; note?: string } + | { ok: false; message: string; alert: boolean }; + +export async function xJobGuard(opts: { + paths: Paths; + channelSlug?: string; + now?: number; +}): Promise<XGuardResult> { + const now = opts.now ?? Date.now(); + const alert = await raisedServiceAlert(opts.paths, X_SERVICE); + if (alert) { + const at = (alert.raisedAt ?? alert.since).slice(11, 16); + return { + ok: false, + alert: true, + message: + `X answered with a challenge at ${at} UTC (${alert.evidence.line}) and its cookie alert is up, ` + + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, + }; + } + const settings = settingsNow(); + if (!settings) return { ok: true }; + const status = await readXSessionStatus(opts.paths); + const resolved = resolveXCookieSource({ + stored: settings.social?.x?.cookieSource, + browserSpec: await channelCookieSpec(opts.paths, opts.channelSlug, settings), + profileConnected: status.looksAuthenticated, + }); + const verdict = xJarVerdict({ + source: resolved.source, + status, + maxAgeMinutes: settings.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings.social?.x), + now, + }); + return verdict.ok ? verdict : { ok: false, message: verdict.message, alert: false }; +} + +// ── the one entry point ──────────────────────────────────────────────────── + +export type NetworkGuardResult = + | { ok: true; notes: string[] } + | { ok: false; error: string }; + +// Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the X +// alert is recorded against the alert, so "Re-run stopped jobs" offers it). +export async function guardNetworkJob( + opts: NetworkJobOpts & { job?: { id: string } }, +): Promise<NetworkGuardResult> { + if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; + const empty = emptyQueueRefusal(opts.kind, opts.queueKey); + if (empty) return { ok: false, error: empty }; + const platform = await networkJobPlatform(opts); + if (platform !== "twitter") return { ok: true, notes: [] }; + const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug }); + if (x.ok) return { ok: true, notes: x.note ? [x.note] : [] }; + if (x.alert && opts.job) { + await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); + } + return { ok: false, error: x.message }; +} diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -0,0 +1,246 @@ +// THE NIGHT OF 2026-10-23, AGAIN (plans/pacing-guard.md): an agent queued +// fetch-posts for 13 X accounts in one loop; they ran ~0.6 s apart on a +// 16-day-old cookie jar, gallery-dl printed `[twitter][warning] Cloudflare +// challenge`, exited 0, read nothing, and every job ended `done`. +// +// The same 13 jobs through the real job funnel (runManagedFunction), the real +// fetch controller and the real gallery-dl fetcher, against a fake gallery-dl: +// - a challenge in job 1 fails job 1, raises the X alert, and refuses jobs +// 2–13 when they reach the head (none runs gallery-dl); +// - with no challenge they start ≥ 5 min apart (a fake clock); +// - a stale jar refuses at enqueue and at start; "" is refused. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/pacingGuard.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "pacing-guard-")); +const BIN = path.join(ROOT, "fake-gallery-dl.mjs"); +const RUNS = path.join(ROOT, "runs.log"); +// getPaths() is cached at its first call: set before any import that calls it. +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.GALLERY_DL_BIN = BIN; +process.env.FAKE_RUNS = RUNS; +delete process.env.E2E_JOB_GAP_SECONDS; + +// FAKE_MODE=challenge: X's answer that night — a warning, exit 0, no posts. +await writeFile( + BIN, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +appendFileSync(process.env.FAKE_RUNS, process.argv.slice(2).join(" ") + "\\n"); +if (process.env.FAKE_MODE === "challenge") { + process.stderr.write("[twitter][warning] Cloudflare challenge\\n"); +} +process.exit(0); +`, +); +await chmod(BIN, 0o755); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile" } } })); + +const transcripts = path.join(ROOT, "transcripts"); +const SLUGS = Array.from({ length: 13 }, (_, i) => `x-acct-${String(i + 1).padStart(2, "0")}`); +for (const slug of SLUGS) { + const dir = path.join(transcripts, "channels", slug); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + postFetcher: "x-gallery-dl", + socialHandle: slug.replace(/-/g, ""), + platform: "twitter", + name: slug, + url: `https://x.com/${slug.replace(/-/g, "")}`, + }), + ); +} + +const JAR = path.join(transcripts, ".x-session", "cookies.txt"); +async function writeJar(ageMs: number, authed = true): Promise<void> { + await mkdir(path.dirname(JAR), { recursive: true }); + await mkdir(path.join(transcripts, ".x-session", "profile"), { recursive: true }); + await writeFile( + JAR, + `# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\t${authed ? "auth_token" : "guest_id"}\tv\n`, + ); + const t = new Date(Date.now() - ageMs); + await utimes(JAR, t, t); +} + +const { getPaths } = await import("../lib/paths"); +const { runManagedFunction } = await import("./streamCommand"); +const { fetchPosts } = await import("../controller/fetchPosts"); +const { getSettings } = await import("../lib/settings"); +const { setQueueGapClock, clearQueueGaps } = await import("./queueGap"); +const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server"); +await import("../social/xGalleryDlFetcher"); + +const paths = getPaths(); + +// A fake clock: a gap's sleep advances it at once, and every start is stamped. +let fakeNow = Date.parse("2026-10-23T03:00:00Z"); +setQueueGapClock({ + now: () => fakeNow, + sleep: async (ms) => { + fakeNow += ms; + }, +}); + +// One fetch-posts job, as fetchPostsAction makes it (platform:twitter). +async function fetchJob(slug: string, starts: Map<string, number>, queueKey = "platform:twitter") { + return runManagedFunction({ + kind: "fetch-posts", + queueKey, + paths, + channelSlug: slug, + fn: async (onLog, signal) => { + starts.set(slug, fakeNow); + const result = await fetchPosts({ paths, slug, settings: getSettings(), onLog, signal }); + if (!result.ok) throw new Error(result.error ?? "Post fetch failed"); + // A run takes a few seconds of the clock. + fakeNow += 3_000; + }, + }); +} + +async function runCount(): Promise<number> { + try { + return (await readFile(RUNS, "utf8")).split("\n").filter(Boolean).length; + } catch { + return 0; + } +} + +async function reset(): Promise<void> { + clearQueueGaps(); + await rm(RUNS, { force: true }); + await rm(serviceCookiesFile(paths), { force: true }); + await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); +} + +async function readLog(jobId: string): Promise<string> { + return readFile(path.join(paths.jobsDir, `${jobId}.log`), "utf8"); +} + +test("13 X fetches, job 1 meets a Cloudflare challenge: job 1 fails, the X alert is up, jobs 2–13 are refused unrun", async () => { + await reset(); + await writeJar(5 * 60_000); + process.env.FAKE_MODE = "challenge"; + try { + const starts = new Map<string, number>(); + const started = []; + for (const slug of SLUGS) { + const res = await fetchJob(slug, starts); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (res.ok) started.push(res); + } + const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); + assert.deepEqual( + ends.map((e) => e?.status), + ["failed", ...Array(12).fill("failed")], + ); + // gallery-dl ran ONCE: only job 1 asked X. + assert.equal(await runCount(), 1); + assert.deepEqual([...starts.keys()], [SLUGS[0]]); + const first = await readLog(ends[0]!.jobId); + assert.match(first, /Cloudflare challenge/); + assert.match(first, /challenge or a login wall/); + const second = await readLog(ends[1]!.jobId); + assert.match(second, /X answered with a challenge at \d\d:\d\d UTC .*its cookie alert is up, so no X job starts/); + const state = await readServiceCookieState(paths); + const x = state.services.x; + assert.ok(x?.raisedAt && !x.clearedAt, "the X alert is raised"); + assert.equal(x.kind, "challenge"); + // The refused jobs are on the alert, for "Re-run stopped jobs". + assert.equal(x.jobs.length, 13); + // And a fourteenth is refused at enqueue: no job at all. + const again = await fetchJob(SLUGS[0], new Map()); + assert.equal(again.ok, false); + assert.match(again.ok ? "" : again.error, /cookie alert is up/); + } finally { + delete process.env.FAKE_MODE; + } +}); + +test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter (300 s) apart", async () => { + await reset(); + await writeJar(5 * 60_000); + const starts = new Map<string, number>(); + const started = []; + for (const slug of SLUGS) { + const res = await fetchJob(slug, starts); + assert.equal(res.ok, true, res.ok ? "" : res.error); + if (res.ok) started.push(res); + } + const ends = await Promise.all(started.map((r) => (r.ok ? r.done : null))); + assert.deepEqual(ends.map((e) => e?.status), Array(13).fill("done")); + assert.equal(await runCount(), 13); + const at = SLUGS.map((s) => starts.get(s)!); + for (let i = 1; i < at.length; i++) { + assert.ok(at[i] - at[i - 1] >= 300_000, `job ${i + 1} started ${(at[i] - at[i - 1]) / 1000}s after job ${i}`); + } + // The waiting job's log says why it waited. + const log2 = await readLog(ends[1]!.jobId); + assert.match(log2, /waiting 5m00s: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); + // The end survives a restart: the file names the queue. + const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); + assert.equal(typeof file.ends["platform:twitter"], "number"); +}); + +test("a stale jar is refused at enqueue, and at the start of a job queued while it was fresh", async () => { + await reset(); + await writeJar(16 * 24 * 60 * 60_000); + const res = await fetchJob(SLUGS[0], new Map()); + assert.equal(res.ok, false); + assert.match( + res.ok ? "" : res.error, + /^X cookies were last refreshed 16 days ago \(limit 60 min\): press Refresh cookies \(or Connect X account\) on \/settings, then fetch again\.$/, + ); + + // Fresh at enqueue; stale by the time the queue reaches it. + await writeJar(5 * 60_000); + const starts = new Map<string, number>(); + // Job 1 holds the queue until the jar has gone stale. + let release!: () => void; + const held = new Promise<void>((r) => (release = r)); + const a = await runManagedFunction({ + kind: "fetch-posts", + queueKey: "platform:twitter", + paths, + channelSlug: SLUGS[0], + fn: () => held, + }); + const b = await fetchJob(SLUGS[1], starts); + assert.ok(a.ok && b.ok); + await writeJar(2 * 60 * 60_000); + release(); + await a.done; + const bDone = await b.done; + assert.equal(bDone.status, "failed"); + assert.equal(starts.has(SLUGS[1]), false, "job 2 never reached gallery-dl"); + assert.match(await readLog(bDone.jobId), /X cookies were last refreshed 2 h ago \(limit 60 min\)/); + + // A jar with no login. + await writeJar(60_000, false); + const c = await fetchJob(SLUGS[2], new Map()); + assert.match(c.ok ? "" : c.error, /holds no login/); +}); + +test("a network job is never run unqueued: the override \"\" is refused", async () => { + await reset(); + await writeJar(60_000); + const res = await fetchJob(SLUGS[0], new Map(), ""); + assert.equal(res.ok, false); + assert.match(res.ok ? "" : res.error, /never runs unqueued: the queue override "" \(immediate\) is refused/); + // A kind that asks no platform still may. + const local = await runManagedFunction({ kind: "import-forum-pages", queueKey: "", paths, fn: async () => {} }); + assert.equal(local.ok, true); + if (local.ok) assert.equal((await local.done).status, "done"); +}); diff --git a/common/jobs/platformBackoff.test.ts b/common/jobs/platformBackoff.test.ts @@ -200,9 +200,12 @@ test("mergeBackoffEntry takes the max of until and of fails separately", () => { // ── release 17, slice RL ───────────────────────────────────────────────────── test("PACING_DEFAULTS are the settings schema's defaults", () => { - assert.deepEqual({ ...PACING_DEFAULTS }, sanitizePacing({})); + // jobGapSeconds (plans/pacing-guard.md) stores only the keys set; its + // built-ins are jobGapSecondsFor's, never written. + assert.deepEqual({ ...PACING_DEFAULTS, jobGapSeconds: {} }, sanitizePacing({})); assert.deepEqual(sanitizePacing({ sleepRequestsCapSeconds: 999, holdProbeMinutes: 0 }), { ...PACING_DEFAULTS, + jobGapSeconds: {}, sleepRequestsCapSeconds: 120, holdProbeMinutes: 1, }); diff --git a/common/jobs/queueGap.test.ts b/common/jobs/queueGap.test.ts @@ -0,0 +1,122 @@ +// The gap between two jobs on one platform queue (plans/pacing-guard.md). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/queueGap.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + clearQueueGaps, + gapReason, + lastQueueEnd, + noteQueueJobEnd, + queueGapFor, + queueGapLine, + queueGapPlatform, + queueGapWait, + waitForQueueGap, + waitText, +} from "./queueGap"; +import { jobGapSecondsFor, sanitizePacing } from "../lib/settingsSchema"; + +async function jobsDir() { + const root = await mkdtemp(path.join(os.tmpdir(), "queue-gap-")); + return { jobsDir: path.join(root, ".jobs") }; +} + +test("only platform: queues have a gap", () => { + assert.equal(queueGapPlatform("platform:twitter"), "twitter"); + assert.equal(queueGapPlatform("platform:megaphone.fm"), "megaphone.fm"); + assert.equal(queueGapPlatform("clips:youtube"), null); + assert.equal(queueGapPlatform("transcription"), null); + assert.equal(queueGapPlatform(""), null); +}); + +test("the gap: the operator's per platform, else the built-in per platform, else default", () => { + delete process.env.E2E_JOB_GAP_SECONDS; + assert.deepEqual(jobGapSecondsFor(undefined, "twitter"), { seconds: 300, key: "twitter" }); + assert.deepEqual(jobGapSecondsFor(undefined, "xenforo"), { seconds: 60, key: "xenforo" }); + assert.deepEqual(jobGapSecondsFor(undefined, "bluesky"), { seconds: 60, key: "bluesky" }); + assert.deepEqual(jobGapSecondsFor(undefined, "youtube"), { seconds: 20, key: "default" }); + const pacing = sanitizePacing({ jobGapSeconds: { twitter: 600, default: 45, "Bad Key": 3, youtube: -1 } }); + assert.deepEqual(pacing.jobGapSeconds, { twitter: 600, default: 45 }); + assert.deepEqual(jobGapSecondsFor(pacing, "twitter"), { seconds: 600, key: "twitter" }); + // A platform with a built-in keeps it over the operator's default. + assert.deepEqual(jobGapSecondsFor(pacing, "xenforo"), { seconds: 60, key: "xenforo" }); + assert.deepEqual(jobGapSecondsFor(pacing, "megaphone.fm"), { seconds: 45, key: "default" }); + assert.deepEqual(sanitizePacing({ jobGapSeconds: { twitter: 10 ** 9 } }).jobGapSeconds, { twitter: 86400 }); +}); + +test("E2E_JOB_GAP_SECONDS replaces the built-ins only; a set value still applies", () => { + process.env.E2E_JOB_GAP_SECONDS = "0"; + try { + assert.equal(queueGapFor(undefined, "twitter").seconds, 0); + assert.equal(queueGapFor({ jobGapSeconds: { twitter: 3 } }, "twitter").seconds, 3); + } finally { + delete process.env.E2E_JOB_GAP_SECONDS; + } +}); + +test("the sentence", () => { + assert.equal( + gapReason("twitter", { seconds: 300, key: "twitter" }), + "X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)", + ); + assert.equal(waitText(252_000), "4m12s"); + assert.equal(waitText(45_000), "45s"); + assert.equal( + queueGapLine({ until: 0, remainingMs: 252_000, reason: "X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)" }), + "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)", + ); +}); + +test("no end yet: no wait; an end: wait out the rest; the end is persisted and read back after a restart", async () => { + delete process.env.E2E_JOB_GAP_SECONDS; + const paths = await jobsDir(); + const q = "platform:twitter"; + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_000_000 }), null); + await noteQueueJobEnd(paths, q, 1_000_000); + const w = await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_048_000 }); + assert.equal(w?.remainingMs, 252_000); + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_300_000 }), null); + const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); + assert.equal(file.ends[q], 1_000_000); + clearQueueGaps(); // the restart + assert.equal(await lastQueueEnd(paths, q), 1_000_000); + // Not a platform queue: nothing noted. + await noteQueueJobEnd(paths, "transcription", 5); + assert.equal(await lastQueueEnd(paths, "transcription"), undefined); +}); + +test("waitForQueueGap waits, logs once per wait, tells the row, clears it", async () => { + const paths = await jobsDir(); + const q = "platform:xenforo"; + let now = 10_000_000; + await noteQueueJobEnd(paths, q, now); + now += 15_000; + const lines: string[] = []; + const seen: (string | null)[] = []; + const waited = await waitForQueueGap({ + paths, + queueKey: q, + pacing: () => undefined, + onLog: (l) => lines.push(l), + onWait: (w) => seen.push(w ? w.reason : null), + clock: { now: () => now, sleep: async (ms) => void (now += ms) }, + }); + assert.equal(waited, 45_000); + assert.deepEqual(lines, ["waiting 45s: Forum jobs are spaced 1 min apart (pacing.jobGapSeconds.xenforo)"]); + assert.deepEqual(seen, ["Forum jobs are spaced 1 min apart (pacing.jobGapSeconds.xenforo)", null]); +}); + +test("waitForQueueGap rejects on abort", async () => { + const paths = await jobsDir(); + const q = "platform:twitter"; + await noteQueueJobEnd(paths, q, Date.now()); + const ac = new AbortController(); + const p = waitForQueueGap({ paths, queueKey: q, pacing: () => undefined, signal: ac.signal }); + setTimeout(() => ac.abort(), 10); + await assert.rejects(p, { name: "AbortError" }); +}); diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -0,0 +1,281 @@ +// THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE (plans/pacing-guard.md). +// +// The registry runs one job per queueKey at a time and starts the next the +// moment one ends. On 2026-10-23 an agent queued fetch-posts for 13 X +// accounts in one loop: they ran ~0.6 s apart, X answered with a Cloudflare +// challenge, and the operator had to pass a human verification on the +// account. Operator: "be very careful not to do that thing on any sort of +// site" — "This should be enforced in Archilyzer, not just an AI standing +// rule". +// +// So a NETWORK job (a kind declaring `network`, jobs/jobKinds.ts) on a +// `platform:<p>` queue does not start until `pacing.jobGapSeconds[p]` (else +// the built-in for p, else `default`) seconds after the previous network job +// on that queue ENDED. Only jobs that got as far as their work count as an +// end: a job refused at its start (a stale X jar, a raised alert) asked +// nothing, so the next one is not made to wait for it. +// +// The last end per queue is kept in memory and in `<jobsDir>/queue-gaps.json`, +// so an editor restart is not a free pass (the scheduler's first tick after a +// boot would otherwise ask X at once). +// +// Clip windows (`clips:<p>`) keep their own 30–45 s gap (jobs/platformGap.ts) +// and are not on a `platform:` queue; the auto-download lane's units ride the +// platform queues and wait the larger of the lane's own gap +// (sleepBetweenDownloadsSeconds + pace) and this one. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import { spanText, waitText } from "./queueGapText"; +import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; +import type { PacingSettingsBlock } from "../lib/settingsSchema"; + +export { spanText, waitText }; + +export const QUEUE_GAPS_FILE = "queue-gaps.json"; + +export function queueGapsFile(paths: Pick<Paths, "jobsDir">): string { + return path.join(paths.jobsDir, QUEUE_GAPS_FILE); +} + +// `platform:twitter` → "twitter"; any other queue has no gap. +export function queueGapPlatform(queueKey: string): string | null { + const m = /^platform:(.+)$/.exec(queueKey); + return m ? m[1] : null; +} + +// TEST-ONLY: E2E_JOB_GAP_SECONDS replaces every BUILT-IN gap (the e2e server +// sets 0, so its specs do not wait five minutes between two fake X fetches). +// A gap a spec writes into settings.json still applies. Unset everywhere but +// the e2e test server. +function builtInGaps(): Readonly<Record<string, number>> { + const raw = process.env.E2E_JOB_GAP_SECONDS; + if (raw === undefined || raw === "") return JOB_GAP_DEFAULT_SECONDS; + const n = Number(raw); + if (!Number.isFinite(n) || n < 0) return JOB_GAP_DEFAULT_SECONDS; + return Object.fromEntries(Object.keys(JOB_GAP_DEFAULT_SECONDS).map((k) => [k, n])); +} + +export type QueueGap = { seconds: number; key: string }; + +export function queueGapFor( + pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined, + platform: string, +): QueueGap { + return jobGapSecondsFor(pacing, platform, builtInGaps()); +} + +const PLATFORM_NAMES: Record<string, string> = { + twitter: "X", + bluesky: "Bluesky", + xenforo: "Forum", + youtube: "YouTube", + rumble: "Rumble", + odysee: "Odysee", + twitch: "Twitch", + kick: "Kick", + bitchute: "BitChute", + archiveorg: "archive.org", +}; + +export function platformDisplayName(platform: string): string { + return PLATFORM_NAMES[platform] ?? platform; +} + +// Why a job waits: "X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +export function gapReason(platform: string, gap: QueueGap): string { + return ( + `${platformDisplayName(platform)} jobs are spaced ${spanText(gap.seconds)} apart ` + + `(pacing.jobGapSeconds.${gap.key})` + ); +} + +// ── the last end per queue ───────────────────────────────────────────────── + +type GapStore = { + ends: Map<string, number>; + loaded?: Promise<void>; + writing: Promise<void>; +}; + +declare global { + // eslint-disable-next-line no-var + var __yttQueueGaps__: Map<string, GapStore> | undefined; +} + +function storeFor(paths: Pick<Paths, "jobsDir">): GapStore { + const all = (globalThis.__yttQueueGaps__ ??= new Map()); + let st = all.get(paths.jobsDir); + if (!st) { + st = { ends: new Map(), writing: Promise.resolve() }; + all.set(paths.jobsDir, st); + } + return st; +} + +async function loaded(paths: Pick<Paths, "jobsDir">): Promise<GapStore> { + const st = storeFor(paths); + st.loaded ??= (async () => { + const read = await readJsonFile(queueGapsFile(paths)); + const raw = read.ok ? (read.value as { ends?: unknown } | null) : null; + const ends = raw && typeof raw === "object" && raw.ends && typeof raw.ends === "object" + ? (raw.ends as Record<string, unknown>) + : {}; + for (const [k, v] of Object.entries(ends)) { + if (typeof v !== "number" || !Number.isFinite(v)) continue; + // A later end already noted in memory wins. + if ((st.ends.get(k) ?? 0) < v) st.ends.set(k, v); + } + })(); + await st.loaded; + return st; +} + +// When the last network job on `queueKey` ended (epoch ms), if known. +export async function lastQueueEnd( + paths: Pick<Paths, "jobsDir">, + queueKey: string, +): Promise<number | undefined> { + return (await loaded(paths)).ends.get(queueKey); +} + +// A network job on `queueKey` ended at `at`. Kept in memory at once; the file +// is rewritten in the background (best effort: a failed write costs only the +// restart-safety of this one end). +export function noteQueueJobEnd( + paths: Pick<Paths, "jobsDir">, + queueKey: string, + at: number = Date.now(), +): Promise<void> { + if (!queueGapPlatform(queueKey)) return Promise.resolve(); + const st = storeFor(paths); + if ((st.ends.get(queueKey) ?? 0) < at) st.ends.set(queueKey, at); + st.writing = st.writing + .then(async () => { + await loaded(paths); + await writeJsonAtomic( + queueGapsFile(paths), + { version: 1, ends: Object.fromEntries(st.ends) }, + { mkdir: true }, + ); + }) + .catch(() => {}); + return st.writing; +} + +export function clearQueueGaps(): void { + globalThis.__yttQueueGaps__?.clear(); +} + +// ── the wait ─────────────────────────────────────────────────────────────── + +export type QueueGapClock = { + now: () => number; + sleep: (ms: number, signal?: AbortSignal) => Promise<void>; +}; + +const realClock: QueueGapClock = { now: () => Date.now(), sleep: abortableSleep }; + +export type QueueGapWait = { + // Epoch ms the job may start at. + until: number; + remainingMs: number; + reason: string; +}; + +// How long a network job on `queueKey` must still wait, or null for none. +export async function queueGapWait(opts: { + paths: Pick<Paths, "jobsDir">; + queueKey: string; + pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + now: number; +}): Promise<QueueGapWait | null> { + const platform = queueGapPlatform(opts.queueKey); + if (!platform) return null; + const gap = queueGapFor(opts.pacing, platform); + if (gap.seconds <= 0) return null; + const last = await lastQueueEnd(opts.paths, opts.queueKey); + if (last === undefined) return null; + const until = last + gap.seconds * 1000; + if (until <= opts.now) return null; + return { until, remainingMs: until - opts.now, reason: gapReason(platform, gap) }; +} + +// The line a waiting job's log carries: +// "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +export function queueGapLine(w: QueueGapWait): string { + return `waiting ${waitText(w.remainingMs)}: ${w.reason}`; +} + +// Wait out the gap — re-read after each wait (the operator may change the +// setting while a job waits) — logging once per wait, telling `onWait` what it +// waits for (the /jobs row shows it), and `onWait(null)` when done. Rejects +// with an AbortError when `signal` aborts. Answers the ms waited. +export async function waitForQueueGap(opts: { + paths: Pick<Paths, "jobsDir">; + queueKey: string; + pacing: () => Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + signal?: AbortSignal; + onLog?: (line: string) => void; + onWait?: (wait: QueueGapWait | null) => void; + clock?: QueueGapClock; +}): Promise<number> { + const clock = opts.clock ?? queueGapClock(); + let waited = 0; + try { + for (;;) { + if (opts.signal?.aborted) throw abortError(); + let pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + try { + pacing = opts.pacing(); + } catch { + pacing = undefined; + } + const w = await queueGapWait({ paths: opts.paths, queueKey: opts.queueKey, pacing, now: clock.now() }); + if (!w) return waited; + opts.onWait?.(w); + opts.onLog?.(queueGapLine(w)); + await clock.sleep(w.remainingMs, opts.signal); + waited += w.remainingMs; + } + } finally { + opts.onWait?.(null); + } +} + +// TEST-ONLY: the clock runManagedFunction's wait uses (a fake one makes "≥ 5 +// min apart" checkable in milliseconds). Reset with setQueueGapClock(null). +declare global { + // eslint-disable-next-line no-var + var __yttQueueGapClock__: QueueGapClock | undefined; +} + +export function setQueueGapClock(clock: QueueGapClock | null): void { + globalThis.__yttQueueGapClock__ = clock ?? undefined; +} + +export function queueGapClock(): QueueGapClock { + return globalThis.__yttQueueGapClock__ ?? realClock; +} + +function abortError(): Error { + const err = new Error("aborted while waiting for the queue gap"); + err.name = "AbortError"; + return err; +} + +function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve, reject) => { + if (signal?.aborted) return reject(abortError()); + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(abortError()); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} diff --git a/common/jobs/queueGapText.ts b/common/jobs/queueGapText.ts @@ -0,0 +1,27 @@ +// The queue gap's words (jobs/queueGap.ts), client-safe: no node imports, so +// the /jobs row can count a waiting job down. + +// "5 min", "20 s", "1 h", "1 h 30 min". +export function spanText(seconds: number): string { + if (seconds < 60) return `${seconds} s`; + if (seconds < 3600) { + const m = Math.floor(seconds / 60); + const s = seconds % 60; + return s ? `${m} min ${s} s` : `${m} min`; + } + const h = Math.floor(seconds / 3600); + const m = Math.round((seconds % 3600) / 60); + return m ? `${h} h ${m} min` : `${h} h`; +} + +// "4m12s", "45s", "1h02m". +export function waitText(ms: number): string { + const total = Math.max(0, Math.ceil(ms / 1000)); + const h = Math.floor(total / 3600); + const m = Math.floor((total % 3600) / 60); + const s = total % 60; + if (h) return `${h}h${String(m).padStart(2, "0")}m`; + if (m) return `${m}m${String(s).padStart(2, "0")}s`; + return `${s}s`; +} + diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -152,6 +152,13 @@ export type JobRecord = { // time from — a slow scan at 10 videos/min that holds a slot for an hour with // no in-flight tasks is still moving (release 9, B4a). progressAt?: number; + // THE QUEUE GAP THIS JOB IS WAITING OUT (jobs/queueGap.ts): set while a + // network job its queue has started waits `pacing.jobGapSeconds` after the + // previous one ended — the epoch ms it may begin at and why ("X jobs are + // spaced 5 min apart (pacing.jobGapSeconds.twitter)"). Cleared when it + // begins. The /jobs row draws "waiting 4m12s: …" from it. + pacedUntil?: number; + pacedReason?: string; }; // Store a progress snapshot on the record, stamping `progressAt` only when the diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -20,7 +20,10 @@ import { import { writeJobMeta } from "./jobMeta"; import { maybePruneJobLogs } from "./listJobs"; import type { JobSpec } from "./jobSpec"; -import { kindNeedsMedia, kindNeedsText } from "./jobKinds"; +import { kindIsNetwork, kindNeedsMedia, kindNeedsText } from "./jobKinds"; +import { guardNetworkJob } from "./networkGuard"; +import { noteQueueJobEnd, queueGapClock, waitForQueueGap } from "./queueGap"; +import { getSettings } from "../lib/settings"; import { assertChannelMediaReachable, assertChannelTextReadable, @@ -76,6 +79,12 @@ type CommonOpts = { // queued background work without interrupting a running one. The auto-download // runner marks its per-video units background so a clicked Sync preempts them. background?: boolean; + // THIS job asks no platform, though its kind may (a fetch-chat whose replay + // is already on disk only normalizes it). `false` skips the network guard + // and the queue gap (plans/pacing-guard.md) and leaves no end for the next + // job's gap; absent, the kind decides (`network` in jobs/jobKinds.ts). Only + // ever `false`: a caller cannot make a job network that its kind is not. + network?: false; }; export type RunManagedCommandOpts = CommonOpts & { @@ -379,6 +388,11 @@ export async function runManagedFunction( ): Promise<StreamActionResult> { const refusal = await refuseForUnreachableMedia(opts); if (refusal) return { ok: false, error: refusal }; + // THE NETWORK GUARD (jobs/networkGuard.ts, plans/pacing-guard.md): a job + // that asks a platform never runs unqueued, and one aimed at X needs a fresh + // cookie jar and no raised X alert. Asked here and again at the start. + const network = opts.network === false ? null : await guardNetworkJob(opts); + if (network && !network.ok) return { ok: false, error: network.error }; const registry = getRegistry(); await ensureJobsDir(opts.paths); const { id, logPath, record } = makeJob( @@ -457,6 +471,7 @@ export async function runManagedFunction( // THE JOB'S ASYNC CONTEXT (lib/jobContext.ts): code under `fn` — the one // yt-dlp runner, a forum fetch — reads which job it runs in, so a cookie // refresh alert can name the job it stopped and write into its log. + let reachedWork = false; const jobCtx: JobContext = { jobId: id, kind: opts.kind, @@ -464,13 +479,58 @@ export async function runManagedFunction( onLog, staleServices: new Set<string>(), }; + // A NETWORK JOB (jobs/jobKinds.ts `network`) is guarded again at its + // start — an X job queued behind a challenge is refused here, not run — + // then waits its platform queue's gap after the previous network job + // there ended (jobs/queueGap.ts), then is guarded once more: a jar can + // go stale during a five-minute wait. Only a job that reached its work + // counts as an end for the next one's gap. + const network = opts.network !== false && kindIsNetwork(opts.kind); + const guard = async () => { + const res = await guardNetworkJob({ ...opts, job: { id } }); + if (!res.ok) throw new Error(res.error); + return res.notes; + }; const run = async () => { const refusal = await refuseForUnreachableMedia(opts); if (refusal) throw new Error(refusal); + if (network) { + await guard(); + const waitAbort = AbortSignal.any([abort.signal, drain.signal]); + try { + await waitForQueueGap({ + paths: opts.paths, + queueKey: opts.queueKey, + pacing: () => getSettings().pacing, + signal: waitAbort, + onLog, + onWait: (w) => { + record.pacedUntil = w?.until; + record.pacedReason = w?.reason; + }, + clock: queueGapClock(), + }); + } catch (err) { + if (!abort.signal.aborted && drain.signal.aborted) { + onLog("Drained while waiting for the queue gap; nothing was asked."); + return; + } + throw err; + } + for (const note of await guard()) onLog(note); + reachedWork = true; + } await runInJobContext(jobCtx, () => opts.fn(onLog, abort.signal, setProgress, ctx)); }; + // The end the next network job on this queue is spaced from, noted + // BEFORE finalize promotes that job (noteQueueJobEnd sets the in-memory + // end synchronously). + const noteEnd = () => { + if (reachedWork) void noteQueueJobEnd(opts.paths, opts.queueKey, queueGapClock().now()); + }; run() .then(() => { + noteEnd(); if (record.status === "cancelled") { registry.finalize(id, "cancelled"); return; @@ -478,6 +538,7 @@ export async function runManagedFunction( registry.finalize(id, "done"); }) .catch((err) => { + noteEnd(); if (record.status === "cancelled") { registry.finalize(id, "cancelled"); return; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -233,6 +233,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." }, { name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, + { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, + { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, { name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index, Save Page Now) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." }, diff --git a/common/lib/jobGap.ts b/common/lib/jobGap.ts @@ -0,0 +1,43 @@ +// THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE — `pacing.jobGapSeconds` +// (plans/pacing-guard.md). Pure and client-safe: the settings schema +// sanitizes with it, the job funnel (jobs/queueGap.ts) waits by it, and the +// /settings form shows the gaps in force. + +// The built-in gaps: every platform queue waits `default` seconds after the +// previous network job on it ended; X five minutes, a forum and Bluesky one. +export const JOB_GAP_DEFAULT_SECONDS: Readonly<Record<string, number>> = Object.freeze({ + default: 20, + twitter: 300, + xenforo: 60, + bluesky: 60, +}); +export const JOB_GAP_MAX_SECONDS = 24 * 60 * 60; + +export function sanitizeJobGapSeconds(v: unknown): Partial<Record<string, number>> { + const out: Partial<Record<string, number>> = {}; + if (!v || typeof v !== "object" || Array.isArray(v)) return out; + for (const [k, raw] of Object.entries(v as Record<string, unknown>)) { + if (!/^[a-z0-9][a-z0-9.-]{0,99}$/.test(k)) continue; + if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) continue; + out[k] = Math.min(JOB_GAP_MAX_SECONDS, Math.floor(raw)); + } + return out; +} + +// The gap (seconds) a job on `platform`'s queue waits after the previous one +// ended: the operator's value for the platform, else the built-in one for it, +// else the operator's `default`, else the built-in default. `builtIn` lets the +// e2e server shrink the BUILT-IN values (E2E_JOB_GAP_SECONDS) while a value a +// spec sets explicitly still applies. +export function jobGapSecondsFor( + pacing: { jobGapSeconds?: Partial<Record<string, number>> } | undefined, + platform: string, + builtIn: Readonly<Record<string, number>> = JOB_GAP_DEFAULT_SECONDS, +): { seconds: number; key: string } { + const set = pacing?.jobGapSeconds ?? {}; + if (set[platform] !== undefined) return { seconds: set[platform]!, key: platform }; + if (builtIn[platform] !== undefined) return { seconds: builtIn[platform]!, key: platform }; + if (set.default !== undefined) return { seconds: set.default, key: "default" }; + return { seconds: builtIn.default ?? JOB_GAP_DEFAULT_SECONDS.default, key: "default" }; +} + diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts @@ -18,6 +18,7 @@ import { getSettings } from "./settings"; import { detectPlatform } from "./platform"; import { ARCHIVE_TODAY_SERVICE, + X_SERVICE, applyServiceCookieClean, applyServiceCookieSignal, coerceServiceCookieState, @@ -303,3 +304,75 @@ export async function markServiceCookieRerun( now, ); } + +// ── X (plans/pacing-guard.md) ───────────────────────────────────────────── + +// One gallery-dl run against X: a challenge or login-wall line raises the X +// alert (one is enough); a run that read without one is a clean request. Never +// throws. Answers the line for the job log when a clean request cleared it. +export async function noteXServiceOutcome( + paths: Pick<Paths, "transcriptsDir">, + outcome: { challengeLine?: string; url?: string; channel?: string }, +): Promise<string | null> { + try { + if (outcome.challengeLine) { + await noteServiceCookieSignal( + paths, + { service: X_SERVICE, kind: "challenge", line: outcome.challengeLine.trim().slice(0, 300) }, + { + ...(outcome.url ? { url: outcome.url } : {}), + ...(outcome.channel ? { channel: outcome.channel } : {}), + }, + ); + return null; + } + const now = Date.now(); + if (!(await cleanWouldChange(paths, X_SERVICE, now))) return null; + return await noteServiceCookieClean( + paths, + X_SERVICE, + outcome.url ? { url: outcome.url, ...(outcome.channel ? { channel: outcome.channel } : {}) } : undefined, + { now }, + ); + } catch { + return null; + } +} + +// The raised (not cleared) alert of `service`, or null. Never throws. +export async function raisedServiceAlert( + paths: Pick<Paths, "transcriptsDir">, + service: string, +): Promise<ServiceCookieEntry | null> { + try { + const e = (await readServiceCookieState(paths)).services[service]; + return isAlertRaised(e) ? e! : null; + } catch { + return null; + } +} + +// A job the raised alert REFUSED before it started (common/jobs/networkGuard.ts): +// recorded against the alert, without counting as a signal, so "Re-run stopped +// jobs" offers it once the alert clears. Never throws. +export async function noteServiceStoppedJob( + paths: Pick<Paths, "transcriptsDir">, + service: string, + job: { id: string; kind?: string }, + now: number = Date.now(), +): Promise<void> { + try { + await mutate( + paths, + (state) => { + const e = state.services[service]; + if (!isAlertRaised(e) || e!.jobs.some((j) => j.id === job.id)) return { changed: false, out: undefined }; + e!.jobs = [...e!.jobs, { id: job.id, ...(job.kind ? { kind: job.kind } : {}) }].slice(-20); + return { changed: true, out: undefined }; + }, + now, + ); + } catch { + // bookkeeping only + } +} diff --git a/common/lib/serviceCookies.test.ts b/common/lib/serviceCookies.test.ts @@ -248,3 +248,19 @@ test("the view: a stale banner with its fix; OK again offers the stopped jobs, b const after = buildServiceCookieAlerts(state, { now: T0 + 180_000 + OK_AGAIN_SHOW_MS + 1, statusOf: (id) => statuses[id] }); assert.equal(after.alerts.some((a) => a.service === "rumble"), false); }); + +// plans/pacing-guard.md: X is a service, its family "x", Recheck always offered. +test("X is a cookie-alert service: key, label, family, fix; one challenge raises it", async () => { + const sc = await import("./serviceCookies"); + assert.equal(sc.isServiceKey("x"), true); + assert.equal(sc.serviceLabel("x"), "X"); + assert.equal(sc.serviceFamily("x"), "x"); + assert.match(sc.serviceFixText("x"), /Refresh cookies/); + const state = sc.emptyServiceCookieState(); + const r = sc.applyServiceCookieSignal(state, { service: "x", kind: "challenge", line: "[twitter][warning] Cloudflare challenge" }, {}, Date.parse("2026-10-23T03:00:00Z")); + assert.equal(r.raisedNow, true); + const view = sc.buildServiceCookieAlerts(state, { now: Date.parse("2026-10-23T03:01:00Z") }); + assert.equal(view.alerts[0]?.service, "x"); + assert.equal(view.alerts[0]?.canRecheck, true); + assert.match(view.alerts[0]?.headline ?? "", /^X needs fresh cookies: /); +}); diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts @@ -1,7 +1,8 @@ // COOKIE REFRESH ALERTS (plans/cookie-refresh-alerts.md): one record per // SERVICE saying "the cookies this app reads for it look stale" — Rumble's // Cloudflare clearance, YouTube's sign-in, Odysee's Cloudflare check, a forum's -// browser check (by host), archive.today's check page. The dashboard draws a +// browser check (by host), archive.today's check page, X's challenge or login +// wall (plans/pacing-guard.md). The dashboard draws a // banner per stale service; the next clean request to it clears the alert by // itself. // @@ -37,7 +38,14 @@ export type YtdlpCookieService = (typeof YTDLP_COOKIE_SERVICES)[number]; export const ARCHIVE_TODAY_SERVICE = "archive.today"; -export type ServiceFamily = "ytdlp" | "forum" | "archive"; +// X (plans/pacing-guard.md): a Cloudflare challenge, a 401/403 or a login wall +// in gallery-dl's output. Unlike every other service, WHILE ITS ALERT IS UP NO +// X JOB STARTS (common/jobs/networkGuard.ts) — X answered a burst with a +// human verification on the account once, and the next request after a +// challenge is the one that gets an account locked. +export const X_SERVICE = "x"; + +export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x"; export function isYtdlpCookieService(s: string): s is YtdlpCookieService { return (YTDLP_COOKIE_SERVICES as readonly string[]).includes(s); @@ -47,13 +55,14 @@ export function isYtdlpCookieService(s: string): s is YtdlpCookieService { // (lowercased, no www.). Anything else is not a service. export function isServiceKey(s: unknown): s is string { if (typeof s !== "string" || s.length === 0 || s.length > 100) return false; - if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE) return true; + if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE || s === X_SERVICE) return true; return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(s); } export function serviceFamily(service: string): ServiceFamily { if (isYtdlpCookieService(service)) return "ytdlp"; if (service === ARCHIVE_TODAY_SERVICE) return "archive"; + if (service === X_SERVICE) return "x"; return "forum"; } @@ -72,6 +81,8 @@ export function serviceLabel(service: string): string { return "Odysee"; case ARCHIVE_TODAY_SERVICE: return "archive.today"; + case X_SERVICE: + return "X"; default: return /(^|\.)kiwifarms\./.test(service) ? `Kiwi Farms (${service})` : service; } @@ -91,6 +102,11 @@ export function serviceFixText(service: string, browser?: string): string { return `open odysee.com in ${b} and let its check pass`; case ARCHIVE_TODAY_SERVICE: return "Connect archive session (Settings → Archive sources) and pass the check once in the window"; + case X_SERVICE: + return ( + "pass X's check by hand — Connect X account on /settings and clear it in the window (with the " + + "browser login: open x.com in that browser) — then press Refresh cookies there; no X job starts until then" + ); default: return `use “Connect forum session” on the thread's channel page and clear the check in the window`; } @@ -534,6 +550,7 @@ export function buildServiceCookieAlerts( ...(e.clearedAt ? { clearedAt: e.clearedAt, clearedBy: e.clearedBy } : {}), canRecheck: serviceFamily(e.service) === "archive" || + serviceFamily(e.service) === "x" || !!state.lastGood[e.service] || !!e.evidence.url, stoppedJobs, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -129,6 +129,8 @@ import { export type { Worker } from "./workers"; export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource"; +import { sanitizeJobGapSeconds } from "./jobGap"; +export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap"; // The `social` block (release 16 slice XL). The types and the coercion live // with the source they choose, in social/xCookieSource.ts (pure, client-safe); @@ -168,6 +170,17 @@ export const X_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XSocialSettings> = { "fetching does not; a site already published changes on its next build and deploy, and " + "flipping back is a rebuild. Chosen in the X account session section of /settings; the " + "rule is common/lib/postsVisibility.ts.", + maxCookieAgeMinutes: + "THE FRESH-JAR RULE: with the `\"profile\"` login source, a job that sends requests to X " + + "(Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted " + + "posts — and the scheduler's fetches) is refused when it STARTS unless the profile's exported " + + "cookie jar was written within this many minutes and carries a login (an auth_token). The " + + "refusal says what to do: press Refresh cookies (or Connect X account) on /settings, then " + + "fetch again. A refresh is a human click — it loads x.com/home, itself a request to X — so " + + "the editor never refreshes the jar to satisfy this. With the `\"browser\"` source the age " + + "cannot be read: the job logs that and proceeds. ABSENT: 60. 0 turns the rule off; at most " + + "10080 (a week). Set in the X account session section of /settings. " + + "common/jobs/networkGuard.ts.", }; export type { AutoQueueSettings } from "./autoQueueTypes"; export type { ChannelPriority } from "./channelPriority"; @@ -759,6 +772,11 @@ export type PacingSettingsBlock = { decayAfterCleanUnits: number; holdAfterFailsAtCap: number; holdProbeMinutes: number; + // THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE (plans/pacing-guard.md): + // seconds, keyed by platform (`platform:<p>`'s <p>) or "default". Only the + // keys the operator set are stored; the rest come from + // JOB_GAP_DEFAULT_SECONDS at read time (jobGapSecondsFor). + jobGapSeconds: Partial<Record<string, number>>; }; export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = { @@ -779,6 +797,17 @@ export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = { holdProbeMinutes: "Minutes between probes while a platform is held. Clamped 1–1440; " + "default 60.", + jobGapSeconds: + "THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE, in seconds, keyed by platform (the " + + "`<p>` of a `platform:<p>` queue — `twitter`, `youtube`, `megaphone.fm` …) or `default`. A " + + "job that sends requests to a platform (a kind declaring `network` in " + + "common/jobs/jobKinds.ts) does not start until this long after the previous such job on " + + "its queue ended; while it waits its log and its /jobs row say so (\"waiting 4m12s: X jobs " + + "are spaced 5 min apart (pacing.jobGapSeconds.twitter)\"). The last end per queue survives " + + "a restart (`.jobs/queue-gaps.json`). Built in, for a key not set here: default 20, twitter " + + "300, xenforo 60, bluesky 60 — only the keys set here are stored. 0 for a key: no gap on that " + + "platform. At most 86400. Set on /settings beside the download sleep. " + + "common/jobs/queueGap.ts.", }; export const PACING_DEFAULT_SLEEP_REQUESTS_CAP_SECONDS = 16; @@ -818,6 +847,7 @@ export function sanitizePacing(v: unknown): PacingSettingsBlock { 1440, PACING_DEFAULT_HOLD_PROBE_MINUTES, ), + jobGapSeconds: sanitizeJobGapSeconds(r.jobGapSeconds), }; } @@ -1788,7 +1818,7 @@ export const siteSettingsSchema = z.object({ "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", ), social: settingsField((v): SocialSettings => sanitizeSocial(v)).describe( - "Per-platform settings of the social posts: X's two, both chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`) and where X posts may appear (`social.x.visibility`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", + "Per-platform settings of the social posts: X's three, all chosen in the X account session section of /settings — where the X fetchers' login comes from (`social.x.cookieSource`), where X posts may appear (`social.x.visibility`) and how fresh its cookies must be for an X job to start (`social.x.maxCookieAgeMinutes`) — and a forum thread's retry on a block (`social.xenforo.retryOnBlock`, set on a forum channel's page). See common/social/xCookieSource.ts.", ), sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe( "Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.", diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -51,8 +51,30 @@ export type XSocialSettings = { cookieSource?: XCookieSource; // Absent = "public". visibility?: XPostsVisibility; + // THE FRESH-JAR RULE (plans/pacing-guard.md): with the "profile" source, a + // job that asks X starts only when the exported jar was written within this + // many minutes and carries a login. 0 turns the rule off. Absent = + // X_DEFAULT_MAX_COOKIE_AGE_MINUTES. common/jobs/networkGuard.ts. + maxCookieAgeMinutes?: number; }; +// Absent `social.x.maxCookieAgeMinutes`: an hour. A refresh is a human click +// on /settings (refreshXCookies loads x.com/home — itself a request to X), so +// the editor never refreshes the jar on its own to satisfy this. +export const X_DEFAULT_MAX_COOKIE_AGE_MINUTES = 60; +// A week: past that, "fresh" means nothing. +export const X_MAX_COOKIE_AGE_MINUTES_CAP = 7 * 24 * 60; + +export function parseXMaxCookieAgeMinutes(v: unknown): number | undefined { + if (typeof v !== "number" || !Number.isFinite(v) || v < 0) return undefined; + return Math.min(X_MAX_COOKIE_AGE_MINUTES_CAP, Math.floor(v)); +} + +// The limit in force (0 = the rule is off). +export function xMaxCookieAgeMinutes(x: XSocialSettings | undefined): number { + return x?.maxCookieAgeMinutes ?? X_DEFAULT_MAX_COOKIE_AGE_MINUTES; +} + // A forum thread's (platform "xenforo") settings (release 37 lane G). export type XenforoSocialSettings = { // The Fetch posts button's retry on a block: wait `minutes` after a @@ -80,10 +102,12 @@ export function sanitizeSocial(value: unknown): SocialSettings { ? r.xenforo : {}) as Record<string, unknown>; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); + const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes); return { x: { ...(isXCookieSource(x.cookieSource) ? { cookieSource: x.cookieSource } : {}), ...(isXPostsVisibility(x.visibility) ? { visibility: x.visibility } : {}), + ...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}), }, ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), }; diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -30,6 +30,7 @@ import { createInterface } from "node:readline"; import type { Readable } from "node:stream"; import { execa } from "execa"; import { getPaths } from "../lib/paths"; +import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { cookieArgs } from "../lib/cookiePolicy"; import type { Post } from "../lib/posts"; import type { OlderBackfillPosition } from "../lib/posts-server"; @@ -89,6 +90,45 @@ function looksLikeAuthFailure(text: string): boolean { return AUTH_ERROR_PATTERNS.some((p) => lower.includes(p)); } +// X STOPPED ANSWERING (plans/pacing-guard.md). On 2026-10-23 gallery-dl +// printed `[twitter][warning] Cloudflare challenge`, EXITED 0, read nothing, +// and the job ended `done` — the next twelve fetches went straight on. A +// challenge word on any stderr line, or an auth failure (AUTH_ERROR_PATTERNS) +// on a warning or error line, now stops the run whatever the exit code: the +// fetch fails (posts read so far kept) and the X cookie alert is raised, which +// refuses every X job until it is cleared (jobs/networkGuard.ts). +const X_CHALLENGE_LINE = /cloudflare|\bchallenge\b|just a moment|captcha/i; +const LEVEL_LINE = /\]\[(warning|error)\]/i; + +export function xBlockLine(line: string): boolean { + if (X_CHALLENGE_LINE.test(line)) return true; + return LEVEL_LINE.test(line) && looksLikeAuthFailure(line); +} + +export function xBlockedError(line: string): string { + return ( + `X answered with a challenge or a login wall (${line.trim().slice(0, 200)}): stopped here, posts read so far ` + + "kept. The X cookie alert is up — no X job starts until it is cleared (pass X's check by hand, Refresh " + + "cookies on /settings, then Recheck on the dashboard)." + ); +} + +// The alert, raised (or, for a clean run, cleared); the line for the log. +async function noteXOutcome( + challengeLine: string | undefined, + url: string, + channel: string, + onLog?: (line: string) => void, +): Promise<void> { + if (challengeLine) onLog?.(`[auth] ${xBlockedError(challengeLine)}`); + const cleared = await noteXServiceOutcome(getPaths(), { + ...(challengeLine ? { challengeLine } : {}), + ...(url ? { url } : {}), + ...(channel ? { channel } : {}), + }); + if (cleared) onLog?.(cleared.trimEnd()); +} + // The argv for a text-only timeline read. Exported so a test can assert the // flags without spawning anything. // gallery-dl's `twitter:user` extractor treats a bare profile URL as a @@ -311,6 +351,11 @@ export async function downloadXPostMedia(args: { for (const line of stderr.split("\n")) { if (line.trim()) args.onLog?.(`gallery-dl: ${line.trim()}`); } + const blocked = stderr.split("\n").find((l) => !/\]\[debug\]/.test(l) && xBlockLine(l)); + if (blocked && !res.isCanceled) { + await noteXOutcome(blocked, `https://x.com/i/status/${args.id}`, "", args.onLog); + return { ok: false, needsCookies: true, error: xBlockedError(blocked) }; + } if (res.isCanceled || res.timedOut || res.exitCode !== 0) { const tail = stderr.trim().split("\n").slice(-5).join("\n"); if (looksLikeAuthFailure(tail)) { @@ -558,6 +603,8 @@ export class GalleryDlStream { known = 0; older = 0; rateLimited = false; + // The first challenge or login-wall line on stderr (xBlockLine), if any. + challengeLine?: string; stopReached = false; cursor?: string; // The oldest post id read this run (any post, archived or not) — a search @@ -609,6 +656,7 @@ export class GalleryDlStream { if (DEBUG_LINE.test(line) || !line.trim()) return undefined; const waiting = RATE_LIMIT_LINE.test(line); if (waiting) this.rateLimited = true; + if (!waiting && !this.challengeLine && xBlockLine(line)) this.challengeLine = line.trim(); this.tail.push(line); if (this.tail.length > STDERR_TAIL_LINES) this.tail.shift(); this.opts.onLog?.(`gallery-dl: ${line.trim()}`); @@ -1093,6 +1141,10 @@ async function walkSearchWindows( (stream.known ? `, ${stream.known} already archived` : ""), ); + if (stream.challengeLine) { + await noteXOutcome(stream.challengeLine, xSearchPageUrl(spec.queryFor(windowStart)), channelSlug, onLog); + return stopped(here, { needsCookies: true, error: xBlockedError(stream.challengeLine) }); + } if (res.isCanceled || signal.aborted || res.timedOut) { onLog?.( res.timedOut @@ -1371,6 +1423,17 @@ export const xGalleryDlFetcher: SocialFetcher = { input.cursor ?? (timeline && stream.newPosts > 0 ? RESTART_FROM_TOP_CURSOR : undefined); + if (stream.challengeLine) { + await noteXOutcome(stream.challengeLine, accountUrl, channelSlug, onLog); + return { + posts, + complete: false, + cursor: resumeAt, + needsCookies: true, + error: xBlockedError(stream.challengeLine), + }; + } + if (stoppedAtKnown) return { posts, complete: true }; if (res.isCanceled || signal.aborted || res.timedOut) { @@ -1407,6 +1470,9 @@ export const xGalleryDlFetcher: SocialFetcher = { }; } + // A clean run: the X alert (if a pending one) is settled, and this is the + // request a Recheck can name. + await noteXOutcome(undefined, accountUrl, channelSlug, onLog); // A clean exit walked everything it was given: gallery-dl waits out rate // limits rather than skipping pages. Only a --post-range cap leaves history // behind — resume from the last page it finished. diff --git a/common/views/jobRowView.ts b/common/views/jobRowView.ts @@ -98,6 +98,11 @@ export type JobRowView = { // boot pass's reason for a job a restart left queued ("server restarted; // the scheduler re-derives syncs"). History rows only; see listJobs.ts. cancelReason?: string; + // A network job its queue has started, waiting out the gap after the + // previous one on that platform queue (jobs/queueGap.ts): when it may begin + // (epoch ms) and why. Live rows only. Drawn as "waiting 4m12s: X jobs are + // spaced 5 min apart (pacing.jobGapSeconds.twitter)". + paced?: { until: number; reason: string }; // Which adapter built it. Never rendered; tests and the merge read it — // except "runner": an auto-queue lane's in-flight unit (fromInFlight), which // links to a job page only when `inRegistry` says it has one. diff --git a/common/views/jobRows.ts b/common/views/jobRows.ts @@ -262,6 +262,9 @@ export function fromRecord(j: JobRecord, ctx: FromRecordContext): JobRowView { replayable: Boolean(j.spec), position: ctx.position >= 0 ? ctx.position : undefined, detail: jobSpecDetail(j.kind, j.spec), + ...(j.status === "running" && j.pacedUntil !== undefined && j.pacedReason + ? { paced: { until: j.pacedUntil, reason: j.pacedReason } } + : {}), source: "registry", }; } diff --git a/common/ytdlp/managedDownloadsSleep.test.ts b/common/ytdlp/managedDownloadsSleep.test.ts @@ -109,9 +109,15 @@ test("a fetched video sleeps before the next one", async () => { assert.equal(await sleepsFor([FETCHED, FETCHED]), 1); }); -test("a video the download filter declined does not sleep", async () => { - assert.equal(await sleepsFor([FILTERED, FETCHED]), 0); - assert.equal(await sleepsFor([FILTERED, FILTERED, FILTERED]), 0); +// A PROBE IS A REQUEST (plans/pacing-guard.md, 2026-10-23): release 9 B2 let +// a declined video skip the gap, and a podcast feed's download-missing probed +// ~1,150 episodes back to back. A declined video whose prefetch ran now waits; +// one that asked nothing (declined from what was already known) does not. +test("a video the download filter declined after a probe sleeps; one that asked nothing does not", async () => { + assert.equal(await sleepsFor([FILTERED, FETCHED]), 1); + assert.equal(await sleepsFor([FILTERED, FILTERED, FILTERED]), 2); + const ASKED_NOTHING = outcome("skipped-filtered", []); + assert.equal(await sleepsFor([ASKED_NOTHING, ASKED_NOTHING, FETCHED]), 0); }); // Release 9 review: a per-video failure KEEPS the pace, even one that never @@ -207,7 +213,8 @@ test("a soft block backs the platform off and stops the batch; a deleted video d test("the last video never sleeps, whatever it was", async () => { assert.equal(await sleepsFor([FETCHED]), 0); - assert.equal(await sleepsFor([FILTERED, FETCHED]), 0); + assert.equal(await sleepsFor([FETCHED, FILTERED]), 1); + assert.equal(await sleepsFor([FILTERED]), 0); }); test("a real fetch that failed still sleeps, per-video or not", async () => { diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -46,6 +46,7 @@ import { } from "../lib/cookiePolicy"; import { resolveEffectiveAvailability } from "../lib/availability-server"; import { withMetadataHistory } from "../lib/metadataHistory-server"; +import { seedFeedTitles } from "../controller/feedTitlePrefilter"; import { settledByTitleFilterIds, upsertMetadataScan, @@ -878,6 +879,17 @@ async function downloadPlaylistManaged( // (and re-failing) on every batch. A forceCookies run resolves to mode // "always" and so bypasses the defer exclusion. const runCookiePolicy = resolveRunCookiePolicy(opts, effectiveChannelConfig); + // A PODCAST FEED'S TITLES FIRST (plans/pacing-guard.md): one read of the + // feed titles every unscanned episode in the metadata-scan store, so the + // settled set below declines a filtered episode without probing it. + await seedFeedTitles({ + paths: opts.paths, + slug: opts.channelSlug, + config: effectiveChannelConfig, + playlistUrls: tofetch, + onLog: opts.onLog, + signal: opts.signal, + }).catch(() => 0); // ONE read of the channel-level metadata-scan store for the whole batch. const settledByFilter = await settledByTitleFilterIds( opts.paths, @@ -1051,6 +1063,15 @@ export type ManagedDownloadsDeps = { // ("This content isn't available, try again later") reading as `deleted` → // per_video — is gone since release 10: it is `rate_limit` now (isSoftBlock), // backs the platform off and stops the batch. The pace stays anyway. +// A video that asked NOTHING (plans/pacing-guard.md): no attempt at all — the +// filter declined it from what was already known. Only that one skips the gap; +// a declined video whose metadata prefetch ran (a probe) asked the platform and +// waits like any other (2026-10-23: a feed channel's ~1,150 probes ran back to +// back under the release 9 B2 rule below). +export function madeNoRequest(outcome: DownloadOutcomeRecord): boolean { + return outcome.attempts.length === 0; +} + export function declinedWithoutMediaFetch( outcome: DownloadOutcomeRecord, ): boolean { @@ -1271,12 +1292,15 @@ export async function runManagedDownloads( processedCount++; const isLast = processedCount >= urls.length; const willAbortLoop = firstFailure !== null && abortOnError; - // A VIDEO THE FILTER DECLINED DOES NOT PAY FOR A FETCH IT NEVER MADE - // (release 9, B2). On 2026-09-25 paramount-tactical's download-missing - // slept 193 times for 14 archives: every video the download filter - // declined slept 30 s after nothing but its metadata prefetch. Every - // other outcome still sleeps — a real fetch, success or failure, and - // every failure, per-video ones included (see declinedWithoutMediaFetch). + // A PROBE IS A REQUEST (plans/pacing-guard.md, 2026-10-23). Release 9 + // B2 let a video the download filter declined after only its metadata + // prefetch skip the gap (paramount-tactical slept 193 times for 14 + // archives) — and a podcast feed's download-missing then probed ~1,150 + // episodes back to back. Every outcome that asked anything now waits + // the gap; only one that asked nothing (madeNoRequest) does not. The + // cost B2 removed is paid down instead by asking less: the metadata + // scan's settled set and a feed's titles (seedFeedTitles) decline a + // filtered video before any probe. const gapMs = downloadGapMs(sleepSeconds, paceNow(), basePace, { minSeconds: minGap, }); @@ -1285,7 +1309,7 @@ export async function runManagedDownloads( !isLast && !willAbortLoop && !opts.signal.aborted && - !declinedWithoutMediaFetch(outcome) + !madeNoRequest(outcome) ) { opts.onLog(`Sleeping ${gapMs / 1000}s before next download...\n`); await sleep(gapMs, opts.signal); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] - **Record live reads Rumble's new segment packaging.** Rumble's CDN now serves a stream's pieces as byte ranges of one `.tar` file, which ffmpeg refused by its name ("not in allowed_segment_extensions"), so a recording through the browser path ended with nothing recorded. The recorder now also allows `tar` segments, and nothing looser. Needs a rebuild of the editor. +- **Jobs that ask a site are spaced apart, and X jobs start only on fresh cookies.** On 2026-10-23 thirteen X fetches queued in one loop ran less than a second apart on a cookie jar refreshed 16 days earlier; X answered with a Cloudflare challenge and the account needed a human verification. Now every job that sends requests to a platform waits after the previous one on the same platform ended — 5 minutes for X, 1 minute for forums and Bluesky, 20 seconds for everything else — and its row on /jobs and its log say so: "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". The gaps are on /settings beside the download sleep (`pacing.jobGapSeconds`), and the last job's end is remembered across a restart. With the connected X profile, a job that asks X is refused — when it is queued and again when its turn comes — unless the cookies were refreshed within the last hour: "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again." The limit is in the X account section of /settings (`social.x.maxCookieAgeMinutes`, 0 turns it off). The editor never refreshes the cookies itself, because a refresh loads x.com. With the browser login the age cannot be read; the job says so and runs. A job that asks a site can no longer be run "(immediate)": the queue picker leaves the option out, and `"queueKey": ""` from `pnpm ops` is refused with a sentence. Needs a restart of the editor. +- **An X challenge stops X.** When gallery-dl prints a Cloudflare challenge, a 401 or 403, or a login wall, the fetch now fails even if gallery-dl exits cleanly (the posts it read are kept), and the dashboard shows an **X needs fresh cookies** banner. While it is up, every X job (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts, the scheduler's fetches) is refused before it asks anything, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand, press **Refresh cookies** on /settings, then **Recheck**: for X it sends no request and clears the banner when the login on disk is newer than the challenge. `pnpm ops get services` and `archilyzer doctor` list it as `x`. Needs a restart of the editor. +- **A podcast feed's download-missing no longer probes every episode back to back.** A probe — the metadata request that tells the download filter an episode's title — now waits the sleep between downloads like any download; only an episode decided without any request skips it. To keep that cheap, a channel with a download filter whose playlist is a feed's episode files reads its feed once per run and records every episode's title, so an episode the filter declines costs no request at all. Release 9 had let a declined video skip the sleep, and a feed channel's run then made about 1,150 probes with no gap. Needs a restart of the editor. - **A clip in a fact-check video can stamp and count more than once.** The clip editor's **Count & stamp** box is now **Marks**, on every clip: a list of the clip's marks, each its own stamp and its own step of the tally at its own second — its verdict picked by this cut's words (Episodes, Grift…), when it lands (**Set at playhead**, Shift+S for the selected mark), how long it stays, whether it is drawn, how much it counts, what it says, **Remove**. **Add mark at playhead** (Shift+M) adds one under a new id; **Clear** removes them all. Two stamps on one clip that would sit on each other are refused, saying where the second may land. From a terminal: `umtool set <project> <clip> mark.add=Episodes@190.2`, `mark.remove=<id>`, `mark.verdict=…`, `marks=<json>`; `umtool show` lists them. A clip with one mark is written as before, so an existing video renders the same. - **Walk a report video's clips in umtool's clip editor with the on-screen chrome drawn over them, no build.** Under the clip editor's player, **Live preview** draws the cut's deck over the playing clip, in step with the playhead: the clip's date title and subtitle, the timeline with its pip and flags, the tally as it stands at that moment (stepping when a stamp lands), the stamp, the posts, the QR, and the finale's page on the last clip. A trimmed edge, a moved stamp or new words show about a second after they are saved; an unsaved nudge moves the picture at once. **Title** and **Subtitle** under the picture edit the clip's on-screen words, shown as they are typed. A line under the picture says what the preview does not do (the build snaps each edge to a silence and crossfades the clips). **Render this clip** makes the clip with its chrome exactly as the build would, in a minute or two, and plays it in place (`node umtool/report-to-video/build-video.mjs <manifest> --skip-fetch --clip-preview <id>`). The On-screen preview now draws the finale too. Needs a restart of umtool. - **A long report video with on-screen chrome is no longer stopped partway through its build.** umtool gave a build two minutes per clip (a whole-cut take one minute), which a 36-clip, 25-minute cut with its panel, posts column and stamps outruns: drawing those alone takes over half an hour. A build or take of a cut with on-screen chrome now gets five times the cut's length when that is longer. Needs a restart of umtool. diff --git a/editor/app/api/ops/recheck-service/route.ts b/editor/app/api/ops/recheck-service/route.ts @@ -4,11 +4,12 @@ import { ops, opsFail, reqString } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | <forum host> } +// POST { service: "rumble" | "youtube" | "odysee" | "archive.today" | "x" | <forum host> } // // The cookie refresh banner's Recheck: ONE request through the service's own // path (a yt-dlp metadata request for its last clean video; a forum page -// through the host's profile; archive.today's request again), as a one-step +// through the host's profile; archive.today's request again; for X no request +// at all — the login on disk, renewed since the alert), as a one-step // job (kind `recheck-service-cookies`) the answer waits for: // { ok, jobId, result: "clean" | "stale" | "failed", message }. "clean" // clears the alert. diff --git a/editor/app/api/test/invalidate-cache/route.ts b/editor/app/api/test/invalidate-cache/route.ts @@ -133,6 +133,12 @@ function invalidate() { // object. // eslint-disable-next-line @typescript-eslint/no-explicit-any (globalThis as any).__yttAutoQueueStatusMemo__ = undefined; + // And the platform queues' last-end memory (jobs/queueGap.ts): a spec that + // sets a job gap must not make the next spec's first job on that queue wait + // for the previous spec's last one. Dropped through its global, like the + // memo above. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (globalThis as any).__yttQueueGaps__ = undefined; revalidatePath("/", "layout"); return NextResponse.json({ ok: true }); } diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -235,9 +235,12 @@ export async function fetchPostsAction( } } - // queueKeyForUrl() already routes x.com / bsky.app to platform:x.com / - // platform:bsky.app, so per-platform serialization and the existing 429 - // backoff come free with no new queue plumbing. + // downloadQueueKey() puts an X channel on `platform:twitter` (x.com is + // detected as twitter), Bluesky on `platform:bluesky`, a forum thread on + // `platform:xenforo`: one fetch per platform at a time, spaced by + // `pacing.jobGapSeconds`, and — for X — refused on a stale jar or a raised X + // alert (common/jobs/networkGuard.ts, plans/pacing-guard.md). The video + // downloads' 429 backoff does NOT apply to post fetchers. const key = resolveQueueKey(downloadQueueKey(config), queueKey); return runManagedFunction({ diff --git a/editor/app/components/QueueControl.tsx b/editor/app/components/QueueControl.tsx @@ -10,6 +10,10 @@ type Props = { defaultQueueKey: string; existingQueues: string[]; actionLabel: string; + // Whether "(immediate)" — queue "" — is offered. Absent: not for an action + // whose default is a platform queue, because a job that asks a platform is + // refused unqueued (common/jobs/networkGuard.ts, plans/pacing-guard.md). + allowImmediate?: boolean; }; export function QueueControl({ @@ -18,7 +22,9 @@ export function QueueControl({ defaultQueueKey, existingQueues, actionLabel, + allowImmediate, }: Props) { + const immediate = allowImmediate ?? !defaultQueueKey.startsWith("platform:"); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(value); @@ -31,7 +37,7 @@ export function QueueControl({ onChange={(e) => setDraft(e.target.value)} aria-label={`custom queue for ${actionLabel}`} autoFocus - placeholder="leave empty for immediate" + placeholder={immediate ? "leave empty for immediate" : "queue name"} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); @@ -95,7 +101,7 @@ export function QueueControl({ }} className="font-mono px-2 py-1 rounded border border-border bg-card text-foreground" > - <option value="">(immediate)</option> + {(immediate || value === "") && <option value="">(immediate)</option>} {named.map((opt) => ( <option key={opt} value={opt}> {opt} diff --git a/editor/app/components/dashboard/CookieAlertsPanel.tsx b/editor/app/components/dashboard/CookieAlertsPanel.tsx @@ -54,7 +54,7 @@ function AlertCard({ alert, onChange }: { alert: ServiceCookieAlertView; onChang </Link> </> )} - {alert.family === "archive" && ( + {(alert.family === "archive" || alert.family === "x") && ( <> {" · "} <Link href="/settings" className="underline underline-offset-2 hover:text-foreground"> diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx @@ -4,6 +4,7 @@ import Link from "next/link"; import { useState } from "react"; import type { JobRowView } from "yt-dlp-transcript-common/views/jobRowView"; import { formatDuration } from "yt-dlp-transcript-common/lib/format"; +import { waitText } from "yt-dlp-transcript-common/jobs/queueGapText"; import { JobLogTail } from "../[id]/components/JobLogTail"; import { jobKindLabel } from "../jobKindLabels"; import { formatElapsed } from "../../lib/formatElapsed"; @@ -130,6 +131,23 @@ function cancelReasonOf(job: JobRowView): string | undefined { return job.status === "cancelled" ? job.cancelReason : undefined; } +// A network job waiting out its platform queue's gap (jobs/queueGap.ts): +// "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". +// Counted from the poll's payload. +function PacedLine({ job, compact }: { job: JobRowView; compact?: boolean }) { + if (!job.paced) return null; + return ( + <span + data-testid="job-paced" + className={compact ? "min-w-0 truncate text-xs text-muted-foreground" : "self-start text-xs text-muted-foreground"} + title={job.paced.reason} + suppressHydrationWarning + > + waiting {waitText(job.paced.until - Date.now())}: {job.paced.reason} + </span> + ); +} + function CancelReason({ job, inline }: { job: JobRowView; inline?: boolean }) { const reason = cancelReasonOf(job); if (!reason) return null; @@ -303,6 +321,7 @@ function JobRowHeading({ {job.background && " · waiting behind a manual job"} </span> )} + <PacedLine job={job} compact={compact} /> {/* Its counterpart for a cancelled job: why. Compact rows carry it as the pill's title instead — they are one line, always. */} {!compact && <CancelReason job={job} inline />} @@ -542,6 +561,7 @@ function TableRow({ {j.status} </span> <CancelReason job={j} /> + <PacedLine job={j} /> {j.stuck && ( <span data-stuck={j.stuck.reason} diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts @@ -30,6 +30,38 @@ import { isSourceVideoQuality, } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { formValues, type FormState } from "../lib/formState"; +import { + JOB_GAP_DEFAULT_SECONDS, + JOB_GAP_MAX_SECONDS, +} from "yt-dlp-transcript-common/lib/jobGap"; + +// The job-gap fields (SettingsForm's JOB_GAP_FIELDS): a value equal to the +// built-in is NOT stored, so a later change to a built-in reaches this +// install; every other key already set is kept. +const JOB_GAP_FORM_KEYS = ["default", "twitter", "xenforo", "bluesky"] as const; + +function parseJobGaps( + formData: FormData, + current: Partial<Record<string, number>>, +): { ok: true; gaps: Partial<Record<string, number>> } | { ok: false; error: string } { + const gaps: Partial<Record<string, number>> = { ...current }; + for (const key of JOB_GAP_FORM_KEYS) { + const raw = formData.get(`jobGap.${key}`); + if (raw === null) continue; + const text = String(raw).trim(); + if (text === "") { + delete gaps[key]; + continue; + } + const n = Number(text); + if (!Number.isInteger(n) || n < 0 || n > JOB_GAP_MAX_SECONDS) { + return { ok: false, error: `The ${key} job gap must be a whole number of seconds, 0–${JOB_GAP_MAX_SECONDS}.` }; + } + if (n === JOB_GAP_DEFAULT_SECONDS[key]) delete gaps[key]; + else gaps[key] = n; + } + return { ok: true, gaps }; +} // THE SHARED SAVE RESULT of /settings and the four operation-settings forms. A // failure carries what was submitted, so the form keeps what was typed @@ -129,6 +161,10 @@ export async function saveSettingsAction( }; } + const currentSettings = getSettings(); + const jobGaps = parseJobGaps(formData, currentSettings.pacing.jobGapSeconds); + if (!jobGaps.ok) return { ok: false, error: jobGaps.error, values }; + // 0 disables passive refresh; any other value must land in the allowed window. const autoRefreshParsed = Number.parseInt(autoRefreshRaw, 10); if (!Number.isFinite(autoRefreshParsed)) { @@ -238,6 +274,8 @@ export async function saveSettingsAction( cookiesFromBrowser, cookieMode, sleepBetweenDownloadsSeconds: sleepParsed, + // The whole pacing block as it is, with only the job gaps this form edits. + pacing: { ...currentSettings.pacing, jobGapSeconds: jobGaps.gaps }, downloadFormat, sourceVideoQuality, minFreeDiskGB: minFreeDiskParsed, diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -20,6 +20,17 @@ import { SeededSelect, } from "../../components/forms/Field"; import { seedChecked } from "../../lib/formState"; +import { jobGapSecondsFor } from "yt-dlp-transcript-common/lib/jobGap"; + +// The gaps this form edits (pacing.jobGapSeconds, plans/pacing-guard.md): the +// default and the three platforms with a built-in of their own. Any other +// platform's key is set by hand in settings.json. +const JOB_GAP_FIELDS = [ + { key: "default", label: "Every platform" }, + { key: "twitter", label: "X" }, + { key: "xenforo", label: "Forums" }, + { key: "bluesky", label: "Bluesky" }, +] as const; import { SocialLinksField, toSocialRow, @@ -118,6 +129,32 @@ export function SettingsForm({ initial }: Props) { type="number" hint="Pause inserted between per-video yt-dlp invocations in managed batch downloads (download-from-playlist, download-missing). 0 disables. Default 10s. Each channel can override this in its Advanced settings." /> + <fieldset aria-label="job gaps" className="flex flex-col gap-1 text-sm"> + <legend className="font-medium">Gap between jobs on one platform (seconds)</legend> + <div className="grid grid-cols-2 gap-2 sm:grid-cols-4"> + {JOB_GAP_FIELDS.map(({ key, label }) => ( + <label key={key} className="flex flex-col gap-1 text-xs"> + <span>{label}</span> + <SeededInput + state={state} + name={`jobGap.${key}`} + initial={String(jobGapSecondsFor(initial.pacing, key).seconds)} + type="number" + min={0} + aria-label={`job gap ${key}`} + className="rounded border border-border bg-card px-2 py-1 text-sm" + /> + </label> + ))} + </div> + <span className="text-xs text-muted-foreground"> + A job that asks a platform (a sync, a download, Fetch posts…) starts + only this long after the previous one on the same platform ended; + its row on /jobs says how long it still waits. Built in: 20 s + everywhere, 300 s for X, 60 s for forums and Bluesky. 0 turns a + gap off. + </span> + </fieldset> <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Default download format</span> <SeededSelect diff --git a/editor/app/settings/components/XSessionSection.tsx b/editor/app/settings/components/XSessionSection.tsx @@ -18,6 +18,7 @@ import { connectXAccountAction, refreshXCookiesAction, setXCookieSourceAction, + setXMaxCookieAgeAction, type XSessionActionResult, } from "../xSessionActions"; import type { XSessionStatus } from "yt-dlp-transcript-common/social/xSessionBroker"; @@ -34,12 +35,16 @@ export function XSessionSection({ initial, initialSource, initialVisibility, + initialMaxCookieAge, }: { initial: XSessionStatus; initialSource: XCookieSourceView; // `social.x.visibility`, resolved (absent = "public"); release 17 slice XP. initialVisibility: XPostsVisibility; + // `social.x.maxCookieAgeMinutes`, resolved (absent = 60; 0 = off). + initialMaxCookieAge: number; }) { + const [maxAge, setMaxAge] = useState(String(initialMaxCookieAge)); const [status, setStatus] = useState<XSessionStatus>(initial); const [source, setSource] = useState<XCookieSourceView>(initialSource); const [login, setLogin] = useState<XLoginStatus | null>(null); @@ -200,6 +205,48 @@ export function XSessionSection({ </p> )} + <div className="flex flex-wrap items-center gap-2"> + <label htmlFor="x-max-cookie-age" className="text-sm"> + Fetch only with cookies refreshed in the last + </label> + <input + id="x-max-cookie-age" + aria-label="x max cookie age minutes" + type="number" + min={0} + value={maxAge} + onChange={(e) => setMaxAge(e.target.value)} + className="w-20 rounded-md border border-border bg-background px-2 py-1 text-sm" + /> + <span className="text-sm">min</span> + <button + type="button" + aria-label="save x max cookie age" + disabled={checking} + onClick={() => + startChecking(async () => { + setError(null); + setNote(null); + const res = await setXMaxCookieAgeAction(Number(maxAge)); + if (res.ok) setNote(res.minutes === 0 ? "Cookie age check off." : `X jobs now need cookies refreshed within ${res.minutes} min.`); + else setError(res.error); + }) + } + className="rounded-md border border-border px-3 py-1 text-sm hover:bg-muted disabled:opacity-50" + > + Save + </button> + </div> + <p className="text-xs text-muted-foreground"> + With the connected profile, a job that asks X (Fetch posts, an X search, + Capture posts, Import one post, the scheduler&apos;s fetches) is refused + unless the cookies were refreshed this recently — press Refresh cookies + first. The editor never refreshes them itself: a refresh loads x.com. + With the browser login the age cannot be read and is not checked. 0 + turns the check off. X jobs are also spaced 5 minutes apart, and none + starts while X&apos;s cookie alert is up on the dashboard. + </p> + <div className="flex flex-wrap gap-2"> <button type="button" diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -8,6 +8,7 @@ import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { SettingsForm } from "./components/SettingsForm"; import { XSessionSection } from "./components/XSessionSection"; +import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; @@ -100,6 +101,7 @@ export default async function SettingsPage() { initial={xSession} initialSource={xSource} initialVisibility={xPostsVisibility(settings)} + initialMaxCookieAge={xMaxCookieAgeMinutes(settings.social.x)} /> </section> diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -35,6 +35,8 @@ import { type XCookieSourceView, type XPostsVisibility, type XSocialSettings, + X_DEFAULT_MAX_COOKIE_AGE_MINUTES, + X_MAX_COOKIE_AGE_MINUTES_CAP, } from "yt-dlp-transcript-common/social/xCookieSource"; import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { saveSettings } from "./saveSettings"; @@ -177,3 +179,28 @@ export async function setXPostsVisibilityAction( revalidatePath("/settings"); return { ok: true, visibility: xPostsVisibility(getSettings()) }; } + +// THE FRESH-JAR RULE'S LIMIT — `social.x.maxCookieAgeMinutes` +// (plans/pacing-guard.md): a job aimed at X starts only when the profile's +// jar was exported within this many minutes. The default (60) is written as +// no key; 0 turns the rule off. +export type XMaxCookieAgeResult = + | { ok: true; minutes: number } + | { ok: false; error: string }; + +export async function setXMaxCookieAgeAction(minutes: number): Promise<XMaxCookieAgeResult> { + if (!Number.isInteger(minutes) || minutes < 0 || minutes > X_MAX_COOKIE_AGE_MINUTES_CAP) { + return { ok: false, error: `The X cookie age limit must be a whole number of minutes, 0–${X_MAX_COOKIE_AGE_MINUTES_CAP}.` }; + } + try { + await saveSettings( + socialXPatch(({ maxCookieAgeMinutes: _was, ...rest }) => + minutes === X_DEFAULT_MAX_COOKIE_AGE_MINUTES ? rest : { ...rest, maxCookieAgeMinutes: minutes }, + ), + ); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + revalidatePath("/settings"); + return { ok: true, minutes }; +} diff --git a/editor/e2e/cookie-alerts.spec.ts b/editor/e2e/cookie-alerts.spec.ts @@ -10,7 +10,7 @@ // // Same token as /api/ops/* (WORKER_TOKEN=test-worker-token on the test server). -import { readFile, writeFile } from "node:fs/promises"; +import { mkdir, readFile, utimes, writeFile } from "node:fs/promises"; import { test, expect, type APIRequestContext } from "@playwright/test"; import { resetData, resolvePath, testPaths, writeSettings } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -134,3 +134,102 @@ test("ops: get services is behind the token; recheck-service refuses a name that }); expect(await dismiss.json()).toMatchObject({ ok: true, message: "YouTube had no cookie alert to dismiss." }); }); + +// ── X (plans/pacing-guard.md) ───────────────────────────────────────────── +// +// The 2026-10-23 case: fetch-posts for 13 X accounts in one loop, a 16-day-old +// cookie jar, X answering with a Cloudflare challenge that gallery-dl printed +// as a WARNING and exited 0 on. Now the jar's age refuses the fetch, the +// challenge fails the job and raises the X alert, and every X job is refused +// while it is up. The fake gallery-dl answers `challenged_user` with the +// challenge; the jar is written by hand (no X, no browser). The test server +// turns the built-in age limit off (E2E_X_MAX_COOKIE_AGE_MINUTES=0), so this +// spec sets its own. + +async function xChannel(slug: string, handle: string): Promise<void> { + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`); + await mkdir(dir, { recursive: true }); + await writeFile( + `${dir}/config.json`, + JSON.stringify({ + name: `${handle} (X)`, + handling: "transcribe", + sourceKind: "social", + postFetcher: "x-gallery-dl", + platform: "twitter", + socialHandle: handle, + url: `https://x.com/${handle}`, + }), + ); +} + +async function xJar(ageMs: number): Promise<void> { + const dir = resolvePath(`${testPaths().transcriptsDir}/.x-session`); + await mkdir(`${dir}/profile`, { recursive: true }); + await writeFile(`${dir}/cookies.txt`, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n"); + const t = new Date(Date.now() - ageMs); + await utimes(`${dir}/cookies.txt`, t, t); +} + +async function fetchPosts(request: APIRequestContext, slug: string, extra: Record<string, unknown> = {}) { + const res = await request.post(`${baseUrl}/api/ops/fetch-posts`, { headers: AUTH, data: { slug, ...extra } }); + return { status: res.status(), body: (await res.json()) as { ok: boolean; jobId?: string; error?: string } }; +} + +test("X: a stale jar refuses Fetch posts; \"\" is refused; a challenge fails the job, raises the X banner and refuses the next fetch; Recheck asks X nothing", async ({ + page, + request, +}) => { + test.setTimeout(120_000); + await writeSettings({ minFreeDiskGB: 0, social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } } }); + await xChannel("x-challenged", "challenged_user"); + await xChannel("x-other", "faketester"); + + // A 16-day-old jar: refused before any job exists. + await xJar(16 * 24 * 60 * 60_000); + const stale = await fetchPosts(request, "x-other"); + expect(stale.status).toBe(400); + expect(stale.body.error).toBe( + "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.", + ); + + // A fresh jar; an unqueued fetch is still refused. + await xJar(60_000); + const unqueued = await fetchPosts(request, "x-other", { queueKey: "" }); + expect(unqueued.status).toBe(400); + expect(unqueued.body.error).toMatch(/never runs unqueued: the queue override "" \(immediate\) is refused/); + + // X answers with a challenge (a warning, exit 0): the job FAILS. + const challenged = await fetchPosts(request, "x-challenged"); + expect(challenged.body.ok).toBe(true); + expect(await waitJob(request, challenged.body.jobId!)).toBe("failed"); + const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${challenged.body.jobId}.log`), "utf8"); + expect(log).toContain("[twitter][warning] Cloudflare challenge"); + expect(log).toMatch(/X answered with a challenge or a login wall/); + + // The next X fetch is refused with the alert's sentence. + const after = await fetchPosts(request, "x-other"); + expect(after.status).toBe(400); + expect(after.body.error).toMatch(/^X answered with a challenge at \d\d:\d\d UTC .*its cookie alert is up, so no X job starts/); + + // The banner. + await page.goto(`${baseUrl}/`); + const banner = page.getByRole("alert", { name: "X cookies" }); + await expect(banner).toContainText("X needs fresh cookies: pass X's check by hand"); + await expect(banner).toHaveAttribute("data-state", "stale"); + + // Recheck before the jar is refreshed: stale, and no request was made. + await banner.getByRole("button", { name: "Recheck" }).click(); + await expect(page.getByRole("status", { name: "X cookies result" })).toContainText("Recheck sends X no request", { + timeout: 30_000, + }); + await expect(banner).toHaveAttribute("data-state", "stale"); + + // The operator refreshes the jar (Refresh cookies on /settings); Recheck clears it. + await xJar(0); + await banner.getByRole("button", { name: "Recheck" }).click(); + await expect(banner).toHaveAttribute("data-state", "ok-again", { timeout: 30_000 }); + const ok = await fetchPosts(request, "x-other"); + expect(ok.body.ok).toBe(true); + expect(await waitJob(request, ok.body.jobId!)).toBe("done"); +}); diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs @@ -30,6 +30,14 @@ if (rangeIdx >= 0 && args[rangeIdx + 1]) { if (m) limit = Number(m[1]); } +// X'S ANSWER ON 2026-10-23 (plans/pacing-guard.md): a Cloudflare challenge +// as a WARNING, exit 0, nothing read — for the account `challenged_user`, so a +// spec picks it by the channel's URL (cookie-alerts.spec). +if (handle === "challenged_user") { + process.stderr.write("[twitter][warning] Cloudflare challenge\n"); + process.exit(0); +} + // Mirror the real failure the Needs-cookies bucket models: when the fixture is // asked to simulate an expired session, exit non-zero with an auth-shaped // message on stderr. diff --git a/editor/e2e/pacing.spec.ts b/editor/e2e/pacing.spec.ts @@ -1,4 +1,4 @@ -import { mkdir, writeFile } from "node:fs/promises"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; import { test, expect } from "@playwright/test"; import { readJson, resetData, resolvePath, writeSettings, testPaths } from "./helpers"; import { baseUrl } from "./baseUrl"; @@ -231,3 +231,37 @@ test("a live 429 backs youtube off, defers the video, and the next pick is the n .toContain("a2"); expect(pickOrder(await getStatus(request))).toEqual(["wp429vid1", "a2"]); }); + +// THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE (plans/pacing-guard.md). The +// test server turns the built-in gaps off (E2E_JOB_GAP_SECONDS=0); this spec +// sets YouTube's to 6 s. Two download-missing jobs on platform:youtube: the +// second waits, its /jobs row says so while it does, and its log keeps the line. +test("a second job on platform:youtube waits pacing.jobGapSeconds after the first ended, and says so", async ({ + page, + request, +}) => { + test.setTimeout(60_000); + await resetData("empty"); + await writeSettings({ minFreeDiskGB: 0, sleepBetweenDownloadsSeconds: 0, pacing: { jobGapSeconds: { youtube: 6 } } }); + await makeDownloadChannel("gap-chan", []); + const AUTH = { authorization: "Bearer test-worker-token" }; + const start = async () => { + const res = await request.post(`${baseUrl}/api/ops/download-missing`, { headers: AUTH, data: { slug: "gap-chan" } }); + expect(res.status()).toBe(200); + return ((await res.json()) as { jobId: string }).jobId; + }; + const status = async (id: string) => + ((await (await request.get(`${baseUrl}/api/ops/job/${id}`, { headers: AUTH })).json()) as { job?: { status?: string } }) + .job?.status ?? ""; + const first = await start(); + await expect.poll(() => status(first), { timeout: 20_000 }).toBe("done"); + const second = await start(); + await page.goto(`${baseUrl}/jobs`); + await expect(page.getByTestId("job-paced").first()).toContainText( + "YouTube jobs are spaced 6 s apart (pacing.jobGapSeconds.youtube)", + { timeout: 10_000 }, + ); + await expect.poll(() => status(second), { timeout: 30_000 }).toBe("done"); + const log = await readFile(resolvePath(`${testPaths().transcriptsDir}/.jobs/${second}.log`), "utf8"); + expect(log).toMatch(/waiting \ds: YouTube jobs are spaced 6 s apart \(pacing\.jobGapSeconds\.youtube\)/); +}); diff --git a/editor/e2e/queues.spec.ts b/editor/e2e/queues.spec.ts @@ -205,37 +205,25 @@ test("cancels a queued job without disturbing the one running ahead of it", asyn await expect(slowARow.getByText("running", { exact: true })).toBeVisible(); }); -test("empty queue runs immediately even when another job is queued in the same name", async ({ +// A NETWORK JOB IS NEVER RUN UNQUEUED (plans/pacing-guard.md, 2026-10-23). +// "(immediate)" — queue "" — used to run a Sync at once beside everything, +// outside its platform's queue and gap; it is no longer offered on an action +// whose default is a platform queue, and typed by hand it is refused before +// any job exists. +test("a Sync is never run unqueued: no (immediate) option, and an empty custom queue is refused", async ({ page, }) => { await resetData("two-slow-channels"); - - // Park slow-a's Sync into qShared and start it. - await generateReport(page, "slow-a"); - await page.goto(channelStage("slow-a", "playlist")); - await setQueueViaCustom(page, "Sync", "qShared"); - await page.getByRole("button", { name: "Sync" }).click(); - await expect(page.getByLabel("Sync output")).toContainText("test-slow", { - timeout: 15_000, - }); - - // slow-b sets queue to immediate (the default empty option) and starts; - // it should bypass qShared and run right away. await generateReport(page, "slow-b"); await page.goto(channelStage("slow-b", "playlist")); - await page - .getByLabel("queue for Sync", { exact: true }) - .selectOption({ label: "(immediate)" }); + const picker = page.getByLabel("queue for Sync", { exact: true }); + await expect(picker.locator("option", { hasText: "(immediate)" })).toHaveCount(0); + await setQueueViaCustom(page, "Sync", ""); await page.getByRole("button", { name: "Sync" }).click(); - // No "queued" banner: it goes straight to running and produces output. - await expect(page.getByLabel("Sync output")).toContainText("test-slow", { - timeout: 15_000, - }); - + await expect(page.getByLabel("Sync error")).toContainText( + 'never runs unqueued: the queue override "" (immediate) is refused', + { timeout: 10_000 }, + ); await page.goto("/jobs"); - const slowARow = page.getByRole("row").filter({ hasText: "slow-a" }).first(); - const slowBRow = page.getByRole("row").filter({ hasText: "slow-b" }).first(); - await expect(slowARow.getByText("running", { exact: true })).toBeVisible(); - await expect(slowBRow.getByText("running", { exact: true })).toBeVisible(); - await expect(slowBRow).toContainText("(immediate)"); + await expect(page.getByRole("row").filter({ hasText: "slow-b" })).toHaveCount(0); }); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -40,6 +40,13 @@ export const E2E_SERVER_ENV: Record<string, string> = { E2E_AUDIO_CHECK_RECOVER_AFTER: "2", E2E_BACKOFF_BASE_MS: "20000", E2E_CLIP_WINDOW_GAP_MS: "2000", + // The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on + // the test server — a spec's two fake X fetches would otherwise sit five + // minutes apart, and every fake X fetch would need a fresh jar. A spec that + // sets pacing.jobGapSeconds or social.x.maxCookieAgeMinutes in settings.json + // gets exactly that (pacing.spec, x-session.spec). + E2E_JOB_GAP_SECONDS: "0", + E2E_X_MAX_COOKIE_AGE_MINUTES: "0", E2E_LIVE_CHECK: "skip", WRANGLER_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-wrangler.mjs"), ARCHILYZER_BRANCH: "main", diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -30,6 +30,10 @@ import { currentSlot } from "./e2e/testPaths"; // batch (30–45 s in production; 2 s here), so // fetch-window.spec sees the one it owes // (common/controller/fetchWindows.ts) +// E2E_JOB_GAP_SECONDS, 0: the pacing guard's BUILT-IN job gap and X +// E2E_X_MAX_COOKIE_AGE_MINUTES cookie-age limit are off on the test server +// (common/jobs/queueGap.ts, networkGuard.ts); a +// value a spec writes into settings.json applies // E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN diff --git a/plans/pacing-guard.md b/plans/pacing-guard.md @@ -0,0 +1,116 @@ +# Pacing guard — no unpaced network job, X only on a fresh jar, a challenge stops X + +Lane `lane/pacing-guard`, 2026-10-23. + +## Why + +On the night of 2026-10-23 an agent queued `fetch-posts` for 13 X accounts in one loop. The registry runs +one job per queue and starts the next the moment one ends, so they ran ~0.6 s apart on a cookie jar exported +16 days earlier. X answered with a Cloudflare challenge; gallery-dl printed `[twitter][warning] Cloudflare +challenge`, exited 0, read nothing, and every job ended `done`. The operator had to pass a human verification +on the account. + +Operator, verbatim: "Let's be more cautious- only start X downloads with a recent cookie refresh", "yeah never +do that, be very careful not to do that thing on any sort of site", "This should be enforced in Archilyzer, not +just an AI standing rule". + +The same night a podcast feed channel's (`platform:megaphone.fm`) download-missing probed ~1,150 episodes with +yt-dlp back to back to learn their titles for the download filter. + +## What is enforced + +All of it in code, in the one job funnel (`runManagedFunction`, `common/jobs/streamCommand.ts`), driven by a +declarative flag on the kind. + +1. **`network` on a job kind** (`common/jobs/jobKinds.ts`). 40 kinds that send requests to a platform declare + `network: true` (fetch-posts, capture-posts, import-post, check-post-availability, sync, download-*, + import-one, import-archive-org, metadata-scan, store-playlist, refresh-metadata, fetch-window(s), + record-live, persist-*, fetch-chat, auto-download-unit, the availability checks, import-page, + save-page-now, wayback-scan, browser-lookup, find-copy, fetch-copies, whisper-video, transcribe-one, + check-kept-deleted, import-media, recheck-service-cookies …); the two offline kinds on a platform queue + (import-forum-pages, reextract-pages) declare `false`. `jobKinds.test.ts` fails if a platform-queue kind + declares neither. A caller may mark one job `network: false` (a fetch-chat whose replay is already on disk + only normalizes it); never the other way. +2. **No unpaced network job** (`common/jobs/networkGuard.ts`). A queue override of `""` (immediate) is refused + for a network kind, before any job exists. `QueueControl` no longer offers "(immediate)" on an action whose + default is a `platform:` queue. +3. **The gap between jobs on a platform queue** (`common/jobs/queueGap.ts`, `common/lib/jobGap.ts`). A network + job on `platform:<p>` does not begin until `pacing.jobGapSeconds[p]` (else the built-in for p, else + `default`) after the previous network job there ENDED. Built in: default 20, twitter 300, xenforo 60, + bluesky 60; only keys the operator sets are stored. While it waits, the job is `running` (its queue slot + held) and its log and /jobs row say `waiting 4m12s: X jobs are spaced 5 min apart + (pacing.jobGapSeconds.twitter)`. Only a job that got past its guards counts as an end, so a refused job does + not make the next one wait. The last end per queue is in memory and in `.jobs/queue-gaps.json`, so a restart + is not a free pass. Cancel aborts the wait; Drain ends the job `done` without asking anything. +4. **X only on a fresh jar.** Before a network job aimed at X (its queue is `platform:twitter`, or its channel's + platform is twitter) is queued, and again when its queue starts it (and once more after its gap), with the + `"profile"` login source: refused unless the exported jar's mtime is within `social.x.maxCookieAgeMinutes` + (absent 60, 0 off) and it carries an auth_token. The sentence: `X cookies were last refreshed 16 days ago + (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again.` With the + `"browser"` source the age cannot be read: the job logs that and proceeds. Nothing refreshes the jar + automatically — `refreshXCookies` loads x.com/home, itself a request to X. +5. **A challenge stops X.** `GalleryDlStream` records the first stderr line with a challenge word + (`cloudflare`, `challenge`, `just a moment`, `captcha`) or an AUTH_ERROR_PATTERNS match on a warning/error + line, on ANY exit code. The timeline walk, the older/search windows and the media capture then fail (posts + read so far kept; `needsCookies`, an `error`) and raise **X as a cookie-alert service** (`"x"`, label "X", + family `x`; `lib/serviceCookies.ts`) — one signal is enough. **While the X alert is raised, every X job is + refused before it starts** with `X answered with a challenge at HH:MM UTC (<line>) and its cookie alert is + up, so no X job starts: …, then Recheck on the dashboard.`, and the refused job is recorded on the alert for + **Re-run stopped jobs**. A clean gallery-dl run notes a clean request (clears a pending one, remembers the + last good URL). **Recheck for X sends X no request**: clean when the login on disk (the profile jar, or the + browser's x.com auth_token last-sent time) was renewed after the alert was raised. The dashboard banner, `pnpm + ops get services`, `recheck-service`, `dismiss-service`, `rerun-service-jobs` and `archilyzer doctor` carry + it like the other services. +6. **A probe is a request.** Release 9 B2 let a video the download filter declined after only its metadata + prefetch skip `sleepBetweenDownloadsSeconds`; now only an outcome with no attempt at all skips it + (`madeNoRequest`, `common/ytdlp/runYtdlp.ts`). To keep that cheap: a channel with a download filter, no + known platform, and a playlist that is mostly direct media files (a feed's enclosures) reads its feed ONCE per + download run and writes each unscanned episode's title into the metadata-scan store + (`common/controller/feedTitlePrefilter.ts`); `settledByTitleFilterIds` then declines a filtered episode + with no request. + +Settings: `pacing.jobGapSeconds` (on /settings beside the download sleep: every platform, X, forums, Bluesky; +a value equal to the built-in is not stored) and `social.x.maxCookieAgeMinutes` (the X account section). +SETTINGS.md regenerated. Test-only: `E2E_JOB_GAP_SECONDS` and `E2E_X_MAX_COOKIE_AGE_MINUTES` replace the +BUILT-IN values (the e2e server sets both to 0); a value written into settings.json still applies. + +## The lanes + +The auto-download lane's units (`auto-download-unit`) ride the platform queues and are network jobs, so they +wait `max(the lane's own gap, the queue gap)`: the lane already waits `sleepBetweenDownloadsSeconds` (+ the +adaptive pace) after a unit settles before it queues the next on that platform. With the operator's 30 s sleep +the 20 s default adds nothing; with the shipped default sleep (10 s) a YouTube unit starts 20 s after the last +instead of 10. Other effects: a scheduler tick's syncs on one platform start 20 s apart; imports on archive.org's +queue (import-page, save-page-now, import-archive-org) 20 s apart; a channel's X fetches 5 min apart. The +transcription, digest, backfill and clip-window lanes are not on `platform:` queues and are unchanged. + +## Verified + +- `pnpm typecheck` clean. `pnpm --filter yt-dlp-transcript-common test`: 5005 pass, 0 fail, 2 skipped (the two + autoRunner computeLeafPending failures seen on main did not reproduce here). `pnpm test:scripts`: 1446 pass, + 0 fail. `pnpm --filter editor test`: 370 pass. Docs: `archilyzer settings example --check`, `docs cli + --check`, `docs env --check`, `docs files --check` clean. +- `common/jobs/pacingGuard.test.ts` reproduces the night through the real funnel, the real fetch controller and + the real gallery-dl fetcher against a fake binary: 13 `fetch-posts` on `platform:twitter`; job 1 meets the + Cloudflare warning (exit 0) → job 1 `failed`, the X alert raised, jobs 2–13 refused at their start without + spawning gallery-dl (one gallery-dl run in all), all 13 on the alert, a fourteenth refused at enqueue; with + no challenge the 13 start ≥ 300 s apart on a fake clock and the second's log carries the waiting line; a + 16-day-old jar is refused at enqueue and a jar that went stale while a job was queued refuses it at start; + `""` is refused for a network kind and allowed for an offline one. +- Unit tests: `jobs/queueGap.test.ts`, `jobs/networkGuard.test.ts`, `jobs/jobKinds.test.ts` (every platform + kind decided), `lib/serviceCookies.test.ts` (X), `controller/recheckServiceCookies.test.ts` (X asks nothing), + `controller/feedTitlePrefilter.test.ts`, `ytdlp/managedDownloadsSleep.test.ts` (a probe sleeps), + `controller/fetchPosts.test.ts` (an auth failure now fails the fetch). +- e2e (written, NOT run in the lane — the orchestrator runs the suite): `cookie-alerts.spec` (a stale jar's + sentence, `""` refused, the fake gallery-dl's `challenged_user` answers with the challenge → the job fails, + the next fetch is refused, the X banner, Recheck stale then clean after the jar is refreshed, then a fetch + runs), `pacing.spec` (two download-missing jobs on `platform:youtube` with a 6 s gap: the /jobs row and the + log), `queues.spec` (no "(immediate)" on Sync; an empty custom queue is refused — replaces "empty queue runs + immediately"). + +## Not done + +- A Bluesky or forum jar-age rule (X only, as asked). The forum's own challenge alert already existed; it still + only logs and does not refuse the next forum job (a forum fetch has `retryOnBlock`). +- The X Article/screenshot half of capture-posts loads pages through the profile, not gallery-dl; a challenge + page there is not yet recognised (its media download through gallery-dl is). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1056,9 +1056,11 @@ export function usage() { "", 'recheck-service asks a service whose cookie refresh alert is up ONE request', ' through its own path, as the dashboard banner\'s Recheck: {"service"}', - ' ("rumble", "youtube", "odysee", "archive.today" or a forum host). Waits', - ' for it: {jobId, result: "clean" | "stale" | "failed", message}; "clean"', - " clears the alert (and a yt-dlp service's backoff, as any clean request).", + ' ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host).', + ' Waits for it: {jobId, result: "clean" | "stale" | "failed", message};', + " \"clean\" clears the alert (and a yt-dlp service's backoff, as any clean", + ' request). For "x" it sends X NO request: clean when the login on disk', + ' was renewed after the alert (Refresh cookies on /settings).', 'dismiss-service clears a service\'s cookie alert by hand: {"service"}.', 'rerun-service-jobs retries every job a service\'s cookie alert stopped, once', ' it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them.', diff --git a/settings.json.example b/settings.json.example @@ -13,7 +13,8 @@ "sleepRequestsCapSeconds": 16, "decayAfterCleanUnits": 5, "holdAfterFailsAtCap": 3, - "holdProbeMinutes": 60 + "holdProbeMinutes": 60, + "jobGapSeconds": {} }, "downloadFormat": "auto", "sourceVideoQuality": "original",