Archilyzer · Source

archilyzer

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

commit 1cf75802566e90aae960c3137e0bbe685dc96ec9
parent e2a485d9c59443cd6b9b022208cc3b5f662b13a7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 08:11:09 -0400

Merge lane/no-interruptions: interrupted jobs resume on boot (pnpm ops job resume-interrupted); reports refresh as items land; a channel's chat later (fetch-chat-backlog), subLangs + chat in Configure; downloads write transcript.cues.json

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

# Conflicts:
#	editor/CHANGELOG.md

Diffstat:
MCHANNEL.md | 3++-
MCOMMANDS.md | 11++++++++++-
MOPERATING.md | 44+++++++++++++++++++++++++++++++++++++++++++-
MSETTINGS.md | 19+++++++++++++++++++
Mcommon/bin/cli-docs.ts | 7+++++--
Mcommon/controller/attachMedia.ts | 4++++
Mcommon/controller/autoRunner.ts | 34++++++++++++++++++++++++++++++++++
Acommon/controller/chatBacklog.test.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/chatBacklog.ts | 438+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/laneChatBacklog.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/normalizeTranscript.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/controller/persistVideos.ts | 5+++++
Acommon/controller/writeCuesAfterDownload.test.ts | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/bootQueuedJobs.ts | 15++++++++++-----
Mcommon/jobs/jobKinds.test.ts | 27+++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 91++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/jobs/jobMeta.ts | 17+++++++++++++++++
Mcommon/jobs/registry.ts | 9+++++++++
Acommon/jobs/resumeInterrupted.test.ts | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/resumeInterrupted.ts | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/resumeTag.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/snapshotScheduler.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/snapshotScheduler.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/streamCommand.test.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/jobs/streamCommand.ts | 35+++++++++++++++++++++++++++++++++++
Mcommon/lib/channelConfig.ts | 54+++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Acommon/lib/jobsSettings.ts | 33+++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Mcommon/ytdlp/downloadOneManaged.ts | 19++++++++++++++++++-
Mcommon/ytdlp/runYtdlp.ts | 14+++++++++++++-
Meditor/CHANGELOG.md | 4++++
Aeditor/app/api/ops/fetch-chat-backlog/route.test.ts | 42++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/fetch-chat-backlog/route.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/job/route.test.ts | 27+++++++++++++++++++++++++++
Meditor/app/api/ops/job/route.ts | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aeditor/app/api/ops/transcribe-bucket/route.test.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/transcribe-bucket/route.ts | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/attachMediaActions.ts | 1+
Aeditor/app/channels/[slug]/chatBacklogActions.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/DownloadStage.tsx | 15++++++++++++++-
Meditor/app/channels/[slug]/normalizeActions.ts | 12++++++++++++
Meditor/app/channels/[slug]/persistActions.ts | 1+
Meditor/app/channels/[slug]/pipelineActions.ts | 27++++++++++++++++++++++++++-
Meditor/app/channels/[slug]/whisperActions.ts | 14+++++++++++---
Meditor/app/channels/components/ChannelForm.tsx | 41+++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/components/channelConfigToForm.ts | 5+++++
Meditor/app/channels/components/parseChannelForm.test.ts | 25+++++++++++++++++++++++++
Meditor/app/channels/components/parseChannelForm.ts | 17++++++++++++++++-
Meditor/app/jobs/jobReplayRegistry.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/chat-only.spec.ts | 39+++++++++++++++++++++++++++++++++++++++
Meditor/instrumentation.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mscripts/archilyzer-ops.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++--
Mscripts/archilyzer-ops.test.mjs | 14++++++++++++++
Msettings.json.example | 3+++
58 files changed, 2787 insertions(+), 59 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -32,7 +32,8 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `dataDir` | config | RETIRED (release 17). The whole-directory layout's record: the absolute path `channels/<slug>/data` was a symlink to. Still parsed for one release so a write never erases it: a channel that carries it — or whose `data/` is a link — is `legacy`, and every media job, lane and build holds it until `archilyzer storage migrate-tier <slug>` moves its text back and its media into `mediaDir`. Written only by the re-point of a storage location (which keeps it `<root>/<slug>/data` on the new root); removed by that migration. | | `mediaDir` | config | Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an "inconsistent" channel every media guard refuses. The text (`data/`) never moves. | | `ytdlpExtraArgs` | config | Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped. | -| `subLangs` | config | yt-dlp `--sub-langs` value for caption downloads. | +| `subLangs` | config | yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `"with-download"`. A Configure field. | +| `chat` | config | When a stream's live chat replay is fetched: `"with-download"` (default — with the captions, as a `live_chat` subtitle track), `"later"` (the downloads leave it out — each YouTube download of a streaming channel is 2–4× faster — and when the channel has nothing left to download, the download lane queues one paced, resumable `fetch-chat-backlog` job for its `was_live` streams' chats; `pnpm ops fetch-chat-backlog` runs it by hand) or `"never"` (left out; `pnpm ops fetch-chat` still fetches one). A Configure field. | | `lastSyncedAt` | sync state | SYNC STATE. When the channel last synced (ISO time). Stamped by every sync, and by a social fetch; read by the scheduler's cadence gate. | | `lastFullDownloadAt` | sync state | SYNC STATE. When a full download pass last completed (ISO time). | | `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -103,7 +103,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | action | what it does | example | |---|---|---| | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` | -| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). | `pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | +| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | | `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` | @@ -186,6 +186,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -&gt; {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` | | `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}'` | ### Usage, flags and environment @@ -201,6 +202,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] [--limit <n>] pnpm ops job cancel|drain|promote|force-release|retry <id>... [--wait] pnpm ops job retry-failed [--wait] + pnpm ops job resume-interrupted [<id>...] [--dry-run] [--wait] pnpm ops job wait <id>... [--wait-timeout <seconds>] pnpm ops get settings [<key>] pnpm ops get storage | sites | workers | auto-queue | scheduler @@ -236,6 +238,13 @@ job <verb> <id>... is a /jobs row's button: cancel (a running job is Each id is answered in "results"; one that could not be acted on makes the answer ok: false without stopping the rest. --wait follows the jobs a retry started. job wait <id>... follows jobs already running. +job resume-interrupted does by hand what the editor does at boot: re-queues + the jobs a restart interrupted (the last 24 h, or the ids named) whose kind + resumes on a re-run — an archive.org import, a download-missing, a posts + fetch, a persist, a transcription batch… Each once; never one interrupted + twice in a row, a dry run or a full posts re-walk; one superseded by a + newer job is left. --dry-run lists what it would re-queue (wouldResume) + and why the rest are not (notResumed), and changes nothing. get settings [<key>] is settings.json as the editor reads it (migrated and defaulted; a secret is "<redacted>"), or one top-level key of it. diff --git a/OPERATING.md b/OPERATING.md @@ -18,6 +18,25 @@ Recipes for running an archive from a shell or an agent. Every command named her - Every fetch goes through the editor (paced per platform, cookie-aware, provenanced). Never run yt-dlp, whisper or parakeet by hand, and never edit `transcripts/**` by hand: each file has one writer, named below. +### When the editor restarts + +```sh +pnpm ops job resume-interrupted --dry-run +pnpm ops job resume-interrupted +``` + +- A job that was waiting in its queue is re-queued at boot (never a sync: the scheduler re-derives those). +- A job that was RUNNING is closed "interrupted" and, when its kind continues on a re-run, resumed: an archive.org + import, an import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a + post capture, a cues pass, a report, a chat backlog (`resumeOnBoot` in `common/jobs/jobKinds.ts`). Its log + opens with `[resume] Resumes … job <id>`, and the old job's says which job resumed it. +- Not resumed, each with its reason on the old job: a kind that does not continue (Retry is one click), a job + interrupted twice in a row, a dry run, a full posts re-walk (`"full": true` starts over), one superseded by a + newer job with the same request, one whose re-queue was refused (a held platform). +- `jobs.resumeInterruptedOnBoot: false` turns the boot's resume off; an idle boot (`ARCHILYZER_IDLE_BOOT=1`) never + resumes. `pnpm ops job resume-interrupted` does it by hand over the last 24 hours (or the ids named); + `--dry-run` lists `wouldResume` and `notResumed` and changes nothing. + ## Add a channel ```sh @@ -54,6 +73,27 @@ pnpm ops persist-videos --json '{"items":[{"slug":"example","id":"<videoId>"}] (`"operation"` pins one operation's tier). - Bucket names and sizes: `pnpm ops get channel example`. - Keep videos out of cleanup by title or description: `pnpm ops keep-videos --json '{"slug":"example","match":"interview","dryRun":true}'`. +- A new caption download writes its `transcript.cues.json` as it lands (a umtool build reads it); `build-cues` + mends an older one. + +### A streaming channel: its chats after its downloads + +```sh +pnpm ops channel-config --json '{"slug":"example","patch":{"chat":"later"}}' +pnpm ops fetch-chat-backlog --json '{"slug":"example","dryRun":true}' +pnpm ops fetch-chat-backlog --json '{"slug":"example"}' --wait +``` + +- A stream's live chat replay (7–42 MB) rides its caption download by default and makes each YouTube download of a + streaming channel 2–4× slower. `chat` (Configure → Live chat replay): `"with-download"` (default), `"later"` or + `"never"` — the downloads leave the chat out for the last two. +- `"later"`: once the channel has nothing left to download, the download lane queues one `fetch-chat-backlog` job + for it — every held video whose metadata says it was a stream (`live_status` was_live) and whose chat is not here, + one at a time at the platform's pace, on its download queue, at most 25 a run. A re-run skips the chats here and the + streams known to have none (`chat-backlog.json`); a restart resumes it. The channel page's Download stage has + **Fetch chat backlog**; `dryRun` counts from the disk and starts nothing. +- The caption languages are a Configure field too (`subLangs`, yt-dlp's `--sub-langs`; blank = `en.*,live_chat`), + and a `channel-config` patch key. ### Cookies gone stale: the dashboard's banner @@ -336,7 +376,9 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150 off disk (the MCP's `get_transcript` does the same through the editor), and `pnpm ops build-cues --json '{"slug":"<slug>","ids":["<videoId>"]}' --wait` writes its `transcript.cues.json`. - The transcription lane takes every channel's downloaded, untranscribed audio; `transcribe-bucket` runs one - channel's now. + channel's now. Both read the channel's report: a job that adds items (an import, an attach, a persist, a download) + regenerates it as they land, and `transcribe-bucket` regenerates a report that is behind the disk before it + answers. - `transcribe` runs one local file (or a window of it) through the corpus's own engine and model; the result JSON (cues, text, and with `"words": true` the word timings parakeet keeps) is printed on stdout with `--wait`. `"out"` writes it to a file outside the corpus. diff --git a/SETTINGS.md b/SETTINGS.md @@ -54,6 +54,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`tts`](#tts) | object — see below | | [`generation`](#generation) | object — see below | | [`clips`](#clips) | object — see below | +| [`jobs`](#jobs) | object — see below | ## `adminTitle` @@ -1240,3 +1241,21 @@ Default: ] } ``` + +## `jobs` + +What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings. + +#### `jobs` + +| Key | Default | Description | +|---|---|---| +| `resumeInterruptedOnBoot` | `true` | When the editor starts, re-queue the jobs the previous process left RUNNING (closed "interrupted") whose kind resumes on a re-run — it skips what the first run finished: an archive.org import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report, a chat backlog (`resumeOnBoot` in common/jobs/jobKinds.ts). Each resumed job's log says which job it resumes. A job interrupted twice in a row is not resumed again, a dry run or a full re-walk never is, and an idle boot (ARCHILYZER_IDLE_BOOT) resumes nothing. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand. Default true. | + +Default: + +```json +{ + "resumeInterruptedOnBoot": true +} +``` diff --git a/common/bin/cli-docs.ts b/common/bin/cli-docs.ts @@ -200,8 +200,11 @@ export function unknownCommandsIn( ): string[] { const actions = new Set(opsActions(opsUsage)); const nouns = new Set([...opsUsage.matchAll(/pnpm ops get ([a-z][a-z-]*)/g)].map((m) => m[1])); - // `pnpm ops job <verb> <id>` (a /jobs row's button): the verbs its usage line lists. - const jobVerbs = new Set((/pnpm ops job ([a-z|-]+)/.exec(opsUsage)?.[1] ?? "").split("|").filter(Boolean)); + // `pnpm ops job <verb> <id>` (a /jobs row's button, retry-failed, + // resume-interrupted, wait): the verbs every `pnpm ops job …` usage line lists. + const jobVerbs = new Set( + [...opsUsage.matchAll(/pnpm ops job ([a-z|-]+)/g)].flatMap((m) => m[1].split("|")).filter(Boolean), + ); const bad = new Set<string>(); for (const m of markdown.matchAll(/pnpm ops ([^\s`'"]+)(?:[ \t]+([^\s`'"]+))?/g)) { const [, word, next] = m; diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts @@ -254,6 +254,9 @@ export type AttachMediaOptions = { fillDates?: boolean; dryRun?: boolean; onLog: (line: string) => void; + // A video's media landed (its record new or held): the job's itemLanded, + // so the channel's report — and the lanes reading it — see it at once. + onAttached?: (id: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; deps?: { @@ -558,6 +561,7 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia onLog(`${id}: the replaced container ${previous.file} removed`); } result.attached.push(id); + opts.onAttached?.(id); onLog(`${id}: attached ${pointer.file} (${formatBytes(pointer.bytes)}, sha256 ${copied.sha256.slice(0, 12)}…)`); } catch (err) { await rm(staging, { force: true }).catch(() => {}); diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -104,6 +104,7 @@ import { WaybackAutoPicker, type WaybackAutoPick, } from "./laneWaybackAuto"; +import { ChatBacklogLane } from "./laneChatBacklog"; import { isGateHeld } from "../lib/pauseGates"; import { inspectChannelMedia, @@ -1363,6 +1364,9 @@ async function runLoop( // `wayback.auto` channels' new scan rows (release 37 S2): read once a minute // per channel, each row offered once in this runner's life. const waybackAuto = WaybackAutoPicker.forPaths(paths); + // `chat: "later"` channels' chat backlogs (2026-10-26): one job per channel + // once it has nothing left to download, considered at most every 15 min. + const chatBacklogLane = ChatBacklogLane.forPaths(paths); // Platforms this tick may not touch — busy or cooling down. Hoisted out of the // download branch because the metadata-scan pre-pick honours it too: a // platform in a 429 cooldown must not be asked for 1,800 titles either. @@ -1741,6 +1745,36 @@ async function runLoop( ? focusSummary(ctx.model, ctx.focusSlugs, pending) : null; reportFocusHold(focus); + // ── A CHANNEL WITH NOTHING LEFT TO DOWNLOAD GETS ITS CHATS (2026-10-26) ── + // + // A `chat: "later"` channel's downloads leave the live chat out; once no + // video of it is pending here (before the platform gates: a cooling + // platform is not "done"), none is in flight and no metadata scan is owed, + // the lane queues one `fetch-chat-backlog` job for it on the platform's + // download queue, in the background (controller/laneChatBacklog.ts). + // Voided: the consideration reads two small files and never holds the tick. + if (kind === "download") { + const busy = new Set<string>(); + for (const ids of Object.values(pending)) { + for (const id of ids) { + const s = owner.get(id); + if (s) busy.add(s); + } + } + for (const unit of live.inFlight.values()) busy.add(unit.channelSlug); + const listed = new Set<string>(); + for (const c of channels) { + listed.add(c.slug); + if (c.filtered && (c.scanUnscanned ?? 0) > 0) busy.add(c.slug); + } + void chatBacklogLane + .consider(metaCache, { + idle: (slug) => listed.has(slug) && !busy.has(slug), + ...(focus ? { focus: { slugs: new Set(ctx.focusSlugs), holding: focus.holding } } : {}), + onLog, + }) + .catch(() => {}); + } // THE RUNNER JOB'S OWN BAR, on the metrics the per-channel jobs already // use — so a lane's runner row reads like the manual verb's row rather than // like an opaque long-lived loop. `target` moves as the corpus does (this diff --git a/common/controller/chatBacklog.test.ts b/common/controller/chatBacklog.test.ts @@ -0,0 +1,212 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/chatBacklog.test.ts +// +// A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26): the backlog job +// picks every held stream (by its metadata) whose chat is not here, fetches +// them one at a time through a stub runner (no yt-dlp, no network), remembers +// the streams that have none, and a second run asks for nothing it already +// knows. The lane's trigger is pure. Temp corpus only. + +const ROOT = await mkdtemp(path.join(tmpdir(), "chat-backlog-")); +const CORPUS = path.join(ROOT, "transcripts"); +process.env.TRANSCRIPTS_DIR = CORPUS; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(CORPUS, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); + +const { getPaths } = await import("../lib/paths"); +const { effectiveSubLangs } = await import("../lib/channelConfig"); +const { planChatBacklog, readChatBacklogState, runChatBacklog, CHAT_BACKLOG_FILENAME } = await import("./chatBacklog"); +const { ChatBacklogLane, chatBacklogDue, CHAT_BACKLOG_RECHECK_MS } = await import("./laneChatBacklog"); + +const paths = getPaths(); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SLUG = "synth-pod"; +const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth", name: "Synth", chat: "later" } as ChannelConfig; + +function chatLine(sec: number, text: string): string { + return JSON.stringify({ + replayChatItemAction: { + actions: [ + { addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: "v" } } } } }, + ], + videoOffsetTimeMsec: String(sec * 1000), + }, + }); +} +const REPLAY = [chatLine(5, "first"), chatLine(9, "second")].join("\n") + "\n"; + +async function video(id: string, meta: Record<string, unknown>, files: Record<string, string> = {}): Promise<void> { + const dir = path.join(CORPUS, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ id, title: `Episode ${id}`, webpage_url: `https://www.youtube.com/watch?v=${id}`, extractor_key: "Youtube", ...meta }), + ); + for (const [name, body] of Object.entries(files)) await writeFile(path.join(dir, name), body); +} + +// The stub yt-dlp: a replay for the ids in `withChat`, nothing for the rest. +function stub(withChat: Set<string>) { + const asked: string[] = []; + const run = async (cwd: string, args: string[]): Promise<AttemptOutcome> => { + const url = args[args.length - 1]; + const id = new URL(url).searchParams.get("v") ?? url; + asked.push(id); + const i = args.findIndex((a) => a.startsWith("subtitle:")); + if (withChat.has(id)) await writeFile(path.join(cwd, `${args[i].slice("subtitle:".length)}.live_chat.json`), REPLAY); + return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; + }; + return { run, asked }; +} + +await video("strm0000001", { live_status: "was_live", upload_date: "20251001" }); +await video("strm0000002", { live_status: "was_live", upload_date: "20251020" }); +await video("strm0000003", { was_live: true, upload_date: "20251010" }); +await video("upld0000001", { live_status: "not_live", upload_date: "20251015" }); +await video("strm0000004", { live_status: "post_live", upload_date: "20251005" }, { "transcript.live_chat.json": REPLAY }); + +test("effectiveSubLangs: the chat rides the download only when `chat` says so", () => { + assert.equal(effectiveSubLangs({}), "en.*,live_chat"); + assert.equal(effectiveSubLangs({ chat: "with-download", subLangs: "en,de,live_chat" }), "en,de,live_chat"); + assert.equal(effectiveSubLangs({ chat: "later" }), "en.*"); + assert.equal(effectiveSubLangs({ chat: "never", subLangs: "en.*, live_chat ,es" }), "en.*,es"); + assert.equal(effectiveSubLangs({ chat: "later", subLangs: "all" }), "all,-live_chat"); + assert.equal(effectiveSubLangs({ chat: "later", subLangs: "live_chat" }), "en.*"); +}); + +test("the plan: held streams whose chat is not here, newest first; a raw replay is only normalized", async () => { + const plan = await planChatBacklog(paths, SLUG, CONFIG); + assert.deepEqual( + plan.candidates.map((c) => [c.id, c.action]), + [ + ["strm0000002", "fetch"], + ["strm0000003", "fetch"], + ["strm0000004", "normalize"], + ["strm0000001", "fetch"], + ], + ); + assert.equal(plan.notStreams, 1); +}); + +test("a run: one chat at a time, the gap between two, none remembered; a second run asks for nothing", async () => { + const { run, asked } = stub(new Set(["strm0000002", "strm0000001"])); + const slept: number[] = []; + const landed: string[] = []; + const lines: string[] = []; + const result = await runChatBacklog({ + paths, + slug: SLUG, + config: CONFIG, + onLog: (l) => lines.push(l), + signal: new AbortController().signal, + run, + gapMs: () => 7000, + sleep: async (ms) => { + slept.push(ms); + }, + onChat: (id) => landed.push(id), + downloadedAtRun: 5, + }); + assert.deepEqual(asked, ["strm0000002", "strm0000003", "strm0000001"]); + assert.deepEqual(slept, [7000, 7000], "a gap between two requests, none before the first"); + assert.deepEqual(landed.sort(), ["strm0000001", "strm0000002", "strm0000004"]); + assert.equal(result.fetched, 2); + assert.equal(result.normalized, 1); + assert.equal(result.none, 1); + assert.equal(result.complete, true); + const state = await readChatBacklogState(paths, SLUG); + assert.equal(state.settled.strm0000003?.why, "no-chat"); + assert.equal(state.lastRun?.downloadedAtRun, 5); + assert.match(await readFile(path.join(CORPUS, "channels", SLUG, CHAT_BACKLOG_FILENAME), "utf8"), /"no-chat"/); + + const again = stub(new Set()); + const second = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, run: again.run, gapMs: () => 0 }); + assert.deepEqual(again.asked, []); + assert.equal(second.remaining, 0); + assert.equal(second.complete, true); +}); + +test("a run stops at its limit and a drain, and says what is left", async () => { + await video("strm0000010", { live_status: "was_live", upload_date: "20251101" }); + await video("strm0000011", { live_status: "was_live", upload_date: "20251102" }); + const { run, asked } = stub(new Set(["strm0000010", "strm0000011"])); + const limited = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, run, gapMs: () => 0, limit: 1 }); + assert.deepEqual(asked, ["strm0000011"]); + assert.equal(limited.complete, false); + assert.equal(limited.remaining, 1); + assert.match(limited.stopped ?? "", /limit \(1\)/); + const drain = new AbortController(); + drain.abort(); + const drained = await runChatBacklog({ paths, slug: SLUG, config: CONFIG, onLog: () => {}, signal: new AbortController().signal, drainSignal: drain.signal, run, gapMs: () => 0 }); + assert.equal(drained.stopped, "drained"); + assert.equal(drained.remaining, 1); +}); + +test("the lane's trigger: due with no run, after new downloads, or after an unfinished run has rested", () => { + const now = Date.parse("2026-10-26T12:00:00Z"); + const run = (o: Partial<{ complete: boolean; endedAt: string; downloadedAtRun: number }>) => ({ + version: 1 as const, + settled: {}, + lastRun: { + startedAt: "2026-10-26T11:00:00Z", + endedAt: o.endedAt ?? "2026-10-26T11:55:00Z", + complete: o.complete ?? true, + fetched: 0, + normalized: 0, + none: 0, + failed: 0, + remaining: 0, + ...(o.downloadedAtRun !== undefined ? { downloadedAtRun: o.downloadedAtRun } : {}), + }, + }); + assert.equal(chatBacklogDue({ version: 1, settled: {} }, 10, now), true); + assert.equal(chatBacklogDue(run({ downloadedAtRun: 10 }), 10, now), false); + assert.equal(chatBacklogDue(run({ downloadedAtRun: 10 }), 12, now), true); + assert.equal(chatBacklogDue(run({ complete: false, downloadedAtRun: 10 }), 10, now), false, "rested 5 min of 15"); + assert.equal( + chatBacklogDue(run({ complete: false, downloadedAtRun: 10, endedAt: new Date(now - CHAT_BACKLOG_RECHECK_MS).toISOString() }), 10, now), + true, + ); +}); + +test("the lane queues one backlog per idle `later` channel, at most once per recheck", async () => { + let now = 1_000_000; + const started: string[] = []; + const lane = new ChatBacklogLane({ + now: () => now, + readState: async () => ({ version: 1, settled: {} }), + downloadedOf: async () => 3, + isActive: () => false, + start: async (slug) => { + started.push(slug); + return { ok: true, jobId: `J-${slug}`, stream: new ReadableStream<string>(), done: new Promise(() => {}) }; + }, + }); + const later = { ...CONFIG, chat: "later" } as ChannelConfig; + const channels = [ + { slug: "a", config: later }, + { slug: "b", config: later }, + { slug: "c", config: { ...CONFIG, chat: undefined } as ChannelConfig }, + { slug: "d", config: later }, + ]; + const lines: string[] = []; + await lane.consider(channels, { idle: (s) => s !== "b", focus: { slugs: new Set(["a", "b", "c"]), holding: true }, onLog: (l) => lines.push(l) }); + assert.deepEqual(started, ["a"], "b has downloads left, c fetches chat with its downloads, d is outside the focus"); + assert.match(lines[0], /a has nothing left to download; queued its chat backlog \(job J-a/); + await lane.consider(channels, { idle: () => true }); + assert.deepEqual(started, ["a", "b", "d"], "a was considered moments ago"); + now += CHAT_BACKLOG_RECHECK_MS; + await lane.consider(channels, { idle: () => true }); + assert.deepEqual(started, ["a", "b", "d", "a", "b", "d"]); +}); diff --git a/common/controller/chatBacklog.ts b/common/controller/chatBacklog.ts @@ -0,0 +1,438 @@ +// A CHANNEL'S STREAM CHATS, FETCHED AFTER ITS DOWNLOADS (2026-10-26) — the +// `fetch-chat-backlog` job: `pnpm ops fetch-chat-backlog {slug}`, and the +// download lane's own for a channel whose `chat` is "later" once it has nothing +// left to download (controller/laneChatBacklog.ts). +// +// WHY. A stream's live chat replay is 7–42 MB and came down with its captions, +// which made each YouTube download of a streaming channel 2–4× slower while +// the Ethanalyzer backlog was archived (2026-10-23…26). The fix then was a hand +// edit of `subLangs` and a hand-written watcher that waited for the downloads +// and ran `pnpm ops fetch-chat` per streamed episode — and died on reboot. A +// `chat: "later"` channel's downloads leave the chat out (effectiveSubLangs), +// and this job fetches the chats afterwards. +// +// WHICH VIDEOS. Every held video whose metadata says it was a stream +// (`live_status` was_live / post_live, or `was_live: true`) and whose chat is +// not here — selected by the METADATA, because a download without `live_chat` +// in its sub-langs records no chat track to look for. A raw replay already on +// disk is only normalized. Newest first. +// +// PACED AND RESUMABLE. One chat at a time through fetchLiveChat (the one +// chat-only pass: the channel's cookies, the platform's live pace), on the +// platform's download queue, with the batch downloads' gap between two +// (downloadGapMs). It stops on a rate limit (the platform's cooldown recorded), +// a held platform, three failures in a row, a drain or `limit` chats; a re-run +// skips every chat already here and every stream already known to have none — +// `chat-backlog.json` beside the channel's config remembers those, and what the +// last run did. Replayable, and resumed after a restart (jobs/jobKinds.ts). + +import path from "node:path"; +import { readdir, readFile } from "node:fs/promises"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import type { ResolvedCookiePolicy } from "../lib/cookiePolicy"; +import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys"; +import { getSettings } from "../lib/settings"; +import { META_FILENAME } from "../lib/videoStatus"; +import { + heldPlatformRefusal, + platformCooldownRemainingMs, + recordDownloadBackoff, + recordPlatformClean, +} from "../jobs/downloadBackoff"; +import { downloadGapMs } from "../jobs/platformBackoff"; +import { getRegistry } from "../jobs/registry"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { + channelPaceSeconds, + channelPlatform, + platformMinGapSeconds, + staticSleepRequestsSeconds, +} from "../ytdlp/channelArgs"; +import { fetchLiveChat, liveChatPlan, noChatFetcherSentence, type ChatRunner } from "./fetchLiveChat"; +import { normalizeLiveChat } from "./normalizeLiveChat"; +import { readChannelSnapshotShared } from "./channels"; + +export const FETCH_CHAT_BACKLOG_KIND = "fetch-chat-backlog"; +export const CHAT_BACKLOG_FILENAME = "chat-backlog.json"; +// Three failures in a row (not a rate limit) stop a run: the source is saying +// something a fourth request will not change. +export const CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW = 3; + +const STREAM_STATUSES = new Set(["was_live", "post_live"]); + +export type ChatBacklogState = { + version: 1; + // Streams whose chat the source does not have (replay off, or never live + // after all), and those with no chat fetcher: never asked again. + settled: Record<string, { at: string; why: "no-chat" | "not-live" | "no-fetcher" }>; + lastRun?: { + jobId?: string; + startedAt: string; + endedAt: string; + // Every stream's chat is here or settled. + complete: boolean; + fetched: number; + normalized: number; + none: number; + failed: number; + remaining: number; + stopped?: string; + // The channel report's downloaded count the run started from: the lane + // queues the next run when it moves. + downloadedAtRun?: number; + }; +}; + +function statePath(paths: Paths, slug: string): string { + return path.join(paths.channelsDir, slug, CHAT_BACKLOG_FILENAME); +} + +export async function readChatBacklogState(paths: Paths, slug: string): Promise<ChatBacklogState> { + const read = await readJsonFile(statePath(paths, slug)); + const v = read.ok ? (read.value as Partial<ChatBacklogState>) : null; + return { + version: 1, + settled: v && v.settled && typeof v.settled === "object" ? v.settled : {}, + ...(v?.lastRun && typeof v.lastRun === "object" ? { lastRun: v.lastRun } : {}), + }; +} + +async function writeChatBacklogState(paths: Paths, slug: string, state: ChatBacklogState): Promise<void> { + await writeJsonAtomic(statePath(paths, slug), state); +} + +async function streamInfo(videoDir: string): Promise<{ live: string | null; date: string }> { + try { + const meta = JSON.parse(await readFile(path.join(videoDir, META_FILENAME), "utf8")) as { + live_status?: unknown; + was_live?: unknown; + upload_date?: unknown; + release_date?: unknown; + }; + const live = meta.was_live === true ? "was_live" : typeof meta.live_status === "string" ? meta.live_status : null; + const date = typeof meta.upload_date === "string" ? meta.upload_date : typeof meta.release_date === "string" ? meta.release_date : ""; + return { live, date }; + } catch { + return { live: null, date: "" }; + } +} + +export type ChatBacklogCandidate = { id: string; date: string; action: "fetch" | "normalize"; url?: string; platform?: string }; + +export type ChatBacklogPlan = { + candidates: ChatBacklogCandidate[]; + // Streams whose chat is already here (fresh live_chat.cues.json). + have: number; + // Streams known to have none (chat-backlog.json `settled`). + settled: number; + // Held videos that were not streams. + notStreams: number; +}; + +// What the job would do, from the disk alone (no request): every held stream +// whose chat is neither here nor settled, newest first. +export async function planChatBacklog( + paths: Paths, + slug: string, + config: ChannelConfig, + state?: ChatBacklogState, +): Promise<ChatBacklogPlan> { + const known = state ?? (await readChatBacklogState(paths, slug)); + const dataDir = path.join(paths.channelsDir, slug, "data"); + let ids: string[]; + try { + ids = (await readdir(dataDir, { withFileTypes: true })) + .filter((e) => e.isDirectory() || e.isSymbolicLink()) + .map((e) => e.name); + } catch { + ids = []; + } + const plan: ChatBacklogPlan = { candidates: [], have: 0, settled: 0, notStreams: 0 }; + for (const id of ids) { + if (known.settled[id]) { + plan.settled++; + continue; + } + const { live, date } = await streamInfo(path.join(dataDir, id)); + if (!live || !STREAM_STATUSES.has(live)) { + plan.notStreams++; + continue; + } + const p = await liveChatPlan(paths, slug, id, config); + if (p.kind === "fresh") plan.have++; + else if (p.kind === "normalize") plan.candidates.push({ id, date, action: "normalize" }); + else if (p.kind === "fetch") plan.candidates.push({ id, date, action: "fetch", url: p.url, platform: p.platform }); + else if (p.kind === "no-fetcher" || p.kind === "not-live") plan.settled++; + } + plan.candidates.sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); + return plan; +} + +export type ChatBacklogResult = NonNullable<ChatBacklogState["lastRun"]>; + +export type RunChatBacklogOpts = { + paths: Paths; + slug: string; + config: ChannelConfig; + cookiePolicy?: ResolvedCookiePolicy; + onLog: (line: string) => void; + signal: AbortSignal; + drainSignal?: AbortSignal; + limit?: number; + jobId?: string; + downloadedAtRun?: number; + // A chat landed (fetched or normalized): the job's itemLanded. + onChat?: (id: string) => void; + // Test seams. + run?: ChatRunner; + sleep?: (ms: number, signal: AbortSignal) => Promise<void>; + gapMs?: () => number; + now?: () => Date; +}; + +function sleepFor(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal.aborted || ms <= 0) return resolve(); + const t = setTimeout(resolve, ms); + signal.addEventListener("abort", () => { + clearTimeout(t); + resolve(); + }, { once: true }); + }); +} + +export async function runChatBacklog(opts: RunChatBacklogOpts): Promise<ChatBacklogResult> { + const now = opts.now ?? (() => new Date()); + const sleep = opts.sleep ?? sleepFor; + const startedAt = now().toISOString(); + const state = await readChatBacklogState(opts.paths, opts.slug); + const plan = await planChatBacklog(opts.paths, opts.slug, opts.config, state); + opts.onLog( + `Chat backlog of ${opts.slug}: ${plan.candidates.length} stream chat(s) to get` + + ` (${plan.candidates.filter((c) => c.action === "normalize").length} already on disk, only normalized);` + + ` ${plan.have} here, ${plan.settled} known to have none, ${plan.notStreams} video(s) not streams.` + + (opts.limit ? ` At most ${opts.limit} this run.` : ""), + ); + const result: ChatBacklogResult = { + ...(opts.jobId ? { jobId: opts.jobId } : {}), + startedAt, + endedAt: startedAt, + complete: false, + fetched: 0, + normalized: 0, + none: 0, + failed: 0, + remaining: plan.candidates.length, + ...(opts.downloadedAtRun !== undefined ? { downloadedAtRun: opts.downloadedAtRun } : {}), + }; + const save = async () => { + result.endedAt = now().toISOString(); + state.lastRun = { ...result }; + await writeChatBacklogState(opts.paths, opts.slug, state); + }; + // The batch downloads' gap between two videos (runYtdlp's subtitle pass + // takes the same): the pause, plus the platform's pace above its base. + const sleepSeconds = opts.config.sleepBetweenDownloadsSeconds ?? getSettings().sleepBetweenDownloadsSeconds; + const platformOfChannel = channelPlatform(opts.config); + const gapMs = + opts.gapMs ?? + (() => + downloadGapMs( + sleepSeconds, + channelPaceSeconds(opts.config), + staticSleepRequestsSeconds(platformOfChannel), + { minSeconds: platformMinGapSeconds(platformOfChannel) }, + )); + let fetchedOnce = false; + let failuresInARow = 0; + let attempted = 0; + for (const c of plan.candidates) { + if (opts.signal.aborted) { + result.stopped = "cancelled"; + break; + } + if (opts.drainSignal?.aborted) { + result.stopped = "drained"; + break; + } + if (opts.limit && attempted >= opts.limit) { + result.stopped = `the run's limit (${opts.limit})`; + break; + } + attempted++; + const videoDir = path.join(opts.paths.channelsDir, opts.slug, "data", c.id); + try { + if (c.action === "normalize") { + const out = await normalizeLiveChat({ + videoDir, + channelSlug: opts.slug, + ...(opts.config.name ? { configName: opts.config.name } : {}), + force: true, + log: (m) => opts.onLog(`${m}\n`), + }); + if (out.status !== "skipped") { + result.normalized++; + opts.onChat?.(c.id); + } + result.remaining--; + continue; + } + const platform = c.platform ?? "youtube"; + const held = await heldPlatformRefusal(platform, "The chat backlog", opts.paths); + if (held) { + result.stopped = held; + break; + } + const cooling = await platformCooldownRemainingMs(platform, opts.paths); + if (cooling > 0) { + result.stopped = `${platform} is in a rate-limit cooldown (${Math.ceil(cooling / 1000)}s remaining)`; + break; + } + if (fetchedOnce) { + const ms = gapMs(); + if (ms > 0) { + opts.onLog(`Sleeping ${Math.round(ms / 1000)}s before the next chat...`); + await sleep(ms, AbortSignal.any([opts.signal, ...(opts.drainSignal ? [opts.drainSignal] : [])])); + if (opts.signal.aborted || opts.drainSignal?.aborted) { + result.stopped = opts.signal.aborted ? "cancelled" : "drained"; + break; + } + } + } + fetchedOnce = true; + const out = await fetchLiveChat({ + paths: opts.paths, + slug: opts.slug, + videoId: c.id, + videoUrl: c.url!, + channelConfig: opts.config, + ...(opts.cookiePolicy ? { cookiePolicy: opts.cookiePolicy } : {}), + onLog: opts.onLog, + signal: opts.signal, + onPlatformBackoff: () => recordDownloadBackoff(platform, opts.paths), + onPlatformClean: () => recordPlatformClean(platform, opts.paths), + ...(opts.run ? { run: opts.run } : {}), + }); + failuresInARow = 0; + result.remaining--; + if (out.status === "fetched") { + result.fetched++; + opts.onChat?.(c.id); + } else { + result.none++; + state.settled[c.id] = { at: now().toISOString(), why: "no-chat" }; + } + } catch (err) { + const message = (err as Error).message; + if (opts.signal.aborted) { + result.stopped = "cancelled"; + break; + } + result.failed++; + failuresInARow++; + opts.onLog(`${c.id}: ${message}`); + if (/rate-limited/i.test(message)) { + result.stopped = "a rate limit (the platform's cooldown is recorded)"; + break; + } + if (failuresInARow >= CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW) { + result.stopped = `${CHAT_BACKLOG_MAX_FAILURES_IN_A_ROW} failures in a row`; + break; + } + } + } + result.complete = result.remaining === 0; + await save(); + opts.onLog( + `Chat backlog of ${opts.slug}: ${result.fetched} fetched, ${result.normalized} normalized, ${result.none} with no chat, ` + + `${result.failed} failed; ${result.remaining} left${result.stopped ? ` — stopped: ${result.stopped}` : ""}.`, + ); + return result; +} + +// Is a backlog job of this channel queued or running? +export function activeChatBacklogJob(slug: string): string | null { + const live = getRegistry() + .list() + .find((j) => j.kind === FETCH_CHAT_BACKLOG_KIND && j.channelSlug === slug && (j.status === "queued" || j.status === "running")); + return live?.id ?? null; +} + +export type StartChatBacklogOpts = { + paths: Paths; + slug: string; + config: ChannelConfig; + cookiePolicy: ResolvedCookiePolicy; + limit?: number; + queueKey?: string; + // The download lane's: behind any foreground job on the queue. + background?: boolean; + downloadedAtRun?: number; + run?: ChatRunner; +}; + +// THE JOB. Every refusal before any job, in the sentences the rest of the +// app uses: a channel whose text cannot be read, one already running a +// backlog, a held platform or one cooling down (`info`: the source is resting). +export async function startChatBacklogJob(opts: StartChatBacklogOpts): Promise<StreamActionResult> { + const { paths, slug, config } = opts; + try { + await assertChannelTextReadable(paths, slug, config); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const active = activeChatBacklogJob(slug); + if (active) return { ok: false, info: true, error: `a chat backlog of ${slug} is already queued or running (job ${active})` }; + const platform = channelPlatform(config) ?? "unknown"; + if (platform !== "youtube") return { ok: false, info: true, error: noChatFetcherSentence(platform) }; + const held = await heldPlatformRefusal(platform, "The chat backlog", paths); + if (held) return { ok: false, info: true, error: held }; + const remainingMs = await platformCooldownRemainingMs(platform, paths); + if (remainingMs > 0) { + return { + ok: false, + info: true, + error: `${platform} is in a rate-limit cooldown (${Math.ceil(remainingMs / 1000)}s remaining). The chat backlog can run once it lapses.`, + }; + } + return runManagedFunction({ + kind: FETCH_CHAT_BACKLOG_KIND, + queueKey: resolveQueueKey(downloadQueueKey(config), opts.queueKey), + paths, + channelSlug: slug, + ...(opts.background ? { background: true } : {}), + spec: { + kind: FETCH_CHAT_BACKLOG_KIND, + slug, + params: { + ...(opts.limit ? { limit: opts.limit } : {}), + ...(opts.queueKey ? { queueKey: opts.queueKey } : {}), + }, + }, + fn: async (onLog, signal, _progress, ctx) => { + const result = await runChatBacklog({ + paths, + slug, + config, + cookiePolicy: opts.cookiePolicy, + onLog, + signal, + drainSignal: ctx.drainSignal, + jobId: ctx.jobId, + ...(opts.limit ? { limit: opts.limit } : {}), + // The report's downloaded count this run starts from (the lane's + // "has anything been downloaded since?"). + downloadedAtRun: + opts.downloadedAtRun ?? (await readChannelSnapshotShared(paths, slug))?.totals?.downloaded, + onChat: () => ctx.itemLanded(), + ...(opts.run ? { run: opts.run } : {}), + }); + if (result.failed > 0 && result.fetched + result.normalized + result.none === 0 && !result.stopped?.startsWith("the run's limit")) { + throw new Error(`${result.failed} chat fetch(es) failed and none landed${result.stopped ? ` — stopped: ${result.stopped}` : ""}`); + } + }, + }); +} diff --git a/common/controller/laneChatBacklog.ts b/common/controller/laneChatBacklog.ts @@ -0,0 +1,119 @@ +// `chat: "later"` IN THE DOWNLOAD LANE (2026-10-26): once a channel that +// fetches its chats later has nothing left to download, the lane queues ONE +// `fetch-chat-backlog` job for it (controller/chatBacklog.ts) — paced, +// resumable, on the platform's download queue as a BACKGROUND job, so a click +// jumps ahead of it, and capped at CHAT_BACKLOG_LANE_LIMIT chats a run so the +// platform's queue is handed back to the downloads between runs. It replaces +// the hand-written watcher that waited for a channel's downloads to finish and +// then ran `pnpm ops fetch-chat` per streamed episode (and died on reboot). +// +// WHEN. A channel is considered at most once per CHAT_BACKLOG_RECHECK_MS, and +// queued only when no backlog of it is queued or running and its last run's +// record (`chat-backlog.json`) says there may be work: no run yet, a run that +// stopped before the end (a limit, a rate limit, a drain) and ended more than +// the recheck ago, or a channel report whose downloaded count has moved since +// the last run began. Never for a channel outside a holding focus (the lane's +// own rule), and never for a paused one (the lane's channel list leaves those +// out). A refusal (a held platform, a cooldown) is the action's own sentence +// in the lane's log, once per consideration. + +import type { ChannelConfig } from "../lib/channelConfig"; +import { resolveCookiePolicy } from "../lib/cookiePolicy"; +import type { Paths } from "../lib/paths"; +import { getSettings } from "../lib/settings"; +import type { StreamActionResult } from "../jobs/streamCommand"; +import { activeChatBacklogJob, readChatBacklogState, startChatBacklogJob, type ChatBacklogState } from "./chatBacklog"; +import { readChannelSnapshotShared } from "./channels"; + +export const CHAT_BACKLOG_RECHECK_MS = 15 * 60 * 1000; +export const CHAT_BACKLOG_LANE_LIMIT = 25; + +export type ChatBacklogLaneDeps = { + now?: () => number; + readState?: (slug: string) => Promise<ChatBacklogState>; + downloadedOf?: (slug: string) => Promise<number | undefined>; + isActive?: (slug: string) => boolean; + start?: (slug: string, config: ChannelConfig, downloadedAtRun: number | undefined) => Promise<StreamActionResult>; +}; + +// Should a backlog run start now, by the channel's last run and its report? +export function chatBacklogDue( + state: ChatBacklogState, + downloaded: number | undefined, + now: number, + recheckMs = CHAT_BACKLOG_RECHECK_MS, +): boolean { + const last = state.lastRun; + if (!last) return true; + if (downloaded !== undefined && last.downloadedAtRun !== downloaded) return true; + if (!last.complete) return now - Date.parse(last.endedAt) >= recheckMs; + return false; +} + +export class ChatBacklogLane { + private readonly considered = new Map<string, number>(); + constructor(private readonly deps: Required<ChatBacklogLaneDeps>) {} + + static forPaths(paths: Paths, deps: ChatBacklogLaneDeps = {}): ChatBacklogLane { + return new ChatBacklogLane({ + now: deps.now ?? Date.now, + readState: deps.readState ?? ((slug) => readChatBacklogState(paths, slug)), + downloadedOf: + deps.downloadedOf ?? + (async (slug) => (await readChannelSnapshotShared(paths, slug))?.totals?.downloaded), + isActive: deps.isActive ?? ((slug) => activeChatBacklogJob(slug) !== null), + start: + deps.start ?? + ((slug, config, downloadedAtRun) => + startChatBacklogJob({ + paths, + slug, + config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + limit: CHAT_BACKLOG_LANE_LIMIT, + background: true, + ...(downloadedAtRun !== undefined ? { downloadedAtRun } : {}), + })), + }); + } + + // The channels with nothing left to download this tick (`idle`), in the + // lane's order. Starts at most one job per channel; answers the ones it + // started. + async consider( + channels: ReadonlyArray<{ slug: string; config: ChannelConfig }>, + opts: { + idle: (slug: string) => boolean; + focus?: { slugs: ReadonlySet<string>; holding: boolean }; + onLog?: (line: string) => void; + }, + ): Promise<string[]> { + const started: string[] = []; + const now = this.deps.now(); + for (const c of channels) { + if (c.config.chat !== "later") continue; + if (opts.focus?.holding && !opts.focus.slugs.has(c.slug)) continue; + if (!opts.idle(c.slug)) continue; + const at = this.considered.get(c.slug); + if (at !== undefined && now - at < CHAT_BACKLOG_RECHECK_MS) continue; + this.considered.set(c.slug, now); + if (this.deps.isActive(c.slug)) continue; + const downloaded = await this.deps.downloadedOf(c.slug).catch(() => undefined); + const state = await this.deps.readState(c.slug).catch(() => null); + if (!state || !chatBacklogDue(state, downloaded, now)) continue; + const res = await this.deps.start(c.slug, c.config, downloaded).catch( + (err) => ({ ok: false, error: (err as Error).message }) as StreamActionResult, + ); + if (res.ok) { + void res.stream.cancel(); + started.push(c.slug); + opts.onLog?.( + `Auto-download: ${c.slug} has nothing left to download; queued its chat backlog (job ${res.jobId}, at most ${CHAT_BACKLOG_LANE_LIMIT} chats).`, + ); + } else { + opts.onLog?.(`Auto-download: ${c.slug}'s chat backlog not queued: ${res.error}`); + } + } + return started; + } +} diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts @@ -106,6 +106,42 @@ export async function normalizeTranscript( return { status: "wrote", cuesPath }; } +// THE CUES OF A DOWNLOAD THAT JUST LANDED (2026-10-26). A youtube-handling +// download fetches captions with --skip-download and never reaches +// transcribeOne — the one automatic caller of normalizeTranscript before this — +// so a fresh caption download had transcript.en(-orig).vtt and no +// transcript.cues.json until someone ran the normalize pass (`pnpm ops +// build-cues`, the digest card's Normalize, or the corpus-wide pass on /sites: +// that is where every older video got its file). umtool's build refused such a +// video ("clip-no-cues"). The managed download's end and the caption-only pass +// call this, so a new download is build-ready the moment it lands. +// +// The same normalize the pass runs (a fresh cues.json is left alone, so a +// transcription that already wrote one costs a readdir and a stat). Never +// throws: the download succeeded, and a cues file that could not be written is +// a line in its log, which the normalize pass can still mend. +export async function writeCuesAfterDownload(opts: { + videoDir: string; + channelSlug: string; + configName?: string; + onLog: (line: string) => void; +}): Promise<NormalizeOutcome | null> { + try { + return await normalizeTranscript({ + videoDir: opts.videoDir, + channelSlug: opts.channelSlug, + ...(opts.configName ? { configName: opts.configName } : {}), + log: (m) => opts.onLog(`${m}\n`), + }); + } catch (err) { + opts.onLog( + `Could not write ${CUES_JSON_FILENAME} for ${path.basename(opts.videoDir)}: ${(err as Error).message} ` + + `(the normalize pass — pnpm ops build-cues — can write it later)\n`, + ); + return null; + } +} + // WHAT normalizeTranscript WOULD WRITE, built in memory and not written: the // summary from metadata.info.json and the cues of the transcript the index // would pick (the caption-track rule for VTTs). Shared by normalize and by a diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts @@ -332,6 +332,7 @@ export async function persistVideos({ minFreeMemMb = 0, dryRun = false, onLog, + onPersisted, signal, drainSignal, deps: depsOverride, @@ -348,6 +349,9 @@ export async function persistVideos({ minFreeMemMb?: number; dryRun?: boolean; onLog?: (line: string) => void; + // A video persisted (its record may be new): the job's itemLanded, so the + // channel's report sees it while the run goes on. + onPersisted?: (item: { slug: string; id: string }) => void; signal?: AbortSignal; drainSignal?: AbortSignal; deps?: Partial<PersistVideosDeps>; @@ -519,6 +523,7 @@ export async function persistVideos({ result.replaced.push({ slug: p.slug, id: p.id }); } result.persisted.push({ slug: p.slug, id: p.id }); + onPersisted?.({ slug: p.slug, id: p.id }); } log( diff --git a/common/controller/writeCuesAfterDownload.test.ts b/common/controller/writeCuesAfterDownload.test.ts @@ -0,0 +1,60 @@ +// A download that just landed gets its transcript.cues.json (2026-10-26): the +// caption download never reached the normalize, so umtool refused the video +// ("clip-no-cues") until `pnpm ops build-cues` ran by hand. +// +// Run with: node_modules/.bin/tsx --test common/controller/writeCuesAfterDownload.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { isCuesJsonFresh, writeCuesAfterDownload } from "./normalizeTranscript"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "cues-after-download-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const VTT = readFileSync(path.join(import.meta.dirname, "..", "lib", "__fixtures__", "vtt-cue-blocks.vtt"), "utf8"); +const META = { + id: "vid", + title: "A video", + upload_date: "20261024", + duration: 30, + webpage_url: "https://www.youtube.com/watch?v=vid", + extractor_key: "Youtube", +}; + +let n = 0; +function videoDir(files: Record<string, string>): string { + const dir = path.join(ROOT, `c${n}`, "data", `vid${n++}`); + mkdirSync(dir, { recursive: true }); + for (const [name, body] of Object.entries(files)) writeFileSync(path.join(dir, name), body); + return dir; +} + +test("a caption download's VTT becomes a fresh transcript.cues.json, said in the log", async () => { + const dir = videoDir({ "metadata.info.json": JSON.stringify(META), "transcript.en-orig.vtt": VTT }); + const lines: string[] = []; + const out = await writeCuesAfterDownload({ videoDir: dir, channelSlug: "c", onLog: (l) => lines.push(l) }); + assert.equal(out?.status, "wrote"); + assert.ok(existsSync(path.join(dir, "transcript.cues.json"))); + assert.equal((await isCuesJsonFresh(dir)).fresh, true); + assert.match(lines.join(""), /Normalized c\/vid\d+ \(transcript\.en-orig\.vtt, \d+ cues\)/); + // Again: fresh, nothing rewritten. + assert.equal((await writeCuesAfterDownload({ videoDir: dir, channelSlug: "c", onLog: () => {} }))?.status, "fresh"); +}); + +test("a download with no transcript (audio for transcription) is skipped, not an error", async () => { + const dir = videoDir({ "metadata.info.json": JSON.stringify(META), "audio.mp3": "x" }); + const out = await writeCuesAfterDownload({ videoDir: dir, channelSlug: "c", onLog: () => {} }); + assert.deepEqual(out, { status: "skipped", reason: "no-raw-transcript" }); + assert.equal(existsSync(path.join(dir, "transcript.cues.json")), false); +}); + +test("a metadata file it cannot read is a log line and null — the download is not failed", async () => { + const dir = videoDir({ "metadata.info.json": "{not json", "transcript.en.vtt": VTT }); + const lines: string[] = []; + const out = await writeCuesAfterDownload({ videoDir: dir, channelSlug: "c", onLog: (l) => lines.push(l) }); + assert.equal(out, null); + assert.match(lines.join(""), /Could not write transcript\.cues\.json for vid\d+: .*pnpm ops build-cues/); +}); diff --git a/common/jobs/bootQueuedJobs.ts b/common/jobs/bootQueuedJobs.ts @@ -39,9 +39,12 @@ import { isPublishStageJobKind } from "./jobKinds"; // writer is gone (`writerIsGone`: another live process — `archilyzer run` — // writes into the same `.jobs/`) are touched: the storage boot pass can // enqueue a job of its own while this runs. `running` metas are not re-queued -// — whether a job that was mid-flight should be re-run is not a decision a -// boot pass can make — but they are CLOSED, by the second pass below -// (`settleRunningJobMetas`, release 17 slice D0). A malformed meta +// here; they are CLOSED, by the second pass below (`settleRunningJobMetas`, +// release 17 slice D0), and the resume pass (jobs/resumeInterrupted.ts, +// 2026-10-26) re-queues the ones whose kind continues on a re-run. A meta is +// rewritten `running` when its job starts (streamCommand.ts openJobLog), so a +// job that waited in its queue and then died mid-run is no longer read here +// as one that never started. A malformed meta // (readJobMeta → null) is skipped. // // Best-effort throughout: a meta that cannot be read or written is skipped, @@ -400,8 +403,10 @@ async function closeMeta( // read `running`. // // Each is CLOSED as the queued pass closes one — `cancelled`, with -// INTERRUPTED_REASON — never re-run (whether a half-finished job should run -// again is the operator's call; Retry is one click). There is no separate +// INTERRUPTED_REASON. This pass re-runs nothing: the resume pass +// (jobs/resumeInterrupted.ts) re-queues the ones whose kind declares +// `resumeOnBoot` — a re-run continues them — and every other one is the +// operator's call (Retry is one click). There is no separate // `interrupted` status: `cancelled` + `cancelReason` is the terminal state this // file already writes for "the server went down under it", and every reader of // a meta (listJobs, /jobs, Retry) already handles it. `endedAt` is the job diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -2,6 +2,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { isDrainableKind, + resumeOnBootKindIds, jobKindLabel, getJobKind, kindNeedsMedia, @@ -365,6 +366,7 @@ test("pacing guard: the kinds that make platform requests are network kinds", () "record-live", "persist-videos", "fetch-chat", + "fetch-chat-backlog", "auto-download-unit", "check-availability", "import-page", @@ -383,3 +385,28 @@ test("pacing guard: the kinds that make platform requests are network kinds", () assert.equal(kindIsNetwork("auto-download"), false); for (const k of jobKindIds()) assert.equal(typeof kindIsNetwork(k), "boolean"); }); + +// 2026-10-26: what a restart interrupted is resumed only for a kind that is +// replayable AND continues on a re-run (jobs/resumeInterrupted.ts). +test("resumeOnBoot: exactly the kinds that continue on a re-run, every one replayable", () => { + assert.deepEqual(resumeOnBootKindIds().sort(), [ + "capture-posts", + "download-missing", + "fetch-chat-backlog", + "fetch-posts", + "fetch-windows", + "import-archive-org", + "import-one", + "normalize-transcripts", + "persist-videos", + "refresh-report", + "whisper-all", + "whisper-bucket-auto-subs", + "whisper-bucket-downloaded-no-transcript", + ]); + for (const k of resumeOnBootKindIds()) assert.equal(getJobKind(k)?.replayable, true, `${k} is replayable`); + // Never a move, a delete or a one-shot. + for (const k of ["relocate-channel-media", "repoint-storage-location", "purge-superseded-auto-subs", "evict-clips", "sync", "fetch-chat", "record-live"]) { + assert.equal(getJobKind(k)?.resumeOnBoot, undefined, `${k} does not resume`); + } +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -48,8 +48,8 @@ export type JobKindMeta = { // // ABSENT MEANS FALSE, and that is deliberate rather than lazy. The guard is // opt-in so a kind that is not listed keeps exactly its current behavior, and - // so that `refresh-report` — which is not in this table at all — still runs - // and lets the snapshot generator itself report the reason it refused. A kind + // so that `refresh-report` — which declares neither — still runs and lets + // the snapshot generator itself report the reason it refused. A kind // that genuinely never opens a video dir (store playlist, clear markers) must // not be refused for a drive it does not read. // @@ -85,6 +85,17 @@ export type JobKindMeta = { // a platform queue says which it is — jobKinds.test.ts holds that, so a new // platform kind cannot slip in unpaced. network?: boolean; + // Whether a job of this kind that a restart INTERRUPTED is re-queued when + // the editor starts again (jobs/resumeInterrupted.ts, 2026-10-26). Only a + // kind that is replayable AND resumes on a re-run — it skips what the first + // run finished (what is held, imported, fetched, transcribed or captured), + // so running it again continues it rather than repeating it. Never a + // one-shot, a destructive or a move kind: whether one of those should run + // twice is not a decision a boot can make. Absent means false; the boot pass + // says each one it resumes in the resumed job's log, refuses a job + // interrupted twice in a row, and is off with `jobs.resumeInterruptedOnBoot` + // or on an idle boot. + resumeOnBoot?: boolean; }; // One entry per kind known to the system. `label` is included only where the @@ -172,6 +183,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, "whisper-bucket-downloaded-no-transcript": { kind: "whisper-bucket-downloaded-no-transcript", @@ -180,6 +192,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, // Replace-auto-captions lane, transcribe half: whisper over videos whose only // transcript is a YouTube ASR VTT (the downloadedAutoSubsOnly bucket). Same @@ -192,6 +205,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, // Delete the superseded English ASR VTTs kept as backups next to a finished // whisper transcript. Manual only — never auto-queued — and the single @@ -251,9 +265,10 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // // Not drainable: the walk honours the cancel signal (which is what stops it) // but has no drain-aware inner loop, and the unit of work is a single file - // write, so "let the in-flight one finish" is already how it behaves. Not - // replayable either — that would need a JobSpec and a jobReplayRegistry - // handler, and the button is one click from the card that reports the count. + // write, so "let the in-flight one finish" is already how it behaves. The + // per-channel pass is replayable (2026-10-26: its spec is the ids and + // `force`) and resumed after a restart — a re-run leaves every fresh + // cues.json alone. The corpus-wide pass on /sites carries no spec. // needsText (release 17; needsMedia before it): it walks `data/<id>/` for // every video and writes a sidecar into each — text, on the corpus disk. // Against an unreadable text tier (a `legacy` channel whose drive is @@ -263,10 +278,11 @@ const JOB_KINDS: Record<string, JobKindMeta> = { kind: "normalize-transcripts", label: "Normalize transcripts", drainable: false, - replayable: false, + replayable: true, queueKeyStrategy: "custom", needsMedia: false, needsText: true, + resumeOnBoot: true, }, "redownload-incomplete-bucket": { kind: "redownload-incomplete-bucket", @@ -294,6 +310,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "platform", network: true, needsMedia: true, + resumeOnBoot: true, }, "download-missing-subs": { kind: "download-missing-subs", @@ -309,23 +326,26 @@ const JOB_KINDS: Record<string, JobKindMeta> = { kind: "import-one", label: "Import video", drainable: false, - replayable: false, + replayable: true, queueKeyStrategy: "custom", network: true, needsMedia: true, + resumeOnBoot: true, }, // CHOSEN FILES OF ONE archive.org ITEM, imported one at a time on // archive.org's own queue (controller/archiveOrgImport.ts). Drainable: a // drain lets the file in flight finish and starts no more; re-running the - // same command resumes, skipping what landed. + // same command resumes, skipping what landed — so it is replayable (its spec + // is the request) and resumed after a restart (2026-10-26). "import-archive-org": { kind: "import-archive-org", label: "Import from archive.org", drainable: true, - replayable: false, + replayable: true, queueKeyStrategy: "platform", network: true, needsMedia: true, + resumeOnBoot: true, }, // AN ODYSEE OR BITCHUTE CHANNEL'S LISTING, diffed against what is held // (release 19 A6, controller/remoteListing.ts): one flat-playlist read on the @@ -375,6 +395,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, needsMedia: false, needsText: true, + resumeOnBoot: true, }, "redownload-archive": { kind: "redownload-archive", @@ -430,9 +451,9 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: true, }, // The corpus-wide corrupt-media scan and its per-channel twin. Registered - // properly, unlike check-availability / refresh-report / detect-duplicates, - // which have no entry here and fall back to their raw machine kind in the UI — - // that absence is a gap, not a pattern worth copying. + // properly, unlike detect-duplicates, which has no entry here and falls back + // to its raw machine kind in the UI — that absence is a gap, not a pattern + // worth copying. "scan-media": { kind: "scan-media", label: "Scan media for corruption", @@ -484,6 +505,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", network: true, needsMedia: true, + resumeOnBoot: true, }, "backup-saved-videos": { kind: "backup-saved-videos", @@ -630,6 +652,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", network: true, + resumeOnBoot: true, }, // Forum thread pages the operator saved from a browser, imported into a // forum-thread channel (controller/importForumPages.ts). Offline — nothing is @@ -714,6 +737,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", network: true, + resumeOnBoot: true, }, // A WAYBACK PAGES CHANNEL'S SCAN (release 37 S2, controller/waybackScan.ts): // the CDX listings of its targets into `wayback-scan.json`, no bodies, on @@ -827,6 +851,26 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, needsMedia: true, }, + // A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26, + // controller/chatBacklog.ts — `pnpm ops fetch-chat-backlog`, and the + // download lane's own for a `chat: "later"` channel with nothing left to + // download): the chat of every held stream that lacks one, one at a time + // through fetch-chat's pass. On the platform download queue, paced (the + // batch downloads' gap between two), `needsMedia` (it writes raw replays, a + // tierable big file). Drainable — it stops between chats — and, since a + // re-run skips every chat here and every stream known to have none, + // replayable and resumed after a restart. An ingest kind: the index reads + // the cues. + "fetch-chat-backlog": { + kind: "fetch-chat-backlog", + label: "Fetch chat backlog", + drainable: true, + replayable: true, + queueKeyStrategy: "platform", + network: true, + needsMedia: true, + resumeOnBoot: true, + }, // A FILE MADE A NORMAL TRANSCRIBED ITEM (controller/importMedia.ts — `pnpm // ops import-media`, "Import a file" on the channel and video pages): the // record (one metadata-only pass for a source page, or by hand), then the @@ -1320,6 +1364,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: false, needsText: true, }, + // ONE CHANNEL'S REPORT (snapshot.json) regenerated (jobs/snapshotScheduler.ts + // startRefreshReport), on the one refresh-report queue. Registered on + // 2026-10-26 to be replayable and resumed after a restart: a regeneration + // the restart cut short is one more walk, and the lanes read their work from + // what it writes. No label — /jobs has always shown it by its raw kind and + // hides it by default (jobsFilterStorage.ts). Neither guard: the snapshot + // generator reports an unreadable channel itself. + "refresh-report": { + kind: "refresh-report", + drainable: false, + replayable: true, + queueKeyStrategy: "custom", + resumeOnBoot: true, + }, // Replayable kinds that never had a JOB_KIND_LABELS entry: label omitted so // jobKindLabel() keeps falling back to the raw kind (unchanged behavior). "store-playlist": { @@ -1458,6 +1516,8 @@ const INGEST_KINDS: ReadonlySet<string> = new Set([ // One video's live chat replay, normalized into the cues the index reads // (release 36 lane A). "fetch-chat", + // Its backlog: every held stream's chat, after the downloads (2026-10-26). + "fetch-chat-backlog", // A file landed as a video's source, its audio beside it; a live recording // landed the same way (plans/live-capture.md). "import-media", @@ -1496,6 +1556,13 @@ export function kindIsNetwork(kind: string): boolean { return JOB_KINDS[kind]?.network ?? false; } +// The kinds a restart's interruption is resumed for (JobKindMeta.resumeOnBoot). +export function resumeOnBootKindIds(): string[] { + return Object.values(JOB_KINDS) + .filter((k) => k.resumeOnBoot === true) + .map((k) => k.kind); +} + // Every kind on a platform queue, for the test that holds each to a decision. export function platformKindIds(): string[] { return Object.values(JOB_KINDS) diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -37,6 +37,13 @@ export type JobMeta = { pid?: number; // The job this one handed its work on to (JobRecord.handedOffTo). handedOffTo?: string; + // A resume of a job a restart interrupted (JobRecord.resumedFrom, + // resumeCount; jobs/resumeInterrupted.ts). + resumedFrom?: string; + resumeCount?: number; + // On an interrupted job's meta: the job that resumed it. Written only by the + // resume pass, so it is never resumed twice. + resumedAs?: string; }; export function metaPath(paths: Paths, id: string): string { @@ -65,6 +72,8 @@ export async function writeJobMeta( spec: record.spec, pid: process.pid, ...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), + ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), + ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); } catch { @@ -94,6 +103,14 @@ export async function readJobMeta( // can't surface an un-runnable Retry. meta.spec = m.spec === undefined ? undefined : (parseJobSpec(m.spec) ?? undefined); if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo; + if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; + if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; + if ( + m.resumeCount !== undefined && + !(typeof m.resumeCount === "number" && Number.isInteger(m.resumeCount) && m.resumeCount > 0) + ) { + delete meta.resumeCount; + } return meta; } catch { return null; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -166,6 +166,15 @@ export type JobRecord = { // waits for the work rather than the job follows it (researchRuns.ts // jobOfPaths, `pnpm ops --wait`). handedOffTo?: string; + // THE JOB A RESTART INTERRUPTED THAT THIS ONE RESUMES (jobs/resumeInterrupted.ts, + // 2026-10-26), and how many resumes in a row it is (1 for the first). Set + // only by the boot's resume pass and `pnpm ops job resume-interrupted`; a + // Retry starts a fresh chain. The pass reads `resumeCount` to refuse a job + // interrupted twice in a row. + resumedFrom?: string; + resumeCount?: number; + // The line the job's log opens with when it is a resume (what it resumes). + resumeNote?: string; }; // Store a progress snapshot on the record, stamping `progressAt` only when the diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts @@ -0,0 +1,237 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { JobMeta } from "./jobMeta"; +import type { JobSpec } from "./jobSpec"; +import { INTERRUPTED_REASON, settleRunningJobMetas, type RequeueFn } from "./bootQueuedJobs"; +import { getRegistry } from "./registry"; +import { runManagedFunction } from "./streamCommand"; +import { + MAX_RESUMES_IN_A_ROW, + RESUME_WINDOW_MS, + resumeInterruptedJobs, + resumeSpecFor, +} from "./resumeInterrupted"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/resumeInterrupted.test.ts +// +// RESUME WHAT A RESTART INTERRUPTED (2026-10-26), over a temp .jobs dir. A +// kind that declares `resumeOnBoot` is re-queued through the injected re-queue +// (the editor's is runJobSpec), once; everything else is said and left. +// Never run against a real corpus. + +const NOW = 2_000_000_000_000; + +async function fixture(metas: Partial<JobMeta>[]) { + const root = await mkdtemp(path.join(tmpdir(), "resume-interrupted-")); + const jobsDir = path.join(root, ".jobs"); + await mkdir(jobsDir, { recursive: true }); + for (const m of metas) { + const meta = { + queueKey: "platform:archiveorg", + status: "cancelled", + cancelReason: INTERRUPTED_REASON, + queuedAt: NOW - 3_600_000, + endedAt: NOW - 60_000, + ...m, + }; + await writeFile(path.join(jobsDir, `${meta.id}.meta.json`), JSON.stringify(meta)); + } + const paths = { jobsDir } as Paths; + return { + paths, + root, + read: async (id: string) => JSON.parse(await readFile(path.join(jobsDir, `${id}.meta.json`), "utf8")) as JobMeta, + log: (id: string) => readFile(path.join(jobsDir, `${id}.log`), "utf8").catch(() => ""), + }; +} + +function recorder(answer: (spec: JobSpec, n: number) => Awaited<ReturnType<RequeueFn>> = (_s, n) => ({ ok: true, jobId: `NEW${n}` })) { + const calls: JobSpec[] = []; + const requeue: RequeueFn = async (spec) => { + calls.push(spec); + return answer(spec, calls.length); + }; + return { calls, requeue }; +} + +const importSpec: JobSpec = { kind: "import-archive-org", slug: "h3", params: { item: "h3-episodes", match: "\\.mp3$" } }; + +test("an interrupted archive.org import is re-queued once, and its meta says by whom", async () => { + const fx = await fixture([{ id: "A1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); + assert.deepEqual(out, [{ id: "A1", kind: "import-archive-org", channelSlug: "h3", action: "resumed", newId: "NEW1" }]); + assert.deepEqual(calls, [importSpec]); + const meta = await fx.read("A1"); + assert.equal(meta.resumedAs, "NEW1"); + assert.equal(meta.cancelReason, `${INTERRUPTED_REASON}; resumed as NEW1`); + assert.match(await fx.log("A1"), /\[resume\] resumed as NEW1/); + // Never twice: the second pass finds it resumed. + const again = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); + assert.deepEqual(again, []); + assert.equal(calls.length, 1); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("the resumed job carries the chain, and its log opens with what it resumes", async () => { + const fx = await fixture([ + { id: "R1", kind: "refresh-report", queueKey: "refresh-report", channelSlug: "h3", spec: { kind: "refresh-report", slug: "h3" } }, + ]); + try { + let newId = ""; + const requeue: RequeueFn = async (spec) => { + const res = await runManagedFunction({ + kind: spec.kind, + queueKey: "test-resume-chain", + paths: fx.paths, + channelSlug: spec.slug, + spec, + fn: async (onLog) => onLog("walked"), + }); + if (!res.ok) return { ok: false, error: res.error }; + newId = res.jobId; + await res.done; + return { ok: true, jobId: res.jobId }; + }; + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["R1"], now: NOW }); + assert.equal(out[0].action, "resumed"); + const record = getRegistry().get(newId); + assert.equal(record?.resumedFrom, "R1"); + assert.equal(record?.resumeCount, 1); + const log = await fx.log(newId); + assert.match(log.split("\n")[0], /^\[resume\] Resumes refresh-report job R1 on h3, interrupted when the process running it stopped: the channel's report is regenerated\.$/); + // On disk too, for the next boot. + for (let i = 0; i < 50; i++) { + const m = await fx.read(newId).catch(() => null); + if (m?.status === "done") { + assert.equal(m.resumedFrom, "R1"); + assert.equal(m.resumeCount, 1); + return; + } + await new Promise((r) => setTimeout(r, 20)); + } + assert.fail("the resumed job's meta never reached done"); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("interrupted twice in a row is not resumed a third time, and says why", async () => { + assert.equal(MAX_RESUMES_IN_A_ROW, 1); + const fx = await fixture([ + { id: "B2", kind: "download-missing", channelSlug: "h3-feed", spec: { kind: "download-missing", slug: "h3-feed" }, resumedFrom: "B1", resumeCount: 1 }, + ]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["B2"], now: NOW }); + assert.equal(calls.length, 0); + assert.equal(out[0].action, "not-resumed"); + assert.equal(out[0].action === "not-resumed" && out[0].category, "repeat"); + const meta = await fx.read("B2"); + assert.match(meta.cancelReason ?? "", /; not resumed: interrupted twice in a row \(it resumed B1 and was interrupted again\) — Retry it by hand$/); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a kind that does not resume is left exactly as the boot closed it", async () => { + const fx = await fixture([{ id: "C1", kind: "relocate-channel-media", channelSlug: "h3" }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["C1"], now: NOW }); + assert.equal(calls.length, 0); + assert.equal(out[0].action === "not-resumed" && out[0].category, "kind"); + assert.equal((await fx.read("C1")).cancelReason, INTERRUPTED_REASON); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a dry run lists and changes nothing", async () => { + const fx = await fixture([{ id: "D1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, dryRun: true, now: NOW }); + assert.deepEqual(out, [{ id: "D1", kind: "import-archive-org", channelSlug: "h3", action: "would-resume" }]); + assert.equal(calls.length, 0); + assert.equal((await fx.read("D1")).cancelReason, INTERRUPTED_REASON); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("by hand: only the last 24 h, and never one superseded by a newer job with the same request", async () => { + const fx = await fixture([ + { id: "E1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec, endedAt: NOW - RESUME_WINDOW_MS - 1 }, + { id: "E2", kind: "fetch-posts", channelSlug: "kf", spec: { kind: "fetch-posts", slug: "kf", params: {} } }, + // Re-queued by hand after the restart. + { id: "E3", kind: "fetch-posts", channelSlug: "kf", status: "done", cancelReason: undefined, queuedAt: NOW - 30_000, spec: { kind: "fetch-posts", slug: "kf", params: {} } }, + ]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, now: NOW }); + assert.equal(calls.length, 0); + assert.deepEqual( + out.map((o) => [o.id, o.action === "not-resumed" ? o.category : o.action]), + [["E2", "superseded"]], + ); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a refused re-queue is said on the meta, and the by-hand command asks again", async () => { + const fx = await fixture([{ id: "F1", kind: "persist-videos", channelSlug: "h3", spec: { kind: "persist-videos", slug: "h3", params: { ids: ["a"] } } }]); + try { + const refused = recorder(() => ({ ok: false, error: "youtube is held" })); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue: refused.requeue, ids: ["F1"], now: NOW }); + assert.equal(out[0].action === "not-resumed" && out[0].category, "refused"); + assert.match((await fx.read("F1")).cancelReason ?? "", /not resumed: the re-queue was refused: youtube is held/); + const later = recorder(); + const again = await resumeInterruptedJobs({ paths: fx.paths, requeue: later.requeue, now: NOW }); + assert.equal(again[0].action, "resumed"); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("resumeSpecFor: a dry run and a full posts re-walk are not resumed; an older walk drops its start date", () => { + assert.ok("skip" in resumeSpecFor({ kind: "import-archive-org", slug: "x", params: { item: "i", dryRun: true } })); + assert.ok("skip" in resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { full: true } })); + assert.deepEqual(resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { older: true, from: "2020-01-01" } }), { + spec: { kind: "fetch-posts", slug: "x", params: { older: true } }, + }); + assert.deepEqual(resumeSpecFor(importSpec), { spec: importSpec }); +}); + +test("the boot's running pass then the resume: what it closed is what it resumes", async () => { + const fx = await fixture([ + { id: "G1", kind: "download-missing", channelSlug: "feed", status: "running", cancelReason: undefined, endedAt: undefined, queuedAt: NOW - 10_000, spec: { kind: "download-missing", slug: "feed" } }, + ]); + try { + const running = await settleRunningJobMetas({ paths: fx.paths, bootedAt: NOW, isProcessAlive: () => false, selfPid: -1 }); + assert.deepEqual(running.interrupted.map((j) => j.id), ["G1"]); + const { calls, requeue } = recorder(); + const lines: string[] = []; + const out = await resumeInterruptedJobs({ + paths: fx.paths, + requeue, + ids: running.interrupted.map((j) => j.id), + prefix: "[boot]", + log: (l) => lines.push(l), + }); + assert.equal(out[0].action, "resumed"); + assert.equal(calls[0].kind, "download-missing"); + assert.deepEqual(lines, ["[boot] resumed download-missing feed: G1 -> NEW1"]); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/resumeInterrupted.ts b/common/jobs/resumeInterrupted.ts @@ -0,0 +1,250 @@ +// RESUME WHAT A RESTART INTERRUPTED (2026-10-26). +// +// The boot pass (bootQueuedJobs.ts settleRunningJobMetas) closes every job a +// dead process left `running` as `cancelled` with INTERRUPTED_REASON, and +// before this nothing ran it again: during the Ethanalyzer archive one restart +// killed an archive.org import (89 files), a feed download-missing (28 +// episodes) and a forum catch-up, and each was re-queued by hand — though each +// kind is BUILT to continue on a re-run (it skips what is held). +// +// This re-queues exactly those: a kind that declares `resumeOnBoot` +// (jobs/jobKinds.ts — replayable, and a re-run continues rather than repeats), +// through the path Retry uses (runJobSpec), on its own queue, each resumed +// job's log opening with what it resumes. It runs from the boot (not on an +// idle boot, not on the e2e test server, not with +// `jobs.resumeInterruptedOnBoot` off) over the jobs THAT boot closed, and by +// hand as `pnpm ops job resume-interrupted [--dry-run]` over the jobs +// interrupted in the last 24 hours. +// +// WHAT IS NOT RESUMED, each said with its reason: +// - a kind that does not resume on a re-run (no `resumeOnBoot`): closed, as +// before — whether a half-finished one-shot should run again is the +// operator's call (Retry is one click); +// - a job with no replay descriptor; +// - a job interrupted TWICE IN A ROW: it was itself a resume +// (`resumeCount` ≥ MAX_RESUMES_IN_A_ROW) and was interrupted again — a job +// that takes the process down with it must not do so on every boot; +// - a dry run (it writes nothing), and a FULL posts re-walk (it starts over +// from the top; a plain fetch is what continues from the saved position); +// - one superseded by a newer job with the same spec (re-queued by hand, or +// resumed already); +// - one whose re-queue the action refused (a held platform, a channel not +// reachable) — by hand later, the same command asks again. +// A job resumed is never resumed twice: its interrupted meta records +// `resumedAs`. + +import path from "node:path"; +import { appendFile, readdir } from "node:fs/promises"; +import { writeFileAtomic } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { INTERRUPTED_REASON, specKey, type RequeueFn } from "./bootQueuedJobs"; +import { metaPath, readJobMeta, type JobMeta } from "./jobMeta"; +import type { JobSpec } from "./jobSpec"; +import { getJobKind, jobKindLabel } from "./jobKinds"; +import { runWithResumeTag } from "./resumeTag"; + +// One resume per interruption chain: a resumed job that is interrupted again +// is "interrupted twice in a row" and is left for the operator. +export const MAX_RESUMES_IN_A_ROW = 1; + +// How far back the by-hand command looks (the boot looks only at what it just +// closed). +export const RESUME_WINDOW_MS = 24 * 60 * 60 * 1000; + +export type ResumeCategory = "kind" | "no-spec" | "repeat" | "not-resumable" | "superseded" | "refused"; + +export type ResumeOutcome = { id: string; kind: string; channelSlug?: string } & ( + | { action: "resumed"; newId: string } + | { action: "would-resume" } + | { action: "not-resumed"; category: ResumeCategory; reason: string } +); + +// What a re-run of each kind skips, for the resumed job's first log line. +const RESUMES_BY: Record<string, string> = { + "import-archive-org": "files already held are skipped", + "import-one": "a file already on disk is not fetched again, and a partial download continues", + "download-missing": "videos already downloaded are skipped", + "fetch-posts": "the walk continues from its saved position", + "persist-videos": "videos already saved are skipped", + "fetch-windows": "windows already fetched are skipped", + "whisper-all": "videos already transcribed are skipped", + "whisper-bucket-downloaded-no-transcript": "videos already transcribed are skipped", + "whisper-bucket-auto-subs": "videos already transcribed are skipped", + "capture-posts": "posts already captured are skipped", + "normalize-transcripts": "fresh cues files are left alone", + "refresh-report": "the channel's report is regenerated", + "fetch-chat-backlog": "chats already fetched, and streams that have none, are skipped", +}; + +// The spec a resume re-queues, or why the job is not resumed. Usually the spec +// as it was; a posts fetch that started an older walk at a date (`from`) +// drops it — its saved position is what continues the walk, and `from` would +// start it afresh. +export function resumeSpecFor(spec: JobSpec): { spec: JobSpec } | { skip: string } { + const p = spec.params ?? {}; + if (p.dryRun === true) return { skip: "a dry run writes nothing; it is not resumed" }; + if (spec.kind === "fetch-posts") { + if (p.full === true) { + return { + skip: "a full re-walk starts over from the top, so it is not resumed — Retry it to walk again", + }; + } + if (p.from !== undefined) { + const { from: _from, ...rest } = p; + return { spec: { ...spec, params: rest } }; + } + } + return { spec }; +} + +export function resumeNote(meta: JobMeta, count: number): string { + const what = RESUMES_BY[meta.kind] ?? "it skips what the first run finished"; + return ( + `Resumes ${jobKindLabel(meta.kind)} job ${meta.id}${meta.channelSlug ? ` on ${meta.channelSlug}` : ""}, ` + + `interrupted when the process running it stopped${count > 1 ? ` (resume ${count} in a row)` : ""}: ${what}.` + ); +} + +export type ResumeInterruptedOpts = { + paths: Paths; + requeue: RequeueFn; + // List what would be re-queued; change nothing. + dryRun?: boolean; + // Only these jobs (the boot: what its running pass just closed). Absent: + // every job interrupted within `windowMs` of `now`. + ids?: readonly string[]; + windowMs?: number; + now?: number; + log?: (line: string) => void; + // The prefix of each log line ("[boot]" from the boot). + prefix?: string; +}; + +function isInterrupted(meta: JobMeta): boolean { + return meta.status === "cancelled" && typeof meta.cancelReason === "string" && meta.cancelReason.startsWith(INTERRUPTED_REASON); +} + +export async function resumeInterruptedJobs(opts: ResumeInterruptedOpts): Promise<ResumeOutcome[]> { + const log = opts.log ?? (() => {}); + const prefix = opts.prefix ?? "[resume]"; + const now = opts.now ?? Date.now(); + const windowMs = opts.windowMs ?? RESUME_WINDOW_MS; + let names: string[]; + try { + names = await readdir(opts.paths.jobsDir); + } catch { + return []; + } + const metas: JobMeta[] = []; + for (const n of names.filter((x) => x.endsWith(".meta.json")).sort()) { + const meta = await readJobMeta(opts.paths, n.slice(0, -".meta.json".length)); + if (meta) metas.push(meta); + } + const only = opts.ids ? new Set(opts.ids) : null; + const candidates = metas + .filter((m) => isInterrupted(m) && !m.resumedAs) + .filter((m) => (only ? only.has(m.id) : (m.endedAt ?? 0) >= now - windowMs)) + .sort((a, b) => (a.queuedAt ?? 0) - (b.queuedAt ?? 0) || a.id.localeCompare(b.id)); + + // Every job by what it would DO, for "superseded by a newer one". + const byKey = new Map<string, JobMeta[]>(); + for (const m of metas) { + if (!m.spec) continue; + const k = specKey(m.spec); + byKey.set(k, [...(byKey.get(k) ?? []), m]); + } + const newerWith = (meta: JobMeta, keys: string[]): JobMeta | undefined => { + for (const k of keys) { + const hit = (byKey.get(k) ?? []).find( + (o) => o.id !== meta.id && (o.queuedAt ?? 0) > (meta.queuedAt ?? 0), + ); + if (hit) return hit; + } + return undefined; + }; + + const outcomes: ResumeOutcome[] = []; + const base = (m: JobMeta) => ({ id: m.id, kind: m.kind, ...(m.channelSlug ? { channelSlug: m.channelSlug } : {}) }); + const decline = async (meta: JobMeta, category: ResumeCategory, reason: string) => { + outcomes.push({ ...base(meta), action: "not-resumed", category, reason }); + // A kind that never resumes is left exactly as the boot closed it. + if (category === "kind" || opts.dryRun) return; + await rewrite(opts.paths, meta, { cancelReason: `${INTERRUPTED_REASON}; not resumed: ${reason}` }); + }; + + for (const meta of candidates) { + if (!getJobKind(meta.kind)?.resumeOnBoot) { + await decline(meta, "kind", `${jobKindLabel(meta.kind)} does not resume on a re-run`); + continue; + } + if (!meta.spec) { + await decline(meta, "no-spec", "it has no replay descriptor"); + continue; + } + const count = meta.resumeCount ?? 0; + if (count >= MAX_RESUMES_IN_A_ROW) { + await decline( + meta, + "repeat", + `interrupted twice in a row (it resumed ${meta.resumedFrom ?? "an interrupted job"} and was interrupted again) — Retry it by hand`, + ); + continue; + } + const resumable = resumeSpecFor(meta.spec); + if ("skip" in resumable) { + await decline(meta, "not-resumable", resumable.skip); + continue; + } + const newer = newerWith(meta, [...new Set([specKey(meta.spec), specKey(resumable.spec)])]); + if (newer) { + await decline(meta, "superseded", `superseded by a newer job with the same request (${newer.id}, ${newer.status})`); + continue; + } + if (opts.dryRun) { + outcomes.push({ ...base(meta), action: "would-resume" }); + continue; + } + let res: Awaited<ReturnType<RequeueFn>>; + try { + res = await runWithResumeTag( + { kind: meta.kind, resumedFrom: meta.id, resumeCount: count + 1, note: resumeNote(meta, count + 1) }, + () => opts.requeue(resumable.spec), + ); + } catch (err) { + res = { ok: false, error: (err as Error).message }; + } + if (!res.ok) { + await decline(meta, "refused", `the re-queue was refused: ${res.error}`); + continue; + } + await rewrite(opts.paths, meta, { + cancelReason: `${INTERRUPTED_REASON}; resumed as ${res.jobId}`, + resumedAs: res.jobId, + }); + outcomes.push({ ...base(meta), action: "resumed", newId: res.jobId }); + } + + const resumed = outcomes.filter((o) => o.action === "resumed"); + const declined = outcomes.filter( + (o): o is Extract<ResumeOutcome, { action: "not-resumed" }> => o.action === "not-resumed" && o.category !== "kind", + ); + const where = (o: ResumeOutcome) => `${o.kind}${o.channelSlug ? ` ${o.channelSlug}` : ""}`; + for (const o of resumed) if (o.action === "resumed") log(`${prefix} resumed ${where(o)}: ${o.id} -> ${o.newId}`); + for (const o of declined) log(`${prefix} not resumed ${where(o)} ${o.id}: ${o.reason}`); + return outcomes; +} + +async function rewrite(paths: Paths, meta: JobMeta, patch: Partial<JobMeta>): Promise<void> { + try { + await writeFileAtomic(metaPath(paths, meta.id), JSON.stringify({ ...meta, ...patch })); + } catch { + return; + } + if (patch.cancelReason) { + try { + await appendFile(path.join(paths.jobsDir, `${meta.id}.log`), `[resume] ${patch.cancelReason.slice(INTERRUPTED_REASON.length + 2)}\n`); + } catch { + /* the meta is the record; the log line is a courtesy */ + } + } +} diff --git a/common/jobs/resumeTag.ts b/common/jobs/resumeTag.ts @@ -0,0 +1,47 @@ +// WHICH INTERRUPTED JOB A NEW ONE RESUMES, carried through the action that +// makes it (jobs/resumeInterrupted.ts, 2026-10-26). +// +// The resume pass re-queues a job the way Retry does — runJobSpec(spec), which +// calls the kind's server action, which calls runManagedFunction — so nothing +// in that path can be handed "this one resumes job X". An async context can: +// the pass runs the re-queue inside `runWithResumeTag`, and the first job of +// the tagged kind made inside it (makeJob in streamCommand.ts) claims the tag +// and records `resumedFrom` / `resumeCount` on its record — before its first +// meta write, so a second crash still finds the count on disk. Claimed once: +// a sub-job the resumed job itself starts (a hand-off, a refresh) is not a +// resume. +// +// SERVER-ONLY (node:async_hooks). One storage per process, on globalThis, the +// house pattern (lib/jobContext.ts). + +import { AsyncLocalStorage } from "node:async_hooks"; + +export type ResumeTag = { + kind: string; + resumedFrom: string; + resumeCount: number; + // The first line of the resumed job's log. + note: string; +}; + +type Held = ResumeTag & { claimed: boolean }; + +const KEY = Symbol.for("archilyzer.resumeTag"); + +function storage(): AsyncLocalStorage<Held> { + const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<Held> | undefined>; + return (g[KEY] ??= new AsyncLocalStorage<Held>()); +} + +export function runWithResumeTag<T>(tag: ResumeTag, fn: () => T): T { + return storage().run({ ...tag, claimed: false }, fn); +} + +// The tag for a job of `kind` being made now, once; else null. +export function claimResumeTag(kind: string): ResumeTag | null { + const held = storage().getStore(); + if (!held || held.claimed || held.kind !== kind) return null; + held.claimed = true; + const { claimed: _claimed, ...tag } = held; + return tag; +} diff --git a/common/jobs/snapshotScheduler.test.ts b/common/jobs/snapshotScheduler.test.ts @@ -183,3 +183,75 @@ test("a failed walk is a failure with its sentence, for the click that found it release(); } }); + +// NEW ITEMS ARE VISIBLE TO THE LANES AT ONCE (2026-10-26): an import that adds +// items asks for its channel's report as they land, not only when it ends. +test("the landed throttle: the first item at once, then every N items or M ms, a waiting one flushed by its timer", async () => { + const { makeLandedThrottle } = await import("./snapshotScheduler"); + let now = 0; + const timers: { fn: () => void; at: number; cleared: boolean }[] = []; + let asks = 0; + const t = makeLandedThrottle(() => asks++, { + everyItems: 3, + everyMs: 1000, + now: () => now, + setTimer: (fn, ms) => { + const timer = { fn, at: now + ms, cleared: false }; + timers.push(timer); + return { clear: () => (timer.cleared = true) }; + }, + }); + t.note(); + assert.equal(asks, 1, "the first item asks at once"); + now = 100; + t.note(); + t.note(); + assert.equal(asks, 1, "two more, inside the window: waiting"); + t.note(); + assert.equal(asks, 2, "the third since the last ask asks"); + now = 200; + t.note(); + assert.equal(asks, 2); + const pending = timers.filter((x) => !x.cleared).at(-1)!; + assert.equal(pending.at, 100 + 1000, "flushed M ms after the last ask"); + now = pending.at; + pending.fn(); + assert.equal(asks, 3, "the waiting item is flushed by the timer"); + now = 5000; + t.note(); + assert.equal(asks, 4, "an item past the window asks at once"); + t.note(); + t.stop(); + for (const x of timers.filter((y) => !y.cleared)) x.fn(); + assert.equal(asks, 4, "nothing after stop: the job's end asks for the rest"); +}); + +test("a job's itemLanded asks for its channel's report while it runs; the regenerated report is what the lanes read next", async () => { + const { runManagedFunction } = await import("./streamCommand"); + const { readChannelSnapshotShared } = await import("../controller/channels"); + const { flushChannelSnapshotsNow } = await import("./snapshotScheduler"); + const paths = getPaths(); + let release!: () => void; + const held = new Promise<void>((r) => (release = r)); + let landedAt = 0; + const job = await runManagedFunction({ + kind: "import-archive-org-test", + queueKey: `test-landed:${newJobId()}`, + paths, + channelSlug: "gamma", + fn: async (_onLog, _signal, _progress, ctx) => { + ctx.itemLanded(); + landedAt = Date.now(); + await held; + }, + }); + assert.ok(job.ok); + while (!landedAt) await new Promise((r) => setTimeout(r, 5)); + await flushChannelSnapshotsNow(); + const snap = await readChannelSnapshotShared(paths, "gamma"); + assert.ok(snap, "the report was written while the job still runs"); + assert.ok(Date.parse(snap.generatedAt) >= landedAt - 1000); + assert.equal(getRegistry().get(job.jobId)?.status, "running"); + release(); + await job.done; +}); diff --git a/common/jobs/snapshotScheduler.ts b/common/jobs/snapshotScheduler.ts @@ -136,6 +136,76 @@ function resolveWindow(): { debounceMs: number; maxWaitMs: number | null } { } } +// NEW ITEMS ARE VISIBLE TO THE LANES AT ONCE (2026-10-26). A job that ADDS +// items to a channel — an archive.org import, an attach with new records, a +// chat backlog — and does not report per-item tasks (whose end already asks +// for a regeneration, ctx.recordTaskDone) refreshed the channel's report only +// when it ENDED. On 2026-10-26 an import-archive-org added 64 items over +// hours while the report kept the 32 it had at 01:10: the transcription lane +// and `transcribe-bucket` read their work out of the report, so 64 imports sat +// untranscribed and the GPU went to another site's backlog. +// +// `ctx.itemLanded()` (streamCommand.ts) feeds this: the FIRST item asks for a +// regeneration at once, then at least every `everyItems` items or `everyMs` +// after the last ask, whichever comes first — a timer flushes an item still +// waiting when no further one arrives. Every ask goes through +// requestChannelSnapshot, so it is debounced, deduped and run on the one +// refresh-report queue like every other. `stop()` at the job's end (whose own +// ask covers what is left). +export const LANDED_REFRESH_EVERY_ITEMS = 10; +export const LANDED_REFRESH_EVERY_MS = 2 * 60 * 1000; + +export type LandedThrottle = { note: () => void; stop: () => void }; + +export function makeLandedThrottle( + ask: () => void, + opts: { + everyItems?: number; + everyMs?: number; + now?: () => number; + setTimer?: (fn: () => void, ms: number) => { clear: () => void }; + } = {}, +): LandedThrottle { + const everyItems = opts.everyItems ?? LANDED_REFRESH_EVERY_ITEMS; + const everyMs = opts.everyMs ?? LANDED_REFRESH_EVERY_MS; + const now = opts.now ?? Date.now; + const setTimer = + opts.setTimer ?? + ((fn: () => void, ms: number) => { + const t = setTimeout(fn, ms); + t.unref?.(); + return { clear: () => clearTimeout(t) }; + }); + let lastAskAt: number | null = null; + let pending = 0; + let timer: { clear: () => void } | null = null; + let stopped = false; + const flush = () => { + timer?.clear(); + timer = null; + if (stopped || pending === 0) return; + pending = 0; + lastAskAt = now(); + ask(); + }; + return { + note() { + if (stopped) return; + pending++; + if (lastAskAt === null || pending >= everyItems || now() - lastAskAt >= everyMs) { + flush(); + return; + } + if (!timer) timer = setTimer(flush, Math.max(0, lastAskAt + everyMs - now())); + }, + stop() { + stopped = true; + timer?.clear(); + timer = null; + }, + }; +} + // Mark a channel's report dirty and (re)arm the global debounce timer. // Synchronous and non-throwing — safe to call from job completion handlers and // request-scoped server actions without awaiting or try/catch. @@ -222,6 +292,9 @@ export async function startRefreshReport( queueKey: REFRESH_REPORT_QUEUE, paths, channelSlug: slug, + // Replayable (2026-10-26): a Retry, or the boot's resume of a + // regeneration a restart interrupted, is one more walk of the channel. + spec: { kind: "refresh-report", slug }, fn: async (onLog) => { onLog(`Regenerating report for ${slug}…`); const snap = await generateChannelSnapshot(paths, slug); diff --git a/common/jobs/streamCommand.test.ts b/common/jobs/streamCommand.test.ts @@ -314,3 +314,39 @@ test("at shutdown a queued job's sidecar stays queued, for the boot pass", async await rm(root, { recursive: true, force: true }); } }); + +// A JOB THAT WAITED IN ITS QUEUE IS `running` ON DISK ONCE IT STARTS +// (2026-10-26). Its sidecar was written only at enqueue and at the end, so one +// that died mid-run read `queued`, and the next boot re-queued it as a job that +// never started. Now the boot closes it as interrupted, and the resume pass +// decides. +test("a queued job's sidecar says running once its queue starts it", async () => { + const { paths, root } = await jobsDir(); + const queueKey = `test:running-meta:${newJobId()}`; + const holder = await hold(paths, queueKey); + let finish!: () => void; + const finished = new Promise<void>((r) => { + finish = r; + }); + try { + const job = ok( + await runManagedFunction({ + kind: "test-waits-then-runs", + queueKey, + paths, + fn: () => finished, + }), + ); + assert.equal((await metaReaches(paths, job.jobId, "queued"))?.status, "queued"); + await holder.release(); + const running = await metaReaches(paths, job.jobId, "running"); + assert.equal(running?.status, "running"); + assert.equal(typeof running?.startedAt, "number"); + finish(); + assert.equal((await job.done).status, "done"); + assert.equal((await metaReaches(paths, job.jobId, "done"))?.status, "done"); + } finally { + finish(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -14,6 +14,7 @@ import { import type { Paths } from "../lib/paths"; import { makeSafeController } from "../lib/safeStreamController"; import { + makeLandedThrottle, requestChannelSnapshot, shouldRequestSnapshot, } from "./snapshotScheduler"; @@ -33,6 +34,7 @@ import { mediaHoldText } from "../lib/channelMediaHold"; import { runInJobContext, type JobContext } from "../lib/jobContext"; import { serviceStoppedLine } from "../lib/serviceCookies"; import { configuredCookieBrowser } from "../lib/serviceCookies-server"; +import { claimResumeTag } from "./resumeTag"; // Mark a job's channel report dirty so the debounced scheduler regenerates the // snapshot — called both on each completed sub-operation and on the job's @@ -112,6 +114,13 @@ export type JobRunContext = { ) => void; removeTask: (taskId: string) => void; recordTaskDone: (durationMs: number, audioSeconds?: number) => void; + // AN ITEM THIS JOB ADDED TO ITS CHANNEL landed (an imported file, a new + // record, a fetched chat): the channel's report is regenerated for the first + // one at once and then at least every few items or minutes, so the lanes + // and `transcribe-bucket` see new work while the job is still running + // (snapshotScheduler.ts makeLandedThrottle). A job that reports per-item + // tasks (recordTaskDone) need not call it: each task's end already asks. + itemLanded: () => void; // This job's work goes on in another job (`jobId`), which this one queued: // recorded on the record and its sidecar as `handedOffTo`, so a caller // waiting for the work follows it there. @@ -154,6 +163,14 @@ function makeJob( queuedAt: Date.now(), logPath, }; + // A RESUME OF A JOB A RESTART INTERRUPTED (jobs/resumeTag.ts): recorded + // before the first meta write, so a second crash finds the count on disk. + const resume = claimResumeTag(kind); + if (resume) { + record.resumedFrom = resume.resumedFrom; + record.resumeCount = resume.resumeCount; + record.resumeNote = resume.note; + } getRegistry().register(record); return { id, logPath, record }; } @@ -185,6 +202,19 @@ function makeDoneDeferred(jobId: string): { return { done, settle }; } +// THE MOMENT A JOB STARTS. Its sidecar is rewritten `running` (2026-10-26): +// it was written only at enqueue and at the end, so a job that waited in its +// queue and then died mid-run read `queued` on disk, and the next boot took it +// for one that never started — re-queueing a half-finished job blind, where +// one that started at once read `running` and was closed interrupted. Both +// are `running` now, and the resume pass (jobs/resumeInterrupted.ts) is the +// one place that decides whether either runs again. A resumed job's log opens +// with what it resumes. +function openJobLog(record: JobRecord, log: WriteStream, persistMeta: () => void): void { + if (record.resumeNote) log.write(`[resume] ${record.resumeNote}\n`); + persistMeta(); +} + // ONE WRITER PER JOB, IN ORDER — DEFENSIVE. A job's sidecar is written at // least twice (at enqueue, then with its terminal state) and each write is // async. writeJobMeta snapshots the record before its first await, so two @@ -255,6 +285,7 @@ export async function runManagedCommand( } fileStream = createWriteStream(logPath); ignoreFileStreamErrors(fileStream); + openJobLog(record, fileStream, persistMeta); const child = execa(opts.command, opts.args, { cwd: opts.cwd, env: opts.env, @@ -437,6 +468,7 @@ export async function runManagedFunction( } fileStream = createWriteStream(logPath); ignoreFileStreamErrors(fileStream); + openJobLog(record, fileStream, persistMeta); const abort = new AbortController(); record.abortController = abort; const drain = new AbortController(); @@ -452,6 +484,7 @@ export async function runManagedFunction( noteProgress(record, snap); }; + const landed = makeLandedThrottle(() => requestSnapshotOnFinish(id, opts)); const ctx: JobRunContext = { jobId: id, drainSignal: drain.signal, @@ -466,6 +499,7 @@ export async function runManagedFunction( // coalesces sub-operations that finish close together. requestSnapshotOnFinish(id, opts); }, + itemLanded: () => landed.note(), handOff: (jobId) => { record.handedOffTo = jobId; persistMeta(); @@ -570,6 +604,7 @@ export async function runManagedFunction( fileStream.end(() => resolve()); }); safe.safeClose(); + landed.stop(); requestSnapshotOnFinish(id, opts); // Persist terminal state (status/endedAt/exitCode now set by finalize). persistMeta(); diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -107,6 +107,53 @@ export function isRejectedLivestreamMode( return v === "skip" || v === "chat-only"; } +// WHEN A STREAM'S LIVE CHAT REPLAY IS FETCHED (2026-10-26). The replay rides +// the caption download as a `live_chat` subtitle track (yt-dlp `--sub-langs`) +// and is 7–42 MB per stream, which made each YouTube download of a streaming +// channel 2–4× slower while the backlog was being archived (Ethanalyzer, +// 2026-10-23…26). Absent = "with-download" (every channel before the field): +// with-download the chat comes down with the captions, as it always has; +// later the downloads leave it out, and once the channel has +// nothing left to download the download lane queues ONE +// paced, resumable `fetch-chat-backlog` job for its streams' +// chats (controller/chatBacklog.ts); +// never the downloads leave it out and nothing fetches it +// (`pnpm ops fetch-chat` still does, one video at a time). +export type ChatMode = "with-download" | "later" | "never"; +export const CHAT_MODES: readonly ChatMode[] = ["with-download", "later", "never"]; + +export function isChatMode(v: unknown): v is ChatMode { + return v === "with-download" || v === "later" || v === "never"; +} + +// yt-dlp's `--sub-langs` when the channel names none. +export const DEFAULT_SUB_LANGS = "en.*,live_chat"; + +// The `--sub-langs` a caption download passes: the channel's (or the +// default), WITHOUT the live chat unless `chat` fetches it with the download. +// An entry that is `live_chat` itself is dropped; one that would still match +// it (`all`, `.*`) gets `-live_chat` after it, yt-dlp's own exclusion. Nothing +// left (a channel whose only track was the chat) falls back to `en.*`. +export function effectiveSubLangs(config: Pick<ChannelConfig, "subLangs" | "chat">): string { + const langs = config.subLangs?.trim() || DEFAULT_SUB_LANGS; + if ((config.chat ?? "with-download") === "with-download") return langs; + const kept = langs + .split(",") + .map((x) => x.trim()) + .filter((x) => x && x !== "live_chat" && x !== "-live_chat"); + const catchesChat = kept.some((x) => { + if (x.startsWith("-")) return false; + if (x === "all") return true; + try { + return new RegExp(`^(?:${x})$`).test("live_chat"); + } catch { + return false; + } + }); + if (kept.length === 0) return "en.*"; + return catchesChat ? [...kept, "-live_chat"].join(",") : kept.join(","); +} + // A channel's `config.json`. Each field is documented in // CHANNEL_CONFIG_FIELD_DOCS below (rendered into CHANNEL.md); the keys that are // SYNC STATE rather than configuration are CHANNEL_SYNC_STATE_KEYS. @@ -138,6 +185,7 @@ export type ChannelConfig = { mediaDir?: string; ytdlpExtraArgs?: string[]; subLangs?: string; + chat?: ChatMode; lastSyncedAt?: string; lastFullDownloadAt?: string; lastFullSweepAt?: string; @@ -197,7 +245,10 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { mediaDir: "Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an \"inconsistent\" channel every media guard refuses. The text (`data/`) never moves.", ytdlpExtraArgs: "Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped.", - subLangs: "yt-dlp `--sub-langs` value for caption downloads.", + subLangs: + "yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `\"with-download\"`. A Configure field.", + chat: + 'When a stream\'s live chat replay is fetched: `"with-download"` (default — with the captions, as a `live_chat` subtitle track), `"later"` (the downloads leave it out — each YouTube download of a streaming channel is 2–4× faster — and when the channel has nothing left to download, the download lane queues one paced, resumable `fetch-chat-backlog` job for its `was_live` streams\' chats; `pnpm ops fetch-chat-backlog` runs it by hand) or `"never"` (left out; `pnpm ops fetch-chat` still fetches one). A Configure field.', lastSyncedAt: "SYNC STATE. When the channel last synced (ISO time). Stamped by every sync, and by a social fetch; read by the scheduler's cadence gate.", lastFullDownloadAt: "SYNC STATE. When a full download pass last completed (ISO time).", @@ -417,6 +468,7 @@ export const CHANNEL_CONFIG_COERCIONS: { ? (v as string[]) : undefined, subLangs: str, + chat: (v) => (isChatMode(v) ? v : undefined), lastSyncedAt: str, lastFullDownloadAt: str, lastFullSweepAt: str, diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 38); // release 38: `xSearch` + assert.equal(CHANNEL_CONFIG_KEYS.length, 39); // 2026-10-26: `chat` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -62,6 +62,7 @@ export const channelConfigObjectSchema = z.object({ mediaDir: field("mediaDir"), ytdlpExtraArgs: field("ytdlpExtraArgs"), subLangs: field("subLangs"), + chat: field("chat"), lastSyncedAt: field("lastSyncedAt"), lastFullDownloadAt: field("lastFullDownloadAt"), lastFullSweepAt: field("lastFullSweepAt"), diff --git a/common/lib/jobsSettings.ts b/common/lib/jobsSettings.ts @@ -0,0 +1,33 @@ +// settings.jobs — what the job system does on its own across a restart +// (jobs/resumeInterrupted.ts). Pure: the type, its defaults, the sanitizer +// settingsSchema.ts runs it through and the per-field docs SETTINGS.md renders. + +import type { FieldDocs } from "./fieldDocs"; + +export type JobsSettings = { + resumeInterruptedOnBoot: boolean; +}; + +// ON BY DEFAULT (operator, 2026-10-26): a restart during the Ethanalyzer +// archive killed an archive.org import, a feed download and a forum catch-up, +// each already built to skip what it held on a re-run, and each was re-queued +// by hand. +export const DEFAULT_JOBS_SETTINGS: JobsSettings = { + resumeInterruptedOnBoot: true, +}; + +export const JOBS_SETTINGS_FIELD_DOCS: FieldDocs<JobsSettings> = { + resumeInterruptedOnBoot: + "When the editor starts, re-queue the jobs the previous process left RUNNING (closed \"interrupted\") whose kind " + + "resumes on a re-run — it skips what the first run finished: an archive.org import, a download-missing, a " + + "posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report, " + + "a chat backlog (`resumeOnBoot` in common/jobs/jobKinds.ts). Each resumed job's log says which job it resumes. " + + "A job interrupted twice in a row is not resumed again, a dry run or a full re-walk never is, and an idle boot " + + "(ARCHILYZER_IDLE_BOOT) resumes nothing. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand. " + + "Default true.", +}; + +export function sanitizeJobs(value: unknown): JobsSettings { + const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>; + return { resumeInterruptedOnBoot: r.resumeInterruptedOnBoot !== false }; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -14,6 +14,7 @@ import { ARCHIVE_ORG_SETTINGS_FIELD_DOCS, ARCHIVES_SETTINGS_FIELD_DOCS, CLIPS_SETTINGS_FIELD_DOCS, + JOBS_SETTINGS_FIELD_DOCS, ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS, ATTRIBUTION_SETTINGS_FIELD_DOCS, BACKFILL_SETTINGS_FIELD_DOCS, @@ -326,6 +327,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.clips), }, ], + jobs: [ + { + path: "jobs", + docs: JOBS_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.jobs), + }, + ], }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -34,6 +34,7 @@ import type { SeederSettings } from "./seederSettings"; import type { TtsSettings } from "./ttsSettings"; import type { ArchivesSettings } from "./archives/settings"; import type { ClipsSettings } from "./clipSettings"; +import type { JobsSettings } from "./jobsSettings"; import type { GenerationSettings } from "./generationSettings"; import type { AttributionSettings, @@ -120,13 +121,15 @@ type PreSchemaSiteSettings = { generation: GenerationSettings; // How clip windows are fetched: the whole-recording platforms. clips: ClipsSettings; + // What the job system does across a restart (2026-10-26). + jobs: JobsSettings; }; // Bracketed so the conditional does not distribute (see commit 8c43231). type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 41 fields, in file order", () => { +test("SiteSettings keeps its 43 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -171,6 +174,7 @@ test("SiteSettings keeps its 41 fields, in file order", () => { "tts", "generation", "clips", + "jobs", ]); // A parsed object carries every key, in that order — writeSettings writes // exactly this, so the order is the on-disk order. diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -82,6 +82,7 @@ export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSetting import { sanitizeTts, type TtsSettings } from "./ttsSettings"; import { sanitizeArchives, type ArchivesSettings } from "./archives/settings"; import { sanitizeClips, type ClipsSettings } from "./clipSettings"; +import { sanitizeJobs, type JobsSettings } from "./jobsSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { GENERATION_CAPS_FIELD_DOCS, @@ -101,6 +102,7 @@ export { export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings"; export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings"; +export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings"; import { DEFAULT_COOKIE_MODE, isCookieMode, @@ -1953,6 +1955,9 @@ export const siteSettingsSchema = z.object({ clips: settingsField((v): ClipsSettings => sanitizeClips(v)).describe( "How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.", ), + jobs: settingsField((v): JobsSettings => sanitizeJobs(v)).describe( + "What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings.", + ), }); export type SiteSettings = z.infer<typeof siteSettingsSchema>; diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -20,6 +20,7 @@ import { import { type AudioFormat, type ChannelConfig, + effectiveSubLangs, } from "../lib/channelConfig"; import { resolvePersistenceDecision, @@ -67,6 +68,7 @@ import { } from "../lib/transcripts-server"; import { evaluateDownloadFilters } from "../lib/downloadFilters"; import { normalizeLiveChat } from "../controller/normalizeLiveChat"; +import { writeCuesAfterDownload } from "../controller/normalizeTranscript"; import { LIVE_CHAT_FILENAME } from "../lib/videoStatus"; import { upsertMetadataScan, @@ -292,7 +294,9 @@ function youtubeHandlingArgs( "--write-auto-subs", "--write-subs", "--sub-langs", - config.subLangs ?? "en.*,live_chat", + // Without the live chat unless the channel fetches it with the download + // (ChannelConfig.chat). + effectiveSubLangs(config), ]; if (!reuseInfoJson) args.push("--write-info-json"); args.push( @@ -2006,6 +2010,19 @@ async function writeOutcome( ); } + // THE CUES SIDECAR, so a fresh download is build-ready (2026-10-26): a + // caption download (youtube handling) never reaches transcribeOne, the only + // other automatic writer of transcript.cues.json. Every success, any path — + // a transcription that already wrote it finds it fresh. Never throws. + if (status.startsWith("ok")) { + await writeCuesAfterDownload({ + videoDir, + channelSlug: opts.channelSlug, + ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}), + onLog: opts.onLog, + }); + } + // Capture an availability history entry when the last attempt observed a // class (e.g. a public video the uploader just deleted). Never touch the // top-level fields (updateTopLevel: false) so resolveEffectiveAvailability's diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -9,6 +9,7 @@ import { type AudioFormat, type ChannelConfig, type ChannelHandling, + effectiveSubLangs, } from "../lib/channelConfig"; import { getSettings } from "../lib/settings"; import { patchChannelConfig } from "../controller/channels"; @@ -88,6 +89,7 @@ import { } from "../jobs/platformBackoff"; import { hasSubtitleRateLimit } from "../lib/availability"; import { computeKeepWindow, type KeepWindow } from "../controller/keptVideos"; +import { writeCuesAfterDownload } from "../controller/normalizeTranscript"; import { downloadOneManaged } from "./downloadOneManaged"; import { STDERR_TAIL_BYTES } from "./runOneYtdlp"; import { observeStderrServiceSignal } from "../lib/serviceCookies-server"; @@ -1500,7 +1502,9 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> { .map((s) => s.trim()) .filter(Boolean); - const subLangs = opts.channelConfig.subLangs ?? "en.*,live_chat"; + // Without the live chat unless the channel fetches it with the download + // (ChannelConfig.chat): a `later` channel's chats are the backlog job's. + const subLangs = effectiveSubLangs(opts.channelConfig); const matchesSubLang = compileSubLangMatcher(subLangs); const tofetch: string[] = []; @@ -1648,6 +1652,14 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> { } else { await clearSubtitleDeferral(id, opts.paths).catch(() => {}); } + // The cues the new tracks make (2026-10-26): what the normalize + // pass would write, written now. Never throws. + await writeCuesAfterDownload({ + videoDir: path.join(dataDir, id), + channelSlug: opts.channelSlug, + ...(opts.channelConfig.name ? { configName: opts.channelConfig.name } : {}), + onLog: task?.onLog ?? opts.onLog, + }); } } catch (err) { failed++; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] - **An assistant can finish a report video from umtool's command line without hand fixes.** `umtool variants <project> --take <take>` now makes the delivery ladder (master, 1080p, 720p, fit24) of a finished take, and so does the Deliver tab's **Make variants** with a take picked. A take used to be refused with "has no build to make variants of" because its render was moved to `takes/<take>/preview.mp4`; the take maker now also leaves it in the take's `out/` under the build's name (a hard link, so no extra disk), and a take made before this is encoded from its `preview.mp4`. `umtool timeline <project> insert` writes a clip the way the rest of the cut is written: in a cut with the on-screen deck, `--title` sets the deck's title (`onscreen.title`; `--stream-title` sets the stream's), a cut whose deck titles are dates gets `--date` as one in the same format (`9 Dec 2024`), the clip takes the section of the clip it goes after unless `--section N` says otherwise, and `--lock` and `--lock-end` lock its edges. `umtool check` now says how to fix a clip with no cue file: `pnpm ops build-cues --json '{"slug":"<channel>","ids":["<video>"]}' --wait` when the video is in the archive, and the Rumble two-ids check when it is not. A take of part of a cut says in its log what timed the window: the last build's schedule, or the clips' own lengths when there is no schedule or it does not time clips inserted since the build. +- **A streaming channel can fetch its live chats after its downloads, by itself.** A stream's chat replay (7–42 MB) came down with its captions and made each YouTube download 2–4× slower while the Ethanalyzer backlog was archived; the fix was a hand edit of `subLangs` and a hand-written watcher that ran `pnpm ops fetch-chat` per streamed episode once the downloads were done — and died on reboot. Configure → **Live chat replay** (`chat`: with the download, Later or Never): with Later the downloads leave the chat out and, once the channel has nothing left to download, the download lane queues one paced **Fetch chat backlog** job for every stream (by its metadata) whose chat is not here, 25 at a time, skipping what landed and the streams known to have none, and resumed after a restart. The Download stage has the button; `pnpm ops fetch-chat-backlog {slug, dryRun?, limit?}` runs it by hand. **Caption languages** (`subLangs`) is a Configure field and a `channel-config` patch key now. Needs a restart of the editor. +- **What an import adds is work for the lanes at once, not when the import ends.** On 2026-10-26 an archive.org import added 64 recordings over several hours while the channel's report still listed the 32 it had at 01:10; the transcription lane reads its work from that report, so the 64 waited untranscribed and the GPU went to another site's backlog, and `pnpm ops transcribe-bucket` answered "64 of ids not in the downloadedNoTranscript bucket". An archive.org import, an attach of local media and a persist now regenerate the channel's report as items land (the first at once, then at least every 10 items or 2 minutes), and `transcribe-bucket` regenerates a report that is behind the disk before it answers. Needs a restart of the editor. +- **A restart no longer kills the long jobs it interrupts: they resume.** On 2026-10-25/26 one restart stopped an archive.org import (89 files), a feed download-missing (28 episodes) and a forum catch-up, each closed "interrupted" and re-queued by hand. At boot the editor now re-queues every job the previous process left running whose kind continues on a re-run — an archive.org import, an import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report — and its log opens with the job it resumes. A job interrupted twice in a row, a dry run and a full posts re-walk are not resumed, and the old job says why. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand; `jobs.resumeInterruptedOnBoot: false` turns the boot's resume off, and an idle boot never resumes. A job that waited in its queue and then died mid-run is now closed as interrupted too, instead of being re-queued as if it had never started. An archive.org import, a single import and a cues pass gained Retry. Needs a restart of the editor. +- **A new caption download is ready for a umtool build the moment it lands.** A YouTube video whose captions were downloaded (the-quartering, 2026-10-23/24) had its `transcript.en-orig.vtt` but no `transcript.cues.json` — only a transcription wrote one, and every older video got its file from the normalize pass — so umtool refused it ("clip-no-cues") until `pnpm ops build-cues` was run by hand. Every successful download, and the Download missing subs pass, now writes the cues file the normalize pass would. Needs a restart of the editor. - **An interrupted catch-up no longer sends a finished forum thread back through its whole history.** When an editor restart cut a thread's catch-up short, the next run saw the page the catch-up still owed as a hole in the history, marked the history unfinished and re-read every held page below it (on 2026-10-26 it re-read 150 pages of the Ethan Klein thread before it was stopped; left alone, every sync would have gone on doing it). The page an unfinished catch-up owes is now its own, and the history stays complete. Needs a restart of the editor. - **A take of part of a cut (`--at`) now shows the clips its own changes add.** The window is timed against the project's cut so every take of a group covers the same clips, and a clip only the take adds (a montage line, an extra beat) was never in it: the Huck cut's pitch-count take rendered seven of its eight pitches. A clip the take adds right after one the window covers now renders with it. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **An assistant can now change a report video's timeline, find a clip's scene cuts, and add a post from the archive, all from the command line.** `umtool timeline <project>` lists the cut (index, id, type, video, start–end, date and title) and does what the Cut tab's timeline does: `insert --after <id> <channel>/<video>@<start>-<end>` with `--title`, `--date`, `--quote` and `--cite`, `move <id> --to <index>`, `remove`, `duplicate`, `post`, `post-remove`, `teaser` and `undo`. It goes through the same writers as the page, so each change saves an undo point first, is refused when the build would refuse it, and leaves an edit note on a generated manifest. A bad `--date` is refused before anything is written. `umtool scenes <project> <clip>` prints where the picture cuts and where it goes black in the clip's fetched window, in the recording's own seconds, for setting a blur's from and to or a trim: the Huck dog clip is black 250.49–251.09 and cuts at 251.09. It fetches nothing. `umtool posts add <project> <channel>/<postId>` makes a post card from the posts archive (its words, date, link, handle and screenshot, with `--attach <clip>` and `--flag`) and copies the capture into the project's `posts-media/`. A post with no screenshot is refused, and the message names the `pnpm ops capture-posts` to run first. diff --git a/editor/app/api/ops/fetch-chat-backlog/route.test.ts b/editor/app/api/ops/fetch-chat-backlog/route.test.ts @@ -0,0 +1,42 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/fetch-chat-backlog/route.test.ts" +// +// A channel's stream chats after its downloads (2026-10-26): the dry run counts +// them from the disk with no job; the body is checked before anything. + +const corpus = await setupOpsCorpus(null); +await corpus.writeSettings(); +await corpus.writeChannelConfig("demo-streams", { handling: "youtube", url: "https://www.youtube.com/@demo", chat: "later" }); +const DATA = path.join(corpus.transcripts, "channels", "demo-streams", "data"); +for (const [id, live] of [["stream00001", "was_live"], ["stream00002", "was_live"], ["upload00001", "not_live"]]) { + await mkdir(path.join(DATA, id), { recursive: true }); + await writeFile( + path.join(DATA, id, "metadata.info.json"), + JSON.stringify({ id, title: id, live_status: live, upload_date: "20251001", webpage_url: `https://www.youtube.com/watch?v=${id}` }), + ); +} + +const { POST } = await import("./route"); +test.after(() => corpus.cleanup()); + +test("a dry run counts the streams whose chat is not here, and starts no job", async () => { + const before = await corpus.listJobIds(); + const res = await callPost(POST, { slug: "demo-streams", dryRun: true }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.chats, 2); + assert.equal(res.body.notStreams, 1); + assert.deepEqual([...(res.body.ids as string[])].sort(), ["stream00001", "stream00002"]); + assert.deepEqual(await corpus.listJobIds(), before); +}); + +test("the body is checked first: a bad limit, a limit on a dry run, an unknown key", async () => { + assert.match(String((await callPost(POST, { slug: "demo-streams", limit: 0 })).body.error), /"limit" must be a whole number above 0/); + assert.match(String((await callPost(POST, { slug: "demo-streams", dryRun: true, limit: 5 })).body.error), /a dry run starts no job/); + assert.equal((await callPost(POST, { slug: "demo-streams", ids: ["x"] })).status, 400); +}); diff --git a/editor/app/api/ops/fetch-chat-backlog/route.ts b/editor/app/api/ops/fetch-chat-backlog/route.ts @@ -0,0 +1,52 @@ +import { NextResponse } from "next/server"; +import { + fetchChatBacklogAction, + previewChatBacklogAction, +} from "../../../channels/[slug]/chatBacklogActions"; +import { jobResponse, OpsInputError, ops, opsFail, optBool, optString, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?, limit?, queueKey? } -> { ok: true, jobId } +// | { ok: true, dryRun: true, chats, … } +// +// A channel's stream chats, after its downloads (2026-10-26; +// controller/chatBacklog.ts): every held video whose metadata says it was a +// stream (`live_status` was_live / post_live) and whose chat is not here, one +// at a time through fetch-chat's pass — the channel's cookies, the platform's +// live pace and the batch downloads' gap between two — on the platform's +// download queue. A re-run skips every chat here and every stream known to +// have none (`chat-backlog.json`). `limit` caps the chats this run asks for. +// The download lane queues the same job by itself for a channel whose `chat` +// is "later" once it has nothing left to download. +// +// `dryRun` answers from the disk alone, no job: `chats` (to get, newest +// first; `ids` the first 50), `normalizeOnly` (raw replays already here), +// `have`, `settled` (known to have none), `notStreams`. +// +// Answered without a job, `info: true`: a channel on a platform with no chat +// fetcher, a backlog already queued or running, a held platform or one in a +// rate-limit cooldown. +export async function POST(request: Request) { + return ops(request, ["slug", "dryRun", "limit", "queueKey"], async (body) => { + const slug = reqSlug(body, "slug"); + const limit = body.limit; + if (limit !== undefined && !(typeof limit === "number" && Number.isInteger(limit) && limit > 0)) { + throw new OpsInputError('"limit" must be a whole number above 0'); + } + if (optBool(body, "dryRun")) { + if (limit !== undefined || body.queueKey !== undefined) { + throw new OpsInputError('a dry run starts no job: "limit" and "queueKey" go with a real run'); + } + const preview = await previewChatBacklogAction(slug); + if (!preview.ok) return opsFail(preview.error); + return NextResponse.json({ ...preview, dryRun: true }); + } + return jobResponse( + await fetchChatBacklogAction(slug, { + ...(typeof limit === "number" ? { limit } : {}), + ...(optString(body, "queueKey") ? { queueKey: optString(body, "queueKey") } : {}), + }), + ); + }); +} diff --git a/editor/app/api/ops/job/route.test.ts b/editor/app/api/ops/job/route.test.ts @@ -210,3 +210,30 @@ test("job verbs: an unknown verb, missing ids, ids on retry-failed and a bad id // Nothing was cancelled by any of them. assert.equal(getRegistry().get("WAIT1")?.status, "queued"); }); + +test("job resume-interrupted: a dry run lists the interrupted job it would re-queue; a stray id or dryRun elsewhere is refused", async () => { + await writeFile( + path.join(JOBS, "RESUMEA1.meta.json"), + JSON.stringify({ + id: "RESUMEA1", + kind: "import-archive-org", + queueKey: "platform:archiveorg", + channelSlug: "demo", + status: "cancelled", + cancelReason: "interrupted: the process running it stopped before it finished", + queuedAt: Date.now() - 60_000, + endedAt: Date.now() - 30_000, + spec: { kind: "import-archive-org", slug: "demo", params: { item: "demo-item", match: "." } }, + }), + ); + const dry = await post({ verb: "resume-interrupted", dryRun: true }); + assert.equal(dry.status, 200); + assert.deepEqual(dry.json.wouldResume, [{ id: "RESUMEA1", kind: "import-archive-org", channelSlug: "demo" }]); + assert.deepEqual(dry.json.jobIds, []); + const stray = await post({ verb: "resume-interrupted", ids: ["NOTAJOB1"], dryRun: true }); + assert.equal(stray.status, 400); + assert.match(String(stray.json.error), /not an interrupted job that was not resumed already: NOTAJOB1/); + const elsewhere = await post({ verb: "cancel", ids: ["RESUMEA1"], dryRun: true }); + assert.equal(elsewhere.status, 400); + assert.match(String(elsewhere.json.error), /"dryRun" goes with "resume-interrupted"/); +}); diff --git a/editor/app/api/ops/job/route.ts b/editor/app/api/ops/job/route.ts @@ -7,13 +7,17 @@ import { retryAllFailedAction, retryJobAction, } from "../../../jobs/actions"; -import { OpsInputError, oneOf, ops, opsFail, reqStringArray } from "../_lib"; +import { OpsInputError, oneOf, ops, opsFail, optBool, reqStringArray } from "../_lib"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { resumeInterruptedJobs } from "yt-dlp-transcript-common/jobs/resumeInterrupted"; +import { runJobSpec } from "../../../jobs/runJobSpec"; export const dynamic = "force-dynamic"; // POST { verb: "cancel" | "drain" | "promote" | "force-release" | "retry", // ids: [<jobId>, …] } // | { verb: "retry-failed" } +// | { verb: "resume-interrupted", ids?: [<jobId>, …], dryRun? } // // The buttons on a /jobs row, over HTTP — each verb is the row's server action // and nothing more (`editor/app/jobs/actions.ts`), so a job cancelled here and @@ -29,6 +33,14 @@ export const dynamic = "force-dynamic"; // queue; the new job's id is returned (`jobIds`). // retry-failed every failed job still in the registry that has one — // the /jobs page's Retry all. Takes no ids. +// resume-interrupted +// what the boot does on its own (jobs/resumeInterrupted.ts): +// re-queue the jobs a restart interrupted in the last 24 h +// whose kind resumes on a re-run — each once, never one +// interrupted twice in a row, a dry run or a full posts +// re-walk — or only the `ids` named. `dryRun` lists what it +// would re-queue and changes nothing. Answers `resumed`, +// `wouldResume` and `notResumed` (each with its reason). // // Every id is acted on in turn and answered in `results` ({id, ok, jobId?, // error?}); one that could not be (an unknown id, a job no longer queued for a @@ -42,20 +54,22 @@ const VERBS = [ "force-release", "retry", "retry-failed", + "resume-interrupted", ] as const; type Verb = (typeof VERBS)[number]; type Result = { id: string; ok: boolean; jobId?: string; error?: string }; // What a row action's `false` means, per verb — the action itself only says no. -const REFUSED: Record<Exclude<Verb, "retry" | "retry-failed">, string> = { +type RowVerb = Exclude<Verb, "retry" | "retry-failed" | "resume-interrupted">; +const REFUSED: Record<RowVerb, string> = { cancel: "not queued or running (or unknown)", drain: "not queued or running (or unknown)", promote: "not queued, or already at the front of its queue", "force-release": "", }; -const DONE: Record<Exclude<Verb, "retry-failed">, string> = { +const DONE: Record<Exclude<Verb, "retry-failed" | "resume-interrupted">, string> = { cancel: "cancelled", drain: "drained", promote: "promoted", @@ -75,14 +89,53 @@ async function act(verb: Verb, id: string): Promise<Result> { drain: drainJobAction, promote: promoteJobAction, "force-release": forceReleaseJobAction, - }[verb as Exclude<Verb, "retry" | "retry-failed">]; + }[verb as RowVerb]; const { ok } = await run(id); return ok ? { id, ok } : { id, ok, error: REFUSED[verb as keyof typeof REFUSED] }; } +// The re-queue the boot uses: the path Retry takes. +async function requeue(spec: Parameters<typeof runJobSpec>[0]) { + const res = await runJobSpec(spec); + if (!res.ok) return { ok: false as const, error: res.error }; + void res.stream.cancel(); + return { ok: true as const, jobId: res.jobId }; +} + export async function POST(request: Request) { - return ops(request, ["verb", "ids"], async (body) => { + return ops(request, ["verb", "ids", "dryRun"], async (body) => { const verb = oneOf(body, "verb", VERBS); + if (verb !== "resume-interrupted" && body.dryRun !== undefined) { + throw new OpsInputError(`"dryRun" goes with "resume-interrupted", not "${verb}"`); + } + if (verb === "resume-interrupted") { + const ids = body.ids === undefined ? undefined : [...new Set(reqStringArray(body, "ids"))]; + const dryRun = optBool(body, "dryRun") ?? false; + const outcomes = await resumeInterruptedJobs({ + paths: getPaths(), + requeue, + dryRun, + ...(ids ? { ids } : {}), + }); + const resumed = outcomes.flatMap((o) => + o.action === "resumed" ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug, jobId: o.newId }] : [], + ); + const wouldResume = outcomes.flatMap((o) => + o.action === "would-resume" ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug }] : [], + ); + const notResumed = outcomes.flatMap((o) => + o.action === "not-resumed" + ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug, category: o.category, reason: o.reason }] + : [], + ); + // A named id that is not an interrupted job is said, not ignored. + const unknown = ids ? ids.filter((id) => !outcomes.some((o) => o.id === id)) : []; + const answer = { verb, dryRun, resumed, wouldResume, notResumed, jobIds: resumed.map((r) => r.jobId) }; + if (unknown.length) { + return opsFail(`not an interrupted job that was not resumed already: ${unknown.join(", ")}`, 400, answer); + } + return NextResponse.json({ ok: true, ...answer }); + } if (verb === "retry-failed") { if (body.ids !== undefined) { throw new OpsInputError('"retry-failed" takes no "ids" — it retries every failed job'); diff --git a/editor/app/api/ops/transcribe-bucket/route.test.ts b/editor/app/api/ops/transcribe-bucket/route.test.ts @@ -0,0 +1,70 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, utimes, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/transcribe-bucket/route.test.ts" +// +// A REPORT BEHIND THE DISK IS REGENERATED FIRST (2026-10-26): 64 archive.org +// imports sat untranscribed because the channel's report predated them, and +// `transcribe-bucket` answered "N of ids not in the downloadedNoTranscript +// bucket". The route now regenerates the report once and reads the bucket +// again. The job it starts waits behind a held queue and is cancelled: nothing +// is transcribed. + +const corpus = await setupOpsCorpus(null); +await corpus.writeSettings(); +await corpus.writeChannelConfig("demo-audio", { handling: "transcribe", url: "https://archive.org/details/demo" }); +const CHANNEL = path.join(corpus.transcripts, "channels", "demo-audio"); +// A report from before the import: no videos at all. +await writeFile( + path.join(CHANNEL, "snapshot.json"), + JSON.stringify({ generatedAt: "2026-10-26T01:10:00.000Z", totals: { videos: 0 }, buckets: { downloadedNoTranscript: [] } }), +); +const past = new Date(Date.now() - 60 * 60 * 1000); +await utimes(path.join(CHANNEL, "snapshot.json"), past, past); +// What the import landed since. +const dir = path.join(CHANNEL, "data", "imported0001"); +await mkdir(dir, { recursive: true }); +await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ id: "imported0001", title: "Episode 1", upload_date: "20200101", duration: 60 }), +); +await writeFile(path.join(dir, "audio.mp3"), Buffer.alloc(4096, 1)); + +const { POST } = await import("./route"); +const { getRegistry, newJobId } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => corpus.cleanup()); + +test("ids the stale report does not hold: the report is regenerated, and the job starts", async () => { + const registry = getRegistry(); + const queueKey = `test-hold-${newJobId()}`; + const holder = { + id: newJobId(), + kind: "test-holder", + queueKey, + status: "queued" as const, + queuedAt: Date.now(), + logPath: "/dev/null", + }; + registry.register(holder); + registry.enqueue(holder, { start: () => {}, onCancel: () => {} }); + try { + const res = await callPost(POST, { slug: "demo-audio", ids: ["imported0001"], queueKey }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + const jobId = String(res.body.jobId); + assert.equal(registry.get(jobId)?.kind, "whisper-bucket-downloaded-no-transcript"); + assert.deepEqual(registry.get(jobId)?.spec?.params?.ids, ["imported0001"], "an ad-hoc selection replays as its ids"); + registry.cancel(jobId); + } finally { + registry.finalize(holder.id, "done"); + } +}); + +test("an id no report holds is still refused, after the one regeneration", async () => { + const res = await callPost(POST, { slug: "demo-audio", ids: ["notavideo01"] }); + assert.equal(res.status, 400); + assert.match(String(res.body.error), /1 of "ids" not in the "downloadedNoTranscript" bucket of demo-audio: notavideo01/); +}); diff --git a/editor/app/api/ops/transcribe-bucket/route.ts b/editor/app/api/ops/transcribe-bucket/route.ts @@ -1,5 +1,12 @@ +import path from "node:path"; +import { stat } from "node:fs/promises"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channels"; +import { channelExists, readChannelSnapshot } from "yt-dlp-transcript-common/controller/channels"; +import { + refreshReportWaitNotice, + requestRefreshReport, + waitForRefreshReport, +} from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import { AUDIO_FORMAT_VALUES } from "yt-dlp-transcript-common/lib/channelConfig"; import { transcribeBucketAction } from "../../../channels/[slug]/whisperActions"; import { @@ -7,6 +14,7 @@ import { OpsInputError, oneOf, ops, + opsFail, optBool, optString, optSubset, @@ -24,20 +32,86 @@ export const dynamic = "force-dynamic"; // it would skip every video in this bucket. // // `ids` NARROWS THE BUCKET, it never widens it (optSubset). With `ids` the job -// carries no bucket key and is not replayable, as an ad-hoc selection is not. +// carries no bucket key and replays as those ids (a re-run skips the ones +// transcribed since). +// +// A REPORT BEHIND THE DISK IS REGENERATED FIRST, once (2026-10-26). The bucket +// is the report's, and a report written before an import landed says "No +// video ids supplied" (an empty bucket) or "64 of ids not in the bucket" for +// audio that is right there. When the bucket is empty, or `ids` names videos +// outside it, and the report is older than the channel's data (reportBehindDisk), +// the route asks for the channel's report on the refresh-report queue, waits +// for it (REGEN_WAIT_MS), and reads the bucket again; a report still +// regenerating when the wait runs out is said, with its job id. +const REGEN_WAIT_MS = 90_000; + +function bucketMisses(bucketIds: readonly string[], ids: unknown): boolean { + if (bucketIds.length === 0) return true; + if (!Array.isArray(ids)) return false; + const known = new Set(bucketIds); + return ids.some((id) => typeof id === "string" && !known.has(id)); +} + +const mtimeOf = (p: string) => stat(p).then((s) => s.mtimeMs, () => null); + +// Is the report OLDER than what it reports on? A new video dir moves `data/`'s +// mtime; audio landing in a named video's dir moves that dir's. A report +// written after both is current, and its answer stands. +async function reportBehindDisk(channelDir: string, ids: unknown): Promise<boolean> { + const report = await mtimeOf(path.join(channelDir, "snapshot.json")); + if (report === null) return true; + const dirs = [path.join(channelDir, "data")]; + if (Array.isArray(ids)) { + for (const id of ids) { + if (typeof id === "string" && /^[A-Za-z0-9_-]+$/.test(id)) dirs.push(path.join(channelDir, "data", id)); + } + } + for (const d of dirs) { + const m = await mtimeOf(d); + if (m !== null && m > report) return true; + } + return false; +} + export async function POST(request: Request) { return ops( request, ["slug", "ids", "queueKey", "audioFormat", "strictAudioFormat"], async (body) => { const slug = reqSlug(body, "slug"); - const snapshot = await readChannelSnapshot(getPaths(), slug); + const paths = getPaths(); + let snapshot = await readChannelSnapshot(paths, slug); + if ( + bucketMisses(snapshot?.buckets.downloadedNoTranscript ?? [], body.ids) && + (await channelExists(paths, slug)) && + (await reportBehindDisk(path.join(paths.channelsDir, slug), body.ids)) + ) { + const asked = await requestRefreshReport(paths, slug); + if (asked.ok) { + const wait = await waitForRefreshReport(paths, asked.jobId, { timeoutMs: REGEN_WAIT_MS }); + if (wait.state === "waiting") { + throw new OpsInputError( + `${slug}'s report is behind what is on disk and is being regenerated: ${refreshReportWaitNotice(wait)} ` + + "Ask again when it ends.", + ); + } + if (wait.state === "failed") throw new OpsInputError(`${slug}'s report could not be regenerated: ${wait.error}`); + snapshot = await readChannelSnapshot(paths, slug); + } + } if (!snapshot) { throw new OpsInputError( `Channel "${slug}" has no report yet — run /api/ops/refresh-report first.`, ); } const bucketIds = snapshot.buckets.downloadedNoTranscript ?? []; + if (bucketIds.length === 0 && body.ids === undefined) { + return opsFail( + `Nothing to transcribe on ${slug}: its report holds no downloaded, untranscribed audio.`, + 400, + { info: true }, + ); + } const subset = optSubset( body, "ids", diff --git a/editor/app/channels/[slug]/attachMediaActions.ts b/editor/app/channels/[slug]/attachMediaActions.ts @@ -73,6 +73,7 @@ export async function attachMediaAction( ...(opts.fillDates ? { fillDates: true } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog, + onAttached: () => ctx.itemLanded(), signal, drainSignal: ctx.drainSignal, }); diff --git a/editor/app/channels/[slug]/chatBacklogActions.ts b/editor/app/channels/[slug]/chatBacklogActions.ts @@ -0,0 +1,67 @@ +"use server"; + +// A CHANNEL'S STREAM CHATS AFTER ITS DOWNLOADS (2026-10-26): the Download +// stage's "Fetch chat backlog" and `pnpm ops fetch-chat-backlog`, over the one +// job controller/chatBacklog.ts makes (the download lane makes the same one +// for a `chat: "later"` channel with nothing left to download). +// +// NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use server" file). + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy"; +import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { planChatBacklog, startChatBacklogJob } from "yt-dlp-transcript-common/controller/chatBacklog"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; + +export async function fetchChatBacklogAction( + slug: string, + opts: { limit?: number; queueKey?: string } = {}, +): Promise<StreamActionResult> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + if (opts.limit !== undefined && !(Number.isInteger(opts.limit) && opts.limit > 0)) { + return { ok: false, error: '"limit" must be a whole number above 0' }; + } + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + return startChatBacklogJob({ + paths, + slug, + config, + cookiePolicy: resolveCookiePolicy(getSettings(), config), + ...(opts.limit ? { limit: opts.limit } : {}), + ...(opts.queueKey ? { queueKey: opts.queueKey } : {}), + }); +} + +export type ChatBacklogPreview = + | { + ok: true; + chats: number; + normalizeOnly: number; + have: number; + settled: number; + notStreams: number; + // The first 50, newest first. + ids: string[]; + } + | { ok: false; error: string }; + +// What a run would do, from the disk alone: no request, no job. +export async function previewChatBacklogAction(slug: string): Promise<ChatBacklogPreview> { + if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` }; + const paths = getPaths(); + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, error: `Channel "${slug}" not found` }; + const plan = await planChatBacklog(paths, slug, config); + return { + ok: true, + chats: plan.candidates.length, + normalizeOnly: plan.candidates.filter((c) => c.action === "normalize").length, + have: plan.have, + settled: plan.settled, + notStreams: plan.notStreams, + ids: plan.candidates.slice(0, 50).map((c) => c.id), + }; +} diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx @@ -20,6 +20,7 @@ import { downloadMissingSubsAction, } from "../../pipelineActions"; import { RetryBucketControl } from "../RetryBucketControl"; +import { fetchChatBacklogAction } from "../../chatBacklogActions"; import { VideoIdList } from "../VideoIdList"; type Props = { @@ -196,7 +197,7 @@ export function DownloadStage({ // the word, on a page where the other two were a lane and a // per-channel action. Nothing about this shares a queue, a pause or a // counter with the speaker lane. - desc="Fetch missing subtitle tracks (live_chat, alt-language captions) for already-downloaded videos. Reads each video's metadata.info.json for advertised tracks, then re-invokes yt-dlp with --skip-download for any whose expected sub file is missing on disk. Uses the channel's subLangs config (defaults to en.*,live_chat)." + desc="Fetch missing subtitle tracks (live_chat, alt-language captions) for already-downloaded videos. Reads each video's metadata.info.json for advertised tracks, then re-invokes yt-dlp with --skip-download for any whose expected sub file is missing on disk. Uses the channel's caption languages (defaults to en.*,live_chat) — without live_chat when its Live chat replay is Later or Never." /> <label className="flex items-center gap-2 text-sm"> <input @@ -228,6 +229,18 @@ export function DownloadStage({ } /> </div> + <div className="flex flex-col gap-2"> + <Heading + title="Fetch chat backlog" + desc="Fetch the live chat replay of every downloaded stream (metadata live_status was_live) that has none yet, one at a time at the platform's pace, on its download queue. Skips chats already here and streams known to have none; stops on a rate limit and picks up where it stopped when run again. A channel whose Live chat replay is Later gets this from the download lane by itself once it has nothing left to download." + /> + <StreamActionLog + trigger={() => fetchChatBacklogAction(slug)} + cancelAction={cancelJobAction} + buttonLabel="Fetch chat backlog" + runningLabel="Fetching chats…" + /> + </div> <NoTranscriptList slug={slug} ids={noTranscriptIds} diff --git a/editor/app/channels/[slug]/normalizeActions.ts b/editor/app/channels/[slug]/normalizeActions.ts @@ -59,6 +59,18 @@ export async function normalizeChannelAction( queueKey: resolveQueueKey(channelQueueKey(slug), queueKey), paths, channelSlug: slug, + // Replayable (2026-10-26): a re-run leaves every fresh cues.json alone, + // so a Retry — or the boot's resume of a pass a restart interrupted — + // writes only what is still missing or stale. + spec: { + kind: "normalize-transcripts", + slug, + params: { + queueKey, + ...(opts.ids ? { ids: opts.ids } : {}), + ...(opts.force ? { force: true } : {}), + }, + }, fn: async (onLog, signal) => { const result = await normalizeChannelTranscripts({ paths, diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts @@ -115,6 +115,7 @@ export async function persistChannelVideosAction( gapMs, minFreeMemMb, onLog, + onPersisted: () => ctx.itemLanded(), signal, drainSignal: ctx.drainSignal, }); diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -660,6 +660,10 @@ export async function importVideoAction( paths, channelSlug: slug, videoId, + // Replayable (2026-10-26): the URL as asked, so a Retry — or the boot's + // resume of an import a restart interrupted — asks this action again, + // which re-resolves it and refuses a file already on disk. + spec: { kind: "import-one", slug, params: { url, queueKey } }, fn: async (onLog, signal, _setProgress, ctx) => { const task = makeTaskTracker(ctx, onLog).start({ id: videoId ?? videoUrl, @@ -871,6 +875,22 @@ export async function importArchiveOrgAction( queueKey: platformQueueKey("archiveorg"), paths, channelSlug: slug, + // Replayable (2026-10-26): the request as asked. A re-run skips every file + // already held, so a Retry — or the boot's resume of an import a restart + // interrupted — continues where it stopped. + spec: { + kind: "import-archive-org", + slug, + params: { + ...(opts.item !== undefined ? { item: opts.item } : {}), + ...(opts.items !== undefined ? { items: opts.items } : {}), + ...(opts.query !== undefined ? { query: opts.query } : {}), + ...(opts.limit !== undefined ? { limit: opts.limit } : {}), + ...(opts.files !== undefined ? { files: opts.files } : {}), + ...(opts.match !== undefined ? { match: opts.match } : {}), + ...(opts.dryRun ? { dryRun: true } : {}), + }, + }, fn: async (onLog, signal, _setProgress, ctx) => { let items = requests; if (opts.query !== undefined) { @@ -897,7 +917,12 @@ export async function importArchiveOrgAction( drainSignal: ctx.drainSignal, dryRun: opts.dryRun, deps: { - onImported: (id) => safeRevalidate([`/channels/${slug}/videos/${id}`]), + onImported: (id) => { + safeRevalidate([`/channels/${slug}/videos/${id}`]); + // The channel's report (and the lanes reading it) see each file + // as it lands, not hours later when the import ends (2026-10-26). + ctx.itemLanded(); + }, }, }); const summary = summarizeArchiveOrgBatch(batch); diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -103,8 +103,8 @@ export async function transcribeBucketAction( audioFormat?: AudioFormat, strictAudioFormat?: boolean, // The snapshot bucket these ids came from (downloadedNoTranscript). Passed by - // the named bucket control so the job is replayable; omitted by ad-hoc - // selections. + // the named bucket control so a replay re-derives the bucket; omitted by + // ad-hoc selections, which replay as their own ids. bucketKey?: ReplayBucket, ): Promise<StreamActionResult> { const paths = getPaths(); @@ -118,6 +118,10 @@ export async function transcribeBucketAction( queueKey: resolveQueueKey(TRANSCRIPTION_QUEUE, queueKey), paths, channelSlug: slug, + // A named bucket replays as the bucket's CURRENT members; an ad-hoc + // selection (2026-10-26) as its own ids — a re-run skips every one already + // transcribed, so a Retry, or the boot's resume of a batch a restart + // interrupted, continues it. spec: bucketKey ? { kind: "whisper-bucket-downloaded-no-transcript", @@ -125,7 +129,11 @@ export async function transcribeBucketAction( bucket: bucketKey, params: { queueKey, audioFormat, strictAudioFormat }, } - : undefined, + : { + kind: "whisper-bucket-downloaded-no-transcript", + slug, + params: { queueKey, audioFormat, strictAudioFormat, ids: cleaned }, + }, fn: async (onLog, signal, setProgress, ctx) => { const stat = await readChannelStat(paths, slug); if (stat) { diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -819,6 +819,47 @@ export function ChannelForm({ </span> </span> </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium"> + Caption languages{" "} + <span className="text-muted-foreground font-normal"> + (yt-dlp --sub-langs) + </span> + </span> + <SeededInput + state={state} + name="subLangs" + initial={c?.subLangs ?? ""} + placeholder="en.*,live_chat" + aria-label="caption languages" + className="rounded border border-border bg-card px-2 py-1 text-sm font-mono" + /> + <span className="text-xs text-muted-foreground"> + Comma-separated; a leading <code>-</code> excludes. Blank ={" "} + <code>en.*,live_chat</code>. + </span> + </label> + <label className="flex flex-col gap-1 text-sm"> + <span className="font-medium">Live chat replay</span> + <SeededSelect + state={state} + name="chat" + initial={c?.chat ?? ""} + aria-label="live chat replay" + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="">With the download — a live_chat caption track</option> + <option value="later"> + Later — downloads skip it; one chat backlog job once downloads are done + </option> + <option value="never">Never — downloads skip it</option> + </SeededSelect> + <span className="text-xs text-muted-foreground"> + A stream&apos;s chat is 7–42 MB and makes its download 2–4× slower. + Later fetches every streamed video&apos;s chat, paced, when the + channel has nothing left to download. + </span> + </label> </Section> <Section title="Retention & persistence"> <label className="flex flex-col gap-1 text-sm"> diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -53,6 +53,9 @@ export const CHANNEL_FORM_VALUES = [ "cookiesFromBrowser", "cookieMode", "storedUrlDownloads", + // Caption languages and when the live chat is fetched (2026-10-26). + "subLangs", + "chat", "downloadFilterInclude", "downloadFilterExclude", "downloadFilterRejectedLivestreams", @@ -122,6 +125,8 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "cookieMode", config.cookieMode); put(fd, "storedUrlDownloads", config.storedUrlDownloads); if (config.browserLookup) fd.set("browserLookup", "on"); + put(fd, "subLangs", config.subLangs); + put(fd, "chat", config.chat); put(fd, "downloadFilterInclude", config.downloadFilter?.include); put(fd, "downloadFilterExclude", config.downloadFilter?.exclude); if (config.downloadFilter?.includeLivestreams) { diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -307,3 +307,28 @@ test("the ops patch round-trips a search channel, its hidden authors kept", () = assert.deepEqual(next.xSearch, { query: "zephyr OR breeze", lang: "en", exclude: ["alice", "bob"] }); assert.equal(next.url, "https://x.com/search?q=zephyr%20OR%20breeze&f=live"); }); + +// 2026-10-26: caption languages and when the live chat comes down are +// Configure fields and `channel-config` patch keys (subLangs could only be set +// offline before). +test("subLangs and chat: parsed, refused when unknown, round-tripped through the ops patch, cleared by empty", () => { + const { config } = parseChannelForm(form({ subLangs: " en.*,es ", chat: "later" })); + assert.equal(config.subLangs, "en.*,es"); + assert.equal(config.chat, "later"); + // The default chat mode is not stored: choosing it clears a stored one. + assert.equal("chat" in parseChannelForm(form({ chat: "with-download" })).config, false); + assert.throws(() => parseChannelForm(form({ chat: "sometimes" })), /Live chat must be one of: with-download, later, never/); + for (const k of ["subLangs", "chat"]) assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes(k), k); + + const fd = channelConfigToFormData({ handling: "youtube", name: "Example VODs", subLangs: "en.*,live_chat" }); + validateChannelFormPatch({ chat: "never" }); + applyChannelFormPatch(fd, { chat: "never" }); + const patched = parseChannelForm(fd).config; + assert.equal(patched.chat, "never"); + assert.equal(patched.subLangs, "en.*,live_chat", "a patch that does not name subLangs keeps it"); + const back = channelConfigToFormData(patched); + applyChannelFormPatch(back, { subLangs: "", chat: "" }); + const cleared = parseChannelForm(back).config; + assert.equal("subLangs" in cleared, false); + assert.equal("chat" in cleared, false); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -46,7 +46,7 @@ import { import { downloadFilterPatternProblem } from "yt-dlp-transcript-common/lib/downloadFilters"; import { recordedDatePatternProblem } from "yt-dlp-transcript-common/lib/recordedDate"; import { mirrorSlugs } from "yt-dlp-transcript-common/lib/mirrors/config"; -import { isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; +import { CHAT_MODES, isChatMode, isRejectedLivestreamMode } from "yt-dlp-transcript-common/lib/channelConfig"; import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPolicy"; export type ParsedChannelForm = { @@ -81,6 +81,10 @@ export const CHANNEL_FORM_FIELDS = [ "audioCheck", "storedUrlDownloads", "browserLookup", + // 2026-10-26: Configure fields since then (subLangs could only be set + // offline before, with patchChannelConfig). + "subLangs", + "chat", "downloadFilter", "recordedDate", "mirror", @@ -274,6 +278,15 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { isStoredUrlMode(storedUrlRaw) && storedUrlRaw !== "never" ? storedUrlRaw : undefined; // The browser lookup (release 32 R9): a checkbox; unchecked = omitted. const browserLookup = formData.get("browserLookup") != null; + // Caption languages and the live chat (2026-10-26). Blank = the default + // (`en.*,live_chat`), omitted; "with-download" is the default chat mode, + // omitted too, so choosing it clears a stored mode. + const subLangs = stringOrUndef(formData, "subLangs"); + const chatRaw = String(formData.get("chat") ?? "").trim(); + if (chatRaw && !isChatMode(chatRaw)) { + throw new Error(`Live chat must be one of: ${CHAT_MODES.join(", ")}`); + } + const chat = isChatMode(chatRaw) && chatRaw !== "with-download" ? chatRaw : undefined; // Download filter. Both patterns are regex SOURCES compiled with "i" at // download time, so the form is the place that refuses an unparseable one: @@ -456,6 +469,8 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (audioCheck) config.audioCheck = audioCheck; if (storedUrlDownloads) config.storedUrlDownloads = storedUrlDownloads; if (browserLookup) config.browserLookup = true; + if (subLangs) config.subLangs = subLangs; + if (chat) config.chat = chat; if (downloadFilter) config.downloadFilter = downloadFilter; if (recordedDateTitlePattern) { config.recordedDate = { titlePattern: recordedDateTitlePattern }; diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -20,7 +20,10 @@ import { downloadAction, downloadMissingAction, downloadMissingSubsAction, + importArchiveOrgAction, + importVideoAction, retryBucketAction, + type ArchiveOrgImportEntry, storePlaylistAction, runMetadataScanAction, syncAction, @@ -61,6 +64,9 @@ import { } from "../channels/[slug]/videos/[id]/videoActions"; import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAction"; import { browserLookupAction } from "../channels/[slug]/browserLookupActions"; +import { normalizeChannelAction } from "../channels/[slug]/normalizeActions"; +import { fetchChatBacklogAction } from "../channels/[slug]/chatBacklogActions"; +import { startRefreshReport } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction"; import { reportsExportAction } from "../sites/lib/reportsExportAction"; @@ -280,6 +286,18 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { }, "whisper-bucket-downloaded-no-transcript": async (spec) => { const { p, queueKey } = params(spec); + // An ad-hoc selection (`transcribe-bucket` with ids, a bulk selection) + // replays as its own ids; the batch skips the ones transcribed since. + const own = strings(p.ids); + if (!spec.bucket && own?.length) { + return transcribeBucketAction( + spec.slug, + own, + queueKey, + str(p.audioFormat) as AudioFormat | undefined, + bool(p.strictAudioFormat), + ); + } if (!spec.bucket) return { ok: false, error: "Job spec is missing its bucket." }; const ids = await idsForBucket(spec.slug, spec.bucket); if (ids.length === 0) { @@ -491,6 +509,55 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { const { queueKey } = params(spec); return checkKeptDeletedAction(spec.slug, queueKey); }, + // The URL as asked: the action re-resolves it, and refuses an archive.org or + // BitChute file already on disk (2026-10-26). + "import-one": (spec) => { + const { p, queueKey } = params(spec); + const url = str(p.url); + if (!url) return Promise.resolve({ ok: false, error: "Job spec is missing its URL." }); + return importVideoAction(spec.slug, url, queueKey); + }, + // The archive.org request as asked; the batch skips every file already held, + // so a replay continues an import that stopped (2026-10-26). + "import-archive-org": (spec) => { + const { p } = params(spec); + const items = Array.isArray(p.items) + ? p.items.filter( + (e): e is ArchiveOrgImportEntry => + typeof e === "string" || (!!e && typeof e === "object" && typeof (e as { item?: unknown }).item === "string"), + ) + : undefined; + return importArchiveOrgAction(spec.slug, { + ...(str(p.item) !== undefined ? { item: str(p.item) } : {}), + ...(items ? { items } : {}), + ...(str(p.query) !== undefined ? { query: str(p.query) } : {}), + ...(num(p.limit) !== undefined ? { limit: num(p.limit) } : {}), + ...(strings(p.files) ? { files: strings(p.files) } : {}), + ...(str(p.match) !== undefined ? { match: str(p.match) } : {}), + ...(bool(p.dryRun) ? { dryRun: true } : {}), + }); + }, + // A cues pass: the ids it was narrowed to, and `force`; a re-run leaves + // every fresh cues.json alone (2026-10-26). + "normalize-transcripts": (spec) => { + const { p, queueKey } = params(spec); + const ids = strings(p.ids); + return normalizeChannelAction(spec.slug, queueKey, { + ...(ids?.length ? { ids } : {}), + ...(bool(p.force) ? { force: true } : {}), + }); + }, + // A channel's stream chats: the same cap; a re-run skips every chat here + // and every stream known to have none (2026-10-26). + "fetch-chat-backlog": (spec) => { + const { p, queueKey } = params(spec); + return fetchChatBacklogAction(spec.slug, { + ...(num(p.limit) !== undefined ? { limit: num(p.limit) } : {}), + ...(queueKey ? { queueKey } : {}), + }); + }, + // One channel's report, regenerated on the refresh-report queue. + "refresh-report": async (spec) => startRefreshReport(getPaths(), spec.slug), "persist-kept": (spec) => { const { queueKey } = params(spec); return persistKeptAction(spec.slug, queueKey); diff --git a/editor/e2e/chat-only.spec.ts b/editor/e2e/chat-only.spec.ts @@ -378,3 +378,42 @@ test("the form round-trips the chat-only tier and the ops API sets it", async ({ ).downloadFilter?.rejectedLivestreams, ).toBe("chat-only"); }); + +// CHAT LATER (2026-10-26). A stream's chat replay made each YouTube download of +// a streaming channel 2–4× slower; `chat: "later"` (Configure → Live chat +// replay) leaves it out of the downloads, and the backlog job — the lane's by +// itself, or the Download stage's button — fetches it afterwards, selected by +// the stream's metadata (a download without live_chat records no chat track). +test("chat later: set on the Configure form, then the Download stage's backlog fetches the stream's chat", async ({ + page, +}) => { + test.setTimeout(180_000); + await resetData("title-filter-channel"); + await writeFilterConfig(null); + await generateReport(page, CHANNEL); + + await page.goto(channelStage(CHANNEL, "configure")); + await page.getByLabel("live chat replay").selectOption("later"); + await page.getByLabel("caption languages").fill("en.*"); + await page.getByRole("button", { name: /save changes/i }).click(); + await expect + .poll(async () => { + const c = await readJson<{ chat?: string; subLangs?: string }>(`${ROOT}/config.json`); + return `${c.chat}|${c.subLangs}`; + }) + .toBe("later|en.*"); + await page.reload(); + await expect(page.getByLabel("live chat replay")).toHaveValue("later"); + + await download(page); + expect(await pathExists(`${ROOT}/data/${LIVE}/transcript.live_chat.json`)).toBe(false); + + await page.goto(channelStage(CHANNEL, "download")); + await page.getByRole("button", { name: "Fetch chat backlog" }).click(); + const out = page.getByLabel("Fetch chat backlog output"); + await expect(out).toContainText(/Chat backlog of test-filter: 1 fetched/, { timeout: 60_000 }); + expect(await pathExists(`${ROOT}/data/${LIVE}/live_chat.cues.json`)).toBe(true); + const state = await readJson<{ lastRun?: { complete: boolean; fetched: number } }>(`${ROOT}/chat-backlog.json`); + expect(state.lastRun?.complete).toBe(true); + expect(state.lastRun?.fetched).toBe(1); +}); diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -155,34 +155,68 @@ export async function register() { ); const testServer = process.env.E2E_TEST_ROUTES === "1"; // STALE `running` METAS FROM A DEAD PROCESS (release 17 slice D0): closed - // `cancelled` as interrupted, never re-run — on every boot, idle and test - // server included, because closing one starts nothing. Does not wait for + // `cancelled` as interrupted — on every boot, idle and test server + // included, because closing one starts nothing. Only the resume pass + // below runs any of them again. Does not wait for // the storage pass: it touches no channel. A meta another live process // still owns (`archilyzer run`) is left alone — see writerIsGone. - void settleRunningJobMetas({ + const runningPass = settleRunningJobMetas({ paths: getPaths(), bootedAt, isLive: (id) => getRegistry().get(id) !== undefined, log: (line) => console.log(line), - }).catch(() => {}); + }); + runningPass.catch(() => {}); const cancelOnly = idle || testServer; - void settleAfterStoragePass(storagePass, { + const requeue = async (spec: import("yt-dlp-transcript-common/jobs/jobSpec").JobSpec) => { + const { runJobSpec } = await import("./app/jobs/runJobSpec"); + const res = await runJobSpec(spec); + if (!res.ok) return { ok: false as const, error: res.error }; + // Nobody reads this stream; release it as the ops routes do. + void res.stream.cancel(); + return { ok: true as const, jobId: res.jobId }; + }; + const queuedPass = settleAfterStoragePass(storagePass, { paths: getPaths(), bootedAt, isLive: (id) => getRegistry().get(id) !== undefined, log: (line) => console.log(line), idleReason: idle ? "idle boot" : testServer ? "test server" : undefined, - requeue: cancelOnly - ? null - : async (spec) => { - const { runJobSpec } = await import("./app/jobs/runJobSpec"); - const res = await runJobSpec(spec); - if (!res.ok) return { ok: false, error: res.error }; - // Nobody reads this stream; release it as the ops routes do. - void res.stream.cancel(); - return { ok: true, jobId: res.jobId }; - }, - }).catch(() => {}); + requeue: cancelOnly ? null : requeue, + }); + queuedPass.catch(() => {}); + // RESUME WHAT THE RESTART INTERRUPTED (2026-10-26): the jobs the running + // pass just closed whose kind resumes on a re-run (`resumeOnBoot`, + // jobs/jobKinds.ts) are re-queued through the path Retry uses, after the + // queued pass (so a channel being re-pointed is reachable, and what was + // waiting keeps its place ahead of them). Never on an idle boot or the + // test server, and not with `jobs.resumeInterruptedOnBoot` off. See + // common/jobs/resumeInterrupted.ts. + if (!cancelOnly) { + void (async () => { + const running = await runningPass; + await queuedPass.catch(() => null); + if (running.interrupted.length === 0) return; + const { getSettings } = await import("yt-dlp-transcript-common/lib/settings"); + if (!getSettings().jobs.resumeInterruptedOnBoot) { + console.log( + `[boot] ${running.interrupted.length} interrupted job(s) not resumed: jobs.resumeInterruptedOnBoot is off ` + + "(pnpm ops job resume-interrupted resumes them by hand)", + ); + return; + } + const { resumeInterruptedJobs } = await import( + "yt-dlp-transcript-common/jobs/resumeInterrupted" + ); + await resumeInterruptedJobs({ + paths: getPaths(), + ids: running.interrupted.map((j) => j.id), + requeue, + prefix: "[boot]", + log: (line) => console.log(line), + }); + })().catch(() => {}); + } } catch { /* a boot pass that fails to start must not block server readiness */ } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -20,6 +20,7 @@ // pnpm ops get coverage <slug> // pnpm ops job <cancel|drain|promote|force-release|retry> <id>... [--wait] // pnpm ops job retry-failed | job wait <id>... +// pnpm ops job resume-interrupted [<id>...] [--dry-run] // pnpm ops list // // ARCHILYZER_EDITOR_URL editor base URL (default http://localhost:3001) @@ -42,6 +43,8 @@ // 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 +// pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}' +// pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}' // pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait // pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait // pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait @@ -336,6 +339,7 @@ export const JOB_VERBS = [ "force-release", "retry", "retry-failed", + "resume-interrupted", "wait", ]; @@ -595,6 +599,11 @@ const ACTIONS = [ // result JSON (the project, its URL, the segments) is what stdout carries. "fetch-chat", "find-clips", + // A channel's stream chats after its downloads ({slug, dryRun?, limit?, + // queueKey?}): every held stream whose chat is not here, paced, one at a + // 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 log line a transcribe job ends with: this marker, then the result as @@ -640,6 +649,8 @@ export function parseArgs(argv) { let counts = false; let leads = false; let tail = 0; + // `job resume-interrupted` only: list what would be re-queued. + let dryRun = false; const jobs = {}; // The noun-specific flags seen, checked against GET_FLAGS once the noun is // known: a flag a read does not take is refused, never ignored. @@ -672,6 +683,8 @@ export function parseArgs(argv) { if (err) return err; } else if (arg === "--quiet") { quiet = true; + } else if (arg === "--dry-run") { + dryRun = true; } else if (arg === "--counts") { counts = true; used.add("counts"); @@ -733,6 +746,9 @@ export function parseArgs(argv) { } } if (positional.length === 0) return { help: true }; + if (dryRun && !(positional[0] === "job" && positional[1] === "resume-interrupted")) { + return { error: '--dry-run goes with "job resume-interrupted" (elsewhere, a body\'s "dryRun": true)' }; + } if (json !== null && file !== null) { return { error: "--json and --file are mutually exclusive" }; } @@ -809,6 +825,8 @@ export function parseArgs(argv) { const ids = positional.slice(2); if (verb === "retry-failed") { if (ids.length) return { error: "job retry-failed takes no ids" }; + } else if (verb === "resume-interrupted") { + // Ids are optional: none is every job interrupted in the last 24 h. } else if (ids.length === 0) { return { error: `job ${verb}: needs one or more job ids` }; } @@ -822,7 +840,12 @@ export function parseArgs(argv) { return { method: "POST", path: "/api/ops/job", - body: verb === "retry-failed" ? { verb } : { verb, ids }, + body: + verb === "retry-failed" + ? { verb } + : verb === "resume-interrupted" + ? { verb, ...(ids.length ? { ids } : {}), ...(dryRun ? { dryRun: true } : {}) } + : { verb, ids }, wait, quiet, waitTimeout, @@ -939,6 +962,7 @@ export function usage() { " [--limit <n>]", " pnpm ops job cancel|drain|promote|force-release|retry <id>... [--wait]", " pnpm ops job retry-failed [--wait]", + " pnpm ops job resume-interrupted [<id>...] [--dry-run] [--wait]", " pnpm ops job wait <id>... [--wait-timeout <seconds>]", " pnpm ops get settings [<key>]", " pnpm ops get storage | sites | workers | auto-queue | scheduler", @@ -976,6 +1000,13 @@ export function usage() { " Each id is answered in \"results\"; one that could not be acted on makes", " the answer ok: false without stopping the rest. --wait follows the jobs a", " retry started. job wait <id>... follows jobs already running.", + "job resume-interrupted does by hand what the editor does at boot: re-queues", + " the jobs a restart interrupted (the last 24 h, or the ids named) whose kind", + " resumes on a re-run — an archive.org import, a download-missing, a posts", + " fetch, a persist, a transcription batch… Each once; never one interrupted", + " twice in a row, a dry run or a full posts re-walk; one superseded by a", + " newer job is left. --dry-run lists what it would re-queue (wouldResume)", + " and why the rest are not (notResumed), and changes nothing.", "", "get settings [<key>] is settings.json as the editor reads it (migrated and", " defaulted; a secret is \"<redacted>\"), or one top-level key of it.", @@ -1241,7 +1272,9 @@ export function usage() { ' recorded date: "patch": {"recordedDateTitlePattern": "<regex with named', ' groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror\'s', ' creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md,', - ' mirror; then mirror-scan).', + ' mirror; then mirror-scan). Caption languages and the live chat:', + ' "patch": {"subLangs": "en.*", "chat": "with-download" | "later" |', + ' "never"} (CHANNEL.md, subLangs and chat).', "", 'site-config sets two keys of a site as its form does: {"siteId"} and any of', ' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s', @@ -1327,6 +1360,20 @@ export function usage() { " 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.", "", + '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).", + "", '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"?}.', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -803,6 +803,20 @@ test("job <verb> <id...> posts the verb and the ids to /api/ops/job", () => { assert.match(parseArgs(["job", "cancel", "A1", "--json", "{}"]).error, /not a body/); }); +test("job resume-interrupted: ids optional, --dry-run in the body, and nowhere else", () => { + assert.deepEqual(parseArgs(["job", "resume-interrupted"]).body, { verb: "resume-interrupted" }); + assert.deepEqual(parseArgs(["job", "resume-interrupted", "--dry-run"]).body, { + verb: "resume-interrupted", + dryRun: true, + }); + const p = parseArgs(["job", "resume-interrupted", "A1", "--wait"]); + assert.deepEqual(p.body, { verb: "resume-interrupted", ids: ["A1"] }); + assert.equal(p.wait, true); + assert.match(parseArgs(["job", "cancel", "A1", "--dry-run"]).error, /--dry-run goes with "job resume-interrupted"/); + assert.match(parseArgs(["sync", "--dry-run"]).error, /--dry-run goes with/); + assert.match(usage(), /pnpm ops job resume-interrupted \[<id>\.\.\.\] \[--dry-run\]/); +}); + test("job wait <id...> sends nothing and follows the ids", () => { const p = parseArgs(["job", "wait", "A1", "B2", "--wait-timeout", "60"]); assert.deepEqual(p.waitFor, ["A1", "B2"]); diff --git a/settings.json.example b/settings.json.example @@ -332,5 +332,8 @@ "wholeRecordingPlatforms": [ "rumble" ] + }, + "jobs": { + "resumeInterruptedOnBoot": true } }