Archilyzer · Source

archilyzer

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

commit 9543fab0995a30f743abe1bb9b8fe3e274540691
parent af03455a1029f5e7a04edea3abe92ec80f3b0de1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 14:21:48 -0500

ops: x-run and get x-run -- the X run over HTTP, its replay a Resume

POST /api/ops/x-run {channels, limit?} | {resume}, GET /api/ops/x-run
[?run=] (the console's payload: the run's view, the X posts channels in the
default order, the jar against social.x.maxCookieAgeMinutes, X's gap).
`pnpm ops x-run` (--wait prints the @@x-run result) and `pnpm ops get
x-run`, with help; COMMANDS.md regenerated. The replay table's x-run entry
resumes the run its spec names, so Retry and "Re-run stopped jobs" after a
refresh take the deferred channels.

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

Diffstat:
MCOMMANDS.md | 11+++++++++++
Mcommon/controller/xRun.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aeditor/app/api/ops/x-run/route.test.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/x-run/route.ts | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 10++++++++++
Aeditor/app/review/xRunActions.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 40++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 16++++++++++++++++
8 files changed, 345 insertions(+), 2 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 &lt;platform&gt;" (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/&lt;id&gt;/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": "&lt;run id&gt;"} 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.ts b/common/controller/xRun.ts @@ -56,8 +56,8 @@ import { siteChannelIndex } from "../lib/site"; import { ulid } from "../jobs/ulid"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; -import { guardNetworkJob } from "../jobs/networkGuard"; -import { noteQueueJobEnd, queueGapClock, waitForQueueGap } from "../jobs/queueGap"; +import { guardNetworkJob, xSessionReport, type XSessionReport } from "../jobs/networkGuard"; +import { noteQueueJobEnd, queueGapClock, queueGapFor, waitForQueueGap } from "../jobs/queueGap"; import { requestChannelSnapshot } from "../jobs/snapshotScheduler"; import { fetchPosts } from "./fetchPosts"; @@ -737,3 +737,58 @@ export async function queueXRun(opts: { // 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/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/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/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/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", () => {