commit f2e4c7f7337b0068d37178b53363105ee02b6281
parent d3cc25ac83f401f99601641fcb8c3381a8bac33d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 15:53:27 -0500
Merge lane/x-console: the X run console on /review and the account activity timeline on a posts channel's page (redesign L9; replaces the hand-run X sequences of 8 and 9 Nov)
One x-run job on X's queue runs fetch-posts over picked channels in order (at most 200 posts each, X's gap
between them), checks the jar before every channel and stops when it is stale, the rest deferred until the next
refresh; it never refreshes cookies and never starts by itself (a boot closes a queued run; Resume is a click).
`pnpm ops x-run` / `get x-run`. A posts channel's page gains posts per day with long silences linked to the posts
on either side (a gap >= 48 h and >= 3x the median).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
30 files changed, 3043 insertions(+), 7 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -216,6 +216,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `fetch-chat` | fetch-chat fetches ONE video's live chat replay and nothing else: {"slug", "id"} — the chat-only yt-dlp pass (the channel's cookies, the platform's pace) on the platform's download queue, then live\_chat.cues.json. YouTube only: another platform answers "no chat fetcher for <platform>" (info, no job), as do a chat already here and fresh and a video never live. A pass that finds no replay ends done and says so. | `pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait` |
| `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/<id>/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` |
| `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` |
+| `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` |
### Usage, flags and environment
@@ -238,6 +239,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get saved-alternates [<slug>]
pnpm ops get services
pnpm ops get x-session [<slug>]
+ pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
@@ -311,6 +313,15 @@ get x-session [<slug>] is the X login an X job would use and whether one
channel whose own cookiesFromBrowser may decide the source. Nothing is
asked of X: a refresh is Refresh cookies / Connect X account on
/settings. Ask it before queueing fetch-posts or capture-posts on X.
+get x-run [<run id>] is the X run as /review's X run console shows it:
+ the latest run (or the one named) — each channel's status (queued,
+ running, done with its new posts, deferred, failed), "summary" ("N
+ done, M deferred until the next refresh"), live, interrupted (the editor
+ stopped mid-run: its unfinished channels read deferred), resumable — and
+ "candidates" (every X posts channel in the default order: focus, tier,
+ rank, slug), "jar" (its age, social.x.maxCookieAgeMinutes, staleAt:
+ when it passes the limit, and whether an X job would start now),
+ gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts
@@ -0,0 +1,392 @@
+// 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");
+});
+
+test("every stop path defers what has not run, and Resume takes it: cancel before a channel, cancel or drain in X's gap, a thrown error", async () => {
+ const resumable = async (id: string) => (await xr.readXRunView(paths, id))!.resumable;
+ const run = async (deps: import("./xRun").XRunDeps, signal = never(), drain = never()) => {
+ const plan = await xr.planXRun(paths, { channels: ["xa", "xb", "xc"] });
+ assert.ok(plan.ok);
+ let threw: Error | null = null;
+ const r = await xr
+ .runXRun({ paths, state: plan.state, deps, onLog: () => {}, signal, drain })
+ .catch((e: Error) => ((threw = e), null));
+ const disk = (await xr.readXRun(paths, plan.state.id))!;
+ return { id: plan.state.id, r, threw: threw as Error | null, disk };
+ };
+ const statuses = (d: import("./xRun").XRunState) => d.channels.map((c) => c.status);
+
+ // Cancelled before the first channel.
+ const pre = new AbortController();
+ pre.abort();
+ const a = await run(stubDeps({ calls: [] }), pre.signal);
+ assert.equal(a.disk.status, "cancelled");
+ assert.deepEqual(statuses(a.disk), ["deferred", "deferred", "deferred"]);
+ assert.equal(await resumable(a.id), 3);
+
+ // Cancelled while waiting X's gap after the first channel.
+ const b = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "aborted" });
+ assert.equal(b.disk.status, "cancelled");
+ assert.deepEqual(statuses(b.disk), ["done", "deferred", "deferred"]);
+ assert.equal(await resumable(b.id), 2);
+
+ // Drained while waiting X's gap.
+ const c = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "drained" });
+ assert.equal(c.disk.status, "drained");
+ assert.deepEqual(statuses(c.disk), ["done", "deferred", "deferred"]);
+
+ // The guard throws on the second channel: the run fails, nothing is lost.
+ let n = 0;
+ const d = await run({
+ ...stubDeps({ calls: [] }),
+ guard: async () => {
+ if (++n === 2) throw new Error("settings unreadable");
+ return { ok: true, notes: [] };
+ },
+ });
+ assert.equal(d.threw?.message, "settings unreadable");
+ assert.equal(d.disk.status, "failed");
+ assert.equal(d.disk.stopped, "settings unreadable");
+ assert.deepEqual(statuses(d.disk), ["done", "deferred", "deferred"]);
+ assert.equal(await resumable(d.id), 2);
+ const again = await xr.planXRun(paths, { resume: d.id });
+ assert.ok(again.ok);
+ assert.deepEqual(again.state.channels.map((ch) => ch.status), ["done", "queued", "queued"]);
+
+ // A file left with queued/running channels by a stopped run (a crash, an
+ // older build) still reads them as resumable.
+ const e = await xr.planXRun(paths, { channels: ["xa", "xb"] });
+ assert.ok(e.ok);
+ e.state.status = "cancelled";
+ e.state.channels[0].status = "running";
+ await xr.writeXRun(paths, e.state);
+ assert.equal(await resumable(e.state.id), 2);
+});
+
+test("two clicks at once queue one run: the second is refused while the first is being queued", async () => {
+ jar(0);
+ const gate: { open?: () => void } = {};
+ const opened = new Promise<void>((r) => (gate.open = r));
+ const deps = (jobId: string) => ({
+ ...xr.defaultXRunDeps(paths, jobId),
+ fetch: async () => {
+ await opened;
+ return { ok: true, written: 0 };
+ },
+ });
+ const [one, two] = await Promise.all([
+ xr.queueXRun({ paths, req: { channels: ["xa"] }, deps }),
+ xr.queueXRun({ paths, req: { channels: ["xb"] }, deps }),
+ ]);
+ const oks = [one, two].filter((r) => r.ok);
+ assert.equal(oks.length, 1);
+ const refused = [one, two].find((r) => !r.ok) as { error: string };
+ assert.match(refused.error, /one at a time/);
+ // And while the first runs, a third is refused by the registry check.
+ const three = await xr.queueXRun({ paths, req: { channels: ["xc"] }, deps });
+ assert.equal(three.ok, false);
+ assert.match((three as { error: string }).error, /already queued or running/);
+ gate.open!();
+ assert.equal((await (oks[0] as { done: Promise<{ status: string }> }).done).status, "done");
+});
+
+test("runs are pruned to the newest X_RUN_KEEP when a new one is made", async () => {
+ const before = await xr.listXRunIds(paths);
+ const removed = await xr.pruneXRuns(paths, 2);
+ assert.equal(removed.length, Math.max(0, before.length - 2));
+ assert.deepEqual(await xr.listXRunIds(paths), before.slice(0, 2));
+ assert.equal(xr.X_RUN_KEEP, 100);
+});
diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts
@@ -0,0 +1,834 @@
+// 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, rm } 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, xSessionReport, type XSessionReport } from "../jobs/networkGuard";
+import { noteQueueJobEnd, queueGapClock, queueGapFor, 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();
+}
+
+// The run files kept: the newest X_RUN_KEEP; older ones are removed when a
+// new run is made (a run's file is its console row and its Resume, nothing
+// else reads it).
+export const X_RUN_KEEP = 100;
+
+export async function pruneXRuns(paths: Pick<Paths, "jobsDir">, keep = X_RUN_KEEP): Promise<string[]> {
+ const old = (await listXRunIds(paths)).slice(keep);
+ for (const id of old) await rm(xRunPath(paths, id), { force: true }).catch(() => {});
+ return old;
+}
+
+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");
+ // A run that is not live has nothing running: an unfinished channel in a
+ // file written before every stop path deferred (or by a crash) reads as
+ // deferred, so Resume counts it.
+ const channels = !live
+ ? 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);
+ await pruneXRuns(paths);
+ 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 });
+ // EVERY STOP PATH ENDS HERE: what has not run (queued, and one cut while
+ // running) is deferred — a Resume takes exactly those — and the run says why.
+ const stop = (status: XRunStatus, reason: string) => {
+ for (const c of state.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred";
+ state.status = status;
+ state.stopped = reason;
+ };
+ let stoppedEarly = false;
+ let first = true;
+ try {
+ for (const ch of todo) {
+ if (signal.aborted) {
+ stop("cancelled", "Cancelled.");
+ stoppedEarly = true;
+ break;
+ }
+ if (drain.aborted) {
+ stop("drained", "Drained: the channels not yet fetched stay for a Resume.");
+ 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();
+ save().catch((err) => onLog(`[warn] could not save the run's wait: ${(err as Error).message}`));
+ },
+ });
+ delete state.waitingUntil;
+ if (waited === "aborted") {
+ stop("cancelled", "Cancelled while waiting for X's gap.");
+ stoppedEarly = true;
+ break;
+ }
+ if (waited === "drained") {
+ stop("drained", "Drained while waiting for X's gap: the channels not yet fetched stay for a Resume.");
+ 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}`);
+ stop("deferred", 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.
+ if (r.written > 0) ch.posts = r.written;
+ stop("cancelled", "Cancelled.");
+ 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) {
+ stop("drained", "Drained: the channels not yet fetched stay for a Resume.");
+ stoppedEarly = true;
+ break;
+ }
+ }
+ } catch (err) {
+ // The run itself broke (a state write, the guard): nothing unfinished is
+ // lost — it is deferred, and Resume takes it.
+ stop("failed", (err as Error).message);
+ delete state.waitingUntil;
+ await save().catch(() => {});
+ throw err;
+ }
+ 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 }> {
+ // ONE AT A TIME, ALSO BETWEEN THE CHECK AND THE ENQUEUE: planXRun asks the
+ // registry for a live x-run, but awaits file I/O before the job exists, so
+ // two clicks on Resume could both pass it. A process-wide flag (globalThis:
+ // a server action and a route are separate module graphs) closes the gap;
+ // once runManagedFunction returns, the job is in the registry.
+ if (globalThis.__yttXRunStarting__) {
+ return { ok: false, error: "An X run is being queued right now: one at a time." };
+ }
+ globalThis.__yttXRunStarting__ = true;
+ try {
+ return await queueXRunNow(opts);
+ } finally {
+ globalThis.__yttXRunStarting__ = false;
+ }
+}
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttXRunStarting__: boolean | undefined;
+}
+
+async function queueXRunNow(opts: Parameters<typeof queueXRun>[0]): 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) {
+ // runXRun has deferred the unfinished channels; make sure the file
+ // says so even when the break came before it began.
+ for (const c of fresh.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred";
+ 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 };
+}
+
+// ── the console's payload (the /review console, `pnpm ops get x-run`) ──────
+
+export type XRunJar = Pick<
+ XSessionReport,
+ "source" | "cookiesUpdatedAt" | "ageMinutes" | "maxAgeMinutes" | "ageChecked" | "allowed" | "reason" | "alert"
+> & {
+ // When the jar passes social.x.maxCookieAgeMinutes (ISO), when the age is
+ // checked and a jar exists: the console counts down to it.
+ staleAt: string | null;
+};
+
+export type XRunConsole = {
+ run: XRunView | null;
+ candidates: XRunCandidate[];
+ jar: XRunJar;
+ // X's queue gap between two channels (pacing.jobGapSeconds.twitter), seconds.
+ gapSeconds: number;
+ maxPosts: number;
+};
+
+export function xRunJar(report: XSessionReport): XRunJar {
+ const staleAt =
+ report.ageChecked && report.cookiesUpdatedAt
+ ? new Date(Date.parse(report.cookiesUpdatedAt) + report.maxAgeMinutes * 60_000).toISOString()
+ : null;
+ return {
+ source: report.source,
+ cookiesUpdatedAt: report.cookiesUpdatedAt,
+ ageMinutes: report.ageMinutes,
+ maxAgeMinutes: report.maxAgeMinutes,
+ ageChecked: report.ageChecked,
+ allowed: report.allowed,
+ reason: report.reason,
+ alert: report.alert,
+ staleAt,
+ };
+}
+
+// Nothing here asks X or writes: the jar is read from disk (xSessionReport),
+// the runs and the channels from theirs.
+export async function xRunConsole(paths: Paths, runId?: string): Promise<XRunConsole> {
+ const [run, candidates, report] = await Promise.all([
+ readXRunView(paths, runId),
+ listXRunCandidates(paths),
+ xSessionReport({ paths }),
+ ]);
+ let gapSeconds = 0;
+ try {
+ gapSeconds = queueGapFor(getSettings().pacing, "twitter").seconds;
+ } catch {
+ gapSeconds = queueGapFor(undefined, "twitter").seconds;
+ }
+ return { run, candidates, jar: xRunJar(report), gapSeconds, maxPosts: X_RUN_MAX_POSTS };
+}
diff --git a/common/jobs/bootQueuedJobs.test.ts b/common/jobs/bootQueuedJobs.test.ts
@@ -9,6 +9,7 @@ import type { JobSpec } from "./jobSpec";
import {
INTERRUPTED_REASON,
PUBLISH_RESTART_REASON,
+ PERSON_RESTART_REASON,
STORAGE_PASS_WAIT_MS,
processIsAlive,
settleAfterStoragePass,
@@ -595,3 +596,23 @@ test("a queued publish stage is cancelled as `publish`, never re-queued, even wi
await rm(f.root, { recursive: true, force: true });
}
});
+
+// Lane x-console: an X run left QUEUED by a restart is never re-queued — an X
+// sequence starts only on a person's click (its run reads interrupted, and
+// Resume on /review is that click) — even with a fresh, replayable spec.
+test("a queued x-run is cancelled as `person`, never re-queued", async () => {
+ const run: JobSpec = { kind: "x-run", slug: "_x-run", params: { run: "xr-01JZZZZZZZZZZZZZZZZZZZZZZZ" } };
+ const f = await fixture([
+ { id: "X1", kind: "x-run", queueKey: "platform:twitter", spec: run },
+ { id: "F1", spec: SPEC },
+ ]);
+ try {
+ const rq = recordingRequeue();
+ const res = await settleQueuedJobMetas({ paths: f.paths, requeue: rq.fn, bootedAt: BOOT, log: () => {} });
+ assert.deepEqual(rq.calls, [SPEC]);
+ assert.deepEqual(res.cancelled.map((c) => [c.id, c.category]), [["X1", "person"]]);
+ assert.equal((await f.read("X1")).cancelReason, PERSON_RESTART_REASON);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/jobs/bootQueuedJobs.ts b/common/jobs/bootQueuedJobs.ts
@@ -4,7 +4,7 @@ import { writeFileAtomic } from "../lib/jsonFile-server";
import type { Paths } from "../lib/paths";
import { metaPath, readJobMeta, type JobMeta } from "./jobMeta";
import type { JobSpec } from "./jobSpec";
-import { isPublishStageJobKind } from "./jobKinds";
+import { getJobKind, isPublishStageJobKind } from "./jobKinds";
// THE BOOT PASS OVER STALE `queued` METAS (release 9, B4b).
//
@@ -27,7 +27,8 @@ import { isPublishStageJobKind } from "./jobKinds";
// paced; nor is a publish stage (release 18, `publish-*`): the publish
// lane and Publish now re-derive stages from the stamps on disk, and a
// stage re-queued with its run's preconditions would wait on a run that
-// is gone;
+// is gone; nor is a kind that starts only on a person's click
+// (`startedByPerson`: the X run);
// 3. a meta queued more than REQUEUE_MAX_AGE_MS before this boot is stale;
// 4. a meta with no replay spec cannot be re-queued;
// 5. of what is left, only the NEWEST meta per kind + channel + params is
@@ -55,7 +56,7 @@ export type RequeueFn = (
) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
export type CancelCategory =
- "idle" | "sync" | "publish" | "stale" | "no-spec" | "superseded" | "refused";
+ "idle" | "sync" | "publish" | "person" | "stale" | "no-spec" | "superseded" | "refused";
export type BootQueuedResult = {
requeued: { id: string; newId: string }[];
@@ -65,6 +66,8 @@ export type BootQueuedResult = {
export const RESTART_REASON = "server restarted before it ran";
export const PUBLISH_RESTART_REASON =
"server restarted; the publish lane re-derives stages from on-disk state";
+export const PERSON_RESTART_REASON =
+ "server restarted; this kind starts only on a person's click (an X run: Resume it on /review)";
export const REQUEUE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
// Key a spec by what it would DO: kind + channel + bucket + params, with the
@@ -294,6 +297,9 @@ export async function settleQueuedJobMetas(
);
} else if (isPublishStageJobKind(meta.kind)) {
await cancel(meta, "publish", PUBLISH_RESTART_REASON);
+ } else if (getJobKind(meta.kind)?.startedByPerson) {
+ // An X run starts only on a person's click, never by a boot.
+ await cancel(meta, "person", PERSON_RESTART_REASON);
} else if (
typeof meta.queuedAt !== "number" ||
opts.bootedAt - meta.queuedAt > maxAgeMs
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,20 @@ 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);
+ // A restart never re-queues one left queued (jobs/bootQueuedJobs.ts).
+ assert.equal(meta.startedByPerson, true);
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -96,6 +96,13 @@ export type JobKindMeta = {
// interrupted twice in a row, and is off with `jobs.resumeInterruptedOnBoot`
// or on an idle boot.
resumeOnBoot?: boolean;
+ // Whether a job of this kind starts ONLY on a person's click: one left
+ // QUEUED by a restart is closed, never re-queued by the boot pass
+ // (jobs/bootQueuedJobs.ts), whatever its spec says. The X run (operator: an
+ // X sequence starts only when a person says so) — its run file then reads
+ // as interrupted, and Resume on /review is the person's click. Absent
+ // means false.
+ startedByPerson?: boolean;
};
// One entry per kind known to the system. `label` is included only where the
@@ -654,6 +661,26 @@ 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,
+ startedByPerson: 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 +1588,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/common/lib/accountActivity.test.ts b/common/lib/accountActivity.test.ts
@@ -0,0 +1,131 @@
+// Account activity (lane x-console): posts per day over the archive's range,
+// and long silences — ≥ 3× the median gap AND ≥ 48 h — each with the post
+// before and after.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/accountActivity.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { accountActivity, median, medianText, spanHours } from "./accountActivity";
+
+const post = (id: string, createdAt: string, author = "acct", text = `post ${id}`) => ({
+ id,
+ createdAt,
+ url: `https://x.com/${author}/status/${id}`,
+ text,
+ author,
+});
+
+// A busy account (a post every 15 min on 3–4 Nov), three days of nothing,
+// then busy again on 8 Nov — the shape of Mr Obvious's 5–8 Nov 2026 gap.
+function busyWithGap() {
+ const out = [];
+ let n = 0;
+ for (const day of ["2026-11-03", "2026-11-04"]) {
+ for (let m = 0; m < 8 * 60; m += 15) {
+ const h = String(10 + Math.floor(m / 60)).padStart(2, "0");
+ const mm = String(m % 60).padStart(2, "0");
+ out.push(post(String(++n), `${day}T${h}:${mm}:00.000Z`));
+ }
+ }
+ for (let m = 0; m < 4 * 60; m += 15) {
+ const h = String(19 + Math.floor(m / 60)).padStart(2, "0");
+ out.push(post(String(++n), `2026-11-08T${h}:${String(m % 60).padStart(2, "0")}:00.000Z`));
+ }
+ return out;
+}
+
+test("a busy account's three-day gap is one silence, with the posts on either side; nights are not", () => {
+ const a = accountActivity(busyWithGap())!;
+ assert.equal(a.medianGapMinutes, 15);
+ // 3 × 15 min is far below 48 h: the 48 h floor decides.
+ assert.equal(a.thresholdHours, 48);
+ assert.equal(a.silences.length, 1);
+ const s = a.silences[0];
+ assert.equal(s.before.createdAt, "2026-11-04T17:45:00.000Z");
+ assert.equal(s.after.createdAt, "2026-11-08T19:00:00.000Z");
+ assert.equal(s.before.url, `https://x.com/acct/status/${s.before.id}`);
+ assert.equal(spanHours(s.hours), "4 d 1 h");
+ // The overnight gap 3 → 4 Nov (≈ 16 h) is not a silence.
+ // Days: 3 Nov .. 8 Nov, empty days included.
+ assert.deepEqual(
+ a.days.map((d) => [d.day, d.count]),
+ [["2026-11-03", 32], ["2026-11-04", 32], ["2026-11-05", 0], ["2026-11-06", 0], ["2026-11-07", 0], ["2026-11-08", 16]],
+ );
+ assert.equal(a.maxPerDay, 32);
+});
+
+test("a sparse account: 3× its median gap decides, so its usual week is not a silence", () => {
+ // Every 4 days, then a 20-day gap, then every 4 days again.
+ const days = ["2026-01-01", "2026-01-05", "2026-01-09", "2026-01-13", "2026-02-02", "2026-02-06", "2026-02-10"];
+ const a = accountActivity(days.map((d, i) => post(String(i), `${d}T12:00:00.000Z`)))!;
+ assert.equal(a.medianGapMinutes, 4 * 24 * 60);
+ assert.equal(a.thresholdHours, 12 * 24);
+ assert.equal(a.silences.length, 1);
+ assert.equal(a.silences[0].before.createdAt, "2026-01-13T12:00:00.000Z");
+ assert.equal(a.silences[0].ratio, 5);
+});
+
+test("silences are newest first; a trailing silence runs to the last fetch", () => {
+ const posts = [
+ post("1", "2026-10-01T00:00:00Z"),
+ post("2", "2026-10-01T00:10:00Z"),
+ post("3", "2026-10-05T00:00:00Z"),
+ post("4", "2026-10-05T00:10:00Z"),
+ post("5", "2026-10-05T00:20:00Z"),
+ post("6", "2026-10-10T00:00:00Z"),
+ post("7", "2026-10-10T00:10:00Z"),
+ ];
+ const a = accountActivity(posts, { asOf: "2026-10-14T00:10:00.000Z" })!;
+ assert.deepEqual(a.silences.map((s) => [s.before.id, s.after.id]), [["5", "6"], ["2", "3"]]);
+ assert.equal(a.trailing?.since.id, "7");
+ assert.equal(spanHours(a.trailing!.hours), "4 d");
+ assert.equal(accountActivity(posts, { asOf: "2026-10-11T00:00:00.000Z" })!.trailing, null);
+});
+
+test("only the account's own posts count when any carry its handle; none, and every post counts", () => {
+ const posts = [
+ post("1", "2026-10-01T00:00:00Z", "Acct"),
+ post("2", "2026-10-02T00:00:00Z", "someone_else"),
+ post("3", "2026-10-03T00:00:00Z", "acct"),
+ ];
+ const own = accountActivity(posts, { author: "@acct" })!;
+ assert.equal(own.posts, 2);
+ assert.equal(own.author, "acct");
+ const all = accountActivity(posts, { author: "nobody" })!;
+ assert.equal(all.posts, 3);
+ assert.equal(all.author, null);
+});
+
+test("fewer than two datable posts: nothing to measure", () => {
+ assert.equal(accountActivity([]), null);
+ assert.equal(accountActivity([post("1", "2026-10-01T00:00:00Z"), post("2", "not a date")]), null);
+});
+
+test("the words", () => {
+ assert.equal(median([3, 1, 2]), 2);
+ assert.equal(median([4, 1, 2, 3]), 2.5);
+ assert.equal(spanHours(0.5), "30 min");
+ assert.equal(spanHours(47.6), "48 h");
+ assert.equal(spanHours(48), "2 d");
+ assert.equal(spanHours(4 * 24 + 8.2), "4 d 8 h");
+ assert.equal(spanHours(2 * 24 + 23.8), "3 d");
+ assert.equal(medianText(13), "13 min");
+ assert.equal(medianText(150), "2.5 h");
+});
+
+test("a bogus date is left out: before 2006 or more than a day ahead never stretches the strip", () => {
+ const now = Date.parse("2026-11-09T12:00:00Z");
+ const a = accountActivity(
+ [
+ post("0", "1970-01-01T00:00:00Z"),
+ post("1", "2026-11-01T00:00:00Z"),
+ post("2", "2026-11-02T00:00:00Z"),
+ post("3", "9999-12-31T00:00:00Z"),
+ ],
+ { now },
+ )!;
+ assert.equal(a.posts, 2);
+ assert.equal(a.days.length, 2);
+ assert.equal(accountActivity([post("0", "1970-01-01T00:00:00Z"), post("3", "9999-12-31T00:00:00Z")], { now }), null);
+});
diff --git a/common/lib/accountActivity.ts b/common/lib/accountActivity.ts
@@ -0,0 +1,187 @@
+// AN ACCOUNT'S ACTIVITY, FROM ITS ARCHIVED POSTS (lane x-console): posts per
+// UTC day over the archive's range, and its LONG SILENCES — the gaps between
+// two consecutive archived posts that are long for THIS account.
+//
+// A silence is a gap of at least SILENCE_MEDIAN_FACTOR (3) times the
+// account's median gap between consecutive posts AND at least
+// SILENCE_MIN_HOURS (48 h). Either rule alone is wrong: a prolific account's
+// median is minutes, so "3× the median" alone marks every night's sleep; a
+// once-a-week account's normal week would pass "48 h" alone. Together, a busy
+// account's silence is anything over two days, and a sparse one's is three of
+// its usual gaps. Mr Obvious's 5–8 Nov 2026 gap (the real-data case) is the
+// first kind: a median of minutes, and three days of nothing.
+//
+// IT IS A SILENCE IN THE ARCHIVE, not necessarily on the account: a fetch that
+// did not reach a stretch (an older walk not yet run below it, a capped run)
+// shows the same hole. The panel says "no archived post", not "the account was
+// silent".
+//
+// Pure and client-safe: the channel page reads the posts (lib/posts-server.ts)
+// and hands this the four fields it needs.
+
+export const SILENCE_MEDIAN_FACTOR = 3;
+export const SILENCE_MIN_HOURS = 48;
+// A post dated outside 2006-01-01 (X's first year) … a day from now is a
+// bogus date, not activity: one such date would stretch the strip to millions
+// of days. It is left out.
+export const ACTIVITY_EARLIEST = Date.parse("2006-01-01T00:00:00Z");
+
+export type ActivityPost = {
+ id: string;
+ createdAt: string;
+ url: string;
+ text?: string;
+ // The post's author's handle.
+ author?: string;
+};
+
+export type ActivityEnd = {
+ id: string;
+ createdAt: string;
+ url: string;
+ // The post's first line, short (a tooltip).
+ snippet: string;
+};
+
+export type ActivitySilence = {
+ before: ActivityEnd;
+ after: ActivityEnd;
+ hours: number;
+ // The gap over the median gap.
+ ratio: number;
+};
+
+export type ActivityDay = { day: string; count: number };
+
+export type AccountActivity = {
+ posts: number;
+ // The account counted, when only its own posts were (a with-replies
+ // timeline also archives the posts it answers, by others).
+ author: string | null;
+ firstAt: string;
+ lastAt: string;
+ // Every UTC day from the first post's to the last's, empty days included.
+ days: ActivityDay[];
+ maxPerDay: number;
+ medianGapMinutes: number;
+ // max(SILENCE_MIN_HOURS, SILENCE_MEDIAN_FACTOR × the median gap), hours.
+ thresholdHours: number;
+ // Newest first.
+ silences: ActivitySilence[];
+ // No archived post since the last one for at least the threshold, as of
+ // `asOf` (the last fetch): open-ended, so it has no post after it.
+ trailing: { since: ActivityEnd; hours: number; asOf: string } | null;
+};
+
+const HOUR = 3_600_000;
+const DAY = 24 * HOUR;
+
+function snippet(text: string | undefined): string {
+ const first = (text ?? "").split("\n").find((l) => l.trim()) ?? "";
+ const t = first.trim();
+ return t.length > 90 ? `${t.slice(0, 89)}…` : t;
+}
+
+function end(p: ActivityPost): ActivityEnd {
+ return { id: p.id, createdAt: p.createdAt, url: p.url, snippet: snippet(p.text) };
+}
+
+export function median(values: readonly number[]): number {
+ if (values.length === 0) return 0;
+ const s = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(s.length / 2);
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
+}
+
+function utcDay(ms: number): string {
+ return new Date(ms).toISOString().slice(0, 10);
+}
+
+// null when there are fewer than two datable posts (no gap to measure).
+//
+// `author` (the channel's handle) counts only the account's own posts when
+// any carry it — a with-replies timeline archives the posts it answers too,
+// and another account's post is not this one's activity. No post by it (an X
+// search channel's many accounts, a forum thread): every post counts.
+export function accountActivity(
+ input: readonly ActivityPost[],
+ opts: { asOf?: string; minHours?: number; factor?: number; author?: string; now?: number } = {},
+): AccountActivity | null {
+ const minHours = opts.minHours ?? SILENCE_MIN_HOURS;
+ const factor = opts.factor ?? SILENCE_MEDIAN_FACTOR;
+ const who = opts.author?.replace(/^@/, "").toLowerCase();
+ const own = who ? input.filter((p) => p.author?.replace(/^@/, "").toLowerCase() === who) : [];
+ const author = own.length > 0 ? opts.author!.replace(/^@/, "") : null;
+ const latest = (opts.now ?? Date.now()) + DAY;
+ const posts = (own.length > 0 ? own : input)
+ .map((p) => ({ p, t: Date.parse(p.createdAt) }))
+ .filter((x) => Number.isFinite(x.t) && x.t >= ACTIVITY_EARLIEST && x.t <= latest)
+ .sort((a, b) => a.t - b.t || a.p.id.localeCompare(b.p.id));
+ if (posts.length < 2) return null;
+ const gaps: number[] = [];
+ for (let i = 1; i < posts.length; i++) gaps.push(posts[i].t - posts[i - 1].t);
+ const med = median(gaps);
+ const thresholdMs = Math.max(minHours * HOUR, factor * med);
+ const silences: ActivitySilence[] = [];
+ for (let i = 1; i < posts.length; i++) {
+ const gap = gaps[i - 1];
+ if (gap < thresholdMs) continue;
+ silences.push({
+ before: end(posts[i - 1].p),
+ after: end(posts[i].p),
+ hours: gap / HOUR,
+ ratio: med > 0 ? gap / med : Infinity,
+ });
+ }
+ silences.reverse();
+ // Days, first to last, zeros included.
+ const counts = new Map<string, number>();
+ for (const { t } of posts) {
+ const d = utcDay(t);
+ counts.set(d, (counts.get(d) ?? 0) + 1);
+ }
+ const first = posts[0].t;
+ const last = posts[posts.length - 1].t;
+ const days: ActivityDay[] = [];
+ let maxPerDay = 0;
+ for (let t = Date.parse(`${utcDay(first)}T00:00:00Z`); t <= last; t += DAY) {
+ const day = utcDay(t);
+ const count = counts.get(day) ?? 0;
+ if (count > maxPerDay) maxPerDay = count;
+ days.push({ day, count });
+ }
+ let trailing: AccountActivity["trailing"] = null;
+ const asOf = opts.asOf ? Date.parse(opts.asOf) : NaN;
+ if (Number.isFinite(asOf) && asOf - last >= thresholdMs) {
+ trailing = { since: end(posts[posts.length - 1].p), hours: (asOf - last) / HOUR, asOf: opts.asOf! };
+ }
+ return {
+ posts: posts.length,
+ author,
+ firstAt: posts[0].p.createdAt,
+ lastAt: posts[posts.length - 1].p.createdAt,
+ days,
+ maxPerDay,
+ medianGapMinutes: med / 60_000,
+ thresholdHours: thresholdMs / HOUR,
+ silences,
+ trailing,
+ };
+}
+
+// "2 d 19 h", "52 h" → "2 d 4 h", "50 min".
+export function spanHours(hours: number): string {
+ if (hours < 1) return `${Math.round(hours * 60)} min`;
+ if (hours < 48) return `${Math.round(hours)} h`;
+ const d = Math.floor(hours / 24);
+ const h = Math.round(hours - d * 24);
+ return h === 24 ? `${d + 1} d` : h > 0 ? `${d} d ${h} h` : `${d} d`;
+}
+
+// "22 min", "3.5 h", "2 d".
+export function medianText(minutes: number): string {
+ if (minutes < 90) return `${Math.max(0, Math.round(minutes))} min`;
+ const h = minutes / 60;
+ if (h < 48) return `${Math.round(h * 10) / 10} h`;
+ return spanHours(h);
+}
diff --git a/common/lib/postTimes-server.test.ts b/common/lib/postTimes-server.test.ts
@@ -0,0 +1,61 @@
+// The account activity's cheap read (lane x-console): each shard's light rows,
+// cached by mtime and size, deduped by id, a missing permalink derived.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/postTimes-server.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { clearPostTimesCache, readChannelActivity, readPostTimes } from "./postTimes-server";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "post-times-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const channel = path.join(ROOT, "demo-x");
+mkdirSync(path.join(channel, "posts"), { recursive: true });
+const line = (id: string, createdAt: string, extra: Record<string, unknown> = {}) =>
+ JSON.stringify({ id, channelSlug: "demo-x", createdAt, author: "demo", platform: "twitter", text: `first line ${id}\nsecond`, isReply: false, isRepost: false, links: [], url: `https://x.com/demo/status/${id}`, ...extra }) + "\n";
+
+test("light rows from every shard, deduped by id, a missing url derived, a bad line skipped", async () => {
+ clearPostTimesCache();
+ writeFileSync(path.join(channel, "posts", "2026-10.jsonl"), line("1", "2026-10-01T00:00:00Z") + "{not json\n" + line("2", "2026-10-02T00:00:00Z"));
+ writeFileSync(path.join(channel, "posts", "2026-11.jsonl"), line("2", "2026-10-02T00:00:00Z") + line("3", "2026-11-01T00:00:00Z", { url: undefined }));
+ const rows = await readPostTimes(channel);
+ assert.deepEqual(
+ rows.map((r) => [r.id, r.createdAt, r.author, r.url, r.text]).sort(),
+ [
+ ["1", "2026-10-01T00:00:00Z", "demo", "https://x.com/demo/status/1", "first line 1"],
+ ["2", "2026-10-02T00:00:00Z", "demo", "https://x.com/demo/status/2", "first line 2"],
+ ["3", "2026-11-01T00:00:00Z", "demo", "https://x.com/demo/status/3", "first line 3"],
+ ],
+ );
+});
+
+test("a shard a fetch appended to is re-read; the others come from the cache", async () => {
+ await readPostTimes(channel);
+ const oct = path.join(channel, "posts", "2026-10.jsonl");
+ const nov = path.join(channel, "posts", "2026-11.jsonl");
+ const octRows = globalThis.__yttPostTimes__!.get(oct)!.rows;
+ const novRows = globalThis.__yttPostTimes__!.get(nov)!.rows;
+ appendFileSync(nov, line("4", "2026-11-02T00:00:00Z"));
+ const rows = await readPostTimes(channel);
+ assert.deepEqual(rows.map((r) => r.id).sort(), ["1", "2", "3", "4"]);
+ // October was not re-read (the same rows); November was.
+ assert.equal(globalThis.__yttPostTimes__!.get(oct)!.rows, octRows);
+ assert.notEqual(globalThis.__yttPostTimes__!.get(nov)!.rows, novRows);
+ // No shards: nothing.
+ assert.deepEqual(await readPostTimes(path.join(ROOT, "nope")), []);
+});
+
+test("the activity is memoised by the shards' signature: the same object until a shard changes", async () => {
+ const one = await readChannelActivity(channel, { author: "demo" });
+ assert.ok(one);
+ assert.equal(await readChannelActivity(channel, { author: "demo" }), one);
+ // Other options are another key.
+ assert.notEqual(await readChannelActivity(channel, { author: "demo", asOf: "2026-12-01T00:00:00Z" }), one);
+ appendFileSync(path.join(channel, "posts", "2026-11.jsonl"), line("5", "2026-11-03T00:00:00Z"));
+ const two = await readChannelActivity(channel, { author: "demo" });
+ assert.notEqual(two, one);
+ assert.equal(two!.posts, one!.posts + 1);
+});
diff --git a/common/lib/postTimes-server.ts b/common/lib/postTimes-server.ts
@@ -0,0 +1,148 @@
+// A POSTS CHANNEL'S TIMES, CHEAPLY (lane x-console): what the account
+// activity panel needs of every archived post — id, createdAt, author,
+// permalink and a short first line — without materialising whole posts.
+//
+// readAllPosts parses, validates and sorts every post on every call: ~1 s for
+// the largest posts channel (kf-quartering-thread, 66 MB, 37,802 posts) on
+// every render of its page. This keeps each SHARD's light rows in memory,
+// keyed by the shard's path and re-read only when its mtime or size changes
+// (a fetch appends to the newest shard; the rest never change), so a render
+// re-reads at most the shard a fetch just wrote.
+//
+// Dedupe by id across shards, as readAllPosts does (an interrupted archive
+// write can leave one post in two shards). Unordered: accountActivity sorts.
+
+import { readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { channelPostsDir, listPostShards } from "./posts-server";
+import { parsePost } from "./posts";
+import { accountActivity, type AccountActivity, type ActivityPost } from "./accountActivity";
+
+type ShardRows = { mtimeMs: number; size: number; rows: ActivityPost[] };
+
+// Shards kept, process-wide; the oldest entry goes first past this.
+const MAX_SHARDS = 4000;
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttPostTimes__: Map<string, ShardRows> | undefined;
+}
+
+function cache(): Map<string, ShardRows> {
+ return (globalThis.__yttPostTimes__ ??= new Map());
+}
+
+export function clearPostTimesCache(): void {
+ globalThis.__yttPostTimes__?.clear();
+ globalThis.__yttActivityMemo__?.clear();
+}
+
+function snippet(text: unknown): string | undefined {
+ if (typeof text !== "string") return undefined;
+ const first = text.split("\n", 8).find((l) => l.trim());
+ if (!first) return undefined;
+ const t = first.trim();
+ return t.length > 90 ? `${t.slice(0, 89)}…` : t;
+}
+
+function rowsOf(text: string, channelSlug: string): ActivityPost[] {
+ const rows: ActivityPost[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ let raw: Record<string, unknown>;
+ try {
+ raw = JSON.parse(line) as Record<string, unknown>;
+ } catch {
+ continue;
+ }
+ if (!raw || typeof raw !== "object") continue;
+ const { id, createdAt } = raw;
+ if (typeof id !== "string" || !id || typeof createdAt !== "string" || !createdAt) continue;
+ let url = typeof raw.url === "string" ? raw.url : "";
+ // A record stored without its permalink: the full parse derives it (a
+ // forum post's needs its forum's origin).
+ if (!url) url = parsePost({ ...raw, channelSlug })?.url ?? "";
+ rows.push({
+ id,
+ createdAt,
+ url,
+ ...(typeof raw.author === "string" ? { author: raw.author } : {}),
+ ...(snippet(raw.text) ? { text: snippet(raw.text) } : {}),
+ });
+ }
+ return rows;
+}
+
+// The shards' identity: when no shard changed, nothing derived from them did.
+async function shardSignature(channelRoot: string): Promise<string> {
+ const dir = channelPostsDir(channelRoot);
+ const parts: string[] = [];
+ for (const shard of await listPostShards(channelRoot)) {
+ try {
+ const st = await stat(path.join(dir, `${shard}.jsonl`));
+ parts.push(`${shard}:${st.mtimeMs}:${st.size}`);
+ } catch {
+ // gone between the listing and the stat
+ }
+ }
+ return parts.join("|");
+}
+
+type ActivityMemo = { key: string; activity: AccountActivity | null };
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttActivityMemo__: Map<string, ActivityMemo> | undefined;
+}
+
+// THE PANEL'S DATA: accountActivity over readPostTimes, memoised per channel
+// by the shards' signature and the options — an unchanged channel costs one
+// stat per shard (sorting 37,802 posts' dates is ~100 ms; a render should not
+// pay it twice). A day's turn is part of the key too, so a bogus date's
+// "a day from now" bound moves.
+export async function readChannelActivity(
+ channelRoot: string,
+ opts: { asOf?: string; author?: string } = {},
+): Promise<AccountActivity | null> {
+ const memo = (globalThis.__yttActivityMemo__ ??= new Map());
+ const key = `${await shardSignature(channelRoot)}#${opts.asOf ?? ""}#${opts.author ?? ""}#${new Date().toISOString().slice(0, 10)}`;
+ const hit = memo.get(channelRoot);
+ if (hit && hit.key === key) return hit.activity;
+ const activity = accountActivity(await readPostTimes(channelRoot), opts);
+ memo.delete(channelRoot);
+ memo.set(channelRoot, { key, activity });
+ while (memo.size > 500) memo.delete(memo.keys().next().value!);
+ return activity;
+}
+
+export async function readPostTimes(channelRoot: string): Promise<ActivityPost[]> {
+ const shards = await listPostShards(channelRoot);
+ const dir = channelPostsDir(channelRoot);
+ const channelSlug = path.basename(channelRoot);
+ const c = cache();
+ const byId = new Map<string, ActivityPost>();
+ for (const shard of shards) {
+ const file = path.join(dir, `${shard}.jsonl`);
+ let st;
+ try {
+ st = await stat(file);
+ } catch {
+ continue;
+ }
+ let hit = c.get(file);
+ if (!hit || hit.mtimeMs !== st.mtimeMs || hit.size !== st.size) {
+ let text: string;
+ try {
+ text = await readFile(file, "utf8");
+ } catch {
+ continue;
+ }
+ hit = { mtimeMs: st.mtimeMs, size: st.size, rows: rowsOf(text, channelSlug) };
+ c.delete(file);
+ c.set(file, hit);
+ while (c.size > MAX_SHARDS) c.delete(c.keys().next().value!);
+ }
+ for (const row of hit.rows) byId.set(row.id, row);
+ }
+ return [...byId.values()];
+}
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -27,6 +27,9 @@ export const VIEW_NAMES = [
"widgetActionable",
"cleanable",
"cookieAlerts",
+ // /review's X run console (common/controller/xRun.ts xRunConsole): the
+ // latest run, the X posts channels, the jar's age. Reads disk only.
+ "xRun",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -54,4 +57,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
widgetActionable: "construct",
cleanable: "construct",
cookieAlerts: "construct",
+ xRun: "construct",
};
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **The X run console: several X channels' posts fetched as one job that stops when the cookies go stale.** On 8 and 9 Nov an agent ran X fetch-posts by hand, one channel after another, watching the cookie jar age and putting off the rest once it went stale. `/review`'s new **X run** section lists the X posts channels in priority order (focus, tier, rank; paused ones unticked), with a tick and up/down buttons for each, and **Start X run** queues ONE `x-run` job on X's queue. The job fetches each channel in turn (new posts only, at most 200 each), waits X's queue gap (`pacing.jobGapSeconds.twitter`) between two channels, and checks the cookie jar again before EACH one. Once the jar is past `social.x.maxCookieAgeMinutes`, or the X alert is up, the run stops and the rest are **deferred until the next refresh**. It never refreshes cookies itself. The console shows each channel's state (queued, running, done with its new posts, deferred, failed), "N done, M deferred until the next refresh", the jar's age counted down to the limit, and the wait before the next channel. **Resume** runs the deferred channels after the operator presses Refresh cookies on /settings. A Retry of the job, and "Re-run stopped jobs", do the same. A restart does not resume a run: an interrupted run ends deferred. `pnpm ops x-run {"channels": [...]}` / `{"resume": "<run id>"}` and `pnpm ops get x-run` do the same from a terminal.
+- **Account activity on a posts channel's page: posts per day, with the long silences marked.** A compact bar strip shows posts per UTC day over the archive's range. Long silences are shaded and listed: a gap of at least 3× the account's median gap AND 48 h, each linked to the post before it and the post after. An open-ended silence since the last post is listed too, when the last fetch came that long after it. Only the account's own posts count (a with-replies timeline also archives the posts it answers). The silence is the archive's ("no archived post"), and a stretch no fetch reached looks the same. Mr Obvious's 5–8 Nov gap reads 4 Nov 10:54 → 8 Nov 19:00 UTC on ObviousRises-x.
- **umtool: each character has a voice, auditioned on a page, the same in every project.** The operator wanted to "pick different voices for different characters, and in UI alone be able to try rendering different ones to compare … and try to maintain consistent voices for different repeating characters" -- tonight TheQuartering's reads were re-voiced by hand after scoring five voices against his real one. `/projects/<p>/voices` (from the Cut tab's Reads and voices) lists every character a project's reads use, the voice each reads in now and where it comes from (the cast, the project, the narrator's, the default), its reads in another voice, and its real voice. **Audition** reads one line (its own words here, a stock line, or typed) in 2-6 stock voices -- a job: the editor's tts, then each one's closeness to the real voice (speakers.json, TitaNet, local) -- played side by side at one loudness beside the real voice, a reference never a target. **Use for this project** or **Use everywhere** (the cast, `<reports>/.umtool/cast.json`), then the items to re-read, queued. A recording of an item can be made a character's read: kept, cleaned, converted to its stock voice. Every read -- a single post's and each piece of a thread read -- asks the same order (the read's own, the project's map, the cast, the narrator's, the default), and a cast voice of another engine is synthesized by it. `umtool cast ls|add|set|rm|undo|project|audition|use|reread`, `posts narrate … --recording`, and `umtool lint` warns when a cast character is read in another voice.
- **umtool: Play the cut draws a text card as the render does, and a counter can count her words as she said them.** Play showed a teaser -- the Leaflit video's X posts quoted on text cards -- as a grey placeholder, so the card's words and the count stepping on it could not be checked without a render (operator, 6 Nov: "play the cut needs to handle x posts"). Play now lays each card's own page, composed by the build's own code (`POST /api/report/chrome/teasers`), full frame and seeked on the cut clock, the deck over a card that counts. And the counter takes up to 12 series (8 before): past 8 its cells narrow into one row so the title keeps its column, and `deck.counter.labels: "as-written"` sets each cell's words in their own case in up to two lines instead of capitals cut to their last words -- "moderate conservative" no longer reads CONSERVATIVE (operator: "make groups with the literal spoken label e.g. 'moderate', 'moderate conservative', 'close to MAGA'").
- **Rumble clips play the words their quotes say: one clock per recording.** On 6 Nov seven Rumble clips of the weight video played other words than their quotes, c43 13.1 seconds early (the "310" clip), and one stream was right at 10 minutes and 13.6 seconds off at 38. A Rumble channel's transcript is made from a separate audio download, and its clips were cut from another file; the two do not keep the same time, and not by a constant. The operator: "stop trying to grab rumble individual clips and instead grab whole streams and clip after." **Whole, never seeked:** umtool's fetch (the bench's fetch more, `umtool fetch`, a build's fetch) asks for a Rumble clip through Fetch windows, which saves the stream once and cuts the clip from it; nothing falls back to a seek, and a failed save says why. **The right video:** a report cites a Rumble video by its embed id while the archive keeps it under its page's id; every fetch, save and render now finds the video under either (6 Nov: every such fetch went to a folder that did not exist, and one got a Rumble 403). **The time map:** before a clip is cut from a saved Rumble stream, the stream's audio is matched against the audio the transcript was made from, every 5 minutes and around each clip, and the map (`clock.json` beside the video, with how well it fits) moves every cut onto the transcript's time; clips cut before the map, or by a seek, are cut again. A stretch where the two files part (a dropped piece of the stream) is narrowed to a few seconds, and a clip on it is said to be uncertain. **The check:** `umtool quote-check <project>` has the editor transcribe what each clip will actually play and finds the quote in it: `moved` (heard seconds away), `not-found`, or `ok`; `umtool window <p> <clip> --align` puts the cut on the words as heard, `umtool check` blocks on a moved or missing quote, a take refuses one unless a person rules it (`--quote-ruled`), and `umtool prep --status` counts them. Needs a restart of the editor (umtool's half works at once).
diff --git a/editor/app/api/ops/x-run/route.test.ts b/editor/app/api/ops/x-run/route.test.ts
@@ -0,0 +1,111 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/x-run/route.test.ts"
+//
+// The X run's door: the body's shape, the refusals that come before any job,
+// a stale jar refusing a new run (its file kept, deferred, for a Resume), and
+// GET's console — the X posts channels in the default order and the jar's age.
+// Every case is answered from the disk alone: no job runs and nothing reaches X.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-run-route-"));
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await writeFile(
+ process.env.SETTINGS_FILE,
+ JSON.stringify({
+ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } },
+ channelPriority: { focus: { kind: "none" }, channels: { "low-x": { tier: "low" }, "top-x": { tier: "normal", rank: 1 } } },
+ }),
+);
+async function channel(slug: string, config: Record<string, unknown>) {
+ const dir = path.join(ROOT, "channels", slug);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", ...config }));
+}
+const x = (handle: string) => ({
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-gallery-dl",
+ socialHandle: handle,
+ url: `https://x.com/${handle}`,
+ name: `${handle} (X)`,
+});
+await channel("low-x", x("low"));
+await channel("mid-x", x("mid"));
+await channel("top-x", x("top"));
+await channel("bsky", { sourceKind: "social", platform: "bluesky", url: "https://bsky.app/profile/a.bsky.social" });
+// A jar 16 days old.
+const jarDir = path.join(ROOT, ".x-session");
+await mkdir(path.join(jarDir, "profile"), { recursive: true });
+await writeFile(path.join(jarDir, "cookies.txt"), "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n");
+const old = new Date(Date.now() - 16 * 24 * 60 * 60_000);
+await utimes(path.join(jarDir, "cookies.txt"), old, old);
+
+const { POST, GET } = await import("./route");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const AUTH = { authorization: "Bearer test-token" };
+
+async function post(body: Record<string, unknown>) {
+ const res = await POST(
+ new Request("http://localhost/api/ops/x-run", {
+ method: "POST",
+ headers: { ...AUTH, "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, body: (await res.json()) as { ok: boolean; error?: string; run?: string } };
+}
+
+async function get(q = "") {
+ const res = await GET(new Request(`http://localhost/api/ops/x-run${q}`, { headers: AUTH }));
+ return { status: res.status, body: (await res.json()) as Record<string, unknown> & { error?: string } };
+}
+
+test("the body: one of channels or resume; slugs checked; a limit over 200 refused", async () => {
+ assert.match((await post({})).body.error!, /"channels" \(a new run\) or "resume" \(a run id\) is required/);
+ assert.match((await post({ channels: ["top-x"], resume: "xr-x" })).body.error!, /one at a time/);
+ assert.match((await post({ channels: ["../etc"] })).body.error!, /not a valid channel slug/);
+ assert.match((await post({ channels: ["top-x"], extra: 1 })).body.error!, /unknown key\(s\): extra/);
+ assert.equal((await post({ channels: ["bsky"] })).body.error, "bsky is not an X posts channel.");
+ assert.match((await post({ channels: ["top-x"], limit: 500 })).body.error!, /from 1 to 200/);
+ assert.match((await post({ resume: "nope" })).body.error!, /is not an X run id/);
+});
+
+test("a stale jar refuses a new run before any job; the run's file is kept, deferred, for a Resume", async () => {
+ const res = await post({ channels: ["top-x", "mid-x"] });
+ assert.equal(res.status, 400);
+ assert.match(res.body.error!, /^X cookies were last refreshed 16 days ago \(limit 60 min\)/);
+ assert.match(res.body.run!, /^xr-/);
+ assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []);
+ const view = await get(`?run=${res.body.run}`);
+ assert.equal(view.status, 200);
+ const run = view.body.run as { status: string; summary: string; resumable: number };
+ assert.equal(run.status, "deferred");
+ assert.equal(run.summary, "0 done, 2 deferred until the next refresh");
+ assert.equal(run.resumable, 2);
+});
+
+test("GET: the X posts channels in the default order, the jar against the limit; an unknown run is a 404", async () => {
+ const { status, body } = await get();
+ assert.equal(status, 200);
+ const candidates = body.candidates as { slug: string; tier: string }[];
+ assert.deepEqual(
+ candidates.map((c) => [c.slug, c.tier]),
+ [["top-x", "normal"], ["mid-x", "normal"], ["low-x", "low"]],
+ );
+ const jar = body.jar as { allowed: boolean; maxAgeMinutes: number; staleAt: string; ageChecked: boolean };
+ assert.equal(jar.allowed, false);
+ assert.equal(jar.maxAgeMinutes, 60);
+ assert.equal(jar.ageChecked, true);
+ assert.ok(Date.parse(jar.staleAt) < Date.now());
+ assert.equal(body.maxPosts, 200);
+ assert.equal((await get("?run=xr-01ZZZZZZZZZZZZZZZZZZZZZZZZ")).status, 404);
+ assert.equal((await get("?nope=1")).status, 400);
+});
diff --git a/editor/app/api/ops/x-run/route.ts b/editor/app/api/ops/x-run/route.ts
@@ -0,0 +1,54 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { isXRunId, xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
+import { xRunAction } from "../../../review/xRunActions";
+import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqSlugs } from "../_lib";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// THE X RUN (common/controller/xRun.ts; /review's X run console): fetch-posts
+// for several X posts channels IN SEQUENCE, as one `x-run` job on X's queue —
+// X's gap between two channels, at most 200 posts each, the cookie jar checked
+// before EACH channel. A stale jar (social.x.maxCookieAgeMinutes) or a raised
+// X alert stops the run and defers the rest until the next refresh; nothing
+// here refreshes the jar.
+//
+// POST { channels: [slug, …], limit? } a new run, in this order -> { ok, jobId, run }
+// POST { resume: "<run id>", limit? } its deferred channels -> { ok, jobId, run }
+// Refused before any job: nothing picked, a channel that is not an X posts
+// channel, a run already queued or running, a stale jar (the new run's file
+// is kept, deferred, for a Resume), a run with nothing to resume.
+// GET [?run=<id>] -> { ok, run, candidates, jar, gapSeconds, maxPosts }
+// The run (the latest when none is named) as the console shows it, the X
+// posts channels in the default order, and the jar's age against the limit.
+// Nothing is asked of X and nothing is written.
+export async function POST(request: Request) {
+ return ops(request, ["channels", "limit", "resume"], async (body) => {
+ const resume = optString(body, "resume");
+ const limit = optPositiveInt(body, "limit");
+ if (resume !== undefined && body.channels !== undefined) {
+ throw new OpsInputError('"resume" and "channels" are one at a time.');
+ }
+ if (resume === undefined && body.channels === undefined) {
+ throw new OpsInputError('"channels" (a new run) or "resume" (a run id) is required.');
+ }
+ const res = await xRunAction({
+ ...(resume !== undefined ? { resume } : { channels: reqSlugs(body, "channels") }),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ if (!res.ok) return opsFail(res.error, 400, res.run ? { run: res.run } : undefined);
+ void res.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: res.jobId, run: res.run });
+ });
+}
+
+export async function GET(request: Request) {
+ return readRoute(request, ["run"], async (q) => {
+ const run = q.get("run")?.trim() || undefined;
+ if (run && !isXRunId(run)) return opsFail(`"${run}" is not an X run id`);
+ const out = await xRunConsole(getPaths(), run);
+ if (run && !out.run) return opsFail(`No X run ${run}`, 404);
+ return { ...out };
+ });
+}
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [
// Views born after the consolidation: there is no old path to rewrite, so
// they are served only at /api/view/<name>.
-const NEW_VIEWS = ["cookieAlerts"];
+const NEW_VIEWS = ["cookieAlerts", "xRun"];
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
loadActionableSummary,
widgetActionableRows,
@@ -81,4 +82,9 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// (or are OK again, with the jobs it stopped). One small file and each
// recorded job's status.
cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
+
+ // /review's X run console: the latest run (each channel's state, the
+ // summary), the X posts channels in the default order and the jar's age
+ // against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
+ xRun: async () => NextResponse.json(await xRunConsole(getPaths())),
};
diff --git a/editor/app/channels/[slug]/components/AccountActivityPanel.tsx b/editor/app/channels/[slug]/components/AccountActivityPanel.tsx
@@ -0,0 +1,199 @@
+// ACCOUNT ACTIVITY (lane x-console): a posts channel's archived posts per UTC
+// day over the archive's range, as a compact bar strip, with its long
+// silences shaded — a gap of at least 3× the account's median gap AND 48 h
+// (common/lib/accountActivity.ts says why both) — and each silence linked to
+// the post before it and the post after. Read from the stored posts; a server
+// component, no client code.
+
+import { readChannelActivity } from "yt-dlp-transcript-common/lib/postTimes-server";
+import {
+ medianText,
+ spanHours,
+ type AccountActivity,
+ type ActivityEnd,
+} from "yt-dlp-transcript-common/lib/accountActivity";
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+// "4 Nov 10:54" (UTC); the year when it is not the strip's last.
+function at(iso: string, lastYear: string): string {
+ const d = new Date(iso);
+ const y = String(d.getUTCFullYear());
+ const hm = iso.slice(11, 16);
+ return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}${y === lastYear ? "" : ` ${y}`} ${hm}`;
+}
+
+function dayText(day: string): string {
+ return `${Number(day.slice(8, 10))} ${MONTHS[Number(day.slice(5, 7)) - 1]} ${day.slice(0, 4)}`;
+}
+
+const SHOWN_SILENCES = 12;
+const H = 40;
+
+function PostLink({ end, label }: { end: ActivityEnd; label: string }) {
+ return (
+ <a
+ href={end.url}
+ target="_blank"
+ rel="noreferrer"
+ title={end.snippet || undefined}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {label}
+ </a>
+ );
+}
+
+export function AccountActivityPanel({ activity }: { activity: AccountActivity }) {
+ const { days, maxPerDay, silences } = activity;
+ const n = days.length;
+ const index = new Map(days.map((d, i) => [d.day, i]));
+ const lastYear = activity.lastAt.slice(0, 4);
+ const barW = n <= 120 ? 0.8 : 1;
+ // Labels: about a week apart over two months or less, else month starts
+ // (at most ~12). One too near the right edge would run off it.
+ const starts =
+ n <= 62
+ ? days.flatMap((_, i) => (i % Math.max(1, Math.ceil(n / 7)) === 0 ? [i] : []))
+ : days.flatMap((d, i) => (d.day.endsWith("-01") || i === 0 ? [i] : []));
+ const step = Math.max(1, Math.ceil(starts.length / 12));
+ const ticks = starts.filter((i, k) => k % step === 0 && (i === 0 || i / n < 0.92));
+ const label = (i: number) =>
+ n <= 62 || i === 0 ? dayText(days[i].day).replace(/ \d{4}$/, "") : MONTHS[Number(days[i].day.slice(5, 7)) - 1];
+ // A silence's shading spans the gap itself, from the post before to the
+ // post after (in days from the strip's first midnight), not their whole days.
+ const origin = Date.parse(`${days[0].day}T00:00:00Z`);
+ const silenceSpan = (s: { before: ActivityEnd; after: ActivityEnd }) => {
+ const a = (Date.parse(s.before.createdAt) - origin) / 86_400_000;
+ const b = (Date.parse(s.after.createdAt) - origin) / 86_400_000;
+ return { x: a, w: Math.max(0.2, b - a) };
+ };
+ return (
+ <section aria-label="account activity" className="rounded-lg border border-border bg-card p-4 flex flex-col gap-3">
+ <div className="flex items-baseline gap-x-3 gap-y-1 flex-wrap">
+ <h2 className="text-sm font-medium">{activity.author ? "Account activity" : "Activity"}</h2>
+ <p aria-label="account activity summary" className="text-xs text-muted-foreground">
+ {activity.posts.toLocaleString("en-US")} posts{activity.author ? ` by @${activity.author}` : ""} ·{" "}
+ {dayText(days[0].day)} – {dayText(days[n - 1].day)} · median gap {medianText(activity.medianGapMinutes)} ·
+ busiest day {maxPerDay} · UTC
+ </p>
+ </div>
+ <div className="flex flex-col gap-1">
+ <svg
+ role="img"
+ aria-label="posts per day"
+ viewBox={`0 0 ${n} ${H}`}
+ preserveAspectRatio="none"
+ className="w-full h-14 block"
+ >
+ {silences.map((s) => {
+ const { x, w } = silenceSpan(s);
+ return (
+ <rect key={`s-${s.before.id}`} x={x} y={0} width={w} height={H} className="fill-warning-soft" data-silence="">
+ <title>{`No archived post for ${spanHours(s.hours)}`}</title>
+ </rect>
+ );
+ })}
+ <rect x={0} y={H - 0.5} width={n} height={0.5} className="fill-border" />
+ {days.map((d, i) =>
+ d.count > 0 ? (
+ <rect
+ key={d.day}
+ x={i + (1 - barW) / 2}
+ y={H - Math.max(1.5, (d.count / maxPerDay) * (H - 2))}
+ width={barW}
+ height={Math.max(1.5, (d.count / maxPerDay) * (H - 2))}
+ className="fill-info"
+ >
+ <title>{`${d.day}: ${d.count} post${d.count === 1 ? "" : "s"}`}</title>
+ </rect>
+ ) : null,
+ )}
+ </svg>
+ <div className="relative h-4 text-[11px] text-muted-foreground" aria-hidden="true">
+ {ticks.map((i) => (
+ <span
+ key={days[i].day}
+ className="absolute whitespace-nowrap"
+ style={{ left: `${(i / n) * 100}%` }}
+ >
+ {label(i)}
+ </span>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-col gap-1">
+ <h3 className="text-xs font-medium">
+ Long silences ({silences.length}){" "}
+ <span className="font-normal text-muted-foreground">
+ — no archived post for ≥ {spanHours(activity.thresholdHours)} (≥ 48 h and ≥ 3× the median gap)
+ </span>
+ </h3>
+ {silences.length === 0 && !activity.trailing ? (
+ <p className="text-xs text-muted-foreground">None in the archive's range.</p>
+ ) : (
+ <ul aria-label="long silences" className="flex flex-col gap-0.5 text-xs">
+ {activity.trailing && (
+ <li aria-label={`silence since ${activity.trailing.since.createdAt.slice(0, 10)}`} className="flex gap-2 flex-wrap">
+ <span className="tabular-nums">
+ since {at(activity.trailing.since.createdAt, lastYear)}
+ </span>
+ <span className="text-muted-foreground">
+ {spanHours(activity.trailing.hours)} by the last fetch
+ </span>
+ <PostLink end={activity.trailing.since} label="last post" />
+ </li>
+ )}
+ {silences.slice(0, SHOWN_SILENCES).map((s) => (
+ <li
+ key={s.before.id}
+ aria-label={`silence ${s.before.createdAt.slice(0, 10)} to ${s.after.createdAt.slice(0, 10)}`}
+ className="flex gap-2 flex-wrap"
+ >
+ <span className="tabular-nums">
+ {at(s.before.createdAt, lastYear)} → {at(s.after.createdAt, lastYear)}
+ </span>
+ <span className="text-muted-foreground">{spanHours(s.hours)}</span>
+ <PostLink end={s.before} label="post before" />
+ <PostLink end={s.after} label="post after" />
+ </li>
+ ))}
+ {silences.length > SHOWN_SILENCES && (
+ <li className="text-muted-foreground">and {silences.length - SHOWN_SILENCES} older</li>
+ )}
+ </ul>
+ )}
+ </div>
+ </section>
+ );
+}
+
+// The panel as the page streams it: the posts read through the cached light
+// reader and the result memoised by the shards' signature
+// (lib/postTimes-server.ts), behind the page's Suspense boundary.
+export async function AccountActivitySection({
+ channelRoot,
+ asOf,
+ author,
+}: {
+ channelRoot: string;
+ asOf?: string;
+ author?: string;
+}) {
+ const activity = await readChannelActivity(channelRoot, {
+ ...(asOf ? { asOf } : {}),
+ ...(author ? { author } : {}),
+ });
+ return activity ? <AccountActivityPanel activity={activity} /> : null;
+}
+
+export function AccountActivityLoading() {
+ return (
+ <section
+ aria-label="account activity loading"
+ className="rounded-lg border border-border bg-card p-4 text-xs text-muted-foreground"
+ >
+ Reading the archived posts…
+ </section>
+ );
+}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -1,5 +1,5 @@
import path from "node:path";
-import type { ReactNode } from "react";
+import { Suspense, type ReactNode } from "react";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -33,6 +33,7 @@ import {
meanPagePauseSeconds,
} from "yt-dlp-transcript-common/lib/forumWalk";
import { SocialChannelPanel } from "./components/SocialChannelPanel";
+import { AccountActivityLoading, AccountActivitySection } from "./components/AccountActivityPanel";
import { WaybackPagesPanel } from "./components/WaybackPagesPanel";
import { WaybackLivePanel } from "./components/WaybackLivePanel";
import { waybackLiveState } from "./waybackLiveState";
@@ -243,6 +244,13 @@ export default async function ChannelDetailPage({
// when the full-history walk is part-way, Resume backfill — never a forum
// thread's (its own two walks) or an X search's (one walk).
const timeline = !forumThread && !xSearch ? timelineWalks(fetchState) : null;
+ // ACCOUNT ACTIVITY (lane x-console): posts per day and the long silences,
+ // from the stored posts — every posts channel but a Wayback pages one
+ // (its records are captures) and an X search (its posts are many
+ // accounts' answers to a query, not one account's activity). Streamed
+ // behind its own Suspense boundary, read through the cached light reader
+ // (lib/postTimes-server.ts), so the page never waits on the posts.
+ const showActivity = !isWaybackPagesChannel(config) && !xSearch && postCount >= 2;
return (
<div className="flex flex-col gap-6">
<RunningJobsList jobs={socialRunningJobs} hideChannelSlug />
@@ -320,6 +328,15 @@ export default async function ChannelDetailPage({
}}
/>
)}
+ {showActivity && (
+ <Suspense fallback={<AccountActivityLoading />}>
+ <AccountActivitySection
+ channelRoot={channelRoot}
+ asOf={fetchState?.lastFetchedAt}
+ author={config.socialHandle}
+ />
+ </Suspense>
+ )}
{leads && leads.ok && <XSearchLeadsPanel slug={slug} leads={leads} />}
{/* THE SAME DANGER ZONE A VIDEO CHANNEL HAS, which a social channel
used to lack entirely: this branch returns before the stage list,
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"
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -9,6 +9,7 @@
// so it is never bundled to the client.
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { savePageNowBatchAction } from "../channels/[slug]/waybackLiveActions";
+import { xRunAction } from "../review/xRunActions";
import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow";
import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl";
import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
@@ -430,6 +431,15 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
bool(p.backfill),
);
},
+ // Lane x-console: the run's state file holds the channels and where each
+ // stands; a replay is a RESUME (the deferred and unfinished channels, in
+ // their order) — refused when the run has nothing left.
+ "x-run": (spec) => {
+ const { p } = params(spec);
+ const run = str(p.run);
+ if (!run) return Promise.resolve({ ok: false, error: "Job spec has no run." });
+ return xRunAction({ resume: run });
+ },
// Lane spn-batch: the batch's state file holds the list and each URL's
// status; the re-run continues from the first pending URL.
"save-page-now-batch": (spec) => {
diff --git a/editor/app/review/components/XRunConsole.tsx b/editor/app/review/components/XRunConsole.tsx
@@ -0,0 +1,364 @@
+"use client";
+
+// THE X RUN CONSOLE (/review, lane x-console). Pick X posts channels, order
+// them, start ONE `x-run` job: fetch-posts for each in sequence, X's queue gap
+// between two, at most 200 posts each, the cookie jar checked before each
+// channel. When the jar passes social.x.maxCookieAgeMinutes the run stops and
+// the rest are deferred; after the operator refreshes the jar (/settings),
+// Resume runs them. Nothing here refreshes cookies or asks X anything — the
+// console reads disk (the run's state file, the jar's mtime) through the
+// `xRun` view.
+
+import Link from "next/link";
+import { useEffect, useMemo, useState, useTransition } from "react";
+import type {
+ XRunCandidate,
+ XRunChannelStatus,
+ XRunConsole as XRunConsolePayload,
+ XRunView,
+} from "yt-dlp-transcript-common/controller/xRun";
+import { useNow, usePolledPayload } from "../../lib/usePolledPayload";
+import { resumeXRunAction, startXRunAction } from "../xRunActions";
+
+// "4:05", "1:02:03".
+function clock(ms: number): string {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = String(s % 60).padStart(2, "0");
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
+}
+
+// "45 min", "3 h", "16 days".
+function age(ms: number): string {
+ const min = Math.max(0, Math.floor(ms / 60_000));
+ if (min < 120) return `${min} min`;
+ const h = Math.floor(min / 60);
+ return h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
+}
+
+// X's queue gap, as the run waits it between two channels.
+function gapText(seconds: number): string {
+ if (seconds <= 0) return "no gap between channels";
+ if (seconds < 120) return `${seconds} s between channels`;
+ return `${Math.round(seconds / 60)} min between channels`;
+}
+
+function when(iso: string | null): string {
+ if (!iso) return "never";
+ return `${iso.slice(0, 10)} ${iso.slice(11, 16)}`;
+}
+
+const STATUS_TONE: Record<XRunChannelStatus, string> = {
+ queued: "bg-muted text-muted-foreground",
+ running: "bg-info-soft text-info",
+ done: "bg-success-soft text-success",
+ deferred: "bg-warning-soft text-warning",
+ failed: "bg-destructive-soft text-destructive",
+};
+
+const TIER_TONE: Record<string, string> = {
+ focus: "bg-brand-soft text-brand-ink",
+ normal: "bg-muted text-muted-foreground",
+ low: "bg-muted text-faint",
+ paused: "bg-warning-soft text-warning",
+};
+
+// THE JAR, COUNTED DOWN. Ticks every second from the jar's mtime and the
+// limit; the poll refreshes both (a refresh on /settings rewrites the jar).
+function JarCountdown({ jar, now }: { jar: XRunConsolePayload["jar"]; now: number | null }) {
+ const href = "/settings";
+ if (jar.alert) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="alert" className="text-sm text-destructive">
+ The X cookie alert is up ({jar.alert.line}): no X job starts until it is cleared on the dashboard.
+ </p>
+ );
+ }
+ if (!jar.ageChecked) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="unchecked" className="text-sm text-muted-foreground">
+ {jar.source === "browser"
+ ? "X login: the browser's cookies — their age cannot be read, so the limit is not checked."
+ : "The cookie age limit is off (social.x.maxCookieAgeMinutes = 0)."}
+ </p>
+ );
+ }
+ if (!jar.cookiesUpdatedAt || !jar.staleAt) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="none" className="text-sm text-destructive">
+ No X cookie jar: <Link href={href} className="underline">Connect X account on /settings</Link>.
+ </p>
+ );
+ }
+ const at = now ?? Date.parse(jar.cookiesUpdatedAt);
+ const left = Date.parse(jar.staleAt) - at;
+ const old = at - Date.parse(jar.cookiesUpdatedAt);
+ if (left <= 0) {
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="stale" className="text-sm text-warning">
+ Cookie jar {age(old)} old, past the {jar.maxAgeMinutes} min limit —{" "}
+ <Link href={href} className="underline">Refresh cookies on /settings</Link>, then Resume.
+ </p>
+ );
+ }
+ return (
+ <p role="status" aria-label="x cookie jar" data-jar="fresh" className="text-sm">
+ Cookie jar {age(old)} old ·{" "}
+ <span className="font-mono tabular-nums" aria-label="cookie time left">
+ {clock(left)}
+ </span>{" "}
+ left of {jar.maxAgeMinutes} min
+ </p>
+ );
+}
+
+function RunPanel({
+ run,
+ now,
+ onResume,
+ pending,
+}: {
+ run: XRunView;
+ now: number | null;
+ onResume: () => void;
+ pending: boolean;
+}) {
+ const waitLeft = run.waitingUntil && now ? Date.parse(run.waitingUntil) - now : null;
+ return (
+ <div aria-label="x run" data-run-status={run.status} className="flex flex-col gap-2 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap text-sm">
+ <span className="font-medium">Run {run.id.slice(-6).toLowerCase()}</span>
+ <span className="rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground">{run.status}</span>
+ {run.jobId && (
+ <Link href={`/jobs/${run.jobId}`} className="text-xs underline text-muted-foreground">
+ job log
+ </Link>
+ )}
+ <span className="text-xs text-muted-foreground">≤ {run.limit} posts each</span>
+ </div>
+ <p aria-label="x run summary" className="text-sm font-medium">
+ {run.summary}
+ </p>
+ {waitLeft !== null && waitLeft > 0 && (
+ <p className="text-xs text-muted-foreground">
+ Next channel in <span className="font-mono tabular-nums">{clock(waitLeft)}</span> (X's queue gap).
+ </p>
+ )}
+ {run.stopped && (
+ <p aria-label="x run stopped" className="text-xs text-muted-foreground">
+ {run.stopped}
+ </p>
+ )}
+ <ol className="flex flex-col divide-y divide-border rounded-md border border-border max-h-72 overflow-y-auto">
+ {run.channels.map((c) => (
+ <li
+ key={c.slug}
+ aria-label={`x run channel ${c.slug}`}
+ data-status={c.status}
+ className="flex items-center gap-2 px-2 py-1 text-sm"
+ >
+ <Link href={`/channels/${c.slug}`} className="truncate underline-offset-2 hover:underline">
+ {c.slug}
+ </Link>
+ <span className={`ml-auto shrink-0 rounded-full px-2 py-0.5 text-xs ${STATUS_TONE[c.status]}`}>
+ {c.status === "done" ? `done · ${c.posts ?? 0} posts` : c.status}
+ </span>
+ {c.error && (
+ <span className="basis-full text-xs text-destructive truncate" title={c.error}>
+ {c.error}
+ </span>
+ )}
+ </li>
+ ))}
+ </ol>
+ {run.resumable > 0 && (
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onResume}
+ disabled={pending}
+ className="px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ Resume ({run.resumable} deferred)
+ </button>
+ <span className="text-xs text-muted-foreground">after a cookie refresh; starts with the deferred channels</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Picker({
+ candidates,
+ order,
+ setOrder,
+ picked,
+ setPicked,
+}: {
+ candidates: XRunCandidate[];
+ order: string[];
+ setOrder: (o: string[]) => void;
+ picked: Set<string>;
+ setPicked: (p: Set<string>) => void;
+}) {
+ const bySlug = useMemo(() => new Map(candidates.map((c) => [c.slug, c])), [candidates]);
+ const move = (i: number, d: -1 | 1) => {
+ const j = i + d;
+ if (j < 0 || j >= order.length) return;
+ const next = [...order];
+ [next[i], next[j]] = [next[j], next[i]];
+ setOrder(next);
+ };
+ const toggle = (slug: string) => {
+ const next = new Set(picked);
+ if (next.has(slug)) next.delete(slug);
+ else next.add(slug);
+ setPicked(next);
+ };
+ return (
+ <ol aria-label="x run channels" className="flex flex-col divide-y divide-border rounded-md border border-border max-h-80 overflow-y-auto">
+ {order.map((slug, i) => {
+ const c = bySlug.get(slug);
+ if (!c) return null;
+ return (
+ <li key={slug} aria-label={`pick ${slug}`} className="flex items-center gap-2 px-2 py-1 text-sm">
+ <input
+ type="checkbox"
+ aria-label={`run ${slug}`}
+ checked={picked.has(slug)}
+ onChange={() => toggle(slug)}
+ />
+ <span className="w-5 text-right text-xs tabular-nums text-faint">{i + 1}</span>
+ <span className="min-w-0 truncate" title={c.name}>
+ {slug}
+ </span>
+ <span className={`shrink-0 rounded-full px-1.5 py-0.5 text-[11px] ${TIER_TONE[c.tier] ?? TIER_TONE.normal}`}>
+ {c.tier}
+ </span>
+ {c.search && <span className="shrink-0 text-[11px] text-muted-foreground">search</span>}
+ <span
+ className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums"
+ title={c.lastError ?? undefined}
+ >
+ {c.postCount} · {when(c.lastFetchedAt)}
+ </span>
+ <span className="flex shrink-0">
+ <button
+ type="button"
+ aria-label={`move ${slug} up`}
+ onClick={() => move(i, -1)}
+ disabled={i === 0}
+ className="px-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
+ >
+ ↑
+ </button>
+ <button
+ type="button"
+ aria-label={`move ${slug} down`}
+ onClick={() => move(i, 1)}
+ disabled={i === order.length - 1}
+ className="px-1 text-muted-foreground hover:text-foreground disabled:opacity-30"
+ >
+ ↓
+ </button>
+ </span>
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
+
+export function XRunConsole({ initial }: { initial: XRunConsolePayload }) {
+ const [pending, startTransition] = useTransition();
+ const [fast, setFast] = useState(initial.run?.live ?? false);
+ const { data, refetch } = usePolledPayload<XRunConsolePayload>("/api/view/xRun", true, fast ? 2000 : 10_000, initial, {
+ immediate: false,
+ });
+ const view = data ?? initial;
+ const live = view.run?.live ?? false;
+ // Polled every 2 s while a run is live, every 10 s otherwise.
+ useEffect(() => setFast(live), [live]);
+ const now = useNow();
+ // The default order is the candidates' (focus, tier, rank, slug); paused
+ // channels start unpicked.
+ const [order, setOrder] = useState<string[]>(() => initial.candidates.map((c) => c.slug));
+ const [picked, setPicked] = useState<Set<string>>(
+ () => new Set(initial.candidates.filter((c) => c.tier !== "paused").map((c) => c.slug)),
+ );
+ // A channel added since the page loaded joins the end of the order.
+ const known = new Set(order);
+ const extra = view.candidates.filter((c) => !known.has(c.slug)).map((c) => c.slug);
+ const fullOrder = extra.length ? [...order, ...extra] : order;
+ const chosen = fullOrder.filter((s) => picked.has(s) && view.candidates.some((c) => c.slug === s));
+ const [note, setNote] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const after = (res: Awaited<ReturnType<typeof startXRunAction>>, ok: string) => {
+ if (res.ok) {
+ setNote(ok);
+ setError(null);
+ setFast(true);
+ } else {
+ setNote(null);
+ setError(res.error);
+ }
+ void refetch();
+ };
+ const start = () =>
+ startTransition(async () => {
+ after(await startXRunAction(chosen), `X run queued: ${chosen.length} channel(s).`);
+ });
+ const resume = () =>
+ startTransition(async () => {
+ if (!view.run) return;
+ after(await resumeXRunAction(view.run.id), "Resume queued: the deferred channels run first.");
+ });
+
+ return (
+ <section aria-label="x run console" className="flex flex-col gap-3">
+ <div className="flex items-center justify-between flex-wrap gap-2">
+ <h2 className="text-lg font-semibold">X run</h2>
+ <JarCountdown jar={view.jar} now={now} />
+ </div>
+ {view.candidates.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No X posts channels.</p>
+ ) : (
+ <div className="grid gap-4 lg:grid-cols-2">
+ <div className="flex flex-col gap-2 min-w-0">
+ <Picker candidates={view.candidates} order={fullOrder} setOrder={setOrder} picked={picked} setPicked={setPicked} />
+ <div className="flex items-center gap-2 flex-wrap">
+ <button
+ type="button"
+ onClick={start}
+ disabled={pending || live || chosen.length === 0}
+ className="px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ Start X run ({chosen.length})
+ </button>
+ <span className="text-xs text-muted-foreground">
+ ≤ {view.maxPosts} posts each · {gapText(view.gapSeconds)}
+ </span>
+ </div>
+ {note && (
+ <p role="status" aria-label="x run note" className="text-xs text-muted-foreground">
+ {note}
+ </p>
+ )}
+ {error && (
+ <p role="alert" aria-label="x run error" className="text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ </div>
+ {view.run ? (
+ <RunPanel run={view.run} now={now} onResume={resume} pending={pending} />
+ ) : (
+ <p className="text-sm text-muted-foreground">No X run yet.</p>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx
@@ -20,6 +20,8 @@ import { RunDuplicateDetectionButton } from "./components/RunDuplicateDetectionB
import { RunMediaScanButton } from "./components/RunMediaScanButton";
import { MediaScanFindingRow } from "./components/MediaScanFindingRow";
import { DuplicateClusterReview } from "./components/DuplicateClusterReview";
+import { XRunConsole } from "./components/XRunConsole";
+import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
export const dynamic = "force-dynamic";
@@ -29,12 +31,22 @@ export const metadata: Metadata = { title: "Review" };
// and media-integrity findings are both flag-only, both carry a reviewed state,
// and neither is an operation or a pile of reclaimable bytes — which is why
// they are here rather than on an operation page or on /cleanup.
+//
+// THE X RUN CONSOLE (lane x-console) is here for the same reason: an X run is
+// a pass a person starts and whose outcome needs a person — the cookie jar
+// goes stale mid-run, the rest are deferred, and only the operator's refresh
+// on /settings lets Resume take them. It is the X work that waits on a human
+// (the dashboard's X banner says the jar is stale; this says what waits on
+// it), not a lane the machine dispatches, and /channels is a dense rack whose
+// rows are channels, not a sequence across them.
export default async function ReviewPage() {
- const review = await loadReviewSummary(getPaths());
+ const paths = getPaths();
+ const [review, xRun] = await Promise.all([loadReviewSummary(paths), xRunConsole(paths)]);
return (
<div className="flex flex-col gap-6">
<h1 className="text-2xl font-semibold">Review</h1>
<AutoPausedSection rows={review.autoPaused} />
+ <XRunConsole initial={xRun} />
<DuplicatesSection
report={review.duplicates}
overrides={review.duplicateOverrides}
diff --git a/editor/app/review/xRunActions.ts b/editor/app/review/xRunActions.ts
@@ -0,0 +1,46 @@
+"use server";
+
+// THE X RUN CONSOLE's actions (/review, lane x-console): read the console,
+// start a run over the picked channels in the picked order, resume a deferred
+// one. The job and its rules are common/controller/xRun.ts; nothing here asks
+// X anything or refreshes the jar.
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import {
+ queueXRun,
+ xRunConsole,
+ type XRunConsole,
+ type XRunRequest,
+} from "yt-dlp-transcript-common/controller/xRun";
+import { safeRevalidate } from "../lib/safeRevalidate";
+
+// The job, as the replay table and the ops route take it.
+export async function xRunAction(req: XRunRequest): Promise<StreamActionResult & { run?: string }> {
+ return queueXRun({
+ paths: getPaths(),
+ req,
+ onChannelDone: (slug) => safeRevalidate([`/channels/${slug}`]),
+ });
+}
+
+export type XRunStartResult = { ok: true; jobId: string; run: string } | { ok: false; error: string; run?: string };
+
+async function started(res: StreamActionResult & { run?: string }): Promise<XRunStartResult> {
+ if (!res.ok) return { ok: false, error: res.error, ...(res.run ? { run: res.run } : {}) };
+ // The console follows the run's state file, not the stream.
+ void res.stream.cancel();
+ return { ok: true, jobId: res.jobId, run: res.run! };
+}
+
+export async function startXRunAction(channels: string[], limit?: number): Promise<XRunStartResult> {
+ return started(await xRunAction({ channels, ...(limit !== undefined ? { limit } : {}) }));
+}
+
+export async function resumeXRunAction(run: string): Promise<XRunStartResult> {
+ return started(await xRunAction({ resume: run }));
+}
+
+export async function xRunConsoleAction(run?: string): Promise<XRunConsole> {
+ return xRunConsole(getPaths(), run);
+}
diff --git a/editor/e2e/account-activity.spec.ts b/editor/e2e/account-activity.spec.ts
@@ -0,0 +1,127 @@
+// ACCOUNT ACTIVITY on a posts channel's page (lane x-console): posts per day
+// over the archive's range, and the long silences — ≥ 3× the account's median
+// gap AND ≥ 48 h — each linked to the post before and the post after.
+//
+// The shape is Mr Obvious's 5–8 Nov 2026 gap (verified read-only against the
+// real corpus by an offline script): a busy account, a post every 15 minutes
+// on 3–4 Nov, nothing for four days, busy again on 8 Nov. The posts are
+// written straight to the channel's shard (no fetch, nothing reaches X), plus
+// posts by another account the with-replies timeline archived, which do not
+// count.
+
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+
+const SLUG = "x-obvious";
+const HANDLE = "obvious_user";
+
+type P = { id: string; createdAt: string; author: string };
+
+function posts(): P[] {
+ const out: P[] = [];
+ let n = 1000;
+ for (const day of ["2026-11-03", "2026-11-04"]) {
+ for (let m = 0; m < 8 * 60; m += 15) {
+ const h = String(10 + Math.floor(m / 60)).padStart(2, "0");
+ out.push({ id: String(++n), createdAt: `${day}T${h}:${String(m % 60).padStart(2, "0")}:00.000Z`, author: HANDLE });
+ }
+ }
+ // Another account's post inside the gap (a reply's parent): not this
+ // account's activity.
+ out.push({ id: "9000", createdAt: "2026-11-06T12:00:00.000Z", author: "someone_else" });
+ for (let m = 0; m < 4 * 60; m += 15) {
+ const h = String(19 + Math.floor(m / 60)).padStart(2, "0");
+ out.push({ id: String(++n), createdAt: `2026-11-08T${h}:${String(m % 60).padStart(2, "0")}:00.000Z`, author: HANDLE });
+ }
+ return out;
+}
+
+async function writeChannel(): Promise<P[]> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+ await mkdir(path.join(dir, "posts"), { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ name: "Obvious (X)",
+ handling: "transcribe",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ platform: "twitter",
+ socialHandle: HANDLE,
+ url: `https://x.com/${HANDLE}`,
+ }),
+ );
+ const all = posts();
+ const lines = all.map((p) =>
+ JSON.stringify({
+ id: p.id,
+ slug: `${SLUG}/${p.id}`,
+ channelSlug: SLUG,
+ author: p.author,
+ createdAt: p.createdAt,
+ text: `post ${p.id}`,
+ url: `https://x.com/${p.author}/status/${p.id}`,
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }),
+ );
+ await writeFile(path.join(dir, "posts", "2026-11.jsonl"), lines.join("\n") + "\n");
+ await writeFile(path.join(dir, "posts-archive"), all.map((p) => `twitter ${p.id}\n`).join(""));
+ await writeFile(
+ path.join(dir, "posts-state.json"),
+ JSON.stringify({ lastFetchedAt: "2026-11-09T00:00:00.000Z", lastFetchedCount: 16 }),
+ );
+ return all;
+}
+
+const SHOTS = process.env.E2E_UI_OPS_SHOTS ?? "";
+async function shot(page: Page, name: string) {
+ if (!SHOTS) return;
+ await mkdir(SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false });
+}
+
+test("a posts channel's activity: posts per day, the four-day silence marked and linked to the posts on either side", async ({
+ page,
+}) => {
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+ const all = await writeChannel();
+ const own = all.filter((p) => p.author === HANDLE);
+ const before = own.filter((p) => p.createdAt.startsWith("2026-11-04")).at(-1)!;
+ const after = own.find((p) => p.createdAt.startsWith("2026-11-08"))!;
+
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(`/channels/${SLUG}`);
+ const panel = page.getByRole("region", { name: "account activity" });
+ await expect(panel.getByRole("heading", { name: "Account activity" })).toBeVisible();
+ // Only the account's own posts count; the range is 3 – 8 Nov.
+ await expect(panel.getByLabel("account activity summary")).toContainText(
+ "80 posts by @obvious_user · 3 Nov 2026 – 8 Nov 2026 · median gap 15 min · busiest day 32",
+ );
+ // The strip: one bar per day with a post (4 days carry none), one silence shaded.
+ const strip = panel.getByRole("img", { name: "posts per day" });
+ await expect(strip.locator("rect.fill-info")).toHaveCount(3);
+ await expect(strip.locator("rect[data-silence]")).toHaveCount(1);
+
+ const silences = panel.getByRole("list", { name: "long silences" });
+ await expect(silences.getByRole("listitem")).toHaveCount(1);
+ const gap = silences.getByLabel("silence 2026-11-04 to 2026-11-08");
+ await expect(gap).toContainText("4 Nov 17:45 → 8 Nov 19:00");
+ await expect(gap).toContainText("4 d 1 h");
+ await expect(gap.getByRole("link", { name: "post before" })).toHaveAttribute(
+ "href",
+ `https://x.com/${HANDLE}/status/${before.id}`,
+ );
+ await expect(gap.getByRole("link", { name: "post after" })).toHaveAttribute(
+ "href",
+ `https://x.com/${HANDLE}/status/${after.id}`,
+ );
+ await expect(panel).toContainText("no archived post for ≥ 2 d (≥ 48 h and ≥ 3× the median gap)");
+ await panel.scrollIntoViewIfNeeded();
+ await shot(page, "account-activity");
+});
diff --git a/editor/e2e/fixtures/bin/fake-gallery-dl.mjs b/editor/e2e/fixtures/bin/fake-gallery-dl.mjs
@@ -134,3 +134,21 @@ const TWEETS = [
for (const tweet of TWEETS.slice(0, limit)) {
process.stdout.write(JSON.stringify(tweet) + "\n");
}
+
+// TIME PASSES DURING A FETCH (x-run-console.spec): for the account
+// `jar_ages_user`, the cookie jar it was handed (`--cookies <file>`) is two
+// hours old once the fetch ends — what an X run meets when the jar passes
+// social.x.maxCookieAgeMinutes between two channels. Only the file's mtime
+// changes; nothing is fetched.
+if (handle === "jar_ages_user") {
+ const at = args.indexOf("--cookies");
+ if (at >= 0 && args[at + 1]) {
+ const { utimesSync } = await import("node:fs");
+ const t = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ try {
+ utimesSync(args[at + 1], t, t);
+ } catch {
+ // no jar handed over: nothing to age
+ }
+ }
+}
diff --git a/editor/e2e/x-run-console.spec.ts b/editor/e2e/x-run-console.spec.ts
@@ -0,0 +1,165 @@
+// THE X RUN CONSOLE (/review, lane x-console), end to end.
+//
+// The 8–9 Nov case in miniature: X fetch-posts for several channels, one after
+// another, until the cookie jar passes social.x.maxCookieAgeMinutes — then the
+// rest wait for a refresh. One x-run job does it: the console picks and orders
+// the channels, the run fetches each in turn (the fake gallery-dl: X is NEVER
+// contacted), the jar is read before each channel, and once it is stale the
+// remaining channel is deferred. The operator refreshes the jar (written by
+// hand here — no X, no browser) and Resume runs the deferred channel.
+//
+// The fake gallery-dl ages the jar it is handed for the account
+// `jar_ages_user` (two hours old once its fetch ends): time passing mid-run,
+// deterministically. The test server turns the built-in gap and age limit off
+// (E2E_JOB_GAP_SECONDS=0, E2E_X_MAX_COOKIE_AGE_MINUTES=0); this spec sets the
+// age limit itself.
+
+import { mkdir, utimes, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { pathExists, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+
+async function xChannel(slug: string, handle: string): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/channels/${slug}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ `${dir}/config.json`,
+ JSON.stringify({
+ name: `${handle} (X)`,
+ handling: "transcribe",
+ sourceKind: "social",
+ postFetcher: "x-gallery-dl",
+ platform: "twitter",
+ socialHandle: handle,
+ url: `https://x.com/${handle}`,
+ }),
+ );
+}
+
+async function xJar(ageMs: number): Promise<void> {
+ const dir = resolvePath(`${testPaths().transcriptsDir}/.x-session`);
+ await mkdir(`${dir}/profile`, { recursive: true });
+ await writeFile(`${dir}/cookies.txt`, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tfake\n");
+ const t = new Date(Date.now() - ageMs);
+ await utimes(`${dir}/cookies.txt`, t, t);
+}
+
+const SHOTS = process.env.E2E_UI_OPS_SHOTS ?? "";
+async function shot(page: Page, name: string) {
+ if (!SHOTS) return;
+ await mkdir(SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false });
+}
+
+const posts = (slug: string) => `${testPaths().transcriptsDir}/channels/${slug}/posts-archive`;
+
+test.beforeEach(async () => {
+ await resetData("empty");
+ await writeSettings({
+ minFreeDiskGB: 0,
+ social: { x: { cookieSource: "profile", maxCookieAgeMinutes: 60 } },
+ channelPriority: { focus: { kind: "none" }, channels: { "x-low": { tier: "low" }, "x-paused": { tier: "paused" } } },
+ });
+ await xChannel("x-alpha", "alpha_user");
+ await xChannel("x-beta", "jar_ages_user");
+ await xChannel("x-gamma", "gamma_user");
+ await xChannel("x-low", "low_user");
+ await xChannel("x-paused", "paused_user");
+});
+
+test("an X run: picked and ordered, the jar goes stale mid-run, the rest deferred; a refreshed jar and Resume finish it", async ({
+ page,
+ request,
+}) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await xJar(60_000);
+ await page.goto("/review");
+ const consoleEl = page.getByRole("region", { name: "x run console" });
+ await expect(consoleEl.getByRole("heading", { name: "X run" })).toBeVisible();
+
+ // The default order is the priority tiers': normal (by slug), low, paused;
+ // a paused channel starts unpicked.
+ const picker = consoleEl.getByRole("list", { name: "x run channels" });
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-gamma/, /x-low/, /x-paused/]);
+ await expect(picker.getByRole("checkbox", { name: "run x-paused" })).not.toBeChecked();
+ await expect(picker.getByRole("checkbox", { name: "run x-alpha" })).toBeChecked();
+ // Reorder: x-low up above x-gamma, then back down.
+ await picker.getByRole("button", { name: "move x-low up" }).click();
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-low/, /x-gamma/, /x-paused/]);
+ await picker.getByRole("button", { name: "move x-low down" }).click();
+ await expect(picker.getByRole("listitem")).toHaveText([/x-alpha/, /x-beta/, /x-gamma/, /x-low/, /x-paused/]);
+ await picker.getByRole("checkbox", { name: "run x-low" }).uncheck();
+
+ // The jar, counted down against the limit.
+ const jar = consoleEl.getByRole("status", { name: "x cookie jar" });
+ await expect(jar).toHaveAttribute("data-jar", "fresh");
+ await expect(jar).toContainText(/Cookie jar 1 min old · 5\d:\d\d left of 60 min/);
+ await shot(page, "x-run-console-picker");
+
+ await consoleEl.getByRole("button", { name: "Start X run (3)" }).click();
+ const run = consoleEl.getByLabel("x run", { exact: true });
+ await expect(run).toHaveAttribute("data-run-status", "deferred", { timeout: 60_000 });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("2 done, 1 deferred until the next refresh");
+ await expect(run.getByLabel("x run channel x-alpha")).toHaveAttribute("data-status", "done");
+ await expect(run.getByLabel("x run channel x-alpha")).toContainText("done · 3 posts");
+ await expect(run.getByLabel("x run channel x-beta")).toHaveAttribute("data-status", "done");
+ await expect(run.getByLabel("x run channel x-gamma")).toHaveAttribute("data-status", "deferred");
+ await expect(consoleEl.getByLabel("x run stopped")).toContainText(
+ /X cookies were last refreshed (120 min|2 h) ago \(limit 60 min\)/,
+ );
+ // The jar the fetch aged is stale now: the countdown says so.
+ await expect(jar).toHaveAttribute("data-jar", "stale");
+ expect(await pathExists(posts("x-alpha"))).toBe(true);
+ expect(await pathExists(posts("x-gamma"))).toBe(false);
+ await shot(page, "x-run-console-deferred");
+
+ // The ops twin reads the same run.
+ const got = await request.get(`${baseUrl}/api/ops/x-run`, { headers: AUTH });
+ const body = (await got.json()) as { run: { id: string; summary: string; resumable: number; jobIds: string[] } };
+ expect(body.run.summary).toBe("2 done, 1 deferred until the next refresh");
+ expect(body.run.resumable).toBe(1);
+ expect(body.run.jobIds).toHaveLength(1);
+
+ // The operator refreshes the jar; Resume runs the deferred channel.
+ await xJar(0);
+ await expect(jar).toHaveAttribute("data-jar", "fresh", { timeout: 20_000 });
+ await consoleEl.getByRole("button", { name: "Resume (1 deferred)" }).click();
+ await expect(run).toHaveAttribute("data-run-status", "done", { timeout: 60_000 });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("3 done");
+ await expect(run.getByLabel("x run channel x-gamma")).toHaveAttribute("data-status", "done");
+ expect(await pathExists(posts("x-gamma"))).toBe(true);
+ // x-low was not picked: never fetched.
+ expect(await pathExists(posts("x-low"))).toBe(false);
+ const after = (await (await request.get(`${baseUrl}/api/ops/x-run?run=${body.run.id}`, { headers: AUTH })).json()) as {
+ run: { jobIds: string[] };
+ };
+ expect(after.run.jobIds).toHaveLength(2);
+ await shot(page, "x-run-console-done");
+});
+
+test("the ops twin: a stale jar refuses a new run before any job, and the console offers its Resume", async ({
+ page,
+ request,
+}) => {
+ await xJar(16 * 24 * 60 * 60_000);
+ const res = await request.post(`${baseUrl}/api/ops/x-run`, {
+ headers: AUTH,
+ data: { channels: ["x-alpha", "x-gamma"] },
+ });
+ expect(res.status()).toBe(400);
+ const body = (await res.json()) as { error: string; run: string };
+ expect(body.error).toMatch(/^X cookies were last refreshed 16 days ago \(limit 60 min\)/);
+ expect(body.run).toMatch(/^xr-/);
+
+ await page.goto("/review");
+ const consoleEl = page.getByRole("region", { name: "x run console" });
+ await expect(consoleEl.getByLabel("x run summary")).toHaveText("0 done, 2 deferred until the next refresh");
+ await expect(consoleEl.getByRole("status", { name: "x cookie jar" })).toHaveAttribute("data-jar", "stale");
+ // Resume on the same stale jar is refused with the guard's sentence.
+ await consoleEl.getByRole("button", { name: "Resume (2 deferred)" }).click();
+ await expect(consoleEl.getByRole("alert", { name: "x run error" })).toContainText("X cookies were last refreshed 16 days ago");
+});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -42,6 +42,9 @@
// pnpm ops sync --json '{"slug":"the-quartering"}' --wait
// pnpm ops fetch-posts --json '{"slug":"example-x"}' --wait
// pnpm ops resume-backfill --json '{"slug":"example-x"}' --wait
+// pnpm ops x-run --json '{"channels":["example-x","other-x"]}'
+// pnpm ops x-run --json '{"resume":"xr-01J…"}'
+// pnpm ops get x-run
// pnpm ops metadata-scan --json '{"slug":"the-quartering"}'
// pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait
// pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait
@@ -286,6 +289,11 @@ const GETTERS = {
// network guard's verdict (common/jobs/networkGuard.ts xSessionReport).
"x-session": (slug) =>
slug ? `/api/ops/x-session?slug=${encodeURIComponent(slug)}` : "/api/ops/x-session",
+ // The X run (common/controller/xRun.ts): the latest run (or the one named)
+ // as /review's console shows it — each channel's state, "N done, M deferred
+ // until the next refresh" — the X posts channels in the default order, and
+ // the jar's age against social.x.maxCookieAgeMinutes.
+ "x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"),
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// What a channel holds, by date, and its gaps (release 19 A9): each video
@@ -336,6 +344,7 @@ const GET_ARG_OPTIONAL = new Set([
"scheduler",
"services",
"x-session",
+ "x-run",
"generation-usage",
"render-mode",
]);
@@ -654,6 +663,10 @@ const ACTIONS = [
// time, as one fetch-chat-backlog job on the platform's download queue; a
// re-run skips what landed. `dryRun` counts them from the disk, no job.
"fetch-chat-backlog",
+ // THE X RUN: fetch-posts for several X channels in sequence, as one job on
+ // X's queue, the jar checked before each ({channels: [...], limit?} or
+ // {resume: <run id>}); a stale jar defers the rest.
+ "x-run",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -690,6 +703,8 @@ export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
// The same for a live share (LIVE_CLIP_RESULT_MARKER in
// common/controller/liveClip.ts).
export const LIVE_CLIP_RESULT_MARKER = "@@live-clip ";
+// The same for an X run (X_RUN_RESULT_MARKER in common/controller/xRun.ts).
+export const X_RUN_RESULT_MARKER = "@@x-run ";
// The provenance a tag write from this CLI carries. Everything else ignores it.
function agentSource() {
@@ -941,6 +956,7 @@ export function parseArgs(argv) {
...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}),
...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}),
+ ...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1027,6 +1043,7 @@ export function usage() {
" pnpm ops get saved-alternates [<slug>]",
" pnpm ops get services",
" pnpm ops get x-session [<slug>]",
+ " pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
@@ -1102,6 +1119,15 @@ export function usage() {
" channel whose own cookiesFromBrowser may decide the source. Nothing is",
" asked of X: a refresh is Refresh cookies / Connect X account on",
" /settings. Ask it before queueing fetch-posts or capture-posts on X.",
+ "get x-run [<run id>] is the X run as /review's X run console shows it:",
+ " the latest run (or the one named) — each channel's status (queued,",
+ " running, done with its new posts, deferred, failed), \"summary\" (\"N",
+ " done, M deferred until the next refresh\"), live, interrupted (the editor",
+ " stopped mid-run: its unfinished channels read deferred), resumable — and",
+ " \"candidates\" (every X posts channel in the default order: focus, tier,",
+ " rank, slug), \"jar\" (its age, social.x.maxCookieAgeMinutes, staleAt:",
+ " when it passes the limit, and whether an X job would start now),",
+ " gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1546,6 +1572,20 @@ export function usage() {
" drained fetch stops at its next resume point and the next run of the",
" same walk resumes there.",
"",
+ 'x-run fetches several X posts channels IN SEQUENCE as ONE job on X\'s',
+ ' queue: {"channels": [slug, ...]} in that order, each a fetch-posts sync',
+ ' new of at most 200 posts ("limit": N, 1-200, caps it lower), X\'s queue',
+ " gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH",
+ " channel the jar is checked again: once it is past",
+ " social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and",
+ " the rest are DEFERRED until the next refresh. It never refreshes the",
+ ' jar: Refresh cookies on /settings, then {"resume": "<run id>"} runs the',
+ " deferred channels (the console's Resume; a Retry of the job is the",
+ " same). One run at a time; refused before a job on a stale jar (a new",
+ " run's channels are kept, deferred). An interrupted run is not resumed",
+ " on boot: it ends deferred. Answers {jobId, run}; get x-run follows it.",
+ " The log ends with @@x-run {id, status, stopped?, counts, summary}.",
+ "",
'resume-backfill continues a social channel\'s unfinished full-history',
' timeline walk (X, Bluesky) from its saved resume point, with no',
' watermark: {"slug"} ("limit"? caps the posts this run reads). The walk',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -11,6 +11,7 @@ import {
TRANSCRIBE_RESULT_MARKER,
TTS_RESULT_MARKER,
VOICE_RESULT_MARKER,
+ X_RUN_RESULT_MARKER,
editorEnvFiles,
followJob,
loadEditorEnv,
@@ -635,6 +636,21 @@ test("capture-posts is a POST to its route, named in the usage", () => {
assert.match(usage(), /unless\s+"articles": false/);
});
+// Lane x-console: the X run is a POST to its route whose --wait prints the
+// run's result line; `get x-run` reads the console, the latest run or one named.
+test("x-run is a POST to its route with a result marker; get x-run reads the console", () => {
+ const p = parseArgs(["x-run", "--json", '{"channels":["a-x","b-x"],"limit":50}', "--wait"]);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/x-run");
+ assert.deepEqual(p.body, { channels: ["a-x", "b-x"], limit: 50 });
+ assert.equal(p.resultMarker, X_RUN_RESULT_MARKER);
+ assert.equal(parseArgs(["get", "x-run"]).path, "/api/ops/x-run");
+ assert.equal(parseArgs(["get", "x-run", "xr-01ABC"]).path, "/api/ops/x-run?run=xr-01ABC");
+ assert.match(usage(), /pnpm ops get x-run \[<run id>\]/);
+ assert.match(usage(), /x-run fetches several X posts channels IN SEQUENCE/);
+ assert.match(usage(), /deferred until the next refresh/);
+});
+
// A report site's evidence media: a POST to its route, the body passed through
// untouched — the route judges the site id.
test("reports-prepare is a POST to its route, named in the usage", () => {