// THE TWO RULES EVERY X JOB MEETS, AND THEIR NUMBERS (lane x-followups, R2; // the operator, 18 Nov 2026: "X should refuse and/or have an immutable global // per-account cap"). ONE module: the constants are here and nowhere else. // // 1. X JOBS RUN ON X'S QUEUE ONLY (`platform:twitter`). A job that asks X // as the connected account or with X's cookies — a posts fetch in any // mode, a resumed backfill, a sync, a capture, a trending read, an // import of an X post, an availability check, a channel's turn in an X // run — is refused on any other queue: when it is queued // (jobs/networkGuard.ts) and again where it runs (xJobContextRefusal, // asked by the code that is about to ask X). On another queue it would // run beside the job on X's and outside the gap between X jobs. // // 2. A CAP NOBODY CAN RAISE: at most X_JOB_CAP.perHour X jobs started in any // rolling 60 minutes and X_JOB_CAP.perDay in any rolling 24 hours, ON // THIS MACHINE, over every kind of X job together (review 2 M1: ONE // bucket — never one per login source, cookie spec or channel, which a // flipped source or a respelled spec would turn into a fresh count for // the same X account). A job past it is refused before it starts, with // the time the next may start; one that meets it AT its start ends // deferred, not failed (jobs/networkGuard.ts). // // WHAT COUNTS (review 2, ruling R-a): a job that can ask x.com with the // login or X's cookies — xJobCounts below, decided from the job's own plan // (its kind and its spec), never from a flag a caller passes. // // THE CAP IS A CONSTANT OF THE CODE. It is not in settings.json, not in a // channel's config, not an environment variable, not an option of any action // or command, and no `force` passes it. Changing it is a code change, reviewed // like one. Nothing in this module reads a setting. // // Pure but for xJobContextRefusal, which reads the running job's context // (lib/jobContext.ts). The count's file is jobs/xJobCap.ts. import { currentJobContext } from "./jobContext"; export const X_QUEUE_KEY = "platform:twitter"; // THE HOURLY CAP IS 6 (the operator, 21 Nov 2026: one sitting of 12 timeline // fetches back to back, at the old cap of 12, preceded the account's // suspension). At 6 an hour the daily 150 is implied (6 × 24 = 144): it stays // as a second, independent bound. export const X_JOB_CAP = Object.freeze({ perHour: 6, hourMs: 60 * 60_000, perDay: 150, dayMs: 24 * 60 * 60_000, }); // HOW LONG X IS LEFT ALONE AFTER IT ANSWERED 429: X's own rate-limit window. // Written as the `twitter` platform cooldown (jobs/downloadBackoff.ts // recordPlatformCooldown) by every X reader that meets one — a trending read, // its media, a capture, a gallery-dl run — and read by the network guard, // which refuses EVERY X job while it lasts (jobs/networkGuard.ts). export const X_RATE_LIMIT_HOLD_MS = 15 * 60_000; // ── 1. the queue ─────────────────────────────────────────────────────────── // Why a job that asks X may not be on `queueKey`, or null. `what` names the // job ("fetch-posts for example-x"). export function xQueueRefusal(what: string, queueKey: string | undefined): string | null { if (queueKey === X_QUEUE_KEY) return null; return ( `${what} asks X, and X jobs run on X's queue only (${X_QUEUE_KEY}): the queue ` + `${queueKey === undefined || queueKey === "" ? "it was given" : `"${queueKey}"`} is refused. ` + "On another queue it would run beside the job on X's, outside the gap between X jobs. Leave the queue at its default." ); } // WHERE X IS ABOUT TO BE ASKED: only inside a job of the editor's, and only // one on X's queue. Null when the caller stands there. `door` names the way // in ("pnpm ops fetch-posts --json '{…}' --wait"). export function xJobContextRefusal(what: string, door: string): string | null { const job = currentJobContext(); if (!job) { return ( `${what} asks X, and X is asked only by the editor's own jobs (on X's queue, spaced apart, on a fresh ` + `cookie jar, under X's job cap, stopped by the X alert and held after a rate limit): nothing was asked. ` + `Queue it instead: ${door}` ); } const queue = xQueueRefusal(what, job.queueKey); return queue ? `${queue} Nothing was asked.` : null; } // ── 2. the cap ───────────────────────────────────────────────────────────── export type XJobCapVerdict = { ok: boolean; // X jobs started in the last 60 minutes and the last 24 hours. lastHour: number; lastDay: number; // When the next X job may start (ms since the epoch), when `ok` is false. nextAt?: number; window?: "hour" | "day"; }; // THE CLOCK NEVER FREES A START EARLY, AND A START IN THE FUTURE NEVER HIDES // THE REAL ONES (review 3 S4). A window is every start later than `now` minus // its length — a start stamped after `now` included: a machine clock set back // (by a person, by a time sync) leaves every recorded start inside its window // until the clock has passed it again, and one stamped far ahead (a clock that // jumped forward) counts in both windows without pushing the windows past the // starts around it. export function xJobCapVerdict(starts: ReadonlyArray, now: number): XJobCapVerdict { const recent = [...starts].filter((t) => Number.isFinite(t)).sort((a, b) => b - a); const hour = recent.filter((t) => t > now - X_JOB_CAP.hourMs); const day = recent.filter((t) => t > now - X_JOB_CAP.dayMs); const out = { lastHour: hour.length, lastDay: day.length }; // The next may start once the oldest of the newest starts has left its window. const hourFree = hour.length >= X_JOB_CAP.perHour ? hour[X_JOB_CAP.perHour - 1] + X_JOB_CAP.hourMs : null; const dayFree = day.length >= X_JOB_CAP.perDay ? day[X_JOB_CAP.perDay - 1] + X_JOB_CAP.dayMs : null; if (hourFree === null && dayFree === null) return { ok: true, ...out }; const window = dayFree !== null && (hourFree === null || dayFree >= hourFree) ? "day" : "hour"; return { ok: false, ...out, nextAt: Math.max(hourFree ?? 0, dayFree ?? 0), window }; } const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); const day = (ms: number) => new Date(ms).toISOString().slice(0, 10); // The refusal: which cap, how full, and when the next X job may start. export function xJobCapSentence(v: XJobCapVerdict, now: number): string { if (v.ok || v.nextAt === undefined) return ""; const full = v.window === "day" ? `${v.lastDay} X jobs started in the last 24 hours (the cap is ${X_JOB_CAP.perDay})` : `${v.lastHour} X jobs started in the last 60 minutes (the cap is ${X_JOB_CAP.perHour})`; const minutes = Math.max(1, Math.ceil((v.nextAt - now) / 60_000)); const when = `${day(v.nextAt) === day(now) ? "" : `${day(v.nextAt)} `}${hhmm(v.nextAt)} UTC`; const wait = minutes >= 120 ? `about ${Math.round(minutes / 60)} h` : `${minutes} min`; return ( `X's job cap is reached on this machine: ${full}. The next X job may start at ${when} (in ${wait}); ` + "ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it." ); } // The sentence for a count that cannot be read: nothing starts on a guess. export function xJobCapUnreadableSentence(file: string): string { return ( `X's job count cannot be read (${file}): no X job starts while it is unreadable, because the cap on X jobs ` + "is counted there. Repair the file (it is JSON: {version: 2, starts: [times]}), then ask again." ); } // The sentence for a count that is not on disk and cannot be rebuilt from the // job records (review 2, ruling R-c): `why` says what is missing; `until`, // when known, is when no X job on record can still count. export function xJobCapUnrebuildableSentence(file: string, why: string, until?: number): string { return ( `X's job count is not on disk (${file}) and cannot be rebuilt from the job records: ${why}. ` + "No X job starts while the last day's X jobs cannot be counted" + (until !== undefined ? ` — at the latest until ${day(until)} ${hhmm(until)} UTC, when none on record can still count` : "") + ". Restore the job records (the corpus's .jobs directory) and ask again." ); } // ── 3. what counts ───────────────────────────────────────────────────────── // The job as it will run: its kind, its spec's params (jobs/jobSpec.ts — what // the job's function runs with), and the channel it is for. export type XJobPlan = { kind: string; params?: Readonly>; channel?: { library?: boolean; postCaptureThread?: boolean }; }; // DOES THIS X JOB COUNT AGAINST THE CAP? Every X job does — a read, a fetch in // any mode, an X run's channel, an import, an availability check, and a // capture of any kind, a trending library's media-only capture included // (review 1 F8 of lane x-sittings, the operator's ruling: it asks X's media // hosts, so it is an X job — in the sitting, the cap and the gap). Only the // transcription worker, which reads a file on disk, does not. export function xJobCounts(plan: XJobPlan): boolean { return plan.kind !== "transcribe-one"; } // ── 4. which jobs ask x.com (review 2 S5, review 3 M2/S5/S6) ─────────────── // X's clip windows run on X's own queue (lib/queueKeys.ts clipWindowQueueKey); // the clip queue X once had is X's all the same. export const X_CLIPS_QUEUE_KEY = "clips:twitter"; // Windows cut from saved containers (lib/queueKeys.ts SAVED_VIDEO_CLIP_QUEUE). const SAVED_VIDEO_CLIP_QUEUE = "clips:saved-video"; // IS THIS ADDRESS X'S? x.com and twitter.com and their subdomains, X's short // links (t.co: X answers and redirects to the post — asking it is asking X; // review 3 S6), and X's media hosts (twimg.com: video., pbs. and the rest; // review 4 C). By the HOST alone, lowercased and without a trailing dot: a // host that merely ends in "twitter.com" (nottwitter.com) or begins with an X // host (x.com.example.org) is not X's, and neither is a userinfo that reads // like one (https://x.com@example.org/). An address written without a scheme // is X's when its first segment is an X host ("x.com/u/status/1"). const X_HOSTS: ReadonlyArray = ["x.com", "twitter.com", "t.co", "twimg.com"]; function hostOf(raw: string): string | null { const s = raw.trim(); // A scheme with an authority (https://…); a scheme-relative //host/…; a // scheme with none (mailto:, javascript:), which names no host; else no // scheme at all — the first segment is the host (a port after it allowed). const href = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : s.startsWith("//") ? `https:${s}` : /^[a-z][a-z0-9+.-]*:(?!\d)/i.test(s) ? s : `https://${s}`; try { const host = new URL(href).hostname.toLowerCase().replace(/\.+$/, ""); return host || null; } catch { return null; } } export function isXUrl(url: unknown): boolean { if (typeof url !== "string" || !url.trim()) return false; const host = hostOf(url); return host !== null && X_HOSTS.some((h) => host === h || host.endsWith(`.${h}`)); } // The network job as queued: its kind, its queue, its channel's platform and // its spec's params. `itemChannelPlatforms`: for a batch of windows, the // platform of each item's channel (by slug), read by the caller — an item // that names no URL is fetched from its channel's page. export type XAskPlan = { kind: string; queueKey: string; channelPlatform?: string | null; params?: Readonly>; itemChannelPlatforms?: Readonly>; }; const isWindowKind = (kind: string) => kind === "fetch-window" || kind === "fetch-windows"; // The windows a window job will fetch: each one's page URL (when it names one) // and its channel. A single window's are its params'. function windowAsks(plan: XAskPlan): Array<{ url?: string; slug?: string }> { const p = plan.params; if (plan.kind === "fetch-windows" && p && Array.isArray(p.items)) { return (p.items as unknown[]).map((raw) => { const it = raw && typeof raw === "object" ? (raw as Record) : {}; const url = typeof it.webpageUrl === "string" && it.webpageUrl.trim() ? it.webpageUrl.trim() : undefined; const slug = typeof it.slug === "string" ? it.slug : undefined; return { ...(url ? { url } : {}), ...(slug ? { slug } : {}) }; }); } const url = typeof p?.webpageUrl === "string" && p.webpageUrl.trim() ? p.webpageUrl.trim() : undefined; // No plan to read: one window of the job's channel. return [url ? { url } : {}]; } // DOES THIS NETWORK JOB ASK x.com? It does on X's queue (or X's old clip // queue), whatever its kind. Then: // import-one asks its URL's host (isXUrl: x.com, twitter.com, t.co, twimg.com); // fetch-window(s) ask the URLs of their windows (review 3 M2), ON ANY // CHANNEL: an x.com page is X's wherever it is filed. A // window that names no URL is fetched from its // channel's page, so its CHANNEL decides — "no URL" // never passes by itself (S5). On `clips:saved-video` // they ask nothing: windows cut from the saved copy on // disk — and the controller never goes to the network // for an X source from that queue (M1, // controller/fetchWindows.ts); // fetch-copies archive.org (its controller refuses an X address); // transcribe-one the transcription worker, over a file on disk; // import-media asks its page's address when it names one // (`params.url`, isXUrl — review 4 B), on any channel // and queue; with none, on its own queue // (`import-media:`), a local file; // import-archive-org archive.org. // Everything else an X channel queues asks X, and is refused off X's queue. export function xJobAsksX(plan: XAskPlan): boolean { if (plan.queueKey === X_QUEUE_KEY || plan.queueKey === X_CLIPS_QUEUE_KEY) return true; if (plan.kind === "import-one" && typeof plan.params?.url === "string") return isXUrl(plan.params.url); if (plan.kind === "transcribe-one") return false; if (plan.kind === "import-media" && typeof plan.params?.url === "string" && plan.params.url.trim()) return isXUrl(plan.params.url); if (isWindowKind(plan.kind)) { if (plan.queueKey === SAVED_VIDEO_CLIP_QUEUE) return false; return windowAsks(plan).some((w) => { if (w.url) return isXUrl(w.url); const platform = w.slug !== undefined && plan.itemChannelPlatforms && Object.hasOwn(plan.itemChannelPlatforms, w.slug) ? plan.itemChannelPlatforms[w.slug] : plan.channelPlatform; return platform === "twitter"; }); } if (plan.channelPlatform !== "twitter") return false; if (plan.kind === "fetch-copies") return false; if (plan.kind === "import-media" && plan.queueKey.startsWith("import-media:")) return false; if (plan.kind === "import-archive-org") return false; return true; }