// 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. // INSTAGRAM THE SAME (lane instagram): its alert refuses every Instagram // job until a person's Recheck, and so does its cooldown after a rate // limit (jobs/instagramGuard.ts). Which platforms have a guard is ONE // table, PLATFORM_GUARDS below. // 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 /cookies — 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. // // 4. X IN SITTINGS (lane x-sittings, lib/xSitting.ts, jobs/xSitting.ts): a // cookie refresh admits at most `social.x.sittingJobs` X job starts (4; // 1-6 in the code), of ONE kind (timelines or browse, fixed by the // first); X cooling down after a 429 refuses every X job; and an // account the operator marked suspended refuses the jobs that record // posts as deleted (social/xAccountState.ts). All in xSessionReport, the // one computation behind the refusal and `get x-session`. // // 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 { INSTAGRAM_SERVICE, serviceFixText, X_SERVICE } from "../lib/serviceCookies"; import { instagramJobGuard } from "./instagramGuard"; import { configuredCookieBrowser, noteServiceStoppedJob, noteXJarFresh, noteXJarStale, raisedServiceAlert, } from "../lib/serviceCookies-server"; import { readXSessionStatus, xCookieFile, xProfileDir, type XSessionStatus, } from "../social/xSessionBroker"; import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource"; import { jobKindLabel, kindIsNetwork } from "./jobKinds"; import { xJobAsksX, xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { recordXJobStart, xJobCapStatus } from "./xJobCap"; import { recordXSittingStart, xSittingLook } from "./xSitting"; import { xSittingJobs, xSittingKindOf, xSuspendedRefuses, xSuspendedSentence, type XSittingKind, } from "../lib/xSitting"; import { readXAccountState, xAccountAlertLine } from "../social/xAccountState"; import { heldPlatformRefusal, xStopRemainingMs } from "./downloadBackoff"; import { xRateLimitHoldSentence } from "../lib/xTrending/config"; import { writeJobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; import { getRegistry } from "./registry"; import { queueGapClock, queueGapPlatform } from "./queueGap"; export type NetworkJobOpts = { kind: string; queueKey: string; paths: Paths; channelSlug?: string; // THE LAST GUARD BEFORE THE JOB'S WORK (jobs/streamCommand.ts; an X run's // guard before each channel): an X job that passes it is COUNTED against // X's job cap (lib/xJobRule.ts), checked and recorded in one step. The // guards before it — at enqueue, and at the start before the queue's gap — // only look. countStart?: boolean; // The job's replay descriptor — what its function runs with. X's job cap // reads its PLAN from it (lib/xJobRule.ts xJobCounts): never a flag. spec?: JobSpec; // What a job with NO replay descriptor will ask (import-media's page // address, review 4 B): read by the guards in place of `spec.params`, and // never recorded (a spec would offer a Retry the kind does not have). askParams?: Readonly>; }; // The params the guards judge a job by: its spec's, else what it will ask. function planParams(opts: Pick): Record | undefined { return (opts.spec?.params ?? opts.askParams) as Record | undefined; } // ── 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 { 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:

` 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 { 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; } } async function channelPlatformOf(opts: NetworkJobOpts): Promise { if (!opts.channelSlug) return null; try { return await channelPlatform(opts.paths, opts.channelSlug); } catch { return null; } } // Whether a job asks X: its queue is X's, OR it is an X channel's job whose // work asks X (lane x-followups, R2: a job moved to another platform's queue // used to be taken for that platform's and met none of X's rules), OR it // imports an x.com URL. An X channel's job that asks no platform at all — // its transcription, windows cut from disk, a local file's import — is not // X's (review 2 S5). One predicate: lib/xJobRule.ts xJobAsksX. // // A WINDOW IS X'S BY ITS URL (review 3 M2), on any channel; a window that // names no URL is fetched from its channel's page, so each such item's // channel is read here (a batch may span channels). export async function jobAsksX(opts: NetworkJobOpts): Promise { const params = planParams(opts); const itemChannelPlatforms: Record = {}; if (opts.kind === "fetch-windows" && Array.isArray(params?.items)) { for (const raw of params.items as unknown[]) { const it = raw && typeof raw === "object" ? (raw as Record) : {}; const named = typeof it.webpageUrl === "string" && it.webpageUrl.trim() !== ""; if (named || typeof it.slug !== "string" || Object.hasOwn(itemChannelPlatforms, it.slug)) continue; itemChannelPlatforms[it.slug] = await channelPlatform(opts.paths, it.slug).catch(() => null); } } return xJobAsksX({ kind: opts.kind, queueKey: opts.queueKey, channelPlatform: await channelPlatformOf(opts), ...(params ? { params } : {}), ...(Object.keys(itemChannelPlatforms).length ? { itemChannelPlatforms } : {}), }); } // ── 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; 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 /cookies, 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 /cookies, 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 /cookies, 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 { // Only on the test server (review 1 F6: jobs/queueGap.ts e2eHooksOn). if (process.env.E2E_TEST_ROUTES !== "1") return 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; } // social.x.maxCookieAgeMinutes as every X reader applies it (0 = off). export function resolvedXMaxCookieAgeMinutes(settings: Pick | null): number { return settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x); } function settingsNow(): SiteSettings | null { try { return getSettings(); } catch { return null; } } async function channelCookieSpec(paths: Paths, slug: string | undefined, settings: SiteSettings): Promise { 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; } // `capped`: the refusal is the job cap's (no cookie banner is raised for it), // with `nextAt`, when the next X job may start. export type XGuardResult = | { ok: true; note?: string; accountAlert?: string } | { ok: false; message: string; alert: boolean; refusedBy?: XSessionReport["refusedBy"]; capped?: true; nextAt?: number }; // WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and // its verdict in one record, for `pnpm ops get x-session` (an agent asks it // before it queues an X fetch). xJobGuard below is this record's verdict, so // the report and the refusal are one computation, not two that look alike. export type XSessionReport = { // The login source in use ("profile": the session broker's exported jar; // "browser": cookiesFromBrowser), and whether settings chose it. source: XCookieSource; sourceChosen: boolean; browserSpec?: string; profileDir: string; cookieFile: string; hasProfile: boolean; hasCookies: boolean; looksAuthenticated: boolean; // When the jar was last written (Connect X / Refresh cookies), and its age. cookiesUpdatedAt: string | null; ageMinutes: number | null; // social.x.maxCookieAgeMinutes, resolved (0 = off). maxAgeMinutes: number; // False when the age is not checked: the browser source, or a limit of 0. ageChecked: boolean; // The X cookie alert, when it is up (a challenge or a login wall). alert: { raisedAt: string; line: string } | null; // X'S JOB CAP (lib/xJobRule.ts): the X jobs started ON THIS MACHINE in // the last 60 minutes and 24 hours — one count, whatever the login source, // cookie spec or channel (review 2 M1) — the caps (constants of the code), // and, when the cap is reached, when the next may start. cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true }; // X'S SITTING (lib/xSitting.ts, jobs/xSitting.ts): when it began (the // jar's refresh; null: none on record), its kind (null: no job yet; // "unknown": its record was lost), the starts it admitted and has left, // and the limit (social.x.sittingJobs, 1-6). `unreadable`: the file cannot // be read and no X job starts. sitting: { began: string | null; kind: XSittingKind | "unknown" | null; used: number; left: number; limit: number; // The kind of the job asked about, when one was. asked?: XSittingKind; unreadable?: true; }; // THE ACCOUNT'S STATE as the operator marked it (social/xAccountState.ts): // "suspended" refuses the jobs that record deleted posts; `alert` is the // line /cookies shows. account: { state: "ok" | "suspended"; since?: string; note?: string; alert?: string }; // X cooling down after a rate limit (429: 15 minutes), when it is: until when. cooldown: { until: string } | null; // Would an X job start now? `reason` is the refusal it would get, and // `refusedBy` which rule gave it. allowed: boolean; reason: string | null; refusedBy?: "alert" | "jar" | "cap" | "sitting" | "cooldown" | "suspended"; note?: string; }; export async function xSessionReport(opts: { paths: Paths; channelSlug?: string; now?: number; // False: the job asked about does not count against X's job cap (ruling // R-a: xJobCounts), so the cap does not refuse it — nor does its sitting. // The counts are reported all the same. counts?: boolean; // The job asked about: its sitting kind (absent: only a used-up sitting // refuses), and whether it records posts as deleted or unavailable (a // suspended account refuses it). sittingKind?: XSittingKind; recordsAvailability?: boolean; what?: string; }): Promise { const now = opts.now ?? Date.now(); const status = await readXSessionStatus(opts.paths); const settings = settingsNow(); const resolved = resolveXCookieSource({ stored: settings?.social?.x?.cookieSource, browserSpec: settings ? await channelCookieSpec(opts.paths, opts.channelSlug, settings) : undefined, profileConnected: status.looksAuthenticated, }); const maxAgeMinutes = resolvedXMaxCookieAgeMinutes(settings); const ageMinutes = status.cookiesUpdatedAt ? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000)) : null; // The count's clock is the queue gap's (jobs/queueGap.ts): the two rules // that space X jobs read one clock. const capStatus = await xJobCapStatus(opts.paths, opts.now ?? queueGapClock().now()); const cap = { lastHour: capStatus.lastHour, perHour: capStatus.perHour, lastDay: capStatus.lastDay, perDay: capStatus.perDay, reached: !capStatus.ok, ...(capStatus.nextAt !== undefined ? { nextAt: new Date(capStatus.nextAt).toISOString() } : {}), ...(capStatus.unreadable ? { unreadable: true as const } : {}), }; // X'S SITTING: the jar's refresh begins it; the limit is the setting, // bounded 1-6 in the code. const limit = xSittingJobs(settings?.social?.x); const refreshedAt = status.cookiesUpdatedAt ?? null; const sittingOff = e2eSittingsOff(); const look = await xSittingLook(opts.paths, { refreshedAt, kind: opts.sittingKind ?? "timelines", limit }); const sitting: XSessionReport["sitting"] = { began: look.status.state.began, kind: look.status.state.kind, used: look.status.used, left: look.status.left, limit, ...(opts.sittingKind ? { asked: opts.sittingKind } : {}), ...(!look.status.readable ? { unreadable: true as const } : {}), }; // Without a kind asked, only a used-up (or unreadable) sitting refuses. const sittingRefusal = sittingOff || opts.counts === false || look.verdict.ok ? null : opts.sittingKind || look.verdict.why === "used-up" || !look.status.readable ? look.verdict.sentence : null; // The account's state, as marked. const acct = await readXAccountState(opts.paths); const account: XSessionReport["account"] = acct ? { state: acct.state, since: acct.at, ...(acct.note ? { note: acct.note } : {}), ...(acct.state === "suspended" ? { alert: xAccountAlertLine(acct) } : {}), } : { state: "ok" }; const suspendedRefusal = acct?.state === "suspended" && opts.recordsAvailability === true ? xSuspendedSentence(opts.what ?? "This job", acct.at, acct.note) : null; // X'S COOLDOWN AFTER A 429 (15 minutes) and its hold refuse EVERY X job, // whatever its kind (rule 6 of lane x-sittings: it used to be asked only by // the trending read, its media and the capture). const wallNow = opts.now ?? Date.now(); // READ STRICTLY (review 1 F7): a stop that cannot be read refuses. let coolingMs = 0; let held: string | null = null; let unreadableStop: string | null = null; try { coolingMs = await xStopRemainingMs(opts.paths, wallNow); held = await heldPlatformRefusal("twitter", opts.what ?? "This X job", opts.paths, wallNow); } catch (err) { unreadableStop = `X's rate-limit stop cannot be read (${opts.paths.autoQueueStateFile}: ${(err as Error).message}): no X job starts ` + "while it cannot be told whether X answered a rate limit in the last 15 minutes. Repair or remove the file, then ask again."; } const cooldown = coolingMs > 0 ? { until: new Date(wallNow + coolingMs).toISOString() } : null; const coolRefusal = unreadableStop ?? held ?? (coolingMs > 0 ? xRateLimitHoldSentence("X job", coolingMs, wallNow) : null); // The cap, the sitting, the cooldown and the account refuse whatever else // would let the job through. const capped = (r: T): T & { refusedBy?: XSessionReport["refusedBy"] } => { if (!r.allowed) return r; if (coolRefusal) return { ...r, allowed: false, reason: coolRefusal, refusedBy: "cooldown" }; if (suspendedRefusal) return { ...r, allowed: false, reason: suspendedRefusal, refusedBy: "suspended" }; if (!capStatus.ok && opts.counts !== false) return { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached.", refusedBy: "cap" }; if (sittingRefusal) return { ...r, allowed: false, reason: sittingRefusal, refusedBy: "sitting" }; return r; }; const base = { sitting, account, cooldown, cap, source: resolved.source, sourceChosen: resolved.chosen, ...(resolved.browserSpec ? { browserSpec: resolved.browserSpec } : {}), profileDir: xProfileDir(opts.paths), cookieFile: xCookieFile(opts.paths), hasProfile: status.hasProfile, hasCookies: status.hasCookies, looksAuthenticated: status.looksAuthenticated, cookiesUpdatedAt: status.cookiesUpdatedAt ?? null, ageMinutes, maxAgeMinutes, ageChecked: resolved.source === "profile" && maxAgeMinutes > 0, }; // A raised jar-age alert does not refuse by itself: it IS the fresh-jar // rule's banner, and the rule below decides (and clears it once the jar is // fresh — guardNetworkJob). const raised = await raisedServiceAlert(opts.paths, X_SERVICE); if (raised && raised.kind !== "jar-age") { const at = (raised.raisedAt ?? raised.since).slice(11, 16); const what = raised.kind === "auth-failure" ? "a login failure" : "a challenge"; return { ...base, alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line }, allowed: false, refusedBy: "alert", reason: `X answered with ${what} at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` + `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`, }; } // Settings unreadable: the guard has nothing to apply and lets the job run. if (!settings) return capped({ ...base, alert: null, allowed: true, reason: null }); const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now }); return verdict.ok ? capped({ ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }) : { ...base, alert: null, allowed: false, reason: verdict.message, refusedBy: "jar" }; } // TEST-ONLY: E2E_X_SITTINGS=off on the e2e test server (with // E2E_TEST_ROUTES=1, as it always runs) leaves its fake X jobs out of the // sitting rule — they run many to a test corpus with no jar refresh between. // Unset everywhere but the e2e test server; it does not touch X's job cap. function e2eSittingsOff(): boolean { return process.env.E2E_X_SITTINGS === "off" && process.env.E2E_TEST_ROUTES === "1"; } // Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count), // or null: for the scheduler, which then skips X's channels rather than // queue syncs that would each be refused. export async function xCapHeldReason(paths: Paths, now?: number): Promise { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); if (!status.ok) return status.sentence ?? "X's job cap is reached."; // X's sitting, used up (or unreadable), holds them the same way. const sitting = await xSittingHeld(paths); return sitting?.sentence ?? null; } // X's sitting as the scheduler reads it: what it has left, and its refusal // when it has none (a look: nothing counted). async function xSittingHeld(paths: Paths): Promise<{ left: number; sentence?: string } | null> { if (e2eSittingsOff()) return null; try { const status = await readXSessionStatus(paths); const limit = xSittingJobs(settingsNow()?.social?.x); const look = await xSittingLook(paths, { refreshedAt: status.cookiesUpdatedAt ?? null, kind: "timelines", limit }); // The scheduler queues syncs (timelines jobs): a browse sitting, or one // used up or unreadable, has no room for them. if (look.verdict.ok) return { left: look.status.left }; return { left: 0, sentence: look.verdict.sentence }; } catch { return null; } } // HOW MANY X JOBS MAY START NOW under X's job cap (0 when it is reached or // its count cannot be read): for the scheduler, which queues no more X syncs // than that (review 3 N9). A look: nothing is counted. export async function xCapRoom(paths: Paths, now?: number): Promise { const status = await xJobCapStatus(paths, now ?? queueGapClock().now()); if (!status.ok) return 0; const cap = Math.max(0, Math.min(status.perHour - status.lastHour, status.perDay - status.lastDay)); // No more than X's sitting has left, either. const sitting = await xSittingHeld(paths); return sitting ? Math.min(cap, sitting.left) : cap; } export async function xJobGuard(opts: { paths: Paths; channelSlug?: string; now?: number; counts?: boolean; sittingKind?: XSittingKind; recordsAvailability?: boolean; what?: string; }): Promise { const r = await xSessionReport(opts); if (r.allowed) { return { ok: true, ...(r.note ? { note: r.note } : {}), ...(r.account.state === "suspended" ? { accountAlert: r.account.alert ?? "The X account is marked suspended." } : {}), }; } const capped = r.refusedBy === "cap"; const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : r.refusedBy === "cooldown" && r.cooldown ? Date.parse(r.cooldown.until) : undefined; return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, ...(r.refusedBy ? { refusedBy: r.refusedBy } : {}), ...(capped ? { capped: true as const } : {}), ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}), }; } // THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its // spec's params, and whether its channel is a trending library (read here, // never taken from the caller). type XGuardPlan = XJobPlan & { channel?: XJobPlan["channel"] & { search?: boolean } }; async function xJobPlanOf(opts: NetworkJobOpts): Promise { const params = planParams(opts); let channel: XGuardPlan["channel"]; if (opts.channelSlug) { const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null); const config = read?.ok ? channelConfigSchema.parse(read.value) : null; if (config) { channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}), // An X search channel: its fetch is the search walk (browse). ...(config.xSearch ? { search: true } : {}), }; } } return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) }; } // ── the one entry point ──────────────────────────────────────────────────── // `deferUntil`: the refusal is X's job cap, reached — at a job's start the // job ends DEFERRED (not failed; review 2, ruling R-b), and this is when the // next X job may start. export type NetworkGuardResult = | { ok: true; notes: string[] } | { ok: false; error: string; deferUntil?: number }; // One platform's guard: asked with the job's options, at enqueue and at start. type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promise; // X's (rules 2 and 3 above). async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise { // X's queue only, whatever the job and whoever named the queue. const queue = xQueueRefusal(`${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`, opts.queueKey); if (queue) return { ok: false, error: queue }; // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that // does not count is not refused by the cap either; everything else of X's // guard holds for it. const plan = await xJobPlanOf(opts); const counts = xJobCounts(plan); // ITS SITTING KIND (lib/xSitting.ts): from its plan — its kind and its // channel's config — never from a flag. An X run's own start (no channel) // is no job of either kind: each channel is guarded with its slug. const runStart = opts.kind === "x-run" && !opts.channelSlug; const sittingKind = runStart ? undefined : xSittingKindOf(plan); const what = `${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`; const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts, ...(sittingKind ? { sittingKind } : {}), recordsAvailability: xSuspendedRefuses(plan), what, }); if (x.ok) { const notes: string[] = x.note ? [x.note] : []; // THE START, COUNTED: checked and recorded in one step. An X run's own // start asks X nothing: each of its channels is a start (it is guarded, // with its slug, before each one). if (counts && opts.countStart && opts.job && !runStart) { const at = queueGapClock().now(); const counted = await recordXJobStart(opts.paths, at); if (!counted.ok) { return { ok: false, error: counted.sentence ?? "X's job cap is reached.", ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}), }; } // THE SITTING, COUNTED (lib/xSitting.ts): checked and recorded in one // step under its own lock. Refused here only on a race (the look above // passed): the cap's start stays counted — more rather than fewer. const record = getRegistry().get(opts.job.id); let sat: { began: string | null; kind: XSittingKind } | null = null; if (sittingKind && !e2eSittingsOff()) { const refreshedAt = (await readXSessionStatus(opts.paths)).cookiesUpdatedAt ?? null; const r = await recordXSittingStart(opts.paths, { refreshedAt, kind: sittingKind, limit: xSittingJobs(settingsNow()?.social?.x), jobKind: opts.kind, at: counted.at ?? at, jobId: opts.job.id, ...(opts.channelSlug ? { channel: opts.channelSlug } : {}), }); if (!r.verdict.ok) { if (record && counted.at !== undefined) { (record.xStarts ??= []).push(counted.at); await writeJobMeta(opts.paths, record); } return { ok: false, error: r.verdict.sentence, deferUntil: 0 }; } sat = { began: r.began, kind: sittingKind }; notes.push( `X sitting: ${r.verdict.used} of ${r.verdict.limit} started (${sittingKind}, ` + `${r.began ? `since the refresh at ${r.began.slice(11, 16)} UTC` : "no refresh on record"}); ${r.verdict.left} left.`, ); } // The start on the job's own record (and its sidecar), so a lost count // — and a lost sitting — is rebuilt from the records. if (record && counted.at !== undefined) { (record.xStarts ??= []).push(counted.at); if (sat) (record.xSittings ??= []).push({ ...sat, at: counted.at }); await writeJobMeta(opts.paths, record); } } // A suspended account (marked by hand): every X job's log says so. if (x.accountAlert) notes.push(`${x.accountAlert} What X answers it may be thinned.`); // The jar passed at a job's START: a jar-age banner from an earlier // refusal clears. (Not at enqueue — the start follows, and enqueue stays // as cheap as it was.) if (opts.job) await noteXJarFresh(opts.paths); return { ok: true, notes }; } if (x.alert && opts.job) { await noteServiceStoppedJob(opts.paths, X_SERVICE, { id: opts.job.id, kind: opts.kind }); } else if (!x.alert && x.refusedBy === "jar") { // The fresh-jar rule refused it: X's cookie banner says so on the // dashboard (kind jar-age), and a job refused at its start is offered for // "Re-run stopped jobs" once the jar is fresh. await noteXJarStale(opts.paths, { line: x.message, ...(opts.channelSlug ? { channel: opts.channelSlug } : {}), ...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}), }); } // A cap, a cooldown or a sitting met AT A START ends the job deferred, not // failed: nothing retries it (a sitting's until 0: until a Refresh). const deferUntil = (x.refusedBy === "cap" || x.refusedBy === "cooldown") && x.nextAt !== undefined ? x.nextAt : x.refusedBy === "sitting" ? 0 : undefined; return { ok: false, error: x.message, ...(deferUntil !== undefined ? { deferUntil } : {}) }; } // Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). async function guardInstagramJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise { const g = await instagramJobGuard({ paths: opts.paths }); if (g.ok) return { ok: true, notes: [] }; if (g.alert && opts.job) { await noteServiceStoppedJob(opts.paths, INSTAGRAM_SERVICE, { id: opts.job.id, kind: opts.kind }); } return { ok: false, error: g.message }; } // THE PLATFORMS THAT HAVE A GUARD, by the platform a job asks // (networkJobPlatform). A platform absent here runs on its queue and gap alone. export const PLATFORM_GUARDS: Readonly> = Object.freeze({ twitter: guardXJob, instagram: guardInstagramJob, }); // Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the // platform's alert is recorded against the alert, so "Re-run stopped jobs" // offers it). export async function guardNetworkJob( opts: NetworkJobOpts & { job?: { id: string } }, ): Promise { if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; const empty = emptyQueueRefusal(opts.kind, opts.queueKey); if (empty) return { ok: false, error: empty }; // A job that asks X meets X's guard whatever queue it is on. One that does // not is never taken for X's by its channel: its queue's platform decides. const fromChannel = await networkJobPlatform(opts); const platform = (await jobAsksX(opts)) ? "twitter" : fromChannel === "twitter" ? queueGapPlatform(opts.queueKey) : fromChannel; const guard = platform && Object.hasOwn(PLATFORM_GUARDS, platform) ? PLATFORM_GUARDS[platform] : undefined; return guard ? guard(opts) : { ok: true, notes: [] }; }