Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit af03455a1029f5e7a04edea3abe92ec80f3b0de1
parent 9472acd3cd2a835d7a5a760fc32e6788cc5c8ab7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 14:14:29 -0500

common: the X run -- fetch-posts over several X channels as one job, the jar checked before each

A new job kind `x-run` (controller/xRun.ts) on X's queue: the channels in
the operator's order, one fetchPosts each (sync new, at most 200 posts),
X's queue gap between two channels (noteQueueJobEnd + waitForQueueGap, the
same wait two fetch-posts jobs get), and the network guard asked again
before EACH channel. A stale jar or a raised X alert stops the run and
defers the rest until the next refresh; nothing here refreshes cookies.
The state is a file per run under transcripts/.x-runs/; a deferred or
interrupted run is resumed by its id. Not resumed on boot: an interrupted
run ends deferred.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/controller/xRun.test.ts | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/xRun.ts | 739+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 16++++++++++++++++
Mcommon/jobs/jobKinds.ts | 22++++++++++++++++++++++
Mcommon/jobs/registry.ts | 5++++-
Meditor/app/jobs/components/JobProgressBars.tsx | 3+++
6 files changed, 1080 insertions(+), 1 deletion(-)

diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts @@ -0,0 +1,296 @@ +// The X run (lane x-console): the plan's refusals, the loop (X's gap between +// channels, the guard before each, a stale jar deferring the rest, a failed +// channel not stopping the run, cancel and drain), Resume, the interrupted +// view, the default order — and one whole job through runManagedFunction with +// the REAL network guard over a cookie jar on disk that goes stale mid-run. +// Every fetch is a stub: nothing reaches X. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/xRun.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "x-run-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); +// Before getPaths / getSettings are first imported (both cache). +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +writeFileSync( + process.env.SETTINGS_FILE, + JSON.stringify({ + social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } }, + pacing: { jobGapSeconds: { twitter: 0 } }, + }), +); + +const { getPaths } = await import("../lib/paths"); +const xr = await import("./xRun"); +const { defaultChannelPriority } = await import("../lib/channelPriority"); +const paths = getPaths(); + +function channel(slug: string, config: Record<string, unknown>) { + const dir = path.join(paths.channelsDir, slug); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", ...config })); +} +const xChannel = (slug: string) => + channel(slug, { + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + socialHandle: slug, + url: `https://x.com/${slug}`, + }); + +xChannel("xa"); +xChannel("xb"); +xChannel("xc"); +channel("bsky", { sourceKind: "social", platform: "bluesky", url: "https://bsky.app/profile/a.bsky.social" }); +channel("yt", { platform: "youtube", url: "https://www.youtube.com/@someone" }); + +function jar(ageMs: number) { + const dir = path.join(ROOT, ".x-session"); + mkdirSync(path.join(dir, "profile"), { recursive: true }); + const file = path.join(dir, "cookies.txt"); + writeFileSync(file, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n"); + const t = new Date(Date.now() - ageMs); + utimesSync(file, t, t); +} + +type Call = string; +function stubDeps(o: { + calls: Call[]; + stale?: (slug: string) => boolean; + fail?: Set<string>; + onFetch?: (slug: string) => void; +}): import("./xRun").XRunDeps { + return { + fetch: async (slug, f) => { + o.calls.push(`fetch ${slug} limit=${f.limit}`); + o.onFetch?.(slug); + if (o.fail?.has(slug)) return { ok: false, written: 0, error: "No post fetcher" }; + return { ok: true, written: 3 }; + }, + guard: async (slug) => { + o.calls.push(`guard ${slug}`); + return o.stale?.(slug) + ? { ok: false, error: "X cookies were last refreshed 2 h ago (limit 60 min): press Refresh cookies" } + : { ok: true, notes: [] }; + }, + noteEnd: () => o.calls.push("end"), + waitGap: async () => { + o.calls.push("gap"); + return "waited"; + }, + }; +} + +const never = () => new AbortController().signal; + +test("the plan refuses before any job: nothing picked, a stranger, a non-X channel, twice, a limit over 200", async () => { + const refuse = async (req: Parameters<typeof xr.planXRun>[1]) => { + const r = await xr.planXRun(paths, req); + assert.equal(r.ok, false); + return (r as { error: string }).error; + }; + assert.equal(await refuse({ channels: [] }), "Pick one or more X posts channels to run."); + assert.equal(await refuse({ channels: ["nope"] }), "No such channel: nope"); + assert.equal(await refuse({ channels: ["bsky"] }), "bsky is not an X posts channel."); + assert.equal(await refuse({ channels: ["yt"] }), "yt is not an X posts channel."); + assert.equal(await refuse({ channels: ["xa", "xa"] }), '"xa" is named twice.'); + assert.equal(await refuse({ channels: ["../x"] }), '"../x" is not a valid channel slug.'); + assert.match(await refuse({ channels: ["xa"], limit: 201 }), /from 1 to 200/); + assert.match(await refuse({ resume: "xr-nope" }), /is not an X run id/); +}); + +test("the loop: X's gap between channels (not before the first), the guard before each, 200 posts each; a stale jar defers the rest", async () => { + const plan = await xr.planXRun(paths, { channels: ["xa", "xb", "xc"] }); + assert.ok(plan.ok); + const calls: Call[] = []; + const lines: string[] = []; + const r = await xr.runXRun({ + paths, + state: plan.state, + deps: stubDeps({ calls, stale: (s) => s === "xc" }), + jobId: "JOB1", + onLog: (l) => lines.push(l), + signal: never(), + drain: never(), + }); + assert.deepEqual(calls, [ + "guard xa", + "fetch xa limit=200", + "end", + "gap", + "guard xb", + "fetch xb limit=200", + "end", + "gap", + "guard xc", + ]); + assert.equal(r.status, "deferred"); + assert.equal(r.summary, "2 done, 1 deferred until the next refresh"); + assert.match(r.stopped!, /^X cookies were last refreshed 2 h ago/); + const disk = (await xr.readXRun(paths, plan.state.id))!; + assert.deepEqual( + disk.channels.map((c) => [c.slug, c.status, c.posts]), + [["xa", "done", 3], ["xb", "done", 3], ["xc", "deferred", undefined]], + ); + assert.deepEqual(disk.jobIds, ["JOB1"]); + assert.ok(lines.some((l) => l.startsWith("Stopped before xc: X cookies"))); + + // RESUME starts with the deferred channel, and only it. + const again = await xr.planXRun(paths, { resume: plan.state.id }); + assert.ok(again.ok && again.resumed); + const calls2: Call[] = []; + const r2 = await xr.runXRun({ paths, state: again.state, deps: stubDeps({ calls: calls2 }), jobId: "JOB2", onLog: () => {}, signal: never(), drain: never() }); + assert.deepEqual(calls2, ["guard xc", "fetch xc limit=200", "end"]); + assert.equal(r2.status, "done"); + assert.equal(r2.summary, "3 done"); + assert.deepEqual((await xr.readXRun(paths, plan.state.id))!.jobIds, ["JOB1", "JOB2"]); + // Nothing left: a second resume is refused with the summary. + const none = await xr.planXRun(paths, { resume: plan.state.id }); + assert.equal(none.ok, false); + assert.match((none as { error: string }).error, /has nothing to resume: 3 done\.$/); +}); + +test("a failed channel is the channel's: the run goes on; a custom limit reaches the fetch", async () => { + const plan = await xr.planXRun(paths, { channels: ["xa", "xb"], limit: 50 }); + assert.ok(plan.ok); + const calls: Call[] = []; + const r = await xr.runXRun({ paths, state: plan.state, deps: stubDeps({ calls, fail: new Set(["xa"]) }), onLog: () => {}, signal: never(), drain: never() }); + assert.equal(r.status, "done"); + assert.equal(r.summary, "1 done, 1 failed"); + assert.ok(calls.includes("fetch xb limit=50")); + const disk = (await xr.readXRun(paths, plan.state.id))!; + assert.equal(disk.channels[0].error, "No post fetcher"); +}); + +test("cancel mid-fetch: the channel and the rest wait for a Resume; drain stops between channels", async () => { + const plan = await xr.planXRun(paths, { channels: ["xa", "xb"] }); + assert.ok(plan.ok); + const abort = new AbortController(); + const r = await xr.runXRun({ + paths, + state: plan.state, + deps: stubDeps({ calls: [], onFetch: () => abort.abort() }), + onLog: () => {}, + signal: abort.signal, + drain: never(), + }); + assert.equal(r.status, "cancelled"); + assert.deepEqual(r.counts, { total: 2, queued: 0, running: 0, done: 0, deferred: 2, failed: 0, posts: 0 }); + + const plan2 = await xr.planXRun(paths, { channels: ["xa", "xb"] }); + assert.ok(plan2.ok); + const drain = new AbortController(); + const r2 = await xr.runXRun({ + paths, + state: plan2.state, + deps: stubDeps({ calls: [], onFetch: () => drain.abort() }), + onLog: () => {}, + signal: never(), + drain: drain.signal, + }); + assert.equal(r2.status, "drained"); + assert.equal(r2.summary, "1 done, 1 deferred until the next refresh"); +}); + +test("the view: a run whose file says running with no live job was interrupted — its unfinished channels deferred and resumable", () => { + const state: import("./xRun").XRunState = { + version: 1, + id: "xr-01JZZZZZZZZZZZZZZZZZZZZZZZ", + createdAt: "", + updatedAt: "", + limit: 200, + status: "running", + waitingUntil: "2026-11-09T12:00:00.000Z", + jobIds: ["J"], + channels: [ + { slug: "a", status: "done", posts: 4 }, + { slug: "b", status: "running" }, + { slug: "c", status: "queued" }, + ], + }; + const dead = xr.xRunView(state, null); + assert.equal(dead.interrupted, true); + assert.equal(dead.status, "deferred"); + assert.equal(dead.summary, "1 done, 2 deferred until the next refresh"); + assert.equal(dead.resumable, 2); + assert.equal(dead.waitingUntil, undefined); + const live = xr.xRunView(state, { id: "J", status: "running" }); + assert.equal(live.interrupted, false); + assert.equal(live.resumable, 0); + assert.equal(live.summary, "1 done, 2 to go"); + assert.equal(live.waitingUntil, "2026-11-09T12:00:00.000Z"); +}); + +test("the default order is Sync all's: focus, then the sync tier, then rank (unranked last), then slug", () => { + const p = defaultChannelPriority(); + p.channels = { + low1: { tier: "low" }, + norm2: { tier: "normal", rank: 2 }, + norm1: { tier: "normal", rank: 1 }, + paused: { tier: "paused" }, + syncLow: { tier: "normal", overrides: { sync: "low" } }, + } as typeof p.channels; + const order = xr.defaultXRunOrder(["paused", "low1", "zeta", "norm2", "syncLow", "norm1", "focused"], p, new Set(["focused"])); + assert.deepEqual(order, ["focused", "norm1", "norm2", "zeta", "low1", "syncLow", "paused"]); +}); + +test("one whole job, the REAL guard: the jar goes stale during the second channel, so the third is deferred; then a refreshed jar and Resume", async () => { + jar(60_000); + const fetched: string[] = []; + const deps = (jobId: string) => ({ + ...xr.defaultXRunDeps(paths, jobId), + fetch: async (slug: string) => { + fetched.push(slug); + // Time passes: the jar is two hours old once xb's fetch ends. + if (slug === "xb") jar(2 * 60 * 60_000); + return { ok: true, written: 1 }; + }, + }); + const res = await xr.queueXRun({ paths, req: { channels: ["xa", "xb", "xc"] }, deps }); + assert.ok(res.ok, (res as { error?: string }).error); + assert.equal((await res.done).status, "done"); + assert.deepEqual(fetched, ["xa", "xb"]); + const view = (await xr.readXRunView(paths, res.run))!; + assert.equal(view.status, "deferred"); + assert.equal(view.summary, "2 done, 1 deferred until the next refresh"); + assert.match(view.stopped!, /^X cookies were last refreshed 2 h ago \(limit 60 min\)/); + assert.equal(view.resumable, 1); + assert.equal(view.live, false); + + // A stale jar refuses the Resume before any job (the guard at enqueue), and + // the run stays deferred. + const refused = await xr.queueXRun({ paths, req: { resume: res.run }, deps }); + assert.equal(refused.ok, false); + assert.match((refused as { error: string }).error, /^X cookies were last refreshed/); + assert.equal((await xr.readXRunView(paths, res.run))!.resumable, 1); + + // The operator refreshes the jar; Resume runs the deferred channel. + jar(0); + const resumed = await xr.queueXRun({ paths, req: { resume: res.run }, deps }); + assert.ok(resumed.ok, (resumed as { error?: string }).error); + assert.equal((await resumed.done).status, "done"); + assert.deepEqual(fetched, ["xa", "xb", "xc"]); + const end = (await xr.readXRunView(paths, res.run))!; + assert.equal(end.status, "done"); + assert.equal(end.summary, "3 done"); + assert.equal(end.jobIds.length, 2); + // The latest run is this one. + assert.equal((await xr.readXRunView(paths))!.id, res.run); +}); + +test("a stale jar at the start refuses the new run before a job; its file is deferred for a Resume", async () => { + jar(16 * 24 * 60 * 60_000); + const res = await xr.queueXRun({ paths, req: { channels: ["xa"] } }); + assert.equal(res.ok, false); + assert.match((res as { error: string }).error, /16 days ago/); + const view = (await xr.readXRunView(paths, res.run))!; + assert.equal(view.status, "deferred"); + assert.equal(view.summary, "0 done, 1 deferred until the next refresh"); +}); diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts @@ -0,0 +1,739 @@ +// THE X RUN (lane x-console, 9 Nov). On 8 and 9 Nov an agent ran X +// `fetch-posts` jobs by hand, one channel after another, watching the cookie +// jar age and deferring the rest when the jar went stale. This is that, as ONE +// editor job (`x-run`, on the X queue `platform:twitter`) with a console on +// /review: +// +// - the channels are the operator's, in the operator's order (the console +// defaults to the channel priority tiers: focus, normal, low, paused, then +// rank, then slug); +// - each channel is ONE `fetchPosts` (controller/fetchPosts.ts — the same +// fetcher a channel's Sync new runs; there is no second one), capped at +// `limit` posts (X_RUN_MAX_POSTS, 200); +// - between two channels the job waits X's queue gap exactly as two +// fetch-posts jobs would (`pacing.jobGapSeconds.twitter`, jittered, via +// jobs/queueGap.ts: the end is noted, the gap waited); +// - BEFORE EACH CHANNEL the network guard is asked again (the fresh-jar rule +// and the X alert, jobs/networkGuard.ts). When it refuses, the run STOPS +// there and every channel not yet fetched is DEFERRED. Nothing here ever +// refreshes the jar: a refresh is the operator's click on /settings +// (refreshXCookies loads x.com/home — itself a request to X); +// - a deferred run is resumed by its id (the console's Resume, `pnpm ops +// x-run {"resume": id}`, a Retry of the job): it starts with the deferred +// channels, in the order they had. +// +// THE STATE is a file per run, `<transcripts>/.x-runs/<runId>.json`, written +// at every transition, so the console reads it while the job runs and after +// the editor restarts. +// +// AN INTERRUPTED RUN ENDS DEFERRED; IT IS NOT RESUMED ON BOOT (the kind does +// not declare `resumeOnBoot`). A restart can come minutes or hours after the +// run began, and an X sequence that starts by itself on boot is the +// unattended pattern the fresh-jar rule exists to stop. The state file still +// says `running` for a dead job; the view reads that as interrupted, its +// unfinished channels as deferred, and Resume runs them when the operator +// says so. + +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 { getSettings } from "../lib/settings"; +import { isValidChannelSlug, listChannelConfigs, readChannelConfig } from "./channels"; +import { isSocialChannel } from "../lib/channelConfig"; +import { isWaybackPagesChannel } from "../lib/waybackPages/config"; +import { isXSearchChannel } from "../lib/xSearch/config"; +import { readPostFetchState, countPosts } from "../lib/posts-server"; +import { + effectiveTier, + rankOf, + resolveFocusSlugs, + tierOrder, + type ChannelPriority, + type ChannelTier, +} from "../lib/channelPriority"; +import { siteChannelIndex } from "../lib/site"; +import { ulid } from "../jobs/ulid"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { guardNetworkJob } from "../jobs/networkGuard"; +import { noteQueueJobEnd, queueGapClock, waitForQueueGap } from "../jobs/queueGap"; +import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; +import { fetchPosts } from "./fetchPosts"; + +export const X_RUN_JOB_KIND = "x-run"; +// X's platform queue: the run serialises with every other X job (a channel's +// own fetch-posts, a capture) and is spaced from them by X's gap. +export const X_RUN_QUEUE = "platform:twitter"; +// At most this many posts per channel per run (the fetch's own `limit`, +// gallery-dl's `--post-range 1-N`). +export const X_RUN_MAX_POSTS = 200; +export const X_RUN_MAX_CHANNELS = 500; +export const X_RUN_RESULT_MARKER = "@@x-run "; +// A spec needs a slug; the replay reads params.run (the state holds the list). +export const X_RUN_SPEC_SLUG = "_x-run"; + +export type XRunChannelStatus = "queued" | "running" | "done" | "deferred" | "failed"; + +export type XRunChannel = { + slug: string; + status: XRunChannelStatus; + // New posts written (done; a failed fetch that checkpointed some, too). + posts?: number; + error?: string; + startedAt?: string; + endedAt?: string; +}; + +// queued: made, its job waiting; running; done: every channel ran; +// deferred: the guard stopped it, some channels deferred; cancelled; drained; +// failed: the run itself broke (not a channel's fetch — that is the channel's). +export type XRunStatus = "queued" | "running" | "done" | "deferred" | "cancelled" | "drained" | "failed"; + +export type XRunState = { + version: 1; + id: string; + createdAt: string; + updatedAt: string; + limit: number; + status: XRunStatus; + // Why the run stopped short (the guard's sentence, a drain, a cancel). + stopped?: string; + // While the job waits X's gap before the next channel: until when (ISO). + waitingUntil?: string; + // Every job that ran this run, oldest first (a resume adds one). + jobIds: string[]; + channels: XRunChannel[]; +}; + +export function xRunDir(paths: Pick<Paths, "jobsDir">): string { + return path.join(path.dirname(paths.jobsDir), ".x-runs"); +} + +const RUN_ID = /^xr-[0-9A-Z]{26}$/; + +export function isXRunId(id: unknown): id is string { + return typeof id === "string" && RUN_ID.test(id); +} + +export function xRunPath(paths: Pick<Paths, "jobsDir">, id: string): string { + return path.join(xRunDir(paths), `${id}.json`); +} + +function parseRun(raw: unknown): XRunState | null { + if (!raw || typeof raw !== "object") return null; + const r = raw as Partial<XRunState>; + if (r.version !== 1 || !isXRunId(r.id) || !Array.isArray(r.channels)) return null; + const channels: XRunChannel[] = []; + for (const c of r.channels) { + if (!c || typeof c !== "object" || typeof c.slug !== "string") continue; + const status = (["queued", "running", "done", "deferred", "failed"] as const).includes(c.status) + ? c.status + : "queued"; + channels.push({ ...c, status }); + } + return { + version: 1, + id: r.id, + createdAt: typeof r.createdAt === "string" ? r.createdAt : "", + updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "", + limit: typeof r.limit === "number" && r.limit > 0 ? Math.min(r.limit, X_RUN_MAX_POSTS) : X_RUN_MAX_POSTS, + status: typeof r.status === "string" ? r.status : "queued", + ...(typeof r.stopped === "string" ? { stopped: r.stopped } : {}), + ...(typeof r.waitingUntil === "string" ? { waitingUntil: r.waitingUntil } : {}), + jobIds: Array.isArray(r.jobIds) ? r.jobIds.filter((j): j is string => typeof j === "string") : [], + channels, + }; +} + +export async function readXRun(paths: Pick<Paths, "jobsDir">, id: string): Promise<XRunState | null> { + if (!isXRunId(id)) return null; + const read = await readJsonFile(xRunPath(paths, id)); + return read.ok ? parseRun(read.value) : null; +} + +export async function writeXRun(paths: Pick<Paths, "jobsDir">, state: XRunState, now = Date.now()): Promise<void> { + state.updatedAt = new Date(now).toISOString(); + await writeJsonAtomic(xRunPath(paths, state.id), state, { mkdir: true }); +} + +// The runs on disk, newest first (a run id is a ULID: it sorts by time). +export async function listXRunIds(paths: Pick<Paths, "jobsDir">): Promise<string[]> { + let names: string[]; + try { + names = await readdir(xRunDir(paths)); + } catch { + return []; + } + return names + .filter((n) => n.endsWith(".json")) + .map((n) => n.slice(0, -".json".length)) + .filter(isXRunId) + .sort() + .reverse(); +} + +export async function latestXRun(paths: Pick<Paths, "jobsDir">): Promise<XRunState | null> { + for (const id of await listXRunIds(paths)) { + const run = await readXRun(paths, id); + if (run) return run; + } + return null; +} + +// ── counting and saying ──────────────────────────────────────────────────── + +export type XRunCounts = { + total: number; + queued: number; + running: number; + done: number; + deferred: number; + failed: number; + // New posts written across the done channels. + posts: number; +}; + +export function xRunCounts(channels: readonly XRunChannel[]): XRunCounts { + const c: XRunCounts = { total: channels.length, queued: 0, running: 0, done: 0, deferred: 0, failed: 0, posts: 0 }; + for (const ch of channels) { + c[ch.status]++; + if (ch.status === "done") c.posts += ch.posts ?? 0; + } + return c; +} + +// "3 done, 2 deferred until the next refresh" (+ ", 1 failed"; + ", 4 to go"). +export function xRunSummary(counts: XRunCounts): string { + const parts = [`${counts.done} done`]; + if (counts.deferred > 0) parts.push(`${counts.deferred} deferred until the next refresh`); + if (counts.failed > 0) parts.push(`${counts.failed} failed`); + const toGo = counts.queued + counts.running; + if (toGo > 0) parts.push(`${toGo} to go`); + return parts.join(", "); +} + +// THE RUN AS THE CONSOLE AND `get x-run` SHOW IT. `live` is whether its last +// job is queued or running in this process. A run whose file says queued or +// running but whose job is not live was INTERRUPTED (a restart, a crash): its +// unfinished channels are shown deferred, and Resume runs them. +export type XRunView = XRunState & { + live: boolean; + interrupted: boolean; + jobId: string | null; + counts: XRunCounts; + summary: string; + // Channels a Resume would run (deferred, and an interrupted run's unfinished). + resumable: number; +}; + +export function xRunView(state: XRunState, liveJob: { id: string; status: string } | null): XRunView { + const live = !!liveJob && (liveJob.status === "queued" || liveJob.status === "running"); + const jobId = live ? liveJob!.id : (state.jobIds.at(-1) ?? null); + const interrupted = !live && (state.status === "queued" || state.status === "running"); + const channels = interrupted + ? state.channels.map((c) => + c.status === "queued" || c.status === "running" ? { ...c, status: "deferred" as const } : c, + ) + : state.channels; + const counts = xRunCounts(channels); + const { waitingUntil, ...rest } = state; + return { + ...rest, + ...(live && waitingUntil ? { waitingUntil } : {}), + ...(interrupted + ? { status: "deferred" as const, stopped: "Interrupted: the editor stopped while the run was in progress." } + : {}), + channels, + live, + interrupted, + jobId, + counts, + summary: xRunSummary(counts), + resumable: live ? 0 : counts.deferred, + }; +} + +// The x-run jobs queued or running in this process; a job's run is its +// spec's `params.run` (known before the job starts, unlike its id in the file). +function liveXRunJobs(): { id: string; status: string; run: string | null }[] { + return getRegistry() + .list() + .filter((j) => j.kind === X_RUN_JOB_KIND && (j.status === "queued" || j.status === "running")) + .map((j) => { + const run = j.spec?.params?.run; + return { id: j.id, status: j.status, run: typeof run === "string" ? run : null }; + }); +} + +function liveJobFor(state: XRunState): { id: string; status: string } | null { + return liveXRunJobs().find((j) => j.run === state.id) ?? null; +} + +export async function readXRunView(paths: Pick<Paths, "jobsDir">, id?: string): Promise<XRunView | null> { + const state = id ? await readXRun(paths, id) : await latestXRun(paths); + return state ? xRunView(state, liveJobFor(state)) : null; +} + +// ── the channels a run may take ──────────────────────────────────────────── + +export type XRunCandidate = { + slug: string; + name: string; + // The base tier the default order reads ("focus" when the focus names it). + tier: ChannelTier; + rank: number | null; + // An X search channel (its query's windows), not an account timeline. + search: boolean; + postCount: number; + lastFetchedAt: string | null; + lastFetchedCount: number | null; + lastError: string | null; +}; + +type ConfigLike = Parameters<typeof isSocialChannel>[0] & { + platform?: string; + name?: string; + xSearch?: unknown; + wayback?: unknown; +}; + +// An X posts channel (an account's timeline or an X search): what a run takes. +export function isXPostsChannel(config: ConfigLike | null | undefined): boolean { + return ( + !!config && + isSocialChannel(config) && + config.platform === "twitter" && + !isWaybackPagesChannel(config as Parameters<typeof isWaybackPagesChannel>[0]) + ); +} + +// THE DEFAULT ORDER: the order *Sync all* queues in (editor channels/actions.ts +// syncAllChannelsAction) — focus, then the `sync` tier, then rank (unranked +// last), then slug. +export function defaultXRunOrder( + slugs: readonly string[], + priority: ChannelPriority, + focus: ReadonlySet<string>, +): string[] { + const tierOf = (s: string): ChannelTier => (focus.has(s) ? "focus" : effectiveTier(priority, s, "sync")); + const rank = (a: number | null, b: number | null) => (a === b ? 0 : a === null ? 1 : b === null ? -1 : a - b); + return [...slugs].sort( + (a, b) => + tierOrder(tierOf(a)) - tierOrder(tierOf(b)) || + rank(rankOf(priority, a), rankOf(priority, b)) || + a.localeCompare(b), + ); +} + +export async function listXRunCandidates(paths: Paths): Promise<XRunCandidate[]> { + const all = await listChannelConfigs(paths); + const x = all.filter((c) => isXPostsChannel(c.config)); + const priority = getSettings().channelPriority; + const focus = new Set(resolveFocusSlugs(priority, siteChannelIndex(paths), all.map((c) => c.slug))); + const bySlug = new Map(x.map((c) => [c.slug, c.config])); + const order = defaultXRunOrder(x.map((c) => c.slug), priority, focus); + return Promise.all( + order.map(async (slug): Promise<XRunCandidate> => { + const config = bySlug.get(slug)!; + const root = path.join(paths.channelsDir, slug); + const [state, postCount] = await Promise.all([ + readPostFetchState(root).catch(() => null), + countPosts(root).catch(() => 0), + ]); + return { + slug, + name: config.name ?? slug, + tier: focus.has(slug) ? "focus" : effectiveTier(priority, slug, "sync"), + rank: rankOf(priority, slug), + search: isXSearchChannel(config), + postCount, + lastFetchedAt: state?.lastFetchedAt ?? null, + lastFetchedCount: state?.lastFetchedCount ?? null, + lastError: state?.lastError ?? null, + }; + }), + ); +} + +// ── planning ─────────────────────────────────────────────────────────────── + +export type XRunRequest = { + // A new run over these channels, in this order. + channels?: readonly unknown[]; + // Posts per channel, at most X_RUN_MAX_POSTS (the default). + limit?: number; + // Resume this run: its deferred channels (and an interrupted run's + // unfinished ones), in the order they had. + resume?: string; +}; + +export type XRunPlan = { ok: true; state: XRunState; resumed: boolean } | { ok: false; error: string }; + +export function xRunLimitProblem(limit: unknown): string | null { + if (limit === undefined) return null; + if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > X_RUN_MAX_POSTS) { + return `"limit" is the posts per channel, a whole number from 1 to ${X_RUN_MAX_POSTS}.`; + } + return null; +} + +// The run a request names, made or prepared to resume — refused, with the +// sentence, before any job exists. Writes the state (a new run's file; a +// resume's channels back to queued). +export async function planXRun(paths: Paths, req: XRunRequest, now = Date.now()): Promise<XRunPlan> { + const live = liveXRunJobs()[0]; + if (live) { + return { ok: false, error: `An X run is already queued or running (job ${live.id}): one at a time.` }; + } + if (req.resume !== undefined) { + if (req.channels !== undefined) return { ok: false, error: '"resume" and "channels" are one at a time.' }; + if (!isXRunId(req.resume)) return { ok: false, error: `"${String(req.resume)}" is not an X run id.` }; + const state = await readXRun(paths, req.resume); + if (!state) return { ok: false, error: `No X run ${req.resume}.` }; + const view = xRunView(state, null); + if (view.resumable === 0) { + return { ok: false, error: `X run ${state.id} has nothing to resume: ${view.summary}.` }; + } + for (const c of state.channels) { + if (c.status === "deferred" || c.status === "queued" || c.status === "running") { + c.status = "queued"; + delete c.error; + delete c.startedAt; + delete c.endedAt; + } + } + if (req.limit !== undefined) { + const problem = xRunLimitProblem(req.limit); + if (problem) return { ok: false, error: problem }; + state.limit = req.limit; + } + state.status = "queued"; + delete state.stopped; + delete state.waitingUntil; + await writeXRun(paths, state, now); + return { ok: true, state, resumed: true }; + } + const problem = xRunLimitProblem(req.limit); + if (problem) return { ok: false, error: problem }; + const raw = req.channels ?? []; + if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: "Pick one or more X posts channels to run." }; + if (raw.length > X_RUN_MAX_CHANNELS) return { ok: false, error: `At most ${X_RUN_MAX_CHANNELS} channels in one run.` }; + const slugs: string[] = []; + for (const s of raw) { + if (!isValidChannelSlug(s)) return { ok: false, error: `"${String(s)}" is not a valid channel slug.` }; + if (slugs.includes(s)) return { ok: false, error: `"${s}" is named twice.` }; + const config = await readChannelConfig(paths, s); + if (!config) return { ok: false, error: `No such channel: ${s}` }; + if (!isXPostsChannel(config)) return { ok: false, error: `${s} is not an X posts channel.` }; + slugs.push(s); + } + const at = new Date(now).toISOString(); + const state: XRunState = { + version: 1, + id: `xr-${ulid(now)}`, + createdAt: at, + updatedAt: at, + limit: req.limit ?? X_RUN_MAX_POSTS, + status: "queued", + jobIds: [], + channels: slugs.map((slug) => ({ slug, status: "queued" })), + }; + await writeXRun(paths, state, now); + return { ok: true, state, resumed: false }; +} + +// ── the run ──────────────────────────────────────────────────────────────── + +export type XRunFetchResult = { ok: boolean; written: number; error?: string; drained?: boolean }; + +export type XRunDeps = { + // One channel's fetch (production: fetchPosts, sync new, capped). + fetch: ( + slug: string, + o: { limit: number; onLog: (line: string) => void; signal: AbortSignal; drain: AbortSignal }, + ) => Promise<XRunFetchResult>; + // The network guard, asked before each channel (production: guardNetworkJob). + guard: (slug: string) => Promise<{ ok: true; notes: string[] } | { ok: false; error: string }>; + // A channel's fetch ended: noted as the X queue's last end. + noteEnd: () => void; + // X's gap before the next channel. "drained"/"aborted" when it was cut. + waitGap: (o: { + signal: AbortSignal; + drain: AbortSignal; + onLog: (line: string) => void; + onWait: (until: number | null) => void; + }) => Promise<"waited" | "drained" | "aborted">; + // A channel's fetch ended (production: its report regenerates). + channelDone?: (slug: string) => void; + now?: () => number; +}; + +export type XRunResult = { + id: string; + status: XRunStatus; + stopped?: string; + counts: XRunCounts; + summary: string; +}; + +// THE LOOP, its effects behind `deps` (tested with stubs; no X). +export async function runXRun(opts: { + paths: Pick<Paths, "jobsDir">; + state: XRunState; + deps: XRunDeps; + jobId?: string; + onLog: (line: string) => void; + signal: AbortSignal; + drain: AbortSignal; + onProgress?: (p: { done: number; total: number }) => void; +}): Promise<XRunResult> { + const { paths, state, deps, onLog, signal, drain } = opts; + const now = deps.now ?? Date.now; + const save = () => writeXRun(paths, state, now()); + const iso = () => new Date(now()).toISOString(); + if (opts.jobId && !state.jobIds.includes(opts.jobId)) state.jobIds.push(opts.jobId); + state.status = "running"; + delete state.stopped; + await save(); + const total = state.channels.length; + const settled = () => state.channels.filter((c) => c.status !== "queued" && c.status !== "running").length; + const todo = state.channels.filter((c) => c.status === "queued"); + onLog( + `X run ${state.id}: ${todo.length} channel(s), at most ${state.limit} posts each, ` + + `X's queue gap between them; the cookie jar is checked before each.`, + ); + opts.onProgress?.({ done: settled(), total }); + const deferRest = (reason: string) => { + for (const c of state.channels) if (c.status === "queued") c.status = "deferred"; + state.status = "deferred"; + state.stopped = reason; + }; + let stoppedEarly = false; + let first = true; + for (const ch of todo) { + if (signal.aborted) { + state.status = "cancelled"; + state.stopped = "Cancelled."; + stoppedEarly = true; + break; + } + if (drain.aborted) { + state.status = "drained"; + state.stopped = "Drained: the channels not yet fetched stay queued for a Resume."; + for (const c of state.channels) if (c.status === "queued") c.status = "deferred"; + stoppedEarly = true; + break; + } + // The run's first channel follows the job's own gap (runManagedFunction + // waited it); every later one waits X's gap after the one before. + if (!first) { + const waited = await deps.waitGap({ + signal, + drain, + onLog, + onWait: (until) => { + if (until === null) delete state.waitingUntil; + else state.waitingUntil = new Date(until).toISOString(); + void save(); + }, + }); + delete state.waitingUntil; + if (waited === "aborted") { + state.status = "cancelled"; + state.stopped = "Cancelled."; + stoppedEarly = true; + break; + } + if (waited === "drained") { + state.status = "drained"; + state.stopped = "Drained while waiting for X's gap: the channels not yet fetched stay for a Resume."; + for (const c of state.channels) if (c.status === "queued") c.status = "deferred"; + stoppedEarly = true; + break; + } + } + // THE JAR, BEFORE EACH CHANNEL. A refusal stops the run: this channel and + // every one after it wait for the next refresh. + const g = await deps.guard(ch.slug); + if (!g.ok) { + onLog(`Stopped before ${ch.slug}: ${g.error}`); + deferRest(g.error); + stoppedEarly = true; + break; + } + for (const note of g.notes) onLog(note); + first = false; + ch.status = "running"; + ch.startedAt = iso(); + delete ch.error; + await save(); + onLog(`── ${ch.slug} (${state.channels.indexOf(ch) + 1}/${total}) ──`); + let r: XRunFetchResult; + try { + r = await deps.fetch(ch.slug, { limit: state.limit, onLog, signal, drain }); + } catch (err) { + r = { ok: false, written: 0, error: (err as Error).message }; + } + deps.noteEnd(); + deps.channelDone?.(ch.slug); + ch.endedAt = iso(); + if (signal.aborted) { + // Cancelled mid-fetch: what it checkpointed is on disk; the channel + // runs again on a Resume. + ch.status = "deferred"; + if (r.written > 0) ch.posts = r.written; + state.status = "cancelled"; + state.stopped = "Cancelled."; + for (const c of state.channels) if (c.status === "queued") c.status = "deferred"; + stoppedEarly = true; + break; + } + ch.posts = r.written; + if (r.ok) { + ch.status = "done"; + onLog(`${ch.slug}: ${r.written} new post(s).`); + } else { + ch.status = "failed"; + ch.error = r.error ?? "Post fetch failed"; + onLog(`${ch.slug} failed: ${ch.error}`); + } + await save(); + opts.onProgress?.({ done: settled(), total }); + if (r.drained) { + state.status = "drained"; + state.stopped = "Drained: the channels not yet fetched stay for a Resume."; + for (const c of state.channels) if (c.status === "queued") c.status = "deferred"; + stoppedEarly = true; + break; + } + } + if (!stoppedEarly) { + const left = state.channels.some((c) => c.status === "deferred"); + state.status = left ? "deferred" : "done"; + } + delete state.waitingUntil; + await save(); + const counts = xRunCounts(state.channels); + const summary = xRunSummary(counts); + onLog(`X run ${state.id}: ${summary}${state.stopped ? ` — ${state.stopped}` : ""}.`); + return { id: state.id, status: state.status, ...(state.stopped ? { stopped: state.stopped } : {}), counts, summary }; +} + +// The production deps: fetchPosts (sync new, capped), the network guard, X's +// queue gap and its end, the channel's report. +export function defaultXRunDeps(paths: Paths, jobId: string): XRunDeps { + return { + fetch: async (slug, o) => { + const r = await fetchPosts({ + paths, + slug, + settings: getSettings(), + limit: o.limit, + onLog: o.onLog, + signal: o.signal, + drain: o.drain, + }); + return { ok: r.ok, written: r.written, ...(r.error ? { error: r.error } : {}), ...(r.drained ? { drained: true } : {}) }; + }, + guard: async (slug) => { + const res = await guardNetworkJob({ + kind: X_RUN_JOB_KIND, + queueKey: X_RUN_QUEUE, + paths, + channelSlug: slug, + job: { id: jobId }, + }); + return res.ok ? { ok: true, notes: res.notes } : { ok: false, error: res.error }; + }, + noteEnd: () => void noteQueueJobEnd(paths, X_RUN_QUEUE, queueGapClock().now()), + waitGap: async (o) => { + try { + await waitForQueueGap({ + paths, + queueKey: X_RUN_QUEUE, + pacing: () => getSettings().pacing, + signal: AbortSignal.any([o.signal, o.drain]), + onLog: o.onLog, + onWait: (w) => o.onWait(w ? w.until : null), + clock: queueGapClock(), + }); + return "waited"; + } catch (err) { + if (o.signal.aborted) return "aborted"; + if (o.drain.aborted) return "drained"; + throw err; + } + }, + channelDone: (slug) => requestChannelSnapshot(paths, slug), + }; +} + +// THE JOB: one `x-run` on X's queue, made or resumed. Refused (no job) with +// the plan's sentence — or by the network guard (a stale jar, the X alert), +// in which case a new run's file is marked deferred so Resume can take it +// once the jar is fresh. +export async function queueXRun(opts: { + paths: Paths; + req: XRunRequest; + deps?: (jobId: string) => XRunDeps; + onChannelDone?: (slug: string) => void; + now?: number; +}): Promise<StreamActionResult & { run?: string }> { + const planned = await planXRun(opts.paths, opts.req, opts.now); + if (!planned.ok) return { ok: false, error: planned.error }; + const { state } = planned; + const res = await runManagedFunction({ + kind: X_RUN_JOB_KIND, + queueKey: X_RUN_QUEUE, + paths: opts.paths, + spec: { kind: X_RUN_JOB_KIND, slug: X_RUN_SPEC_SLUG, params: { run: state.id } }, + fn: async (onLog, signal, setProgress, ctx) => { + // Re-read at the start: a queued job runs the state as it is then. + const fresh = (await readXRun(opts.paths, state.id)) ?? state; + const base = opts.deps ? opts.deps(ctx.jobId) : defaultXRunDeps(opts.paths, ctx.jobId); + const deps: XRunDeps = { + ...base, + channelDone: (slug) => { + base.channelDone?.(slug); + opts.onChannelDone?.(slug); + }, + }; + let r: XRunResult; + try { + r = await runXRun({ + paths: opts.paths, + state: fresh, + deps, + jobId: ctx.jobId, + onLog, + signal, + drain: ctx.drainSignal, + onProgress: (p) => setProgress({ metric: "channels", initial: 0, target: p.total, current: p.done }), + }); + } catch (err) { + fresh.status = "failed"; + fresh.stopped = (err as Error).message; + await writeXRun(opts.paths, fresh).catch(() => {}); + throw err; + } + onLog(`${X_RUN_RESULT_MARKER}${JSON.stringify(r)}`); + if (r.status === "cancelled") throw new Error("cancelled"); + }, + }); + if (!res.ok) { + // Refused before a job existed (a stale jar at enqueue): the run's + // channels wait for the next refresh, and Resume takes them. + const back = await readXRun(opts.paths, state.id); + if (back) { + for (const c of back.channels) if (c.status === "queued") c.status = "deferred"; + back.status = "deferred"; + back.stopped = res.error; + await writeXRun(opts.paths, back); + } + return { ...res, run: state.id }; + } + // The job id joins the file when the job starts (runXRun): a write here + // would race the job's own. + return { ...res, run: state.id }; +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -376,6 +376,7 @@ test("pacing guard: the kinds that make platform requests are network kinds", () "import-page", "save-page-now", "wayback-scan", + "x-run", ]; for (const k of required) { assert.ok(getJobKind(k), `${k} is a registered kind`); @@ -415,3 +416,18 @@ test("resumeOnBoot: exactly the kinds that continue on a re-run, every one repla assert.equal(getJobKind(k)?.resumeOnBoot, undefined, `${k} does not resume`); } }); + +// Lane x-console: the X run is fetch-posts over several X channels in one job +// on X's queue — network, drainable, replayable (a Retry is a Resume), an +// ingest kind, and NOT resumed on boot: an interrupted run ends deferred. +test("x-run: a network, drainable, replayable ingest kind on X's queue that a restart does not resume", () => { + const meta = getJobKind("x-run"); + assert.ok(meta, "registered"); + assert.equal(jobKindLabel("x-run"), "X run"); + assert.equal(meta.queueKeyStrategy, "platform"); + assert.equal(kindIsNetwork("x-run"), true); + assert.equal(isDrainableKind("x-run"), true); + assert.equal(meta.replayable, true); + assert.equal(isIngestKind("x-run"), true); + assert.equal(meta.resumeOnBoot, undefined); +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -654,6 +654,25 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, resumeOnBoot: true, }, + // THE X RUN (lane x-console, controller/xRun.ts): fetch-posts for several X + // posts channels IN SEQUENCE, as one job on X's queue (`platform:twitter`), + // X's gap between two channels, at most 200 posts each, and the network + // guard asked again before EACH channel — a stale jar or a raised X alert + // stops the run and defers the rest until the next refresh (it never + // refreshes the jar itself). Network (it asks X); drainable (it stops + // between channels); replayable (its spec names the run, whose state file + // holds the list: a Retry is a Resume). NOT resumed on boot: an interrupted + // run ends deferred — a restart may come hours later, on a stale jar, and an + // X sequence that starts by itself on boot is the unattended pattern the + // fresh-jar rule exists to stop. Resume is the operator's click. + "x-run": { + kind: "x-run", + label: "X run", + drainable: true, + replayable: true, + queueKeyStrategy: "platform", + network: true, + }, // Forum thread pages the operator saved from a browser, imported into a // forum-thread channel (controller/importForumPages.ts). Offline — nothing is // fetched — but on the PLATFORM queue so it never writes the channel's posts @@ -1561,6 +1580,9 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ "persist-videos", "persist-kept", "fetch-posts", + // Fetch-posts over several X channels (it carries no channelSlug: each + // channel's report regeneration is its per-channel trace). + "x-run", "import-forum-pages", "import-post", // A page capture's records (release 37), and their re-derivation. diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -42,7 +42,10 @@ export type JobProgressMetric = | "files" // A Save Page Now batch (controller/savePageNowBatch.ts): URLs settled // (archived already, saved, failed) of the list. The runner sets `current`. - | "pages"; + | "pages" + // An X run's channels (controller/xRun.ts): one fetch-posts each, counted + // by the runner. + | "channels"; export type JobProgress = { metric: JobProgressMetric; diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx @@ -165,6 +165,7 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = { frames: "Frames", files: "Files", pages: "Pages", + channels: "Channels", }; // Per-metric glyph for the compact line ("↓ 5/10"). @@ -181,6 +182,7 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = { frames: "\u25a3 ", files: "\u266a ", pages: "\u2691 ", + channels: "\u2261 ", }; const METRIC_FILL: Record<JobProgressMetric, string> = { @@ -196,6 +198,7 @@ const METRIC_FILL: Record<JobProgressMetric, string> = { frames: "bg-info/60", files: "bg-info/60", pages: "bg-success/60", + channels: "bg-info/60", }; // One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left"