// 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:
` 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.
//
// X'S GAP IS DRAWN, NOT FIXED (lane x-sittings, lib/xSitting.ts): a job on
// `platform:twitter` waits a gap drawn per job, uniform in
// `social.x.gapMinMinutes`-`gapMaxMinutes` (default 5-12 min, never below 5;
// an explicit `pacing.jobGapSeconds.twitter` above the minimum raises it), and
// says what was drawn ("waiting 8m41s (a 9m02s gap drawn from 5-12 min): …").
// 12 fetches each 5-6 minutes after the last preceded the account's
// suspension; a fixed beat is what a script looks like.
//
// The last end per queue is kept in memory and in `/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:`) 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 { readdir } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
import { spanText, waitText } from "./queueGapText";
import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap";
import type { PacingSettingsBlock } from "../lib/settingsSchema";
import { jitterUpStable } from "../lib/jitter.mjs";
import { pacingJitter } from "../lib/jitter";
import { randomInt } from "node:crypto";
import { drawXGapSeconds, xGapRange, xGapRangeText, type XGapRange } from "../lib/xSitting";
import { getSettings } from "../lib/settings";
export { spanText, waitText };
export const QUEUE_GAPS_FILE = "queue-gaps.json";
export function queueGapsFile(paths: Pick): 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.
// THE TEST SERVER'S GATE (review 1 F6): every E2E_ hook here is honoured only
// beside E2E_TEST_ROUTES=1, as the e2e server always runs — never in an
// editor started normally, whatever else its environment carries.
export function e2eHooksOn(): boolean {
return process.env.E2E_TEST_ROUTES === "1";
}
function builtInGaps(): Readonly> {
if (!e2eHooksOn()) return JOB_GAP_DEFAULT_SECONDS;
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 };
// TEST-ONLY, as above: the e2e server's E2E_JOB_GAP_SECONDS, which collapses
// X's drawn range to that one value too (0: no gap), else undefined.
function e2eGapSeconds(): number | undefined {
if (!e2eHooksOn()) return undefined;
const raw = process.env.E2E_JOB_GAP_SECONDS;
if (raw === undefined || raw === "") return undefined;
const n = Number(raw);
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
}
// ── X's gap: drawn per job (lane x-sittings, lib/xSitting.ts) ──────────────
export type XGapSettings = { gapMinMinutes?: number; gapMaxMinutes?: number };
// The range X's gap is drawn from: `social.x.gapMinMinutes`-`gapMaxMinutes`
// (default 5-12 min, never below 5), an explicit pacing.jobGapSeconds.twitter
// raising the minimum. The e2e server's E2E_JOB_GAP_SECONDS collapses it.
export function xQueueGapRange(
pacing: Pick | undefined,
x: XGapSettings | undefined,
): XGapRange {
const e2e = e2eGapSeconds();
if (e2e !== undefined) return { minSeconds: e2e, maxSeconds: e2e };
return xGapRange(x, pacing?.jobGapSeconds?.twitter);
}
// THE DRAW: uniform in the range, from the system's random source — or, in a
// test, a seeded one (setXGapRandom). Drawn ONCE per wait: a wait is re-read
// after every sleep, and a fresh draw per read would end it at the shortest.
declare global {
// eslint-disable-next-line no-var
var __yttXGapRandom__: (() => number) | undefined;
// eslint-disable-next-line no-var
var __yttXGapDraws__: Map | undefined;
}
// TEST-ONLY: a seeded generator (mulberry32) for the draw; null restores the
// system's random source.
export function setXGapRandom(seed: number | null): void {
if (seed === null) {
globalThis.__yttXGapRandom__ = undefined;
return;
}
let a = seed >>> 0;
globalThis.__yttXGapRandom__ = () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function xGapRandom(): number {
return globalThis.__yttXGapRandom__ ? globalThis.__yttXGapRandom__() : randomInt(0, 2 ** 32) / 2 ** 32;
}
// The gap drawn for the wait after the end at `last` on `queueKey` (memoised:
// the same wait, re-read, keeps its draw; a range changed while it waits is
// drawn again, within the new range).
export function drawnXGapSeconds(queueKey: string, last: number, range: XGapRange): number {
const draws = (globalThis.__yttXGapDraws__ ??= new Map());
const key = `${queueKey}@${last}@${range.minSeconds}-${range.maxSeconds}`;
let seconds = draws.get(key);
if (seconds === undefined) {
seconds = drawXGapSeconds(range, xGapRandom());
if (draws.size > 256) draws.clear();
draws.set(key, seconds);
}
return seconds;
}
function xGapSettingsNow(): XGapSettings | undefined {
try {
return getSettings().social?.x;
} catch {
return undefined;
}
}
export function queueGapFor(
pacing: Pick | undefined,
platform: string,
): QueueGap {
return jobGapSecondsFor(pacing, platform, builtInGaps());
}
const PLATFORM_NAMES: Record = {
twitter: "X",
bluesky: "Bluesky",
instagram: "Instagram",
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;
loaded?: Promise;
writing: Promise;
};
declare global {
// eslint-disable-next-line no-var
var __yttQueueGaps__: Map | undefined;
}
function storeFor(paths: Pick): 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): Promise {
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)
: {};
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,
queueKey: string,
): Promise {
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,
queueKey: string,
at: number = Date.now(),
): Promise {
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();
globalThis.__yttXGapDraws__?.clear();
}
// ── the wait ───────────────────────────────────────────────────────────────
export type QueueGapClock = {
now: () => number;
sleep: (ms: number, signal?: AbortSignal) => Promise;
};
const realClock: QueueGapClock = { now: () => Date.now(), sleep: abortableSleep };
export type QueueGapWait = {
// Epoch ms the job may start at.
until: number;
remainingMs: number;
reason: string;
// X's gap: the seconds drawn for this wait, and the range drawn from.
drawn?: { seconds: number; range: XGapRange };
};
// How long a network job on `queueKey` must still wait, or null for none.
//
// THE GAP IS JITTERED, STABLY. It is stretched by up to `pacing.jitter` of
// itself (lib/jitter.mjs: only ever longer, so "X jobs are spaced 5 min apart"
// stays true), and the share is drawn from the queue and the previous job's
// end — the same for every re-read of one wait (waitForQueueGap re-reads after
// each sleep; a fresh draw per read would end the wait at the shortest one).
export async function queueGapWait(opts: {
paths: Pick;
queueKey: string;
pacing: (Pick & { jitter?: number }) | undefined;
now: number;
// X's range settings (`social.x`); absent: read from settings.
xGap?: XGapSettings;
}): Promise {
const platform = queueGapPlatform(opts.queueKey);
if (!platform) return null;
// X'S GAP IS DRAWN PER JOB from its range (lane x-sittings), not stretched
// from a fixed beat: the draw is the unevenness, so no jitter is added.
if (platform === "twitter") {
const range = xQueueGapRange(opts.pacing, opts.xGap ?? xGapSettingsNow());
if (range.maxSeconds <= 0) return null;
// NO END ON RECORD IS NOT "NO X JOB EVER RAN" (review 1 F7): a lost
// queue-gaps.json is answered from the job records — the latest start or
// end of a job on X's queue. Only a corpus with none waits nothing.
const last = (await lastQueueEnd(opts.paths, opts.queueKey)) ?? (await lastXJobFromRecords(opts.paths, opts.queueKey));
if (last === undefined) return null;
const seconds = drawnXGapSeconds(opts.queueKey, last, range);
const until = last + seconds * 1000;
if (until <= opts.now) return null;
return {
until,
remainingMs: until - opts.now,
reason: `X jobs are spaced ${xGapRangeText(range)} apart, drawn per job (social.x.gapMinMinutes, social.x.gapMaxMinutes)`,
drawn: { seconds, range },
};
}
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 +
Math.ceil(
jitterUpStable(
gap.seconds * 1000,
`${opts.queueKey}@${last}`,
opts.pacing?.jitter ?? pacingJitter(),
),
);
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)".
// X's: "waiting 8m41s (a 9m02s gap drawn from 5-12 min): X jobs are spaced …".
export function queueGapLine(w: QueueGapWait): string {
if (w.drawn) {
return `waiting ${waitText(w.remainingMs)} (a ${waitText(w.drawn.seconds * 1000)} gap drawn from ${xGapRangeText(w.drawn.range)}): ${w.reason}`;
}
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;
queueKey: string;
pacing: () => (Pick & { jitter?: number }) | undefined;
signal?: AbortSignal;
onLog?: (line: string) => void;
onWait?: (wait: QueueGapWait | null) => void;
clock?: QueueGapClock;
}): Promise {
const clock = opts.clock ?? queueGapClock();
let waited = 0;
try {
for (;;) {
if (opts.signal?.aborted) throw abortError();
let pacing: (Pick & { jitter?: number }) | 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 {
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 });
});
}
// The latest start or end of an ENDED job on `queueKey` in the job records, if any.
async function lastXJobFromRecords(paths: Pick, queueKey: string): Promise {
let names: string[];
try {
names = await readdir(paths.jobsDir);
} catch {
return undefined;
}
let latest: number | undefined;
for (const name of names) {
if (!name.endsWith(".meta.json")) continue;
const read = await readJsonFile(path.join(paths.jobsDir, name));
const m = read.ok ? (read.value as Record | null) : null;
// An ended job's (not the one now starting, which is running).
if (!m || m.queueKey !== queueKey || m.status === "running" || m.status === "queued") continue;
for (const t of [m.startedAt, m.endedAt]) {
if (typeof t === "number" && Number.isFinite(t) && (latest === undefined || t > latest)) latest = t;
}
}
return latest;
}