// 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 === "ratelimit") { // X's API answered 429: gallery-dl, told ratelimit=abort, stops at once. process.stderr.write("[twitter][error] Rate limit exceeded\\n"); process.exit(1); } if (process.env.FAKE_MODE === "challenge") { // X answers after a moment, as it does: the loop has queued all 13 by then // (on a loaded machine an instant answer raced the loop's later enqueues). await new Promise((r) => setTimeout(r, 2000)); 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 { 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 { xJobStartsFile } = await import("./xJobCap"); const { xSittingFile } = await import("./xSitting"); 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, 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 { try { return (await readFile(RUNS, "utf8")).split("\n").filter(Boolean).length; } catch { return 0; } } async function reset(): Promise { clearQueueGaps(); await rm(RUNS, { force: true }); await rm(serviceCookiesFile(paths), { force: true }); // X's queue gap: a known end long ago (a lost file is answered from the // job records — review 1 F7 — whose clock is the wall's, not this test's). await mkdir(paths.jobsDir, { recursive: true }); await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); // X's job count (jobs/xJobCap.ts): each test starts from none. (Deleting // the file would not: it is rebuilt from the earlier tests' job records.) await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); // X's stop after a 429 or a bot check (jobs/downloadBackoff.ts): none. { const { readAutoQueueState, writeAutoQueueState } = await import("./autoQueueState"); const st = await readAutoQueueState(paths); st.download.platformBackoff = {}; st.download.platformHolds = {}; await writeAutoQueueState(paths, st); } // X's sitting (jobs/xSitting.ts): each test starts a fresh one. await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: null, kind: null, starts: [] })); } async function readLog(jobId: string): Promise { 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(); 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), // Job 1 met X's bot check: it records the X stop and ends deferred // (review 1 F1/F2); jobs 2–13 are refused by the alert. ["done", ...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/); assert.match(first, /^\[deferred\] X answered a bot check \(gallery-dl\) at \d\d:\d\d UTC/m); 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 queued in one loop: the sitting's 4 start 5-12 min apart (drawn), the other 9 end deferred unasked", async () => { await reset(); await writeJar(5 * 60_000); const starts = new Map(); 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")); // Only the sitting's four asked anything (lib/xSitting.ts: 4 per cookie refresh). assert.equal(await runCount(), 4); assert.deepEqual([...starts.keys()], SLUGS.slice(0, 4)); for (const e of ends.slice(4)) { assert.match(await readLog(e!.jobId), /\[deferred\] This X sitting is used up: 4 of 4 X jobs started/); } const at = SLUGS.slice(0, 4).map((s) => starts.get(s)!); for (let i = 1; i < at.length; i++) { // The gap runs from the previous job's end (3 s after its start) and is drawn in 5-12 min. const gap = at[i] - at[i - 1] - 3_000; assert.ok(gap >= 300_000 && gap <= 720_000, `job ${i + 1} started ${gap / 1000}s after job ${i} ended`); } // The waiting job's log says why it waited, and what was drawn. const log2 = await readLog(ends[1]!.jobId); assert.match(log2, /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); // 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 \/cookies, then fetch again\.$/, ); // Fresh at enqueue; stale by the time the queue reaches it. await writeJar(5 * 60_000); const starts = new Map(); // Job 1 holds the queue until the jar has gone stale. let release!: () => void; const held = new Promise((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("the fresh-jar rule raises X's jar-age banner (the job refused at its start is on it); a fresh jar clears it; a challenge escalates it", async () => { await reset(); const { buildServiceCookieAlerts, isBlockingAlert } = await import("../lib/serviceCookies"); // Refused at enqueue: the banner goes up, no job to re-run. await writeJar(3 * 60 * 60_000); const refused = await fetchJob(SLUGS[0], new Map()); assert.equal(refused.ok, false); let x = (await readServiceCookieState(paths)).services.x; assert.ok(x?.raisedAt && !x.clearedAt, "the X banner is up"); assert.equal(x.kind, "jar-age"); assert.equal(isBlockingAlert(x), false, "jar-age does not itself refuse X jobs"); assert.match(x.evidence.line, /^X cookies were last refreshed 3 h ago \(limit 60 min\)/); assert.equal(x.evidence.channel, SLUGS[0]); assert.deepEqual(x.jobs, []); // Queued while fresh, refused at its start: recorded on the banner. await writeJar(5 * 60_000); let release!: () => void; const held = new Promise((r) => (release = r)); const a = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: () => held }); assert.ok(a.ok); // The guard let job a through at its start on a fresh jar: the banner is OK again. for (let i = 0; i < 100 && !(await readServiceCookieState(paths)).services.x?.clearedAt; i++) { await new Promise((r) => setTimeout(r, 20)); } x = (await readServiceCookieState(paths)).services.x; assert.equal(x?.clearedBy, "clean"); const b = await fetchJob(SLUGS[1], new Map()); assert.ok(b.ok); await writeJar(2 * 60 * 60_000); release(); await a.done; const bDone = await b.done; assert.equal(bDone.status, "failed"); x = (await readServiceCookieState(paths)).services.x; assert.ok(x?.raisedAt && !x.clearedAt); assert.equal(x.kind, "jar-age"); assert.deepEqual(x.jobs.map((j) => j.id), [bDone.jobId]); // Three short lines: the age, the one action for the login source in use, the job it refused. const st = await readServiceCookieState(paths); const view = buildServiceCookieAlerts(st, { now: Date.now(), browser: "firefox", xJar: { source: "profile", ageMinutes: 120, maxAgeMinutes: 60 }, }); assert.equal(view.alerts[0]?.headline, "X cookies are 2 h old (limit 60 min)"); assert.equal(view.alerts[0]?.fix, "Refresh cookies (or Connect X account) on /cookies — then Recheck."); assert.equal(view.alerts[0]?.detail, `Refused fetch-posts ${bDone.jobId} (${SLUGS[1]}).`); assert.equal(view.alerts[0]?.compact, true); const browserView = buildServiceCookieAlerts(st, { now: Date.now(), browser: "firefox", xJar: { source: "browser", ageMinutes: 200, maxAgeMinutes: 60 }, }); assert.equal(browserView.alerts[0]?.headline, "X cookies are 3 h old (limit 60 min)"); assert.equal(browserView.alerts[0]?.fix, "Open x.com in Firefox — then Recheck."); // A real challenge from X while the jar-age banner is up escalates it to a // blocking alert, keeping the job it holds. const { noteXServiceOutcome } = await import("../lib/serviceCookies-server"); await noteXServiceOutcome(paths, { challengeLine: "[twitter][warning] Cloudflare challenge", kind: "challenge" }); x = (await readServiceCookieState(paths)).services.x; assert.equal(x?.kind, "challenge"); assert.equal(isBlockingAlert(x), true); assert.deepEqual(x!.jobs.map((j) => j.id), [bDone.jobId]); // And the jar-age path cannot overwrite it. await writeJar(5 * 60_000); await fetchJob(SLUGS[2], new Map()); assert.equal((await readServiceCookieState(paths)).services.x?.kind, "challenge"); }); test("get x-session reports what the guard would answer: source, age, limit, allowed", async () => { await reset(); const { xSessionReport, xJobGuard } = await import("./networkGuard"); await writeJar(5 * 60_000); const fresh = await xSessionReport({ paths }); assert.equal(fresh.source, "profile"); assert.equal(fresh.sourceChosen, true); assert.equal(fresh.looksAuthenticated, true); assert.equal(fresh.maxAgeMinutes, 60); assert.equal(fresh.ageChecked, true); assert.ok(fresh.ageMinutes !== null && fresh.ageMinutes >= 4 && fresh.ageMinutes <= 6, String(fresh.ageMinutes)); assert.equal(fresh.allowed, true); assert.equal(fresh.reason, null); assert.equal(fresh.profileDir, path.join(transcripts, ".x-session", "profile")); assert.deepEqual(await xJobGuard({ paths }), { ok: true }); await writeJar(2 * 60 * 60_000); const stale = await xSessionReport({ paths }); assert.equal(stale.allowed, false); assert.ok(stale.ageMinutes !== null && stale.ageMinutes >= 119); assert.match(stale.reason ?? "", /^X cookies were last refreshed 2 h ago \(limit 60 min\)/); const guard = await xJobGuard({ paths }); assert.equal(guard.ok, false); assert.equal(guard.ok ? "" : guard.message, stale.reason); }); 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"); }); // ── added scope R2 (lane x-followups): X's queue only, and X's job cap ───── const { guardNetworkJob, jobAsksX, xSessionReport: xReport } = await import("./networkGuard"); const { recordXJobStart, xJobCapStatus } = await import("./xJobCap"); const { xQueueRefusal } = await import("../lib/xJobRule"); const { runInJobContext } = await import("../lib/jobContext"); test("R2a: a job that asks X is refused on any queue but X's — at enqueue for every kind, and where it runs", async () => { await reset(); await writeJar(5 * 60_000); const before = await runCount(); // A named queue, another platform's queue: no job is made. for (const queueKey of ["manual", "platform:youtube", "x-second-lane"]) { const res = await fetchJob(SLUGS[0], new Map(), queueKey); assert.equal(res.ok, false, queueKey); assert.equal(res.ok ? "" : res.error, xQueueRefusal(`Fetch posts for ${SLUGS[0]}`, queueKey) ?? "?"); } // Every kind that asks X, by its channel: the queue it was moved to no longer hides that it is X's. for (const kind of ["fetch-posts", "capture-posts", "check-post-availability", "import-post"]) { assert.equal(await jobAsksX({ kind, queueKey: "manual", paths, channelSlug: SLUGS[0] }), true); const g = await guardNetworkJob({ kind, queueKey: "platform:youtube", paths, channelSlug: SLUGS[0] }); assert.equal(g.ok, false, kind); assert.match(g.ok ? "" : g.error, /asks X, and X jobs run on X's queue only \(platform:twitter\): the queue "platform:youtube" is refused/); } // …and the kinds that have no channel are X's by their queue (a trending read, an X run). assert.equal(await jobAsksX({ kind: "read-x-trending", queueKey: "platform:twitter", paths }), true); assert.equal(await jobAsksX({ kind: "download-missing", queueKey: "platform:youtube", paths }), false); // WHERE IT RUNS: a job that is on another queue anyway (a context made by hand) is refused by the fetch itself. const ran = await runInJobContext({ jobId: "by-hand", kind: "fetch-posts", queueKey: "manual", onLog: () => {}, staleServices: new Set() }, () => fetchPosts({ paths, slug: SLUGS[0], settings: getSettings() }), ); assert.equal(ran.ok, false); assert.match(ran.error ?? "", /X jobs run on X's queue only \(platform:twitter\): the queue "manual" is refused\..* Nothing was asked\.$/); assert.equal(await runCount(), before, "gallery-dl was never started"); }); test("R2b: X's job cap — the 7th X job in an hour is refused before it starts, over every kind together, and get x-session shows the count", async () => { await reset(); await writeJar(5 * 60_000); const before = await runCount(); // Five starts on record, of whatever kinds; then one fetch through the funnel is the sixth. for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); const sixth = await fetchJob(SLUGS[0], new Map()); assert.equal(sixth.ok, true, sixth.ok ? "" : sixth.error); if (sixth.ok) assert.equal((await sixth.done).status, "done"); assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); // The seventh, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start. for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) { const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); assert.equal(res.ok, false, kind); assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes \(the cap is 6\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind); } assert.equal(await runCount(), before + 1); // The cap raises no cookie banner: it is not the jar's fault. assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); // get x-session: the count, the caps, and the refusal. const report = await xReport({ paths }); assert.equal(report.allowed, false); assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 6, perHour: 6, lastDay: 6, perDay: 150, reached: true, nextAt: "string" }); assert.match(report.reason ?? "", /^X's job cap is reached/); // An hour on, the oldest starts have left the window and X jobs start again. fakeNow += 61 * 60_000; await writeJar(5 * 60_000); const after = await fetchJob(SLUGS[3], new Map()); assert.equal(after.ok, true, after.ok ? "" : after.error); if (after.ok) assert.equal((await after.done).status, "done"); }); test("R2b: the start is counted once, by the last guard before the work; a look counts nothing; a job that met the cap while it waited is refused at its start", async () => { await reset(); await writeJar(5 * 60_000); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; const job = { id: "job-1" }; const opts = { kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0] }; // Enqueue, and the start's first guard: looks. assert.equal((await guardNetworkJob(opts)).ok, true); assert.equal((await guardNetworkJob({ ...opts, job })).ok, true); assert.equal(await count(), 0); // The last guard before the work: one start. assert.equal((await guardNetworkJob({ ...opts, job, countStart: true })).ok, true); assert.equal(await count(), 1); // An X run's own start asks X nothing; each channel's turn in it is a start. assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); assert.equal(await count(), 1); assert.equal((await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: SLUGS[1], job, countStart: true })).ok, true); assert.equal(await count(), 2); // A job that is no X job is not counted. assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true); assert.equal(await count(), 2); // The cap fills while a job waits its turn: its start is refused, and the refused start is not counted. for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await guardNetworkJob({ ...opts, job, countStart: true }); assert.equal(late.ok, false); assert.match(late.ok ? "" : late.error, /^X's job cap is reached/); assert.equal(await count(), 6); // A count that cannot be read refuses every X job, at enqueue and at the start. await writeFile(path.join(transcripts, ".x-session", "job-starts.json"), "{broken"); for (const g of [await guardNetworkJob(opts), await guardNetworkJob({ ...opts, job, countStart: true })]) { assert.equal(g.ok, false); assert.match(g.ok ? "" : g.error, /^X's job count cannot be read .*no X job starts while it is unreadable/); } await reset(); }); // ── review 2 (lane x-followups): one bucket, what counts, deferred ───────── const { getRegistry } = await import("./registry"); const { readJobMeta } = await import("./jobMeta"); async function writeSettings(x: Record, top: Record = {}): Promise { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ ...top, social: { x } })); } async function channelSpec(slug: string, spec: string | undefined): Promise { const file = path.join(transcripts, "channels", slug, "config.json"); const config = JSON.parse(await readFile(file, "utf8")); if (spec === undefined) delete config.cookiesFromBrowser; else config.cookiesFromBrowser = spec; await writeFile(file, JSON.stringify(config)); } test("M1: ONE count for the machine — a flipped login source, a respelled cookie spec, a channel's own spec and an X run over channels of different specs all fill the same cap", async () => { await reset(); await writeJar(5 * 60_000); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true }); // One sitting of six (the most there is), so the cap is what fills here. const SIX = { sittingJobs: 6 }; try { await writeSettings({ cookieSource: "profile", ...SIX }); // Two starts on the connected profile. for (let i = 0; i < 2; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); assert.equal(await count(), 2); // The login source flipped to the browser: the same count, not a fresh one. await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }); assert.equal((await xReport({ paths })).cap.lastHour, 2); assert.equal((await start("fetch-posts", SLUGS[0])).ok, true); assert.equal(await count(), 3); // The same browser spelled another way: still the same count. await writeSettings({ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: " firefox:default " }); assert.equal((await xReport({ paths })).cap.lastHour, 3); assert.equal((await start("capture-posts", SLUGS[1])).ok, true); // A channel with a cookie spec of its own: the same count. await channelSpec(SLUGS[2], "chromium"); assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 4); assert.equal((await start("check-post-availability", SLUGS[2])).ok, true); // An X run over a channel of another spec: each channel one start, in the one count. await channelSpec(SLUGS[3], "brave"); await channelSpec(SLUGS[4], "chromium:Profile 2"); assert.equal((await start("x-run", SLUGS[3])).ok, true); assert.equal(await count(), 6); // The seventh is refused whatever it uses. for (const [x, top, slug] of [ [{ cookieSource: "profile", ...SIX }, {}, SLUGS[7]], [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "firefox" }, SLUGS[7]], [{ cookieSource: "browser", ...SIX }, { cookiesFromBrowser: "safari" }, SLUGS[4]], ] as const) { await writeSettings(x, top); const refused = await start("fetch-posts", slug); assert.equal(refused.ok, false); assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); } // get x-session names no login: the count is the machine's. const report = await xReport({ paths }); assert.equal("login" in report, false); assert.deepEqual([report.cap.lastHour, report.cap.reached], [6, true]); } finally { await writeSettings({ cookieSource: "profile" }); for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined); await reset(); } }); test("review 1 F8 (R-a reversed): a trending library's media-only capture IS an X job — counted, and refused by the cap like any other", async () => { await reset(); await writeJar(5 * 60_000); const lib = "x-trending-lib"; await mkdir(path.join(transcripts, "channels", lib), { recursive: true }); await writeFile( path.join(transcripts, "channels", lib, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: lib, xTrending: {} }), ); const mediaOnly = { ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true }; const capture = (params: Record, countStart = true) => guardNetworkJob({ kind: "capture-posts", queueKey: "platform:twitter", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params }, job: { id: "ra" }, ...(countStart ? { countStart: true } : {}) }); const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour; assert.equal((await capture(mediaOnly)).ok, true); assert.equal(await count(), 1, "the media-only capture is a start"); // The cap reached: it is refused like the others. for (let i = 0; i < 5; i++) await recordXJobStart(paths, fakeNow); for (const params of [mediaOnly, { ...mediaOnly, shots: true }]) { const refused = await capture(params, false); assert.equal(refused.ok, false); assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached/); } await rm(path.join(transcripts, "channels", lib), { recursive: true, force: true }); await reset(); }); test("R-b: a job that meets the cap AT ITS START ends deferred — done, not failed, the sentence and when the next may start, no banner, nothing asked", async () => { await reset(); await writeJar(5 * 60_000); const before = await runCount(); // An X job holds the queue (it is the first start). let release!: () => void; const gate = new Promise((r) => (release = r)); const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate }); assert.equal(blocker.ok, true); for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20)); // Four more: five. The next passes its enqueue (a slot is left)… for (let i = 0; i < 4; i++) await recordXJobStart(paths, fakeNow); const late = await fetchJob(SLUGS[1], new Map()); assert.equal(late.ok, true, late.ok ? "" : late.error); // …and the cap fills while it waits behind the first. await recordXJobStart(paths, fakeNow); release(); if (!blocker.ok || !late.ok) return; await blocker.done; const end = await late.done; assert.equal(end.status, "done"); const record = getRegistry().get(late.jobId)!; assert.ok(record.deferred, "the record says it was deferred"); assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt); assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m); assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m); const meta = await readJobMeta(paths, late.jobId); assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]); // Nothing was asked, no start was counted, and no cookie banner was raised. assert.equal(await runCount(), before); assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 6); assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined); // The first job's own record carries its start (the count can be rebuilt from it). assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1); await reset(); }); test("S5: an X channel's jobs that ask x.com nothing pass off X's queue; those that ask it are X's — refused elsewhere, on X's queue by default", async () => { await reset(); // A stale jar and a full cap: nothing that is X's would start. await writeJar(5 * 60 * 60_000); for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); const slug = SLUGS[0]; const g = (kind: string, queueKey: string, params?: Record, channelSlug: string | undefined = slug) => guardNetworkJob({ kind, queueKey, paths, ...(channelSlug ? { channelSlug } : {}), ...(params ? { spec: { kind, slug, params } as never } : {}) }); // They ask no platform: they pass, whatever X's jar and cap say. for (const [kind, queueKey, params] of [ ["transcribe-one", `transcribe-one:${slug}:1`], ["fetch-windows", "clips:saved-video"], ["fetch-window", "clips:saved-video"], ["import-media", `import-media:${slug}`], ["import-archive-org", "platform:archiveorg"], ["import-one", "platform:archiveorg", { url: "https://archive.org/details/example" }], ] as const) { const r = await g(kind, queueKey, params); assert.equal(r.ok, true, `${kind} on ${queueKey}: ${r.ok ? "" : r.error}`); } // They ask x.com: X's, so refused off X's queue (and by the jar on it). for (const [kind, queueKey, params, channelSlug] of [ ["fetch-window", "clips:twitter", undefined, slug], ["fetch-windows", "clips:twitter", undefined, undefined], ["record-live", `record-live:${slug}:1`, undefined, slug], ["check-kept-deleted", `channel:${slug}`, undefined, slug], ["redownload-incomplete-bucket", "transcription", undefined, slug], ["import-one", "platform:youtube", { url: "https://x.com/example/status/1" }, "not-an-x-channel"], ] as const) { const r = await g(kind, queueKey, params, channelSlug); assert.equal(r.ok, false, `${kind} on ${queueKey}`); assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, `${kind} on ${queueKey}`); } // Where they are queued by default for an X channel: X's queue. const { clipWindowQueueKey } = await import("../lib/queueKeys"); const { platformQueueKey } = await import("../lib/platform"); assert.equal(clipWindowQueueKey(platformQueueKey("twitter")), "platform:twitter"); assert.equal(clipWindowQueueKey(platformQueueKey("youtube")), "clips:youtube"); await reset(); }); test("review 4 B: an import of a file by an X page's address is X's on any channel — refused off X's queue; a local file's or another page's passes", async () => { await reset(); await writeJar(5 * 60 * 60_000); for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); const yt = "yt-chan-r4"; await mkdir(path.join(transcripts, "channels", yt), { recursive: true }); await writeFile(path.join(transcripts, "channels", yt, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: yt, url: "https://www.youtube.com/@example" })); // import-media has no replay descriptor: what it will ask is given to the guards alone. const g = (slug: string, url?: string) => guardNetworkJob({ kind: "import-media", queueKey: `import-media:${slug}`, paths, channelSlug: slug, ...(url ? { askParams: { url } } : {}) }); for (const [slug, url] of [[yt, "https://t.co/AbC"], [yt, "https://x.com/example/status/1"], [SLUGS[0], "https://t.co/AbC"]] as const) { const r = await g(slug, url); assert.equal(r.ok, false, `${url} on ${slug}`); assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, `${url} on ${slug}`); } for (const [slug, url] of [[yt, "https://www.youtube.com/watch?v=a"], [SLUGS[0], "https://www.youtube.com/watch?v=a"], [SLUGS[0], undefined]] as const) { const r = await g(slug, url); assert.equal(r.ok, true, `${url ?? "a local file"} on ${slug}: ${r.ok ? "" : r.error}`); } await reset(); }); test("review 3 M2/S5: a window job is X's by its URLs on any channel; a URL-less item by its own channel, in a batch across channels", async () => { await reset(); await writeJar(5 * 60 * 60_000); for (let i = 0; i < 12; i++) await recordXJobStart(paths, fakeNow); const yt = "yt-chan-r3"; await mkdir(path.join(transcripts, "channels", yt), { recursive: true }); await writeFile(path.join(transcripts, "channels", yt, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: yt, url: "https://www.youtube.com/@example" })); const xs = SLUGS[0]; const g = (kind: string, queueKey: string, params: Record, channelSlug?: string) => guardNetworkJob({ kind, queueKey, paths, ...(channelSlug ? { channelSlug } : {}), spec: { kind, slug: channelSlug ?? yt, params } as never }); const it = (slug: string, webpageUrl?: string) => ({ slug, id: "1", from: 1, to: 2, ...(webpageUrl ? { webpageUrl } : {}) }); const refusedOffX = (r: Awaited>, what: string) => { assert.equal(r.ok, false, what); assert.match(r.ok ? "" : r.error, /X jobs run on X's queue only/, what); }; // An x.com video on a YouTube channel: X's (POST /api/media/fetch-window with a body webpageUrl). refusedOffX(await g("fetch-window", "clips:youtube", { webpageUrl: "https://x.com/example/status/1" }, yt), "a single x.com window on a non-X channel"); refusedOffX(await g("fetch-windows", "clips:youtube", { items: [it(yt, "https://x.com/example/status/1")] }, yt), "a batch item's x.com URL"); // A multi-channel batch under a queue override: one URL-less item of an X channel makes it X's. refusedOffX(await g("fetch-windows", "manual", { items: [it(yt, "https://www.youtube.com/watch?v=a"), it(xs)] }), "a URL-less X item in a multi-channel batch"); // Passes: no URL of X's and no item of an X channel without one. for (const [what, r] of [ ["find-copy's windows on archive.org's clip queue, for an X channel", await g("fetch-windows", "clips:archiveorg", { items: [it(xs, "https://archive.org/details/example")] }, xs)], ["a mirror on another platform", await g("fetch-windows", "clips:rumble", { items: [it(xs, "https://rumble.com/v-example.html")] }, xs)], ["a multi-channel batch of YouTube pages", await g("fetch-windows", "manual", { items: [it(yt, "https://www.youtube.com/watch?v=a"), it(yt)] })], ["fetch-copies of one X channel's gone videos", await g("fetch-copies", "platform:archiveorg", {}, xs)], ] as const) { assert.equal(r.ok, true, `${what}: ${r.ok ? "" : r.error}`); } await reset(); }); test("rule 6 / review 1 F2: on X's rate limit gallery-dl STOPS (abort); the stop is recorded the moment it is seen; the job ends deferred; every X job of any kind is then refused", async () => { await reset(); await writeJar(5 * 60_000); process.env.FAKE_MODE = "ratelimit"; let jobId = ""; try { const res = await fetchJob(SLUGS[0], new Map()); assert.equal(res.ok, true, res.ok ? "" : res.error); if (!res.ok) return; jobId = res.jobId; assert.equal((await res.done).status, "done"); } finally { delete process.env.FAKE_MODE; } const log = await readLog(jobId); // Recorded at once: the stop line comes before the run's summary. const stopAt = log.indexOf("X answered a rate limit (gallery-dl): X is left alone until"); assert.ok(stopAt >= 0, log); assert.ok(stopAt < log.indexOf("gallery-dl read "), "the stop is recorded when the line is seen, before the run ends"); assert.match(log, /^\[deferred\] X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read/m); const record = getRegistry().get(jobId)!; assert.ok(record.deferred && record.deferred.until > Date.now() + 14 * 60_000); // gallery-dl was told to abort on a rate limit, to read at most 300 posts, and not to write the jar back. const argv = (await readFile(RUNS, "utf8")).trim().split("\n").at(-1) ?? ""; assert.match(argv, /extractor\.twitter\.ratelimit=abort/); assert.doesNotMatch(argv, /ratelimit=wait/); assert.match(argv, /--post-range 1-300/); assert.match(argv, /--cookies \S+cookies\.txt -o cookies-update=false/); for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[2]], ["check-post-availability", SLUGS[3]], ["read-x-trending", undefined]] as const) { const r = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") }); assert.equal(r.ok, false, kind); assert.match(r.ok ? "" : r.error, /^X answered a rate limit \(429\) a short while ago: no X job starts before/, kind); } await reset(); });