commit 7a520a7e2c872b5e00471940e5a207b607ca879b
parent 456c582e0134571a76d79b257b13a3bbb0855631
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 10:57:34 -0400
pacing guard: network kinds never run unqueued, platform queues spaced by pacing.jobGapSeconds, X jobs only on a fresh jar and with no X alert
A kind that sends requests to a platform declares network: true (jobKinds.ts).
runManagedFunction (jobs/networkGuard.ts) refuses a queue override of "" for
it, refuses a job aimed at X while the X cookie alert is raised or when the
profile's exported jar is older than social.x.maxCookieAgeMinutes (default
60) or holds no login -- at enqueue and again at the start -- and waits
pacing.jobGapSeconds[p] (built in: default 20, twitter 300, xenforo 60,
bluesky 60) after the previous network job on platform:<p> ended
(jobs/queueGap.ts, the last end kept in .jobs/queue-gaps.json).
gallery-dl's challenge or login-wall line now stops an X fetch even on exit 0
(the fetch fails, posts read so far kept) and raises X as a cookie-alert
service; Recheck for X sends no request (the login renewed after the alert).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
20 files changed, 1281 insertions(+), 10 deletions(-)
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.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.ts b/common/jobs/networkGuard.ts
@@ -0,0 +1,215 @@
+// 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 };
+}
+
+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: 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.ts b/common/jobs/queueGap.ts
@@ -0,0 +1,284 @@
+// 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,
+ 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,
@@ -379,6 +382,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 = await guardNetworkJob(opts);
+ if (!network.ok) return { ok: false, error: network.error };
const registry = getRegistry();
await ensureJobsDir(opts.paths);
const { id, logPath, record } = makeJob(
@@ -457,6 +465,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 +473,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 = 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 +532,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/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.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
@@ -168,6 +168,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,8 +770,51 @@ 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>>;
};
+// 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;
+
+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: Pick<PacingSettingsBlock, "jobGapSeconds"> | 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" };
+}
+
export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = {
sleepRequestsCapSeconds:
"Ceiling (seconds) on a platform's adaptive `--sleep-requests`. The pace " +
@@ -779,6 +833,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 +883,7 @@ export function sanitizePacing(v: unknown): PacingSettingsBlock {
1440,
PACING_DEFAULT_HOLD_PROBE_MINUTES,
),
+ jobGapSeconds: sanitizeJobGapSeconds(r.jobGapSeconds),
};
}
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/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";
@@ -303,6 +304,18 @@ function JobRowHeading({
{job.background && " · waiting behind a manual job"}
</span>
)}
+ {job.paced && (
+ // A network job waiting out its platform queue's gap
+ // (jobs/queueGap.ts). Counted from the poll's payload.
+ <span
+ data-testid="job-paced"
+ className={compact ? "min-w-0 truncate text-xs text-muted-foreground" : "text-xs text-muted-foreground"}
+ title={job.paced.reason}
+ suppressHydrationWarning
+ >
+ waiting {waitText(job.paced.until - Date.now())}: {job.paced.reason}
+ </span>
+ )}
{/* 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 />}