commit 4b655971d1ca4b2b469d208cd11c041be381a532
parent 2aaca270a98b3bda0abb24c86633996414aa0ebb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 04:27:49 -0500
Merge lane/live-recording-guard: a live recording retries, keeps its failure, and says so
record-live retries a start that records nothing (from the start, then the live edge), classifies
failures, keeps every part the landed file cannot be shown to hold, and removes nothing before the
landing is stored. Every run has a durable row; failed, interrupted, stalled and kept-part rows show
on /review, the banners and the ops client until acknowledged.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
40 files changed, 3309 insertions(+), 92 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | |
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
-| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` |
+| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` |
| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` |
| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -> {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` |
| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -> {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` |
@@ -155,6 +155,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `local-media-link` | local-media-link links a record the channel already holds to its library original: {"slug", "sourceToken", "media", "fingerprint", "dryRun"?} for an "existing" candidate. Only when the library's .info.json and transcript match the record's byte for byte is external-media.json written ("attached"; "already-linked"; "conflict" keeps a different one). Nothing else changes, and no playback is granted. "dryRun" answers "ready" without writing. | `pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'` |
| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
+| `live-recording-ack` | live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every run of the record that needs a person (or the one run startedAt names): listed still, counted no more. {"slug", "file"} acknowledges a set-aside live-recordings.json (it stays where it is). /review's Acknowledge. | `pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
| `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, every other stream and the chapters copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true encodes again one whose last checks failed; "reverify": true checks its KEPT encode again without encoding (a chunk whose own content failed is encoded again). One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | |
| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "<file>" reviews the active copy that replaced a former original instead. | |
@@ -276,6 +277,8 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
pnpm ops get generation-usage [<YYYY-MM-DD>] | iterations <article>
+ pnpm ops get live-recordings [<slug>[/<id>]] [--all]
+ pnpm ops record-live --json '<body>' --wait-started [--wait-timeout <seconds>]
pnpm ops list
--wait follows the job's log and survives a poll that fails (a busy
@@ -463,6 +466,26 @@ get transcript <videoId> [--slug <slug>] reads one video's cues off disk
the English VTT alone — {source, cuesJson, title?, ..., cues}. Nothing is
written. Without --slug, the channel holding data/<id>/ is found.
+get live-recordings [<slug>[/<id>]] [--all] is THE answer to "is this
+ stream being recorded, and is it growing" — never a job for the video
+ id (a live-chat job is one too). Per run, from its own record: status
+ (recording | interrupted: no job runs it, or the editor shut down |
+ landed | failed | cancelled), job, bytes, lastGrowthAt, parts (each its
+ bytes and lastGrowthAt while recording), stalled (not grown for
+ settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,
+ capturedSeconds (once landed), coverage, attempts, failureClass,
+ fallback, lost, missingStream, keptParts, error, mustKeep,
+ needsAttention, reason, check; `files` names a live-recordings.json that
+ did not read (set aside, never overwritten). Default: what is recording,
+ what needs a person, the last 7 days; --all every run kept
+ (channels/<slug>/live-recordings.json, never pruned of a failure).
+ needsAttention — failed, interrupted, cancelled when must-keep, the
+ stream's start lost, a stream missing, parts kept — stays until
+ live-recording-ack, or (all but kept parts) a later recording that lands
+ the WHOLE stream from its start; /review, /jobs, the channel and video
+ pages show the same rows and the stalled ones, and every ops reply then
+ prints "! N live recordings need you; M ... NOT growing" on stderr.
+
"preview": "<branch>" on deploy-site or build-deploy makes it a Cloudflare
Pages PREVIEW instead of production: the same bundle goes to a branch
alias, https://<branch>.<project>.pages.dev, and the live site is left
diff --git a/OPERATING.md b/OPERATING.md
@@ -1102,6 +1102,9 @@ pnpm ops diarize --json '{"slug":"example"}' --wait # one channe
pnpm ops record-live --json '{"slug":"example-rumble","url":"https://rumble.com/v1abcde-a-live-show.html"}'
pnpm ops record-live --json '{"slug":"example-kick","url":"https://kick.com/somechannel","doNotClean":true,"note":"keep"}'
pnpm ops record-live --json '{"slug":"example-youtube","url":"https://www.youtube.com/watch?v=abcdefghijk","fromStart":true}'
+pnpm ops record-live --json '{"slug":"example-youtube","url":"https://www.youtube.com/watch?v=abcdefghijk","doNotClean":true,"note":"keep"}' --wait-started
+pnpm ops get live-recordings example-youtube/abcdefghijk
+pnpm ops live-recording-ack --json '{"slug":"example-youtube","id":"abcdefghijk"}'
pnpm ops import-media --json '{"slug":"example-rumble","path":"/home/me/Podcasts/v1embed.from-start.mp4.part","url":"https://rumble.com/v1abcde-a-live-show.html","move":true,"dryRun":true}' --wait
pnpm ops import-media --json '{"slug":"example-archive","path":"/mnt/old/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"}}' --wait
pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":"keep"}'
@@ -1121,11 +1124,11 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
an earlier run's unmerged pair is merged and landed by the next run. A stream that is not live is refused:
download it, or import a recording of it.
- **An accepted `record-live` is not a recording.** The job can fail seconds after it is accepted (a
- from-start YouTube attempt that ends "The downloaded file is empty" records nothing), and nothing retries
- it. After starting one, and at every later status report, read the recording's OWN record and its files:
+ from-start YouTube attempt that ends "The downloaded file is empty" records nothing); it is retried on the schedule below, and can still end
+ failed. After starting one, and at every later status report, read the recording's OWN record and its files:
`transcripts/channels/<slug>/data/<id>/live-recording.json` must say `"status": "recording"`, and the part
files beside the channel's saved videos (`.<id>.live-*.ytdlp.*`) must be growing between two looks a minute
- apart. **Never infer it from "a job for this video is active"**: the live-chat capture is a separate job on
+ apart (`pnpm ops get live-recordings <slug>/<id>` answers both). **Never infer it from "a job for this video is active"**: the live-chat capture is a separate job on
the same video id and keeps running when the recorder has died (20 Nov 2026: a recording of a stream that
is privated afterwards failed after 55 s and was reported as "still recording" for seven hours on exactly
that evidence). For a stream that cannot be fetched again (`doNotClean`, a note saying why), keep something
@@ -1133,6 +1136,69 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
`failed` while the stream is still live. A from-start recording of a stream hours old is also not safe
until it has caught up: it downloads the past faster than real time, and what it has not reached is lost
if the stream is removed first.
+- **A from-start attempt that records nothing is tried again, then the live edge** (20 Nov 2026: yt-dlp
+ `--live-from-start` said "The downloaded file is empty" after 55 s, and nothing retried). The schedule: from its
+ start at 0, +60 and +180 s, then from the live edge (`--no-live-from-start`, the request Kick's channel recorder
+ already makes) at 0, +60 and +180 s — at most six recorder spawns in about eight minutes, each wait stretched by
+ `pacing.jitter`, a Cancel ending any wait. A separate-streams attempt where one stream wrote bytes and the other
+ nothing is a failed attempt too, on the same schedule. The failure's class (`failureClass` on the part and the
+ row) decides what follows: **not retried** — the stream has ended or is not live (`ended`), private or removed
+ (`private`), members-only or needs a login (`members`), the disk is full or the store unwritable (`disk`), an argv
+ no try can fix ("Requested format is not available", `argv`), a Cancel; **one more try after 15 min, then stop**
+ — HTTP 429 or "Sign in to confirm you're not a bot" (`rate-limited`), said in the log; **the schedule** — "The
+ downloaded file is empty" (`empty`), network errors (`network`), anything else (`unknown`). A part with bytes in
+ both streams ends the attempts whatever yt-dlp's exit (a normal stream end often exits 1): it lands, unretried.
+ A recording that falls back to the live edge says in the log and the record what it lost ("the first 2 h 14 min
+ are NOT recorded"); that is a failure needing a person even while the live edge records. When the attempts end
+ with one stream missing, the row says which (`missingStream`) and the parts that hold bytes are kept.
+- **The landing never removes media it is not known to hold.** The longest part lands. When the landed file is
+ from the start (or a platform VOD) and covers the whole stream — the `coverage` rule below: its length against the
+ ended stream's `duration`, else the clock, within max(60 s, 1 %) — every other part of the stream, this run's or an
+ earlier one's, is inside it and is removed, with no attention raised; the row lists them as `removedParts` (stem,
+ bytes, why). A shorter part of the same run, both from the start, goes too. When the landed file does NOT cover
+ the stream (live edge only, a partial, or a stream whose length cannot be established), every other part that
+ holds bytes — an earlier run's, one from the live edge, one that cannot be landed as it is, fragments a recorder
+ left — stays in the store's staging dir, listed as `keptParts` (files, sizes, why), and the row needs a person
+ until acknowledged. A later recording does not clear that; nothing removes kept files automatically. On Kick, a
+ VOD that covers the stream removes the channel's live-edge part; one that does not keeps it.
+- **An editor shutdown is not a Cancel.** A run stopped by the editor going down (a restart, a rollout) is
+ `interrupted` (`stoppedBy: "shutdown"`), never `cancelled`, and needs a person — Record again if the stream is still
+ live. A person's Cancel is `cancelled`; it needs a person only when the stream was must-keep (`doNotClean` or a
+ `note`), and is quiet otherwise.
+- **Is it recording, and is it growing? `pnpm ops get live-recordings [<slug>[/<id>]] [--all]`** — never "is there
+ a job for this video id" (a live-chat capture is one too). Each run from its own record: `status` (`recording`,
+ `interrupted` when no record-live job runs it, `landed`, `failed`, `cancelled`), the job, `bytes` and
+ `lastGrowthAt` of its staging files (and each part's own while it records), `stalled` (not grown for
+ `settings.liveRecording.stallMinutes`, 10), `streamElapsedSeconds`, `capturedSeconds` and `coverage` once landed,
+ `attempts`, `failureClass`, `fallback`/`lost`, `missingStream`, `keptParts`, `error` (yt-dlp's own `ERROR:` line,
+ and the attempts), `needsAttention`, `reason`, `check`; `files` names a `live-recordings.json` that did not read.
+ record-live's reply carries that `check` command beside the job id; `--wait-started` exits 0 only once a
+ FROM-START part's bytes grow (the row on stdout; a run asked `"fromStart": false`, any part's), **3** when it records
+ only from the live edge (the start is lost), 1 with the reason it failed, within 15 minutes unless
+ `--wait-timeout` says otherwise. A stalled recording (its job runs, its files do not grow) is said wherever a
+ failure is — the banners, /review, and `stalled=M` in the attention header — but is not acknowledged: it clears
+ when the files grow or the run ends.
+- **`landed` is not "the whole stream".** A recorder that dies mid-stream with bytes (network, a full disk, a 429 on
+ fragments) lands what it has and reads `landed`. `coverage` says whether the landed part holds the stream: its
+ captured seconds against the ended stream's `duration` (else the clock: the last part's end minus the stream's
+ start, which can only overstate it), within max(60 s, 1 %). Only a landed run from its start, with both streams,
+ that covers the stream supersedes an earlier failure of the same id; a live-edge landing, a run asked not from
+ its start and a short partial never do (the earlier failure stays until acknowledged). A short landing's `reason`
+ says how much it holds.
+- **A failure is loud until a person says otherwise.** Every run has a row in `channels/<slug>/live-recordings.json`,
+ written on every save of its record and never removed for failing — also when the run removes the empty
+ `data/<id>/` it made, and also for a refusal before any recorder started. A `live-recordings.json` that does not
+ read is never overwritten: the next write renames it aside (`live-recordings.json.corrupt-<time>`, beside it),
+ starts a new file, and the kept file needs a person (`live-recording-ack {"slug","file"}`). A row needs a person
+ when it failed, was interrupted, was cancelled while must-keep, lost the stream's start, is missing a stream, or
+ kept parts; it is shown on /review ("Live recordings that need you", with
+ **Record again** and **Acknowledge**), as a banner on /jobs and the channel and video pages, and as
+ `! N live recordings need you` on stderr after every `pnpm ops` reply (the `x-archilyzer-attention` header). It
+ stops counting at `live-recording-ack` (or Acknowledge), or (all but kept parts) when a later recording of the same
+ id lands the whole stream from its start. The header rides on every ops GET route as well as every action, `get
+ job` and `get jobs` included. **Record again** asks record-live with the run's own options: from the start or not,
+ quality (`maxHeight`), separate streams, transcribe, keep (`doNotClean`) and its note, and the live pre-clip. No
+ desktop notification: the editor has no such path.
- `import-media` (Media → **Import a file**) makes one file from outside the archive a normal transcribed item:
`"url"` makes or refreshes the record from its page (metadata only, under the id the archive keys it by — a
Rumble URL's id, not the embed id in the file name), `"id"` names a record already here, `"meta"` describes one
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -22,6 +22,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`social`](#social) | object — see below |
| [`sleepBetweenDownloadsSeconds`](#sleepbetweendownloadsseconds) | `10` |
| [`livePreclip`](#livepreclip) | object — see below |
+| [`liveRecording`](#liverecording) | object — see below |
| [`pacing`](#pacing) | object — see below |
| [`downloadFormat`](#downloadformat) | `"auto"` |
| [`sourceVideoQuality`](#sourcevideoquality) | `"original"` |
@@ -252,6 +253,24 @@ Default:
}
```
+## `liveRecording`
+
+How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.
+
+#### `liveRecording`
+
+| Key | Default | Description |
+|---|---|---|
+| `stallMinutes` | `10` | Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, the banners) mark it `stalled`. Clamped 1–240; default 10. |
+
+Default:
+
+```json
+{
+ "stallMinutes": 10
+}
+```
+
## `pacing`
How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.
diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts
@@ -670,7 +670,7 @@ export async function startLivePreclipJob(o: {
const rec = await liveRecordingSidecar.load(videoDir);
if (!rec) return { ok: false, error: `${o.slug}/${o.id} is not being recorded (no live-recording.json): start it with record-live {"preclip": true}` };
if (rec.status !== "recording") {
- return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` };
+ return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" || rec.status === "interrupted" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` };
}
}
const busy = runningJobOf(o.slug, o.id);
diff --git a/common/controller/liveRecordings.test.ts b/common/controller/liveRecordings.test.ts
@@ -0,0 +1,205 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveRecordings.test.ts
+//
+// The live recordings listing (controller/liveRecordings.ts) over a temp
+// corpus: rows written through lib/liveRecordings-server.ts, records and
+// staging files made by hand, the job registry a stub.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-recordings-"));
+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 { listLiveRecordings, acknowledgeLiveRecording, countLiveRecordingsNeedingAttention } = await import("./liveRecordings");
+const { upsertLiveRecordingRow, loadLiveRecordingRows } = await import("../lib/liveRecordings-server");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-live";
+await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true });
+await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Synth" }));
+const store = path.join(paths.savedVideosDir, SLUG);
+await mkdir(store, { recursive: true });
+
+const NOW = new Date("2026-11-20T12:00:00.000Z");
+const minutesAgo = (m: number) => new Date(NOW.getTime() - m * 60_000);
+
+async function recording(id: string, stem: string, opts: { jobId?: string; startedAt?: Date } = {}) {
+ const startedAt = (opts.startedAt ?? minutesAgo(60)).toISOString();
+ const rec = {
+ status: "recording" as const,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ fromStart: true,
+ startedAt,
+ parts: [{ method: "ytdlp" as const, url: "u", fromStart: true, startedAt, stem }],
+ attempts: 1,
+ mustKeep: true,
+ streamStartedAt: minutesAgo(120).toISOString(),
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ };
+ const dir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(dir, { recursive: true });
+ await liveRecordingSidecar.write(dir, rec);
+ await upsertLiveRecordingRow(paths, SLUG, { ...rec, id, mustKeep: true, attempts: 1 });
+ return rec;
+}
+
+test("a recording whose job runs and whose files grow: bytes summed, not stalled, elapsed from the stream's start", async () => {
+ const stem = ".exmplgrow01.live-2026-11-20T11-00-00-000Z.ytdlp";
+ await recording("exmplgrow01", stem, { jobId: "job-grow" });
+ await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(3000));
+ await writeFile(path.join(store, `${stem}.f140.m4a`), Buffer.alloc(1000));
+ for (const f of [`${stem}.f247.webm`, `${stem}.f140.m4a`]) await utimes(path.join(store, f), minutesAgo(1), minutesAgo(1));
+ const { rows } = await listLiveRecordings(paths, {
+ slug: SLUG,
+ id: "exmplgrow01",
+ now: NOW,
+ jobs: () => [{ id: "job-grow", kind: "record-live", status: "running", channelSlug: SLUG, videoId: "exmplgrow01" }],
+ });
+ const r = rows[0]!;
+ assert.equal(r.status, "recording");
+ assert.equal(r.bytes, 4000);
+ assert.equal(r.stalled, false);
+ assert.equal(r.lastGrowthAt, minutesAgo(1).toISOString());
+ assert.equal(r.streamElapsedSeconds, 7200);
+ assert.equal(r.needsAttention, false);
+ assert.equal(r.job?.status, "running");
+ assert.equal(r.check, "pnpm ops get live-recordings synth-live/exmplgrow01");
+});
+
+test("stalled: recording, and nothing has grown for stallMinutes", async () => {
+ const stem = ".exmplstal01.live-2026-11-20T11-00-00-000Z.ytdlp";
+ await recording("exmplstal01", stem, { jobId: "job-stall" });
+ await writeFile(path.join(store, `${stem}.ts`), Buffer.alloc(500));
+ await utimes(path.join(store, `${stem}.ts`), minutesAgo(25), minutesAgo(25));
+ const jobs = () => [{ id: "job-stall", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal01" }];
+ const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 10, jobs })).rows[0]!;
+ assert.equal(r.stalled, true);
+ assert.match(r.reason, /NOT growing/);
+ const later = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 30, jobs })).rows[0]!;
+ assert.equal(later.stalled, false);
+});
+
+test("interrupted: the record says recording and no record-live job runs it — it needs a person until acknowledged", async () => {
+ await recording("exmplintr01", ".exmplintr01.live-2026-11-20T11-00-00-000Z.ytdlp", { jobId: "job-gone" });
+ const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!;
+ assert.equal(r.status, "interrupted");
+ assert.equal(r.needsAttention, true);
+ assert.equal(r.stalled, false, "stalled is for a recording that runs");
+ assert.ok((await countLiveRecordingsNeedingAttention(paths)) >= 1);
+ const ack = await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01", by: "test" });
+ assert.deepEqual(ack, { ok: true, acknowledged: 1 });
+ const after = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!;
+ assert.equal(after.needsAttention, false);
+ assert.equal((await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01" })).ok, false, "nothing left to acknowledge");
+});
+
+test("the default listing: recording, needing a person, or of the last week; --all is everything", async () => {
+ const old = { status: "landed" as const, url: "u", platform: "youtube", fromStart: true, startedAt: "2026-10-01T00:00:00.000Z", endedAt: "2026-10-01T03:00:00.000Z", parts: [] };
+ await upsertLiveRecordingRow(paths, SLUG, { ...old, id: "exmplold001", attempts: 1, mustKeep: false });
+ await upsertLiveRecordingRow(paths, SLUG, { ...old, status: "failed", id: "exmplold002", attempts: 6, mustKeep: true, error: "nothing was recorded" });
+ const ids = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, jobs: () => [] })).rows.map((r) => r.id);
+ assert.ok(!ids.includes("exmplold001"), "an old landed recording is not in the default view");
+ assert.ok(ids.includes("exmplold002"), "an old failure that nobody acknowledged is");
+ const all = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, all: true, jobs: () => [] })).rows.map((r) => r.id);
+ assert.ok(all.includes("exmplold001"));
+ assert.equal((await loadLiveRecordingRows(paths, SLUG)).length, all.length);
+});
+
+test("record-live's reply names the command that answers for the recording", async () => {
+ const { recordLiveCheckCommand } = await import("./recordLive");
+ assert.equal(recordLiveCheckCommand("demo-yt", { url: "https://www.youtube.com/watch?v=exampleid01" }), "pnpm ops get live-recordings demo-yt/exampleid01");
+ assert.equal(recordLiveCheckCommand("demo-yt", { id: "exampleid02" }), "pnpm ops get live-recordings demo-yt/exampleid02");
+ assert.equal(recordLiveCheckCommand("demo-kick", { url: "https://kick.com/somechannel" }), "pnpm ops get live-recordings demo-kick", "a Kick channel's VOD is found in the job");
+});
+
+test("1.8: an unparseable live-recordings.json is never overwritten — set aside under a timestamped name, a new file started, and the kept file needs a person", async () => {
+ const slug = "synth-corrupt";
+ const dir = path.join(CORPUS, "channels", slug);
+ await mkdir(path.join(dir, "data"), { recursive: true });
+ await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Corrupt" }));
+ const garbage = '{"rows": [{"id": "exmplcorr01", "status": "failed", "startedAt": "2026-11-19T00:00:00.000Z"'; // truncated
+ await writeFile(path.join(dir, "live-recordings.json"), garbage);
+ // Read side: said, not moved.
+ const before = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] });
+ assert.equal(before.files.length, 1);
+ assert.equal(before.files[0]!.state, "unreadable");
+ assert.equal(before.files[0]!.reason, "unparseable");
+ assert.ok(before.needsAttention >= 1);
+ // A write: the file is renamed aside, byte for byte, and a new one begins.
+ await upsertLiveRecordingRow(paths, slug, {
+ id: "exmplcorr02",
+ url: "u",
+ platform: "youtube",
+ startedAt: NOW.toISOString(),
+ status: "failed",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [],
+ });
+ const names = (await readdir(dir)).filter((n) => n.startsWith("live-recordings.json"));
+ const aside = names.find((n) => /^live-recordings\.json\.corrupt-\d{4}-\d\d-\d\dT[\d-]+Z$/.test(n));
+ assert.ok(aside, names.join(", "));
+ assert.equal(await readFile(path.join(dir, aside!), "utf8"), garbage, "kept as it was");
+ const after = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] });
+ assert.deepEqual(after.rows.map((r) => r.id), ["exmplcorr02"]);
+ assert.equal(after.files.length, 1);
+ assert.equal(after.files[0]!.state, "set-aside");
+ assert.equal(after.files[0]!.file, aside);
+ assert.match(after.files[0]!.message, new RegExp(aside!.replace(/[.]/g, "\\.")));
+ assert.equal(after.needsAttention, 2, "the new failure and the kept file");
+ // A second write does not set the new (good) file aside.
+ await upsertLiveRecordingRow(paths, slug, { id: "exmplcorr03", url: "u", platform: "youtube", startedAt: NOW.toISOString(), status: "landed", fromStart: true, attempts: 1, mustKeep: false, parts: [] });
+ assert.equal((await readdir(dir)).filter((n) => n.includes(".corrupt-")).length, 1);
+ // Acknowledged: no longer counted; the file stays.
+ assert.deepEqual(await acknowledgeLiveRecording(paths, { slug, file: aside!, by: "test" }), { ok: true, acknowledged: 1 });
+ const acked = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] });
+ assert.equal(acked.files.length, 0);
+ assert.equal(acked.needsAttention, 1);
+ assert.ok((await readdir(dir)).includes(aside!));
+});
+
+test("2.2: a stalled recording is counted beside needsAttention, and each part says its own bytes while it records", async () => {
+ const stem = ".exmplstal02.live-2026-11-20T11-00-00-000Z.ytdlp";
+ await recording("exmplstal02", stem, { jobId: "job-stall2" });
+ await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(700));
+ await utimes(path.join(store, `${stem}.f247.webm`), minutesAgo(40), minutesAgo(40));
+ const jobs = () => [{ id: "job-stall2", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal02" }];
+ const l = await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal02", now: NOW, stallMinutes: 10, jobs });
+ assert.equal(l.stalled, 1);
+ assert.equal(l.rows[0]!.needsAttention, false, "stalled is said on its own, not acknowledged");
+ assert.equal(l.rows[0]!.parts[0]!.bytes, 700);
+ assert.equal(l.rows[0]!.parts[0]!.lastGrowthAt, minutesAgo(40).toISOString());
+});
+
+test("2.5: a row that names its job is recording only while THAT job runs (a newer run of the id is another row)", async () => {
+ await recording("exmplstale1", ".exmplstale1.live-2026-11-20T10-00-00-000Z.ytdlp", { jobId: "job-old" });
+ const jobs = () => [{ id: "job-new", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstale1" }];
+ const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstale1", now: NOW, jobs })).rows[0]!;
+ assert.equal(r.status, "interrupted");
+});
+
+test("needsAttention: interrupted always, a cancel only when must-keep, kept parts even when superseded", async () => {
+ const { rowNeedsAttention } = await import("../lib/liveRecordings-server");
+ const base = { fallback: undefined, acknowledgedAt: undefined, supersededBy: undefined } as const;
+ assert.equal(rowNeedsAttention({ ...base, status: "interrupted", mustKeep: false }), true);
+ assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: true }), true);
+ assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: false }), false);
+ const kept = [{ stem: "s", files: [{ name: "s.mp4", bytes: 9 }], bytes: 9, seconds: 1, fromStart: false, run: "this" as const, why: "w" }];
+ assert.equal(rowNeedsAttention({ ...base, status: "landed", supersededBy: "job-x", keptParts: kept }), true);
+ assert.equal(rowNeedsAttention({ ...base, status: "landed", acknowledgedAt: "t", keptParts: kept }), false);
+ assert.equal(rowNeedsAttention({ ...base, status: "landed", missingStream: "video" }), true);
+});
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -0,0 +1,349 @@
+// IS THIS STREAM BEING RECORDED, AND IS IT GROWING? — `pnpm ops get
+// live-recordings`, GET /api/ops/live-recordings, /review's "Live recordings
+// that need you" and the banners on /jobs, the channel and the video page.
+//
+// One answer for people and agents, read from the recordings' own records —
+// never from "is there a job for this video id" (20 Nov 2026: a live-chat job
+// for the same id was read as the recording for seven hours while the
+// recording had failed). Per run (channels/<slug>/live-recordings.json,
+// lib/liveRecordings-server.ts), cross-checked:
+//
+// status the record's own (data/<id>/live-recording.json, when it
+// is this run's), else the row's; `interrupted` when it
+// says recording and no record-live job runs it
+// bytes while recording: the staging files of its parts, summed
+// (stat only); after: what each part held at its end
+// lastGrowthAt the newest of those files' mtimes
+// parts[].bytes while recording: each part's own bytes and lastGrowthAt
+// (what --wait-started reads: a FROM-START part growing)
+// stalled recording, and nothing has grown for stallMinutes
+// (settings.liveRecording.stallMinutes, default 10) —
+// counted beside needsAttention (`stalled`), said wherever a
+// failure is, never acknowledged (it clears when the files
+// grow again or the run ends)
+// needsAttention failed; interrupted (no job runs it, or the editor's
+// shutdown stopped it); cancelled when must-keep; recorded
+// from the live edge (the stream's start lost); one stream
+// missing; parts kept on disk — until a person acknowledges
+// it, or (all but kept parts) a later recording of the id
+// lands the whole stream (rowCoversStream)
+// files a live-recordings.json that did not read: set aside by a
+// write (its kept name) or, until then, unreadable — needs a
+// person, counted in needsAttention
+//
+// Reads only: no request leaves the machine, nothing is written.
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { getSettings } from "../lib/settings";
+import { livePartFiles, spanWords, type LiveRecordingStatus } from "../lib/liveCapture";
+import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import {
+ LIVE_RECORDINGS_FILENAME,
+ acknowledgeLiveRecordingRows,
+ acknowledgeSetAsideFiles,
+ loadLiveRecordingsFile,
+ rowNeedsAttention,
+ type LiveRecordingRow,
+} from "../lib/liveRecordings-server";
+import { savedVideoRoot } from "../lib/savedVideo";
+import { getRegistry, type JobRecord } from "../jobs/registry";
+import { readChannelConfig } from "./channels";
+
+export const LIVE_STALL_MINUTES_DEFAULT = 10;
+// The default listing: what is recording, what needs a person, and the rest
+// of the last week.
+export const LIVE_RECORDINGS_RECENT_DAYS = 7;
+
+export type LiveRecordingViewStatus = LiveRecordingStatus | "interrupted";
+
+export type LiveRecordingView = Omit<LiveRecordingRow, "status"> & {
+ slug: string;
+ status: LiveRecordingViewStatus;
+ job: { id: string; kind: string; status: string } | null;
+ bytes: number | null;
+ lastGrowthAt: string | null;
+ stalled: boolean;
+ streamElapsedSeconds: number | null;
+ capturedSeconds: number | null;
+ needsAttention: boolean;
+ // One sentence: what happened, for a banner or a line of output.
+ reason: string;
+ // The command that answers for this recording again.
+ check: string;
+};
+
+// A channel's live-recordings.json that did not read.
+export type LiveRecordingsFileProblem = {
+ slug: string;
+ // The kept (set-aside) file's name beside live-recordings.json, or
+ // live-recordings.json itself while it does not read and no write has set
+ // it aside yet.
+ file: string;
+ state: "set-aside" | "unreadable";
+ reason: "unreadable" | "unparseable";
+ at: string | null;
+ needsAttention: boolean;
+ acknowledgedAt?: string;
+ message: string;
+};
+
+export type LiveRecordingsListing = {
+ rows: LiveRecordingView[];
+ // Rows that need a person, plus files that need one.
+ needsAttention: number;
+ // Recordings that run and have not grown for stallMinutes.
+ stalled: number;
+ stallMinutes: number;
+ files: LiveRecordingsFileProblem[];
+};
+
+export type ListLiveRecordingsOpts = {
+ slug?: string;
+ id?: string;
+ // Every row, not only what is recording, needs a person or is recent.
+ all?: boolean;
+ stallMinutes?: number;
+ now?: Date;
+ jobs?: () => readonly Pick<JobRecord, "id" | "kind" | "status" | "channelSlug" | "videoId">[];
+};
+
+export function liveRecordingCheckCommand(slug: string, id: string): string {
+ return `pnpm ops get live-recordings ${slug}/${id}`;
+}
+
+function stallMinutesSetting(): number {
+ try {
+ const v = getSettings().liveRecording?.stallMinutes;
+ return typeof v === "number" && v > 0 ? v : LIVE_STALL_MINUTES_DEFAULT;
+ } catch {
+ return LIVE_STALL_MINUTES_DEFAULT;
+ }
+}
+
+async function channelSlugs(paths: Paths): Promise<string[]> {
+ const entries = await readdir(paths.channelsDir, { withFileTypes: true }).catch(() => []);
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
+}
+
+const ACTIVE = new Set(["running", "queued"]);
+
+function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: number): string {
+ const lostWords =
+ v.lost && v.lost.toSeconds !== null ? `the first ${spanWords(v.lost.toSeconds)} of the stream are NOT recorded` : "the stream's start is NOT recorded";
+ const extra: string[] = [];
+ if (v.missingStream) extra.push(`its ${v.missingStream === "unknown" ? "video or audio" : v.missingStream} stream recorded nothing`);
+ if (v.keptParts && v.keptParts.length) {
+ const b = v.keptParts.reduce((n, k) => n + k.bytes, 0);
+ extra.push(`${v.keptParts.length} part${v.keptParts.length === 1 ? "" : "s"} not landed kept in staging (${Math.round(b / 1024 / 1024)} MB): decide what to do with them`);
+ }
+ if (v.status === "landed" && v.coverage && !v.coverage.covers && v.coverage.streamSeconds !== null && v.coverage.capturedSeconds !== null && !v.fallback) {
+ extra.push(`holds ${spanWords(v.coverage.capturedSeconds)} of a ${spanWords(v.coverage.streamSeconds)} stream (${v.coverage.basis === "duration" ? "its duration" : "by the clock"})`);
+ }
+ const tail = extra.length ? `; ${extra.join("; ")}` : "";
+ const cls = v.failureClass && v.failureClass !== "unknown" ? ` [${v.failureClass}]` : "";
+ switch (v.status) {
+ case "failed":
+ return `failed${cls}: ${v.error ?? "no reason recorded"}${tail}`;
+ case "interrupted":
+ return (
+ (v.stoppedBy === "shutdown"
+ ? "interrupted: the editor shut down while it recorded — Record again if the stream is still live"
+ : "interrupted: its record says recording, and no record-live job runs it (an editor restart?) — Record again") + tail
+ );
+ case "cancelled":
+ return `cancelled${v.mustKeep ? " (a must-keep stream: is that what you wanted?)" : ""}${tail}`;
+ case "landed":
+ return (v.fallback === "live-edge" ? `landed from the live edge: ${lostWords}` : "landed") + tail;
+ case "recording": {
+ const parts = [v.fallback === "live-edge" ? `recording from the live edge: ${lostWords}` : "recording"];
+ if (v.bytes !== null) parts.push(`${Math.round(v.bytes / 1024 / 1024)} MB so far`);
+ if (v.stalled) parts.push(`NOT growing for ${stallMinutes}+ min`);
+ return parts.join("; ") + tail;
+ }
+ }
+}
+
+function fileProblemMessage(slug: string, p: Pick<LiveRecordingsFileProblem, "file" | "state" | "reason">): string {
+ const where = `channels/${slug}/${LIVE_RECORDINGS_FILENAME}`;
+ return p.state === "set-aside"
+ ? `${where} did not read (${p.reason}) and was set aside, kept as channels/${slug}/${p.file}: the runs it listed are not in this listing — read it by hand`
+ : `${where} does not read (${p.reason}): the runs it lists are not in this listing; the next write sets it aside (never overwrites it)`;
+}
+
+// Every live recording (of one channel, one id), newest first.
+export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsOpts = {}): Promise<LiveRecordingsListing> {
+ const now = (opts.now ?? new Date()).getTime();
+ const stallMinutes = opts.stallMinutes ?? stallMinutesSetting();
+ const jobs = (opts.jobs ?? (() => getRegistry().list()))();
+ const byId = new Map(jobs.map((j) => [j.id, j]));
+ const slugs = opts.slug ? [opts.slug] : await channelSlugs(paths);
+ const out: LiveRecordingView[] = [];
+ const files: LiveRecordingsFileProblem[] = [];
+ for (const slug of slugs) {
+ const file = await loadLiveRecordingsFile(paths, slug);
+ if (!opts.id) {
+ if (file.problem) {
+ const p = { file: LIVE_RECORDINGS_FILENAME, state: "unreadable" as const, reason: file.problem };
+ files.push({ slug, ...p, at: null, needsAttention: true, message: fileProblemMessage(slug, p) });
+ }
+ for (const f of file.setAside) {
+ const p = { file: f.file, state: "set-aside" as const, reason: f.reason };
+ if (!f.acknowledgedAt || opts.all) {
+ files.push({
+ slug,
+ ...p,
+ at: f.at,
+ needsAttention: !f.acknowledgedAt,
+ ...(f.acknowledgedAt ? { acknowledgedAt: f.acknowledgedAt } : {}),
+ message: fileProblemMessage(slug, p),
+ });
+ }
+ }
+ }
+ const rows = file.rows.filter((r) => !opts.id || r.id === opts.id);
+ if (!rows.length) continue;
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ const slugStore = path.join(savedVideoRoot(paths, config), slug);
+ let names: string[] | null = null;
+ // The newest row of an id is the run its record (data/<id>/) belongs to.
+ for (const row of rows) {
+ const rec = await liveRecordingSidecar.load(path.join(paths.channelsDir, slug, "data", row.id)).catch(() => null);
+ const own = rec && rec.startedAt === row.startedAt ? rec : null;
+ let parts = own?.parts ?? row.parts;
+ let status: LiveRecordingViewStatus = own?.status ?? row.status;
+ const named = row.jobId ? byId.get(row.jobId) : undefined;
+ // A row that names its job is running only if THAT job runs (a newer
+ // run of the same id is another row); one that names none, by any
+ // record-live job of the id.
+ const running = row.jobId
+ ? Boolean(named && ACTIVE.has(named.status))
+ : jobs.some((j) => j.kind === "record-live" && j.channelSlug === slug && j.videoId === row.id && ACTIVE.has(j.status));
+ if (status === "recording" && !running) status = "interrupted";
+ let bytes: number | null = null;
+ let lastGrowthMs: number | null = null;
+ if (status === "recording" || status === "interrupted") {
+ names ??= await readdir(slugStore).catch(() => [] as string[]);
+ const byStem = new Map(livePartFiles(row.id, names).map((g) => [g.stem, g]));
+ let sum = 0;
+ // Each part's own bytes and growth, now (a copy: the record is not
+ // changed by reading it).
+ parts = await Promise.all(
+ parts.map(async (p) => {
+ const g = p.stem ? byStem.get(p.stem) : undefined;
+ if (!g) return p;
+ let pb = 0;
+ let pg: number | null = null;
+ for (const f of [...g.finished, ...g.streams]) {
+ const st = await stat(path.join(slugStore, f)).catch(() => null);
+ if (!st) continue;
+ pb += st.size;
+ pg = Math.max(pg ?? 0, st.mtimeMs);
+ }
+ sum += pb;
+ if (pg !== null) lastGrowthMs = Math.max(lastGrowthMs ?? 0, pg);
+ return { ...p, bytes: pb, ...(pg !== null ? { lastGrowthAt: new Date(pg).toISOString() } : {}) };
+ }),
+ );
+ bytes = sum;
+ } else if (parts.some((p) => typeof p.bytes === "number")) {
+ bytes = parts.reduce((n, p) => n + (p.bytes ?? 0), 0);
+ }
+ const current = parts.at(-1);
+ const sinceMs = lastGrowthMs ?? (current ? Date.parse(current.startedAt) : Date.parse(row.startedAt));
+ const stalled = status === "recording" && Number.isFinite(sinceMs) && now - sinceMs > stallMinutes * 60_000;
+ const landed = own?.landedPart ?? row.landedPart;
+ const capturedSeconds = status === "landed" && landed !== undefined ? (parts[landed]?.seconds ?? null) : null;
+ const streamElapsedSeconds =
+ status === "recording" && row.streamStartedAt ? Math.max(0, Math.round((now - Date.parse(row.streamStartedAt)) / 1000)) : null;
+ const view: Omit<LiveRecordingView, "reason" | "check"> = {
+ ...row,
+ ...(own?.error ? { error: own.error } : {}),
+ ...(own?.fallback ? { fallback: own.fallback } : {}),
+ ...(own?.lost ? { lost: own.lost } : {}),
+ ...(own?.endedAt ? { endedAt: own.endedAt } : {}),
+ ...(own?.failureClass ? { failureClass: own.failureClass } : {}),
+ ...(own?.missingStream ? { missingStream: own.missingStream } : {}),
+ ...(own?.stoppedBy ? { stoppedBy: own.stoppedBy } : {}),
+ ...(own?.keptParts ? { keptParts: own.keptParts } : {}),
+ ...(own?.removedParts ? { removedParts: own.removedParts } : {}),
+ ...(own?.coverage ? { coverage: own.coverage } : {}),
+ attempts: own?.attempts ?? row.attempts,
+ parts,
+ slug,
+ status,
+ job: named ? { id: named.id, kind: named.kind, status: named.status } : null,
+ bytes,
+ lastGrowthAt: lastGrowthMs !== null ? new Date(lastGrowthMs).toISOString() : null,
+ stalled,
+ streamElapsedSeconds,
+ capturedSeconds,
+ needsAttention: rowNeedsAttention({
+ ...row,
+ status,
+ fallback: own?.fallback ?? row.fallback,
+ keptParts: own?.keptParts ?? row.keptParts,
+ missingStream: own?.missingStream ?? row.missingStream,
+ }),
+ };
+ const shown =
+ opts.all ||
+ opts.id ||
+ view.needsAttention ||
+ status === "recording" ||
+ now - Date.parse(view.endedAt ?? view.startedAt) <= LIVE_RECORDINGS_RECENT_DAYS * 86_400_000;
+ if (!shown) continue;
+ out.push({ ...view, reason: reasonOf(view, stallMinutes), check: liveRecordingCheckCommand(slug, row.id) });
+ }
+ }
+ out.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
+ return {
+ rows: out,
+ needsAttention: out.filter((r) => r.needsAttention).length + files.filter((f) => f.needsAttention).length,
+ stalled: out.filter((r) => r.stalled).length,
+ stallMinutes,
+ files,
+ };
+}
+
+// How many recordings (and files) need a person, and how many are stalled,
+// across every channel.
+export async function liveRecordingsAttentionCounts(paths: Paths): Promise<{ needsAttention: number; stalled: number }> {
+ const l = await listLiveRecordings(paths);
+ return { needsAttention: l.needsAttention, stalled: l.stalled };
+}
+
+export async function countLiveRecordingsNeedingAttention(paths: Paths): Promise<number> {
+ return (await listLiveRecordings(paths)).needsAttention;
+}
+
+// A person has seen it (`pnpm ops live-recording-ack`, /review's
+// Acknowledge): every run of `id` that needs a person, or the one run
+// `startedAt` names. The rows stay listed.
+export async function acknowledgeLiveRecording(
+ paths: Paths,
+ opts: { slug: string; id?: string; file?: string; startedAt?: string; by?: string; now?: Date },
+): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> {
+ // A set-aside live-recordings.json: seen (it stays where it is).
+ if (opts.file !== undefined) {
+ const n = await acknowledgeSetAsideFiles(paths, opts.slug, {
+ file: opts.file,
+ ...(opts.by ? { by: opts.by } : {}),
+ ...(opts.now ? { now: opts.now } : {}),
+ });
+ return n ? { ok: true, acknowledged: n } : { ok: false, error: `${opts.slug} has no set-aside file "${opts.file}" that needs acknowledging` };
+ }
+ if (!opts.id) return { ok: false, error: 'send "id" (a recording) or "file" (a set-aside live-recordings.json)' };
+ const listing = await listLiveRecordings(paths, { slug: opts.slug, id: opts.id, all: true });
+ if (!listing.rows.length) return { ok: false, error: `${opts.slug}/${opts.id} has no live recording` };
+ const interrupted = new Set(listing.rows.filter((r) => r.status === "interrupted").map((r) => r.startedAt));
+ const n = await acknowledgeLiveRecordingRows(paths, opts.slug, opts.id, {
+ ...(opts.by ? { by: opts.by } : {}),
+ ...(opts.startedAt ? { startedAt: opts.startedAt } : {}),
+ ...(opts.now ? { now: opts.now } : {}),
+ interrupted: (r) => interrupted.has(r.startedAt),
+ });
+ if (n === 0) return { ok: false, error: `Nothing of ${opts.slug}/${opts.id} needs acknowledging` };
+ return { ok: true, acknowledged: n };
+}
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -51,7 +51,13 @@ async function fakeProbe(file: string): Promise<MediaProbe | null> {
const text = await readFile(file, "utf8").catch(() => "");
const all = [...text.matchAll(/seconds=([\d.]+)/g)].reduce((s, m) => s + Number(m[1]), 0);
if (!/format=/.test(text)) return null;
- return { formatName: /format=([^;]+)/.exec(text)![1]!, seconds: all, videoCodec: "h264", audioCodec: "aac" };
+ // `v=none;` / `a=none;`: a stream with no video / no audio.
+ return {
+ formatName: /format=([^;]+)/.exec(text)![1]!,
+ seconds: all,
+ videoCodec: /v=none;/.test(text) ? null : "h264",
+ audioCodec: /a=none;/.test(text) ? null : "aac",
+ };
}
const land = {
probe: fakeProbe,
@@ -193,7 +199,7 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once
fetchText: async () => DVR,
spawn: async ({ args }) => {
// The pre-clip is asked for while the recorder runs.
- await new Promise((r) => setImmediate(r));
+ await new Promise((r) => setTimeout(r, 10));
await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=60;");
return { exitCode: 0, stderrTail: "", signalled: false };
},
@@ -373,11 +379,18 @@ test("the VOD poller appends new segments in order, counts a gap, and ends when
test("Cancel reaches the recorder as SIGINT, and it gets to finish its file", async () => {
const out = path.join(ROOT, "sigint.txt");
- const script = `process.on("SIGINT", () => { require("fs").writeFileSync(${JSON.stringify(out)}, "finalized"); process.exit(0); }); console.log("frame= 1"); setInterval(() => {}, 1000);`;
+ // The child says "ready" once its SIGINT handler is armed; the Cancel is
+ // sent then, not after a fixed time (a loaded machine starts node slowly).
+ const script = `process.on("SIGINT", () => { require("fs").writeFileSync(${JSON.stringify(out)}, "finalized"); process.exit(0); }); console.log("frame= 1"); console.log("ready"); setInterval(() => {}, 1000);`;
const ac = new AbortController();
const lines: string[] = [];
const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" });
- await new Promise((r) => setTimeout(r, 400));
+ const readyBy = Date.now() + 60_000;
+ // The child's own line (not the echo of its command, which names it too).
+ while (!lines.some((l) => /^(?:\[t\] )?ready\s*$/.test(l))) {
+ assert.ok(Date.now() < readyBy, "the child never said it was ready");
+ await new Promise((r) => setTimeout(r, 10));
+ }
ac.abort();
const o = await p;
assert.equal(o.signalled, true);
@@ -604,3 +617,561 @@ test("an earlier run's unmerged streams are merged and landed by the next run",
assert.equal((await streamsOf(s.landed!.container!)).a, "aac");
assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".ytleft00001")), []);
});
+
+// --- THE INCIDENT (20 Nov 2026): a from-start attempt that records nothing ----------
+//
+// A YouTube stream asked for `fromStart`, `doNotClean` and a note; yt-dlp
+// `--live-from-start` exited 1 after seconds with "The downloaded file is
+// empty" and wrote nothing; the job failed with no retry, no fallback and no
+// alert. The recorder here is a stub that does exactly that, every time (or
+// for the first N attempts); the waits between attempts are recorded, never
+// slept. The listing (controller/liveRecordings.ts) is what a person and an
+// agent read afterwards.
+
+const EMPTY = "[youtube] Sleeping 1.0 seconds ...\nERROR: The downloaded file is empty\n";
+const ytChannel = async () => {
+ await mkdir(path.join(CORPUS, "channels", YT_SLUG, "data"), { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", YT_SLUG, "config.json"), JSON.stringify(YT_CONFIG));
+};
+// The stream started two hours ago.
+const ytLiveMeta = (id: string) => ({ ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 7200 });
+const ytUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`;
+
+type Attempt = (args: string[], n: number) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>;
+const writesAfter = (failures: number, stderr = EMPTY): Attempt => async (args, n) => {
+ if (n <= failures) return { exitCode: 1, stderrTail: stderr, signalled: false };
+ const out = args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ".mp4");
+ await writeFile(out, "format=mov,mp4;seconds=600;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+};
+
+async function incidentRun(
+ id: string,
+ attempt: Attempt,
+ opts: {
+ signal?: AbortSignal;
+ onWait?: (ms: number) => void;
+ request?: Record<string, unknown>;
+ meta?: Record<string, unknown>;
+ deps?: Record<string, unknown>;
+ } = {},
+) {
+ await ytChannel();
+ const calls: string[][] = [];
+ const waits: number[] = [];
+ const log: string[] = [];
+ const run = recordLiveRun({
+ paths,
+ request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", ...(opts.request ?? {}) },
+ plan: { url: ytUrl(id), platform: "youtube", id },
+ channelConfig: YT_CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: (l) => void log.push(l),
+ signal: opts.signal ?? new AbortController().signal,
+ jobId: `job-${id}`,
+ deps: {
+ refresh: refreshWith(opts.meta ?? ytLiveMeta(id)),
+ fetchText: async () => {
+ throw new Error("no playlist read is expected");
+ },
+ spawn: async ({ args }: { args: string[] }) => {
+ calls.push(args);
+ return attempt(args, calls.length);
+ },
+ wait: async (ms) => {
+ waits.push(ms);
+ opts.onWait?.(ms);
+ },
+ jitter: (ms) => ms,
+ land,
+ freeBytes: async () => 1e15,
+ handoff,
+ shuttingDown: () => false,
+ ...(opts.deps ?? {}),
+ },
+ } as Parameters<typeof recordLiveRun>[0]);
+ return { run, calls, waits, log };
+}
+
+const fromStartArg = (args: string[]) => args.includes("--live-from-start");
+const startIndex0 = (args: string[]) => /-live_start_index 0/.test(args[args.indexOf("--downloader-args") + 1] ?? "");
+
+test("THE INCIDENT: 'downloaded file is empty' every time → 3 from-start tries, 3 live-edge tries, then a durable loud failure in the listing", async () => {
+ const id = "exmplincid1";
+ const { run, calls, waits, log } = await incidentRun(id, writesAfter(Infinity));
+ await assert.rejects(run, /The downloaded file is empty/);
+ assert.equal(calls.length, 6, `six recorder attempts, not ${calls.length}`);
+ assert.deepEqual(calls.map(fromStartArg), [true, true, true, false, false, false]);
+ assert.deepEqual(calls.map(startIndex0), [true, true, true, false, false, false], "the live edge asks ffmpeg for no index 0");
+ assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000], "paced: 0/+60/+180 s, then the same from the live edge");
+ assert.ok(log.some((l) => /from its start failed 3 times/.test(l)), "the log says the from-start attempts failed");
+ // The run made data/<id>/ and recorded nothing into it: the dir goes (an
+ // enumerator would read it as fetched) — the failure record does NOT.
+ await assert.rejects(stat(path.join(CORPUS, "channels", YT_SLUG, "data", id)));
+ const { listLiveRecordings, acknowledgeLiveRecording } = await import("./liveRecordings");
+ const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows;
+ assert.equal(rows.length, 1);
+ const row = rows[0]!;
+ assert.equal(row.status, "failed");
+ assert.equal(row.needsAttention, true);
+ assert.equal(row.mustKeep, true);
+ assert.equal(row.attempts, 6);
+ assert.equal(row.jobId, `job-${id}`);
+ assert.match(row.error ?? "", /The downloaded file is empty/);
+ assert.match(row.error ?? "", /6 attempts/);
+ assert.equal(row.parts.length, 6);
+ assert.match(row.parts[0]!.error ?? "", /The downloaded file is empty/);
+ // Acknowledged: it stays listed, and no longer needs anyone.
+ const ack = await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" });
+ assert.equal(ack.ok, true);
+ const after = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!;
+ assert.equal(after.needsAttention, false);
+ assert.ok(after.acknowledgedAt);
+});
+
+test("from its start fails twice, the third try records: landed, 3 attempts, nothing to attend to", async () => {
+ const id = "exmplretry1";
+ const { run, calls, waits } = await incidentRun(id, writesAfter(2));
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 3);
+ assert.ok(calls.every(fromStartArg));
+ assert.deepEqual(waits, [60_000, 180_000]);
+ const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.equal(rec?.attempts, 3);
+ assert.equal(rec?.fallback, undefined);
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!;
+ assert.equal(row.status, "landed");
+ assert.equal(row.needsAttention, false);
+});
+
+test("from its start fails 3 times, the live edge records: landed, the start said LOST, and it needs a person", async () => {
+ const id = "exmpledge01";
+ const { run, calls, log } = await incidentRun(id, writesAfter(3));
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 4);
+ assert.equal(fromStartArg(calls[3]!), false);
+ const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.equal(rec?.fallback, "live-edge");
+ assert.ok(rec?.lost && rec.lost.toSeconds !== null && Math.abs(rec.lost.toSeconds - 7200) < 120, JSON.stringify(rec?.lost));
+ assert.ok(log.some((l) => /are NOT recorded/.test(l)), "the log says what was lost");
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!;
+ assert.equal(row.fallback, "live-edge");
+ assert.equal(row.needsAttention, true, "a lost start is a failure needing attention");
+});
+
+test("a stream that has ended is not retried; a cancel during a wait stops at once (a must-keep stream's cancel needs a person, another's is quiet)", async () => {
+ const ended = await incidentRun("exmplended1", writesAfter(Infinity, "ERROR: [youtube] exmplended1: This live event has ended.\n"));
+ await assert.rejects(ended.run, /ended/);
+ assert.equal(ended.calls.length, 1);
+ assert.deepEqual(ended.waits, []);
+
+ const ac = new AbortController();
+ const cancelled = await incidentRun("exmplcancl1", writesAfter(Infinity), { signal: ac.signal, onWait: () => ac.abort() });
+ const s = await cancelled.run;
+ assert.equal(s.status, "cancelled");
+ assert.equal(cancelled.calls.length, 1, "no attempt after the cancel");
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl1" })).rows[0]!;
+ assert.equal(row.status, "cancelled");
+ assert.equal(row.stoppedBy, "operator");
+ assert.equal(row.needsAttention, true, "a must-keep stream cancelled: is that what was wanted?");
+
+ const ac2 = new AbortController();
+ const plain = await incidentRun("exmplcancl2", writesAfter(Infinity), {
+ signal: ac2.signal,
+ onWait: () => ac2.abort(),
+ request: { doNotClean: false, note: undefined },
+ });
+ assert.equal((await plain.run).status, "cancelled");
+ const quiet = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl2" })).rows[0]!;
+ assert.equal(quiet.mustKeep, false);
+ assert.equal(quiet.needsAttention, false, "a person's Cancel of a stream that is not must-keep is quiet");
+});
+
+test("a healthy recording is untouched: one spawn, no wait, today's argv byte for byte", async () => {
+ const { ytdlpLiveArgs } = await import("../lib/liveCapture");
+ const { channelExtraArgs } = await import("../ytdlp/channelArgs");
+ const id = "exmplhealth";
+ const { run, calls, waits } = await incidentRun(id, writesAfter(0));
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 1);
+ assert.deepEqual(waits, []);
+ const out = calls[0]![calls[0]!.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, "");
+ assert.deepEqual(
+ calls[0],
+ ytdlpLiveArgs({
+ url: ytUrl(id),
+ output: out,
+ fromStart: true,
+ maxHeight: 720,
+ separate: true,
+ waitForVideo: false,
+ channelArgs: [...channelExtraArgs(YT_CONFIG, undefined), "--downloader-args", "ffmpeg_i:-live_start_index 0 -m3u8_hold_counters 180 -seg_max_retry 10"],
+ }),
+ );
+});
+
+test("a later recording of the same stream that lands supersedes the earlier failure", async () => {
+ const id = "exmplsuper1";
+ const first = await incidentRun(id, writesAfter(Infinity));
+ await assert.rejects(first.run);
+ // The second run holds the whole stream: 600 s of a stream that started
+ // ~600 s before it ended (by the clock).
+ const second = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ assert.equal((await second.run).status, "landed");
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows;
+ assert.equal(rows.length, 2);
+ const failed = rows.find((r) => r.status === "failed")!;
+ assert.ok(failed.supersededBy, "the failure names the run that landed");
+ assert.equal(failed.needsAttention, false);
+});
+
+test("the recorder's progress thinning also catches yt-dlp's numbered stream lines", async () => {
+ const { isProgressLine } = await import("./recordLive");
+ assert.equal(isProgressLine("1: [download] 12.3% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 4453/30299)"), true);
+ assert.equal(isProgressLine("2: [download] Destination: x.f140.m4a"), true);
+ assert.equal(isProgressLine("[download] 50.0% of 10MiB"), true);
+ assert.equal(isProgressLine("ERROR: The downloaded file is empty"), false);
+});
+
+// --- REVIEW-1 (21 Nov 2026): what the first slice got wrong, pinned ----------------
+
+const store = () => path.join(paths.savedVideosDir, YT_SLUG);
+const outOf = (args: string[]) => args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, "");
+const rowOf = async (id: string) => {
+ const { listLiveRecordings } = await import("./liveRecordings");
+ return (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows;
+};
+
+test("1.4: a normal stream end where yt-dlp exits 1 but the parts hold bytes lands, unchanged: one spawn, no wait, not failed", async () => {
+ const id = "exmplexit01";
+ const { run, calls, waits, log } = await incidentRun(id, async (args) => {
+ // Both streams written, yt-dlp's merge never ran (exit 1 at the end).
+ await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=3600;");
+ await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 403\nERROR: unable to download fragment\n", signalled: false };
+ });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 1, "not retried");
+ assert.deepEqual(waits, []);
+ assert.ok(!log.some((l) => /recorded nothing/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.status, "landed");
+ assert.equal(row.error, undefined);
+ assert.equal(row.failureClass, undefined);
+ assert.equal(row.parts[0]!.error, undefined);
+ assert.equal(row.needsAttention, false);
+});
+
+test("1.1: an earlier run's longer from-start part lands, and this run's live-edge part — the only copy of the stream's end — is KEPT, listed, needing a person", async () => {
+ const id = "exmplkeep01";
+ await mkdir(store(), { recursive: true });
+ // Run A (an earlier, interrupted run): 3 h from the start, left in staging.
+ const earlier = path.join(store(), `.${id}.live-2026-11-20T01-00-00-000Z.ytdlp.mp4`);
+ await writeFile(earlier, "format=mov,mp4;seconds=10800;");
+ // Run B: from its start fails 3 times; the live edge records 1.8 h.
+ const { run, calls } = await incidentRun(id, async (args, n) => {
+ if (n <= 3) return { exitCode: 1, stderrTail: EMPTY, signalled: false };
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=6480;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ });
+ const s = await run;
+ assert.equal(calls.length, 4);
+ assert.equal(s.landed?.seconds, 10800, "the longest (run A's) lands");
+ const left = (await readdir(store())).filter((n) => n.startsWith(`.${id}.`));
+ assert.equal(left.length, 1, `the live-edge part is still on disk: ${left.join(", ")}`);
+ assert.match(left[0]!, /ytdlp-edge-a4\.mp4$/);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.keptParts?.length, 1);
+ const k = row.keptParts![0]!;
+ assert.equal(k.run, "this");
+ assert.equal(k.fromStart, false);
+ assert.equal(k.seconds, 6480);
+ assert.ok(k.bytes > 0 && k.files[0]!.name === left[0]);
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /kept in staging/);
+ const { acknowledgeLiveRecording } = await import("./liveRecordings");
+ assert.equal((await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" })).ok, true);
+ assert.equal((await rowOf(id))[0]!.needsAttention, false, "acknowledged");
+ assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 1, "an acknowledgement removes nothing");
+});
+
+test("1.1: of this run's own parts, a shorter from-start part is inside the landed one and goes", async () => {
+ const id = "exmplkeep02";
+ // Attempt 1 records audio only for 45 s (one stream missing: retried),
+ // attempt 2 records both from the start.
+ const { run, calls } = await incidentRun(id, async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=45;v=none;");
+ return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)), []);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.keptParts, undefined);
+ assert.equal(row.missingStream, undefined, "the second attempt has both");
+ assert.equal(row.parts[0]!.missingStream, "video");
+ assert.equal(row.parts[0]!.failureClass, "partial");
+});
+
+test("1.7: one stream with bytes and the other empty is a failed attempt, retried; when every attempt ends so, the row names the missing stream and keeps the parts", async () => {
+ const id = "exmplpart01";
+ const videoOnly: Attempt = async (args) => {
+ await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;");
+ return { exitCode: 1, stderrTail: "1: [download] Destination: x\n2: ERROR: The downloaded file is empty\n", signalled: false };
+ };
+ const { run, calls, waits } = await incidentRun(id, videoOnly);
+ await assert.rejects(run, /audio stream recorded nothing/);
+ assert.equal(calls.length, 6, "the schedule, as for nothing at all");
+ assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000]);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.status, "failed");
+ assert.equal(row.missingStream, "audio");
+ assert.equal(row.failureClass, "partial");
+ assert.equal(row.keptParts?.length, 6, "every video-only part stays on disk");
+ assert.ok(row.keptParts!.every((k) => k.bytes > 0 && /not landable/.test(k.why)));
+ assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 6);
+ assert.equal(row.needsAttention, true);
+});
+
+test("2.1: an editor shutdown stops a recording as `interrupted`, never `cancelled`, and it needs a person", async () => {
+ const ac = new AbortController();
+ const { run } = await incidentRun("exmplshut01", writesAfter(Infinity), {
+ signal: ac.signal,
+ onWait: () => ac.abort(),
+ request: { doNotClean: false, note: undefined },
+ deps: { shuttingDown: () => true },
+ });
+ const s = await run;
+ assert.equal(s.status, "interrupted");
+ const row = (await rowOf("exmplshut01"))[0]!;
+ assert.equal(row.status, "interrupted");
+ assert.equal(row.stoppedBy, "shutdown");
+ assert.equal(row.needsAttention, true, "interrupted needs a person, must-keep or not");
+ assert.match(row.reason, /editor shut down/);
+
+ // Shut down mid-recording with bytes: what was recorded lands, interrupted.
+ const ac2 = new AbortController();
+ const mid = await incidentRun("exmplshut02", async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ ac2.abort();
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }, { signal: ac2.signal, deps: { shuttingDown: () => true } });
+ const s2 = await mid.run;
+ assert.equal(s2.status, "interrupted");
+ assert.equal(s2.landed?.seconds, 300);
+ assert.equal((await rowOf("exmplshut02"))[0]!.needsAttention, true);
+});
+
+test("2.3: only a landed from-start run that covers the stream supersedes; a live-edge run, a fromStart:false run and a short partial never do", async () => {
+ const id = "exmplcover1";
+ const first = await incidentRun(id, writesAfter(Infinity));
+ await assert.rejects(first.run);
+ const stillNeeds = async () => (await rowOf(id)).find((r) => r.status === "failed")!;
+ // (a) asked not from its start: lands, does not supersede.
+ const edge = await incidentRun(id, writesAfter(0), { request: { fromStart: false } });
+ assert.equal((await edge.run).status, "landed");
+ assert.equal((await stillNeeds()).needsAttention, true, "a run from now does not hold the start");
+ assert.equal((await stillNeeds()).supersededBy, undefined);
+ // (b) from its start, 600 s of a stream that has run two hours.
+ const short = await incidentRun(id, writesAfter(0));
+ const shortLog = short.log;
+ assert.equal((await short.run).status, "landed");
+ assert.equal((await stillNeeds()).needsAttention, true, "a short partial does not supersede");
+ assert.ok(shortLog.some((l) => /does not supersede/.test(l)));
+ const shortRow = (await rowOf(id)).find((r) => r.status === "landed" && r.fromStart && r.coverage)!;
+ assert.equal(shortRow.coverage?.covers, false);
+ assert.equal(shortRow.coverage?.basis, "clock");
+ // (c) the ended stream's own duration, 610 s, against 600 s captured: covers.
+ const whole = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), live_status: "post_live", duration: 610 } });
+ assert.equal((await whole.run).status, "landed");
+ const failed = await stillNeeds();
+ assert.ok(failed.supersededBy, "the whole stream, from its start, supersedes");
+ assert.equal(failed.needsAttention, false);
+});
+
+test("3.1: ended, private, members-only and a full disk are not retried; the row records the class", async () => {
+ const cases: [string, string, string][] = [
+ ["exmplcls001", "ERROR: [youtube] exmplcls001: This live event has ended.\n", "ended"],
+ ["exmplcls002", "ERROR: [youtube] exmplcls002: Private video. Sign in if you've been granted access to this video\n", "private"],
+ ["exmplcls003", "ERROR: [youtube] exmplcls003: Join this channel to get access to members-only content like this video, and other exclusive perks.\n", "members"],
+ ["exmplcls004", "ERROR: unable to write data: [Errno 28] No space left on device\n", "disk"],
+ ];
+ for (const [id, stderr, cls] of cases) {
+ const r = await incidentRun(id, writesAfter(Infinity, stderr));
+ await assert.rejects(r.run);
+ assert.equal(r.calls.length, 1, `${cls}: one spawn`);
+ assert.deepEqual(r.waits, []);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.failureClass, cls);
+ assert.equal(row.needsAttention, true);
+ }
+});
+
+test("3.1: a 429 or the bot check gets ONE more try after 15 min, then stops and says so", async () => {
+ for (const [id, stderr] of [
+ ["exmpl429001", "ERROR: [youtube] exmpl429001: HTTP Error 429: Too Many Requests\n"],
+ ["exmplbot001", "ERROR: [youtube] exmplbot001: Sign in to confirm you're not a bot. Use --cookies-from-browser or --cookies for the authentication.\n"],
+ ] as const) {
+ const r = await incidentRun(id, writesAfter(Infinity, stderr));
+ await assert.rejects(r.run, /429|not a bot/);
+ assert.equal(r.calls.length, 2, "one retry");
+ assert.deepEqual(r.waits, [15 * 60_000]);
+ assert.ok(r.calls.every(fromStartArg), "the same mode");
+ assert.ok(r.log.some((l) => /refused again/.test(l) && /not retried again/.test(l)));
+ assert.equal((await rowOf(id))[0]!.failureClass, "rate-limited");
+ }
+ // Refused once, then the retry records: landed.
+ const ok = await incidentRun("exmpl429002", writesAfter(1, "ERROR: HTTP Error 429: Too Many Requests\n"));
+ assert.equal((await ok.run).status, "landed");
+ assert.equal(ok.calls.length, 2);
+});
+
+test("a network or unknown failure keeps the designed schedule", async () => {
+ const r = await incidentRun("exmplnet001", writesAfter(Infinity, "ERROR: [download] Got error: <urlopen error [Errno 101] Network is unreachable>\nERROR: Unable to download fragment\n"));
+ await assert.rejects(r.run);
+ assert.equal(r.calls.length, 6);
+ assert.equal((await rowOf("exmplnet001"))[0]!.failureClass, "network");
+});
+
+test("Record again asks what the run was asked: from the start, quality, transcribe, keep, its note and the pre-clip", async () => {
+ const { recordAgainRequest } = await import("./recordLive");
+ const preclip = { everyMinutes: 10, maxChunkMinutes: 20, overlapSeconds: 5, scan: true, mine: false };
+ assert.deepEqual(
+ recordAgainRequest({ slug: "s", url: "u", fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip } as never),
+ { fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip },
+ );
+});
+
+// --- Kept only when its footage might not be inside the landed file ----------------
+//
+// When the landed file is from the start (or a platform VOD) and covers the
+// whole stream (streamCoverage, the 2.3 rule), every other part is inside it
+// and goes, recorded on the row; otherwise every other part with bytes stays.
+
+const leftover = async (id: string, seconds: number) => {
+ await mkdir(store(), { recursive: true });
+ const f = path.join(store(), `.${id}.live-2026-11-20T01-00-00-000Z.ytdlp.mp4`);
+ await writeFile(f, `format=mov,mp4;seconds=${seconds};`);
+ return f;
+};
+
+test("covered (a): a Kick VOD that covers the stream lands, the channel's live-edge part is removed, nobody is asked", async () => {
+ const KICK = { handling: "transcribe", url: "https://kick.com/synthb/videos", platform: "kick", name: "Synth Kick B" } as ChannelConfig;
+ const slug = "synth-kick-b";
+ await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true });
+ await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK));
+ const uuid = "01a164b1-0c18-723a-a785-f9637c98aaaa";
+ const s = await recordLiveRun({
+ paths,
+ request: { slug, url: "https://kick.com/synthb" },
+ plan: { url: "https://kick.com/synthb", platform: "kick", id: null, kickChannel: "synthb" },
+ channelConfig: KICK,
+ cookiePolicy: NO_COOKIES,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: {
+ kickVod: async () => ({ id: uuid, url: `https://kick.com/synthb/videos/${uuid}` }),
+ refresh: refreshWith({
+ id: uuid,
+ extractor: "kick:vod",
+ live_status: "is_live",
+ uploader_id: "synthb",
+ // Started 5000 s ago: the VOD's 5000 s is the whole stream.
+ release_timestamp: Math.floor(Date.now() / 1000) - 5000,
+ formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }],
+ }),
+ spawn: async ({ args }) => {
+ await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=1000;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ poll: async (o) => {
+ await writeFile(o.output, "format=mpegts;seconds=5000;");
+ return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" };
+ },
+ land,
+ freeBytes: async () => 1e15,
+ handoff,
+ shuttingDown: () => false,
+ },
+ });
+ assert.equal(s.landed?.seconds, 5000);
+ assert.deepEqual((await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`)), [], "the live-edge part went");
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!;
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.keptParts, undefined);
+ assert.equal(row.removedParts?.length, 1);
+ assert.match(row.removedParts![0]!.why, /holds the whole stream/);
+ assert.equal(row.needsAttention, false);
+});
+
+test("covered (b): a from-start landing that covers the stream removes an earlier run's partial, nobody is asked", async () => {
+ const id = "exmplcov0b1";
+ const earlier = await leftover(id, 300);
+ const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ assert.equal((await run).status, "landed");
+ await assert.rejects(stat(earlier), "the earlier partial is inside the landed file");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.keptParts, undefined);
+ assert.equal(row.removedParts?.length, 1);
+ assert.equal(row.needsAttention, false);
+});
+
+test("not covered (c): a landing shorter than the stream keeps the earlier run's part, and needs a person", async () => {
+ const id = "exmplcov0c1";
+ const earlier = await leftover(id, 300);
+ const { run } = await incidentRun(id, writesAfter(0)); // 600 s of a stream two hours old
+ assert.equal((await run).status, "landed");
+ assert.ok((await stat(earlier)).size > 0, "kept");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.coverage?.covers, false);
+ assert.equal(row.keptParts?.length, 1);
+ assert.equal(row.keptParts![0]!.run, "earlier");
+ assert.equal(row.needsAttention, true);
+});
+
+test("not covered (d): a stream whose length cannot be established keeps every other part", async () => {
+ const id = "exmplcov0d1";
+ const earlier = await leftover(id, 300);
+ // No start time and no duration: the stream's length is not known.
+ const { run } = await incidentRun(id, writesAfter(0), { meta: YT_META(id) });
+ assert.equal((await run).status, "landed");
+ assert.ok((await stat(earlier)).size > 0, "kept");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.coverage?.streamSeconds, null);
+ assert.equal(row.coverage?.covers, false);
+ assert.equal(row.keptParts?.length, 1);
+ assert.equal(row.needsAttention, true);
+});
+
+test("a landing that fails removes nothing: the covered landing's other part and the part itself stay, listed, and the row needs a person", async () => {
+ const id = "exmplland01";
+ const earlier = await leftover(id, 300);
+ const { run } = await incidentRun(id, writesAfter(0), {
+ meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 },
+ // The store's disk is full: landMediaFile throws.
+ deps: { land: { ...land, freeBytes: async () => 0 } },
+ });
+ await assert.rejects(run, /the landing failed/);
+ assert.ok((await stat(earlier)).size > 0, "the earlier part is still on disk");
+ const mine = (await readdir(store())).filter((n) => n.startsWith(`.${id}.`) && n !== path.basename(earlier));
+ assert.equal(mine.length, 1, "this run's part is still on disk");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.status, "failed");
+ assert.equal(row.removedParts, undefined);
+ assert.equal(row.keptParts?.length, 2);
+ assert.equal(row.needsAttention, true);
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -40,7 +40,12 @@
// interrupted run left — is landed by landMediaFile, the landing
// import-media uses: probe, keep the longer over a container already in
// the store, `-c copy` remux to mp4, the store, audio.<fmt>, the archive
-// line, media-import.json. The other parts are removed (staging scratch).
+// line, media-import.json. A part the landed one is known to contain (a
+// shorter part of this run, both from the start) is removed; every other
+// part that holds media — an earlier run's, one recorded from another
+// point of the stream, one that cannot be landed — is KEPT in staging and
+// listed on the record and the channel's row (keptParts) until a person
+// decides. Nothing removes those automatically.
// 4. live-recording.json beside the record says what was recorded, how, and
// what was landed; the "Do not clean" marker when asked; the hand-off to
// the transcription lane (never lifting a pause).
@@ -48,7 +53,7 @@
import path from "node:path";
import { spawn } from "node:child_process";
import { createWriteStream } from "node:fs";
-import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
+import { mkdir, readFile, readdir, rm, rmdir, stat } from "node:fs/promises";
import { execa } from "execa";
import type { ChannelConfig } from "../lib/channelConfig";
import { assertChannelTextReadable } from "../lib/channelMedia";
@@ -56,10 +61,14 @@ import { alwaysCookies, type ResolvedCookiePolicy } from "../lib/cookiePolicy";
import {
BROWSER_FALLBACK_PLATFORMS,
LIVE_DEFAULT_MAX_HEIGHT,
+ LIVE_RATE_LIMIT_WAIT_MS,
+ classifyAttempt,
extractionRefused,
ffmpegLiveArgs,
formatUnavailable,
- liveFromStartUnsupported,
+ lastErrorLine,
+ liveAttemptSchedule,
+ liveFailureClass,
livePartFiles,
mergeStreamsArgs,
newSegments,
@@ -67,16 +76,24 @@ import {
pickVariant,
playlistReach,
separateStreamsDefault,
+ spanWords,
ytdlpLiveArgs,
+ type KeptPart,
+ type RemovedPart,
+ type LiveFailureClass,
type LivePart,
type LivePartFiles,
type LivePartMethod,
type LiveRecordingRecord,
type MediaPlaylist,
type MediaSegment,
+ type MissingStream,
type PlaylistReach,
+ type StreamCoverage,
} from "../lib/liveCapture";
import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import { loadLiveRecordingRows, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
+import { liveRecordingCheckCommand } from "./liveRecordings";
import { setDoNotClean } from "../lib/doNotClean-server";
import type { Paths } from "../lib/paths";
import { detectPlatform } from "../lib/platform";
@@ -267,6 +284,16 @@ export async function resolveRecordLivePlan(
return { ...plan, id };
}
+// The command that answers for this recording (the record-live reply's
+// `check`): its id from the body's `id`, else the URL's; a Kick channel URL
+// (its VOD is found in the job) names the channel alone.
+export function recordLiveCheckCommand(slug: string, body: { id?: unknown; url?: unknown }): string {
+ const id = typeof body.id === "string" && body.id.trim() ? body.id.trim() : null;
+ const plan = !id && typeof body.url === "string" ? planForUrl(body.url.trim()) : null;
+ const known = id ?? (plan && !("error" in plan) ? plan.id : null);
+ return known ? liveRecordingCheckCommand(slug, known) : `pnpm ops get live-recordings ${slug}`;
+}
+
export function recordLiveQueueKey(slug: string, id: string | null, kickChannel?: string): string {
return `record-live:${slug}:${id ?? `kick-${kickChannel ?? "?"}`}`;
}
@@ -284,10 +311,17 @@ export type RecorderSpawn = (opts: {
label: string;
}) => Promise<RecorderOutcome>;
-// A progress line yt-dlp or ffmpeg repeats every second for hours.
-const PROGRESS_RE = /^(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/;
+// A progress line yt-dlp or ffmpeg repeats every second for hours. yt-dlp
+// numbers each of a separate-streams recording's lines (`1: [download] …`,
+// `2: [download] …`): those are progress too (20 Nov 2026: unthinned, they
+// wrote ~1 MB of job log a minute while a from-start download caught up).
+const PROGRESS_RE = /^(?:\d+:\s*)?(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/;
const PROGRESS_EVERY_MS = 5 * 60_000;
+export function isProgressLine(line: string): boolean {
+ return PROGRESS_RE.test(line);
+}
+
// ONE RECORDER: spawned as a plain child (so a SIGINT reaches yt-dlp, which
// asks its ffmpeg to quit with `q` and the file is finalized), its output in
// the job's log with the per-second progress thinned to one line every five
@@ -306,7 +340,7 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la
for (const line of text.split(/[\r\n]+/)) {
const l = line.trim();
if (!l) continue;
- if (PROGRESS_RE.test(l)) {
+ if (isProgressLine(l)) {
const now = Date.now();
if (now - lastProgress < PROGRESS_EVERY_MS) continue;
lastProgress = now;
@@ -534,6 +568,13 @@ export type RecordLiveDeps = {
merge?: (args: string[], signal: AbortSignal) => Promise<void>;
freeBytes?: (dir: string) => Promise<number>;
now?: () => Date;
+ // The wait between two recorder attempts (default: a sleep a Cancel ends),
+ // and the stretch applied to it (default jitterMs, pacing.jitter).
+ wait?: (ms: number, signal: AbortSignal) => Promise<void>;
+ jitter?: (ms: number) => number;
+ // Whether the editor is shutting down (default: the job registry's): a run
+ // stopped then is `interrupted`, never `cancelled`.
+ shuttingDown?: () => boolean;
};
export type RecordLiveJobOpts = {
@@ -547,6 +588,8 @@ export type RecordLiveJobOpts = {
// first part begins.
startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
afterRun?: () => void | Promise<void>;
+ // The job running it: written into the record and the channel's row.
+ jobId?: string;
deps?: RecordLiveDeps;
};
@@ -682,13 +725,149 @@ export async function resolvePart(
return { error: `video with no audio (${streams.map((s) => path.basename(s.file)).join(", ")}): nothing to transcribe` };
}
+// What the run tells its wrapper (recordLiveRun) as it goes, so a failure the
+// run did not record itself — a refusal before the recording, a throw in the
+// middle of it — still ends in the record and the channel's row.
+type RunHooks = {
+ startedAt: string;
+ id?: string;
+ url?: string;
+ platform?: string;
+ record?: LiveRecordingRecord;
+ save?: () => Promise<void>;
+};
+
+const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note);
+
+// A stopped run: by the editor shutting down (`interrupted`, which needs a
+// person: the stream may still be live and nobody chose to stop it), else by a
+// person's Cancel (`cancelled`).
+function stopOf(deps: RecordLiveDeps | undefined): { status: "interrupted" | "cancelled"; by: "shutdown" | "operator" } {
+ let down = false;
+ try {
+ down = deps?.shuttingDown ? deps.shuttingDown() : getRegistry().isShuttingDown?.() === true;
+ } catch {
+ down = false;
+ }
+ return down ? { status: "interrupted", by: "shutdown" } : { status: "cancelled", by: "operator" };
+}
+
+// The request's recording keys, as the channel's row keeps them (what "Record
+// again" asks again): from the start or not, the quality, separate streams,
+// transcribe, keep (doNotClean) and its note, and the live pre-clip.
+export function recordAgainRequest(req: RecordLiveRequest): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "preclip"] as const) {
+ if (req[k] !== undefined) out[k] = req[k];
+ }
+ return out;
+}
+
+const rowExtra = (req: RecordLiveRequest) => ({ ...(req.note ? { note: req.note } : {}), request: recordAgainRequest(req) });
+
+// DOES THE LANDED RECORDING HOLD THE WHOLE STREAM — what supersedes an
+// earlier failure of the same id (lib/liveRecordings-server.ts). The stream's
+// length is the ended stream's own `duration` when its record has one, else
+// the clock: the last part's end minus the stream's start. The clock can only
+// OVERSTATE it (a recorder exits after the stream's last segment, and a
+// scheduled start may precede the real one), so a whole recording may read
+// "does not cover" by the clock — the safe direction: the earlier failure
+// then stays until a person acknowledges it.
+// The tolerance, max(60 s, 1 %): a recording from the start misses only
+// seconds at its two ends (the first fragment, the live edge's last few
+// segments of 2-6 s each, the container's rounding); 1 % absorbs probe and
+// rounding drift on a stream of many hours. A recording short by more than
+// that is missing content a person should hear about.
+export const COVERAGE_MIN_TOLERANCE_SECONDS = 60;
+export const COVERAGE_TOLERANCE_FRACTION = 0.01;
+
+export function streamCoverage(o: {
+ capturedSeconds: number | null;
+ endMeta: Record<string, unknown> | null;
+ streamStartedAt: string | null;
+ lastEndedAt: string | null;
+ // From its start as asked, with both streams, not a live-edge fallback.
+ wholeFromStart: boolean;
+}): StreamCoverage {
+ const ls = typeof o.endMeta?.live_status === "string" ? o.endMeta.live_status : null;
+ const duration =
+ typeof o.endMeta?.duration === "number" && o.endMeta.duration > 0 && ls !== "is_live" && ls !== "is_upcoming" ? (o.endMeta.duration as number) : null;
+ const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN;
+ const endMs = o.lastEndedAt ? Date.parse(o.lastEndedAt) : NaN;
+ const clock = Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs ? (endMs - startMs) / 1000 : null;
+ const streamSeconds = duration ?? clock;
+ const basis = duration !== null ? "duration" : clock !== null ? "clock" : null;
+ const toleranceSeconds = Math.round(Math.max(COVERAGE_MIN_TOLERANCE_SECONDS, (streamSeconds ?? 0) * COVERAGE_TOLERANCE_FRACTION));
+ const covers =
+ o.wholeFromStart && o.capturedSeconds !== null && streamSeconds !== null && o.capturedSeconds + toleranceSeconds >= streamSeconds;
+ return { capturedSeconds: o.capturedSeconds, streamSeconds: streamSeconds !== null ? Math.round(streamSeconds) : null, basis, toleranceSeconds, covers };
+}
+
+// THE RUN, AND ITS FAILURE RECORDED. Every way a recording can end without a
+// landing leaves a row in channels/<slug>/live-recordings.json that says why
+// (lib/liveRecordings-server.ts): the run's own saves write it; a throw the
+// run did not record (a refusal before any recorder started, a failure in the
+// middle) is written here, and the record, when there is one, says `failed`.
export async function recordLiveRun(
opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal },
): Promise<RecordLiveSummary> {
+ const now = opts.deps?.now ?? (() => new Date());
+ const hooks: RunHooks = { startedAt: now().toISOString() };
+ try {
+ return await recordLiveRunInner(opts, hooks);
+ } catch (err) {
+ const message = (err as Error).message;
+ const stopped = opts.signal.aborted ? stopOf(opts.deps) : null;
+ try {
+ if (hooks.record && hooks.save) {
+ if (hooks.record.status === "recording") {
+ hooks.record.status = stopped?.status ?? "failed";
+ if (stopped) hooks.record.stoppedBy = stopped.by;
+ hooks.record.endedAt = now().toISOString();
+ hooks.record.error = message;
+ await hooks.save();
+ }
+ } else if (hooks.id && !opts.request.dryRun) {
+ const failureClass = stopped ? undefined : liveFailureClass(message);
+ await upsertLiveRecordingRow(opts.paths, opts.request.slug, {
+ ...rowOfRecord(
+ hooks.id,
+ {
+ status: stopped?.status ?? "failed",
+ ...(stopped ? { stoppedBy: stopped.by } : {}),
+ ...(failureClass && failureClass !== "unknown" ? { failureClass } : {}),
+ url: hooks.url ?? opts.plan.url,
+ platform: hooks.platform ?? opts.plan.platform,
+ fromStart: opts.request.fromStart !== false,
+ startedAt: hooks.startedAt,
+ endedAt: now().toISOString(),
+ parts: [],
+ error: `nothing was recorded: ${message}`,
+ attempts: 0,
+ mustKeep: isMustKeep(opts.request),
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ },
+ rowExtra(opts.request),
+ ),
+ });
+ }
+ } catch (e) {
+ opts.onLog(`The failure could not be recorded in the channel's live recordings (${(e as Error).message}).\n`);
+ }
+ throw err;
+ }
+}
+
+async function recordLiveRunInner(
+ opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal },
+ hooks: RunHooks,
+): Promise<RecordLiveSummary> {
const { paths, request: req, onLog, signal } = opts;
const say = (s: string) => onLog(s.endsWith("\n") ? s : `${s}\n`);
const deps = opts.deps ?? {};
const now = deps.now ?? (() => new Date());
+ const waitFor = deps.wait ?? sleep;
+ const stretch = deps.jitter ?? ((ms: number) => jitterMs(ms));
const runRecorder = deps.spawn ?? spawnRecorder;
const getText = deps.fetchText ?? fetchText;
const fromStart = req.fromStart !== false;
@@ -705,6 +884,9 @@ export async function recordLiveRun(
plan = { ...plan, url: vod.url, id: vod.id };
}
const id = plan.id!;
+ hooks.id = id;
+ hooks.url = plan.url;
+ hooks.platform = plan.platform;
const separate = req.separate ?? separateStreamsDefault(plan.platform);
const cfg = configForVideoUrl(opts.channelConfig, plan.url);
const channelDir = path.join(paths.channelsDir, req.slug);
@@ -740,10 +922,14 @@ export async function recordLiveRun(
// A record this run made and recorded nothing into is not left behind: a
// data/<id>/ with metadata is what every enumerator reads as "fetched".
const RECORD_ONLY = new Set(["metadata.info.json", "metadata.history.json", "live-recording.json"]);
+ // By name, then an rmdir that fails on anything else: a file another job
+ // (the live chat) writes into the dir meanwhile is never removed with it.
const abandon = async () => {
if (!created) return;
const left = await readdir(videoDir).catch(() => [] as string[]);
- if (left.every((n) => RECORD_ONLY.has(n))) await rm(videoDir, { recursive: true, force: true });
+ if (!left.every((n) => RECORD_ONLY.has(n))) return;
+ for (const n of RECORD_ONLY) await rm(path.join(videoDir, n), { force: true });
+ await rmdir(videoDir).catch(() => {});
};
let extractionError: string | null = null;
const refresh = () =>
@@ -805,18 +991,38 @@ export async function recordLiveRun(
const stemPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}`);
const partPath = (tag: string) => `${stemPath(tag)}.ts`;
const leftovers = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[]));
- if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed.`);
+ if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed, and the others are kept.`);
+ // When the stream started, as its record says (what a live-edge fallback
+ // has lost is measured from it).
+ const streamStartSec =
+ typeof meta?.release_timestamp === "number" ? (meta.release_timestamp as number) : typeof meta?.timestamp === "number" ? (meta.timestamp as number) : null;
const record: LiveRecordingRecord = {
status: "recording",
url: plan.url,
platform: plan.platform,
fromStart,
separate,
- startedAt: now().toISOString(),
+ startedAt: hooks.startedAt,
parts: [],
+ attempts: 0,
+ mustKeep: isMustKeep(req),
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ ...(streamStartSec !== null ? { streamStartedAt: new Date(streamStartSec * 1000).toISOString() } : {}),
};
- const save = () => liveRecordingSidecar.write(videoDir, record);
+ // The record beside the video, and the channel's row (which outlives it).
+ let rowWarned = false;
+ const save = async () => {
+ await liveRecordingSidecar.write(videoDir, record);
+ try {
+ await upsertLiveRecordingRow(paths, req.slug, rowOfRecord(id, record, rowExtra(req)));
+ } catch (err) {
+ if (!rowWarned) say(`The channel's live recordings could not be written (${(err as Error).message}).`);
+ rowWarned = true;
+ }
+ };
+ hooks.record = record;
+ hooks.save = save;
// How far back the playlist reaches (best effort, one read).
// (Not for separate streams from the start: YouTube's DASH from the start is
@@ -848,7 +1054,8 @@ export async function recordLiveRun(
let preclipAsked = false;
const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => {
const stem = path.basename(file).replace(/\.ts$/, "");
- const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem };
+ record.attempts = (record.attempts ?? 0) + 1;
+ const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem, attempt: record.attempts };
record.parts.push(part);
parts.push({ part, stem });
if (req.preclip && !preclipAsked && opts.startPreclip) {
@@ -869,6 +1076,8 @@ export async function recordLiveRun(
};
// 2. The recording.
+ // What the attempts came to when none recorded anything (the failure's words).
+ let attemptsSummary: string | null = null;
// "from-start": yt-dlp `--live-from-start` (and ffmpeg told index 0 too,
// the same thing for a DVR playlist); "index0": `--no-live-from-start` with
// ffmpeg told index 0 — for an extractor that does not mark a format from
@@ -911,6 +1120,20 @@ export async function recordLiveRun(
for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f));
return n;
};
+ const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s));
+ // A separate-streams part where only one stream wrote bytes: which is
+ // missing (null: both wrote, or a finished file holds them).
+ const missingStreamOf = async (stem: string): Promise<MissingStream | null> => {
+ const g = await filesOf(stem);
+ if (!g) return null;
+ for (const f of g.finished) if ((await sizeOf(path.join(slugStore, f))) > 0) return null;
+ const withBytes: string[] = [];
+ for (const f of g.streams) if ((await sizeOf(path.join(slugStore, f))) > 0) withBytes.push(f);
+ if (withBytes.length !== 1) return null;
+ const p = await probe(path.join(slugStore, withBytes[0]!)).catch(() => null);
+ if (p?.videoCodec && p.audioCodec) return null;
+ return p?.videoCodec ? "audio" : p?.audioCodec ? "video" : "unknown";
+ };
if (plan.platform === "kick") {
const vodFmt = fmt;
@@ -948,27 +1171,126 @@ export async function recordLiveRun(
} else {
let pathB = false;
if (extractionError === null) {
- let o = await ytdlpPart(plan.url, "ytdlp", fromStart ? "from-start" : "now");
- if (!signal.aborted && fromStart && liveFromStartUnsupported(o.stderrTail)) {
- say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment.");
- o = await ytdlpPart(plan.url, "ytdlp-index0", "index0", "--no-live-from-start + -live_start_index 0; ");
- }
- if (!signal.aborted && o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) {
- say(
- 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.',
- );
+ // THE ATTEMPTS (lib/liveCapture.ts liveAttemptSchedule): from its start
+ // at 0, +60 and +180 s, then from the live edge at 0, +60 and +180 s —
+ // each wait stretched by pacing.jitter, ended by a Cancel. An attempt
+ // that recorded NOTHING (or, for separate streams, only one of the two)
+ // is retried when another try may not meet the same failure: the
+ // failure's class (liveFailureClass) decides —
+ // ended, private, members-only, the disk not retried
+ // 429 / the bot check ONE more try, the same
+ // mode, after 15 min; then
+ // not again
+ // empty, network, unknown, one stream the schedule
+ // A part with bytes in both streams (whatever yt-dlp's exit: a normal
+ // stream end often exits 1), a Cancel and an argv no try can fix end the
+ // attempts.
+ const schedule = liveAttemptSchedule(fromStart);
+ let index0 = false;
+ let fromStartFailures = 0;
+ let edgeFailures = 0;
+ let lastReason: string | null = null;
+ let rateLimitRetried = false;
+ for (let slot = 0; slot < schedule.length && !signal.aborted; ) {
+ const step = schedule[slot]!;
+ const n = (record.attempts ?? 0) + 1;
+ const mode = step.mode === "live-edge" ? "now" : index0 ? "index0" : "from-start";
+ const tag = `ytdlp${mode === "index0" ? "-index0" : ""}${mode === "now" && fromStart ? "-edge" : ""}${n > 1 && !(mode === "index0" && n === 2) ? `-a${n}` : ""}`;
+ const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "");
+ const last = parts[parts.length - 1]!;
+ const bytes = await bytesOf(last.stem);
+ const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(last.stem) : null;
+ const cls = classifyAttempt({ ...o, bytes, partial: missing !== null });
+ if (cls === "recorded" || cls === "stopped" || signal.aborted) {
+ delete record.missingStream;
+ delete record.failureClass;
+ break;
+ }
+ const errLine = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ const failure: LiveFailureClass =
+ cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail);
+ const reason =
+ missing !== null
+ ? `${missing === "unknown" ? "one of its two streams" : `the ${missing} stream`} recorded nothing (${errLine})`
+ : errLine;
+ last.part.error = reason;
+ last.part.failureClass = failure;
+ if (missing !== null) last.part.missingStream = missing;
+ record.failureClass = failure;
+ if (missing !== null) record.missingStream = missing;
+ else delete record.missingStream;
+ await save();
+ lastReason = reason;
+ if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) {
+ say(
+ 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.',
+ );
+ }
+ if (bytes === 0 && o.exitCode !== 0 && BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(o.stderrTail)) {
+ say("yt-dlp was refused; recording from the page's own playlist.");
+ pathB = true;
+ break;
+ }
+ if (cls === "unsupported" && !index0) {
+ say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment.");
+ index0 = true;
+ continue;
+ }
+ if (cls === "argv") {
+ say(`Attempt ${n} recorded nothing (${reason}); the same command would fail the same way: not retried.`);
+ break;
+ }
+ if (cls === "final") {
+ const why =
+ failure === "ended"
+ ? "the stream is over"
+ : failure === "private"
+ ? "the stream is private, removed or unavailable"
+ : failure === "members"
+ ? "the stream is members-only or needs a login"
+ : "the store's disk cannot take it";
+ say(`Attempt ${n} recorded nothing (${reason}); ${why} (${failure}): not retried.`);
+ break;
+ }
+ if (step.mode === "from-start") fromStartFailures++;
+ else edgeFailures++;
+ if (cls === "rate-limited") {
+ if (rateLimitRetried) {
+ say(
+ `Attempt ${n} was refused again (${reason}) after a ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)} wait: a rate limit or the bot check — stopping, not retried again.`,
+ );
+ break;
+ }
+ rateLimitRetried = true;
+ say(
+ `Attempt ${n} was refused (${reason}): a rate limit or the bot check — ONE more try ${step.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`,
+ );
+ await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal);
+ continue;
+ }
+ slot++;
+ const next = schedule[slot];
+ if (!next) break;
+ if (next.mode === "live-edge" && step.mode === "from-start") {
+ const lostTo = streamStartSec !== null ? Math.max(0, Math.round(now().getTime() / 1000 - streamStartSec)) : null;
+ record.fallback = "live-edge";
+ record.lost = { fromSeconds: 0, toSeconds: lostTo };
+ await save();
+ say(
+ `${plan.url} from its start failed ${fromStartFailures} times (${reason}); recording from the live edge` +
+ (lostTo !== null
+ ? ` since ${spanWords(lostTo)} into the stream — the first ${spanWords(lostTo)} are NOT recorded.`
+ : ` — the stream before now (its start is not known) is NOT recorded.`),
+ );
+ } else {
+ say(`Attempt ${n} recorded nothing (${reason}); attempt ${n + 1} ${next.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(next.waitMs / 1000)}.`);
+ }
+ await waitFor(stretch(next.waitMs), signal);
}
- const last = parts[parts.length - 1];
- if (
- !signal.aborted &&
- o.exitCode !== 0 &&
- last &&
- (await bytesOf(last.stem)) === 0 &&
- BROWSER_FALLBACK_PLATFORMS.has(plan.platform) &&
- extractionRefused(o.stderrTail)
- ) {
- say("yt-dlp was refused; recording from the page's own playlist.");
- pathB = true;
+ if (lastReason !== null && record.failureClass !== undefined) {
+ const tries = record.attempts ?? 0;
+ const split = fromStartFailures && edgeFailures ? ` (${fromStartFailures} from its start, ${edgeFailures} from the live edge)` : "";
+ attemptsSummary = `${tries} attempt${tries === 1 ? "" : "s"}${split}: ${lastReason}`;
}
} else pathB = true;
if (pathB && !signal.aborted) {
@@ -995,21 +1317,26 @@ export async function recordLiveRun(
}
// 3. The stream is over (or the recording was stopped): land the longest.
- const cancelled = signal.aborted;
+ // A stop by the editor's shutdown is `interrupted` (it needs a person: the
+ // stream may still be live), a person's Cancel `cancelled`.
+ const stopped = signal.aborted ? stopOf(deps) : null;
+ const cancelled = stopped !== null;
const landSignal = new AbortController().signal;
try {
await refresh();
} catch (err) {
say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
}
- const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s));
+ const endMeta = await readMeta(videoDir);
const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s));
const at = (n: string) => path.join(slugStore, n);
// Every part on disk now — this run's and an earlier run's — by its stem.
const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[]));
const partOf = new Map(parts.map((p) => [p.stem, p.part]));
- const candidates: { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }[] = [];
+ type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles };
+ const candidates: Candidate[] = [];
const unlandable: string[] = [];
+ const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = [];
const empty: LivePartFiles[] = [];
for (const g of groups) {
const part = partOf.get(g.stem);
@@ -1018,6 +1345,7 @@ export async function recordLiveRun(
got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say });
} catch (err) {
unlandable.push(`${g.stem}: ${(err as Error).message}`);
+ unlandableGroups.push({ group: g, why: (err as Error).message, ...(part ? { part } : {}) });
}
if (part) {
part.bytes = 0;
@@ -1025,8 +1353,10 @@ export async function recordLiveRun(
part.seconds = got && !("error" in got) ? got.seconds : null;
if (got && !("error" in got) && got.merged) part.merged = true;
}
- if (got && "error" in got) unlandable.push(`${g.stem}: ${got.error}`);
- else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) });
+ if (got && "error" in got) {
+ unlandable.push(`${g.stem}: ${got.error}`);
+ unlandableGroups.push({ group: g, why: got.error, ...(part ? { part } : {}) });
+ } else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) });
else {
empty.push(g);
for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true });
@@ -1034,13 +1364,76 @@ export async function recordLiveRun(
}
for (const u of unlandable) say(`Not landable: ${u}`);
summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart }));
+
+ // WHAT STAYS ON DISK. A part that holds captured media and is not known to
+ // be inside the landed file is never removed: it is kept in staging and
+ // listed (record.keptParts, the channel's row), needing a person.
+ const kept: KeptPart[] = [];
+ const keep = async (g: LivePartFiles, why: string, o: { seconds?: number | null; part?: LivePart; extra?: string[] } = {}) => {
+ const names = [...new Set([...g.finished, ...g.streams, ...g.scratch, ...(o.extra ?? []).map((f) => path.basename(f))])];
+ const files: { name: string; bytes: number }[] = [];
+ for (const name of names) {
+ const b = await sizeOf(at(name));
+ if (b > 0) files.push({ name, bytes: b });
+ }
+ if (!files.length) return;
+ kept.push({
+ stem: g.stem,
+ files,
+ bytes: files.reduce((n, f) => n + f.bytes, 0),
+ seconds: o.seconds ?? null,
+ fromStart: o.part ? o.part.fromStart : null,
+ run: o.part ? "this" : "earlier",
+ why,
+ });
+ };
+ // Every part that is not the landed one, and why it would be kept.
+ type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[] };
+ const others: Other[] = [];
+ for (const u of unlandableGroups) others.push({ group: u.group, why: `not landable as it is: ${u.why}`, ...(u.part ? { part: u.part } : {}) });
+ for (const g of empty) {
+ // Fragments a recorder left hold media too; yt-dlp's resume state does not.
+ for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true });
+ const part = partOf.get(g.stem);
+ others.push({ group: g, why: "fragments a recorder left, not landable as they are", ...(part ? { part } : {}) });
+ }
+ const removed: RemovedPart[] = [];
+ // DECIDED BEFORE THE LANDING, DONE AFTER IT: a part is removed only once the
+ // landed file is in the store (landMediaFile returned and the stored file is
+ // there with its size). A landing that fails removes nothing.
+ const toRemove: { group: LivePartFiles; why: string; extra: string[]; o: Other }[] = [];
+ const removeGroup = async (g: LivePartFiles, why: string, extra: string[] = []) => {
+ let bytes = 0;
+ for (const f of [...new Set([...extra.map((e) => path.basename(e)), ...g.finished, ...g.streams, ...g.scratch])]) {
+ bytes += await sizeOf(at(f));
+ await rm(at(f), { force: true });
+ }
+ if (bytes > 0) removed.push({ stem: g.stem, bytes, why });
+ };
+ const sayKept = () => {
+ for (const k of kept) {
+ say(`Kept, not landed: ${k.stem} (${formatBytes(k.bytes)}, ${k.files.length} file${k.files.length === 1 ? "" : "s"}) — ${k.why}.`);
+ }
+ if (kept.length) say(`${kept.length} part${kept.length === 1 ? " is" : "s are"} kept in staging, listed in pnpm ops get live-recordings ${req.slug}/${id}; nothing removes them.`);
+ for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`);
+ };
+
if (candidates.length === 0) {
- const error = unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : "nothing was recorded";
- record.status = cancelled ? "cancelled" : "failed";
+ for (const o of others) await keep(o.group, o.why, o);
+ const error = [
+ unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : null,
+ attemptsSummary ? `${unlandable.length ? "" : "nothing was recorded — "}${attemptsSummary}` : null,
+ ]
+ .filter(Boolean)
+ .join(" — ") || "nothing was recorded";
+ record.status = stopped?.status ?? "failed";
+ if (stopped) record.stoppedBy = stopped.by;
record.endedAt = now().toISOString();
record.error = error;
+ if (kept.length) record.keptParts = kept;
+ sayKept();
await save();
- if (!unlandable.length) await abandon();
+ if (!unlandable.length && !kept.length) await abandon();
summary.status = record.status;
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
if (!cancelled) throw new Error(error);
@@ -1048,34 +1441,149 @@ export async function recordLiveRun(
}
candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1));
const best = candidates[0]!;
+ // Inside the landed file without asking how long the stream is: a shorter
+ // part of THIS run, both from the start (both begin where the stream's
+ // record begins).
+ const contained = (c: Candidate) =>
+ c !== best &&
+ c.part !== undefined &&
+ best.part !== undefined &&
+ c.part.fromStart &&
+ best.part.fromStart &&
+ c.seconds !== null &&
+ best.seconds !== null &&
+ c.seconds <= best.seconds;
+ const where = (p?: LivePart) => (p ? (p.fromStart ? "from its start" : "from the live edge") : "by an earlier run");
for (const c of candidates) {
say(`part ${path.basename(c.file)}: ${c.seconds !== null ? `${Math.round(c.seconds)} s` : "length unknown"}${c === best ? " — landed" : ""}`);
+ if (c === best) continue;
+ if (contained(c)) {
+ toRemove.push({
+ group: c.group,
+ why: "a shorter part of this run from its start: inside the landed part",
+ extra: [c.file],
+ o: { group: c.group, why: `recorded ${where(c.part)}, not landed`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] },
+ });
+ continue;
+ }
+ others.push({
+ group: c.group,
+ why:
+ c.part && best.part
+ ? `recorded ${where(c.part)}, the landed part ${where(best.part)}: it may hold time the landed part does not`
+ : `recorded ${where(c.part)}; the landed part was recorded ${where(best.part)}: it may hold time the landed part does not`,
+ seconds: c.seconds,
+ ...(c.part ? { part: c.part } : {}),
+ extra: [c.file],
+ });
}
- const landed = await landMediaFile({
- paths,
- slug: req.slug,
- channelConfig: opts.channelConfig,
- videoId: id,
- sourcePath: best.file,
- via: "record-live",
- move: true,
- url: plan.url,
- note: req.note ?? `a live recording (${best.part?.method ?? "an earlier run's part"})`,
- onLog,
- signal: landSignal,
- ...(deps.land ? { deps: deps.land } : {}),
+ if (separate && !record.missingStream) {
+ const bp = await probe(best.file, landSignal).catch(() => null);
+ if (bp && !bp.videoCodec) record.missingStream = "video";
+ }
+ // DOES THE LANDED FILE HOLD THE WHOLE STREAM (streamCoverage, the rule that
+ // also decides superseding). Its own record says whether it was from the
+ // start: this run's part, or an earlier run's by the channel's rows (a part
+ // no row names is not known to be).
+ let landedFromStart: boolean | null = best.part ? best.part.fromStart : null;
+ if (landedFromStart === null) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const p = rows.filter((r) => r.id === id).flatMap((r) => r.parts).find((x) => x.stem === best.group.stem);
+ landedFromStart = p ? p.fromStart : null;
+ }
+ record.coverage = streamCoverage({
+ capturedSeconds: best.seconds,
+ endMeta,
+ streamStartedAt: record.streamStartedAt ?? null,
+ lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null),
+ wholeFromStart: landedFromStart === true && !record.missingStream,
});
- // Every part's files were staging scratch (the landed one is moved or
- // copied into the store); a shorter (or unlanded) part goes, and so do the
- // streams a merge was made from.
- for (const c of candidates) await rm(c.file, { force: true });
- for (const g of [...candidates.map((c) => c.group), ...empty]) {
- for (const f of [...g.finished, ...g.streams, ...g.scratch]) await rm(at(f), { force: true });
+ const cov = record.coverage;
+ // Covered: every other part of the stream, this run's or an earlier one's,
+ // is inside the landed file by definition, and goes (recorded, with why).
+ // Not covered — a live-edge landing, a partial, a stream whose length is
+ // not known — every other part with bytes is kept and needs a person.
+ for (const o of others) {
+ if (cov.covers) {
+ toRemove.push({
+ group: o.group,
+ why: `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`,
+ extra: o.extra ?? [],
+ o,
+ });
+ } else {
+ await keep(o.group, o.why, o);
+ }
+ }
+ const bestBytes = await sizeOf(best.file);
+ // The landing failed (it threw, or its stored file is not there as it
+ // should be): nothing is removed, and every part with bytes — the one that
+ // was to land included — is kept and listed; the run failed.
+ const landingFailed = async (why: string): Promise<never> => {
+ await keep(best.group, `the landing failed (${why}): not landed`, {
+ seconds: best.seconds,
+ ...(best.part ? { part: best.part } : {}),
+ extra: [best.file],
+ });
+ for (const r of toRemove) await keep(r.group, `${r.o.why}; kept because the landing failed`, r.o);
+ record.status = "failed";
+ record.endedAt = now().toISOString();
+ record.error = `the landing failed: ${why}`;
+ if (kept.length) record.keptParts = kept;
+ sayKept();
+ await save();
+ summary.status = record.status;
+ say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
+ throw new Error(record.error);
+ };
+ let landed: Awaited<ReturnType<typeof landMediaFile>>;
+ try {
+ landed = await landMediaFile({
+ paths,
+ slug: req.slug,
+ channelConfig: opts.channelConfig,
+ videoId: id,
+ sourcePath: best.file,
+ via: "record-live",
+ move: true,
+ url: plan.url,
+ note: req.note ?? `a live recording (${best.part?.method ?? "an earlier run's part"})`,
+ onLog,
+ signal: landSignal,
+ ...(deps.land ? { deps: deps.land } : {}),
+ });
+ } catch (err) {
+ return landingFailed((err as Error).message);
}
+ {
+ const st = landed.container ? await stat(landed.container).catch(() => null) : null;
+ const sizeOk = st?.isFile() && st.size > 0 && (landed.kept !== "new" || landed.finalized !== "copied" || st.size === bestBytes);
+ if (!sizeOk) {
+ await landingFailed(
+ st ? `the stored file is ${st.size} bytes, the part ${bestBytes}` : `the stored file ${landed.container ?? "(none)"} is not there`,
+ );
+ }
+ }
+ for (const r of toRemove) await removeGroup(r.group, r.why, r.extra);
+ // The landed part's files were staging scratch (it is moved or copied into
+ // the store), and so were the streams a merge was made from.
+ await rm(best.file, { force: true });
+ for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true });
+ sayKept();
record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined;
record.kept = landed.kept;
- record.status = cancelled ? "cancelled" : "landed";
+ record.status = stopped?.status ?? "landed";
+ if (stopped) record.stoppedBy = stopped.by;
+ if (kept.length) record.keptParts = kept;
record.endedAt = now().toISOString();
+ if (removed.length) record.removedParts = removed;
+ if (record.missingStream) say(`Landed without its ${record.missingStream} stream: it needs a person.`);
+ if (!record.coverage.covers && record.coverage.streamSeconds !== null && record.coverage.capturedSeconds !== null) {
+ say(
+ `The landed part holds ${spanWords(record.coverage.capturedSeconds)} of a ${spanWords(record.coverage.streamSeconds)} stream ` +
+ `(${record.coverage.basis === "duration" ? "its record's duration" : "by the clock"}): it does not supersede an earlier failure.`,
+ );
+ }
await save();
summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container };
summary.status = record.status;
@@ -1126,8 +1634,8 @@ export async function runRecordLiveJob(
paths,
channelSlug: req.slug,
...(plan.id ? { videoId: plan.id } : {}),
- fn: async (onLog, signal) => {
- await recordLiveRun({ ...opts, plan, onLog, signal });
+ fn: async (onLog, signal, _progress, ctx) => {
+ await recordLiveRun({ ...opts, plan, onLog, signal, jobId: ctx.jobId });
await opts.afterRun?.();
},
});
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -291,6 +291,12 @@ class JobRegistry {
this.shuttingDown = true;
}
+ // Whether the cancels now arriving are the exit's (a run that is stopped
+ // says `interrupted`, not `cancelled`: controller/recordLive.ts).
+ isShuttingDown(): boolean {
+ return this.shuttingDown;
+ }
+
register(record: JobRecord): void {
this.jobs.set(record.id, record);
// Bound the registry. Drop oldest finished records past 100, but never
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -435,9 +435,66 @@ export type LivePart = {
// Its separate streams were left unmerged (a cancel, a crash) and merged
// by record-live.
merged?: boolean;
+ // Which attempt of the run this part was (1-based; liveAttemptSchedule).
+ attempt?: number;
+ // What the recorder said when the part recorded nothing: its last `ERROR:`
+ // line (lastErrorLine), so the reason is in the record, not only the log.
+ error?: string;
+ // What kind of failure that was (liveFailureClass).
+ failureClass?: LiveFailureClass;
+ // The listing's own (controller/liveRecordings.ts), while it records: when
+ // the part's files last grew. Never written to the record.
+ lastGrowthAt?: string;
+ // A separate-streams attempt where one stream wrote bytes and the other
+ // nothing: the stream that is missing ("unknown": the one that wrote could
+ // not be read).
+ missingStream?: MissingStream;
+};
+
+export type MissingStream = "video" | "audio" | "unknown";
+
+// A PART THE LANDING DID NOT LAND AND DID NOT REMOVE. It holds captured media
+// the landed file is not known to contain (an earlier run's part, a part
+// recorded from another point of the stream, a part that cannot be landed as
+// it is): its files stay in the store's staging dir, listed here with their
+// sizes, until a person decides. Nothing removes them automatically.
+export type KeptPart = {
+ stem: string;
+ files: { name: string; bytes: number }[];
+ bytes: number;
+ seconds: number | null;
+ // Null: an earlier run's part (its record is that run's).
+ fromStart: boolean | null;
+ run: "this" | "earlier";
+ why: string;
+};
+
+// A part the landing removed, and why (a part inside the landed file: a
+// shorter part of the same run from its start, or any part when the landed
+// file holds the whole stream — StreamCoverage).
+export type RemovedPart = { stem: string; bytes: number; why: string };
+
+// Whether the landed recording holds the whole stream: what supersedes an
+// earlier failure (lib/liveRecordings-server.ts). `basis` is where the
+// stream's length came from: the ended stream's own `duration`, else the
+// clock (the last part's end minus the stream's start, which can only
+// overstate it).
+export type StreamCoverage = {
+ capturedSeconds: number | null;
+ streamSeconds: number | null;
+ basis: "duration" | "clock" | null;
+ toleranceSeconds: number;
+ covers: boolean;
};
-export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled";
+// The span of the stream a recording does NOT hold, in stream seconds: a
+// fallback to the live edge starts `toSeconds` into the stream (null: the
+// stream's start is not known).
+export type LostSpan = { fromSeconds: number; toSeconds: number | null };
+
+// `interrupted`: stopped by an editor shutdown, not by a person (a Cancel is
+// `cancelled`).
+export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled" | "interrupted";
export type LiveRecordingRecord = {
status: LiveRecordingStatus;
@@ -456,9 +513,34 @@ export type LiveRecordingRecord = {
// The playlist's reach when the recording started, when it was read.
reach?: PlaylistReach;
error?: string;
+ // How many recorder attempts the run made (liveAttemptSchedule).
+ attempts?: number;
+ // From its start kept failing and the run recorded from the live edge:
+ // what it does not hold is `lost`.
+ fallback?: "live-edge";
+ lost?: LostSpan;
+ // A "must not lose" recording: asked with doNotClean or a note.
+ mustKeep?: boolean;
+ // The job that ran it.
+ jobId?: string;
+ // When the stream started (its record's release_timestamp/timestamp), ISO.
+ streamStartedAt?: string;
+ // The last failed attempt's class (liveFailureClass).
+ failureClass?: LiveFailureClass;
+ // The attempts ended with one of the two streams recording nothing.
+ missingStream?: MissingStream;
+ // Who stopped it, when it was stopped: a person's Cancel, or the editor
+ // shutting down (then the status is `interrupted`).
+ stoppedBy?: "operator" | "shutdown";
+ // Parts left on disk, not landed (KeptPart).
+ keptParts?: KeptPart[];
+ // Parts the landing removed as inside the landed file (RemovedPart).
+ removedParts?: RemovedPart[];
+ // Once landed: does it hold the whole stream (StreamCoverage).
+ coverage?: StreamCoverage;
};
-const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled"]);
+const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled", "interrupted"]);
const PART_METHODS: ReadonlySet<string> = new Set(["ytdlp", "browser", "vod-poll"]);
export function coerceLiveRecording(raw: unknown): LiveRecordingRecord | null {
@@ -487,3 +569,136 @@ export function coerceLiveRecording(raw: unknown): LiveRecordingRecord | null {
// The platforms a recording knows how to follow. Anything else is tried with
// yt-dlp's own `--live-from-start` (YouTube, Twitch) and no fallback.
export const BROWSER_FALLBACK_PLATFORMS: ReadonlySet<string> = new Set(["rumble"]);
+
+// --- attempts: what one recorder run came to, and what is tried next ------------
+//
+// A from-start attempt that records nothing is not the end of a recording
+// (20 Nov 2026: YouTube answered `--live-from-start`'s HEADs without a
+// sequence number for ~45 s, yt-dlp said "The downloaded file is empty", and
+// the same argv seven hours later worked). The run tries again, paced, and
+// then from the live edge, so that something is captured; each wait is
+// stretched by pacing.jitter and no attempt is a new kind of request: the
+// live edge is the `--no-live-from-start` Kick's channel recorder already
+// makes.
+
+// The waits before the 1st, 2nd and 3rd attempt of one mode.
+export const LIVE_RETRY_WAITS_MS: readonly number[] = [0, 60_000, 180_000];
+
+export type LiveAttemptMode = "from-start" | "live-edge";
+
+// Every attempt a run may make, in order: from its start three times (0, +60,
+// +180 s), then from the live edge three times (0, +60, +180 s). A run asked
+// not to start at the start makes only the live-edge three.
+export function liveAttemptSchedule(fromStart: boolean): { mode: LiveAttemptMode; waitMs: number }[] {
+ const edge = LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "live-edge" as const, waitMs }));
+ if (!fromStart) return edge;
+ return [...LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "from-start" as const, waitMs })), ...edge];
+}
+
+// WHY AN ATTEMPT RECORDED NOTHING, from what the recorder said (its stderr
+// tail). The class decides what is tried next and is kept on the part and the
+// row:
+// ended the stream is over, not live, or its recording is not
+// available — not retried
+// private private, removed, unavailable, the account terminated —
+// not retried
+// members members-only, paid, or a login is required — not retried
+// disk no space left, the store read-only or not writable — not
+// retried
+// rate-limited HTTP 429 / "Too Many Requests" / the bot check — ONE more
+// try after LIVE_RATE_LIMIT_WAIT_MS, then not again
+// empty "The downloaded file is empty" (20 Nov 2026) — the schedule
+// network a connection or HTTP 5xx error — the schedule
+// unknown anything else — the schedule
+// (A part with bytes, a Cancel, an argv no try can fix and a stream that
+// cannot start at its start are told apart by classifyAttempt first.)
+export type LiveFailureClass =
+ | "ended"
+ | "private"
+ | "members"
+ | "disk"
+ | "rate-limited"
+ | "empty"
+ | "network"
+ | "unknown"
+ | "argv"
+ | "unsupported"
+ | "partial";
+
+// What yt-dlp says when the stream is over or gone: no attempt can help.
+export function liveStreamGone(stderr: string): boolean {
+ const c = liveFailureClass(stderr);
+ return c === "ended" || c === "private";
+}
+
+export function liveFailureClass(stderr: string): LiveFailureClass {
+ const t = stderr;
+ // First: no space is no space, whatever else the tail says.
+ if (/No space left on device|Errno 28\b|Disk quota exceeded|Read-only file system|\[Errno 13\] Permission denied/i.test(t)) return "disk";
+ // Before `members`: the bot check's message also says "use --cookies".
+ if (/HTTP Error 429|Too Many Requests|Sign in to confirm you(?:'|’)re not a bot|confirm you(?:'|’)re not a bot/i.test(t)) return "rate-limited";
+ if (/This live event has ended|is no longer live|is not currently live|This live stream recording is not available|live stream has ended/i.test(t)) return "ended";
+ if (/Private video|This video is private|Video unavailable|This video has been removed|has been terminated|This video is no longer available/i.test(t)) return "private";
+ if (/Join this channel|available to this channel's members|members-only|members only|requires payment|Sign in to confirm your age|login required|account is required|use --cookies|--cookies-from-browser/i.test(t)) return "members";
+ if (/The downloaded file is empty/i.test(t)) return "empty";
+ if (/timed out|Connection reset|Connection refused|Network is unreachable|Temporary failure in name resolution|getaddrinfo|Name or service not known|IncompleteRead|Remote end closed|HTTP Error 5\d\d|Unable to download/i.test(t)) return "network";
+ return "unknown";
+}
+
+// The wait before the one more try a rate limit or a bot check gets.
+export const LIVE_RATE_LIMIT_WAIT_MS = 15 * 60_000;
+
+// What one attempt came to.
+// recorded it wrote media (whatever its exit): never retried here
+// stopped a Cancel's SIGINT
+// partial separate streams, and one wrote bytes while the other wrote
+// nothing: a failed attempt, retried on the schedule
+// unsupported yt-dlp cannot start this stream at its start (→ index 0)
+// argv the same argv would fail the same way (no format the
+// selector names, a URL no extractor takes): not retried
+// final ended, private, members-only or the disk (liveFailureClass):
+// not retried
+// rate-limited 429 or the bot check: one more try after a long wait
+// nothing it recorded nothing for another reason (empty, network,
+// unknown — an exit 0 with no bytes too: nothing was recorded,
+// and the stream may still be live): retried on the schedule
+export type LiveAttemptClass = "recorded" | "stopped" | "partial" | "unsupported" | "argv" | "final" | "rate-limited" | "nothing";
+
+export function classifyAttempt(o: {
+ exitCode: number | null;
+ signalled: boolean;
+ stderrTail: string;
+ bytes: number;
+ // Separate streams: one of the two wrote nothing (the caller probes).
+ partial?: boolean;
+}): LiveAttemptClass {
+ if (o.signalled) return "stopped";
+ if (o.bytes > 0) return o.partial ? "partial" : "recorded";
+ if (liveFromStartUnsupported(o.stderrTail)) return "unsupported";
+ if (formatUnavailable(o.stderrTail) || /Unsupported URL/i.test(o.stderrTail)) return "argv";
+ const c = liveFailureClass(o.stderrTail);
+ if (c === "ended" || c === "private" || c === "members" || c === "disk") return "final";
+ if (c === "rate-limited") return "rate-limited";
+ return "nothing";
+}
+
+// The recorder's last `ERROR:` line (yt-dlp prefixes a separate stream's lines
+// with its number, `1: ERROR: …`), else its last line; at most 300 characters.
+export function lastErrorLine(stderr: string): string | null {
+ const lines = stderr
+ .split(/[\r\n]+/)
+ .map((l) => l.trim())
+ .filter(Boolean);
+ const err = [...lines].reverse().find((l) => /^(?:\d+:\s*)?ERROR:/.test(l));
+ const line = err ?? lines.at(-1) ?? null;
+ return line ? line.replace(/^\d+:\s*/, "").slice(0, 300) : null;
+}
+
+// "2 h 14 min", "14 min", "40 s".
+export function spanWords(seconds: number): string {
+ const s = Math.max(0, Math.round(seconds));
+ if (s < 60) return `${s} s`;
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ return h ? `${h} h ${m} min` : `${m} min`;
+}
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -0,0 +1,316 @@
+// EVERY LIVE RECORDING OF A CHANNEL, ONE ROW PER RUN — `channels/<slug>/live-recordings.json`
+// ({rows: [...]}, beside pending-keep.json).
+//
+// A recording's own record (`data/<id>/live-recording.json`) is where a run
+// says what it is doing; it is not where a FAILURE can be relied on to stay. A
+// run that made data/<id>/ and recorded nothing removes the dir (every
+// enumerator reads a dir with metadata as "fetched"), and the record with it.
+// This file is the durable side: record-live writes its row on every save of
+// the record, and nothing but the cap below ever removes a row — never a
+// failed run, never a row that needs a person. A row is cleared from
+// attention by a person (acknowledge) or by a later run of the same id that
+// lands (supersededBy).
+//
+// Written only through these functions (one atomic write per change, under the
+// file's lock).
+//
+// A FILE THAT DOES NOT READ IS NEVER OVERWRITTEN. Its rows are the failures
+// nobody has acknowledged yet: a write that finds it unparseable (or
+// unreadable) renames it aside — `live-recordings.json.corrupt-<stamp>`, beside
+// it — starts a new file, and names the kept one in the new file's `setAside`,
+// which needs a person (the listing counts it) until acknowledged. A rename
+// that fails is a write that fails: the file stays as it is.
+
+import path from "node:path";
+import { rename } from "node:fs/promises";
+import type { Paths } from "./paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
+import type {
+ KeptPart,
+ RemovedPart,
+ LiveFailureClass,
+ LivePart,
+ LiveRecordingRecord,
+ LiveRecordingStatus,
+ LostSpan,
+ MissingStream,
+ StreamCoverage,
+} from "./liveCapture";
+
+export const LIVE_RECORDINGS_FILENAME = "live-recordings.json";
+
+// Rows kept per channel; past it the oldest rows that need nobody go first.
+export const LIVE_RECORDINGS_MAX_ROWS = 500;
+
+export type LiveRecordingRow = {
+ id: string;
+ url: string;
+ platform: string;
+ // When the run started (the record's startedAt): with `id`, the row's key.
+ startedAt: string;
+ endedAt?: string;
+ status: LiveRecordingStatus;
+ jobId?: string;
+ fromStart: boolean;
+ separate?: boolean;
+ error?: string;
+ attempts: number;
+ fallback?: "live-edge";
+ lost?: LostSpan;
+ mustKeep: boolean;
+ note?: string;
+ // What record-live was asked (its body's recording keys, no `id`/`dryRun`/
+ // `preclip`): what "Record again" asks again.
+ request?: Record<string, unknown>;
+ streamStartedAt?: string;
+ parts: LivePart[];
+ landedPart?: number;
+ failureClass?: LiveFailureClass;
+ missingStream?: MissingStream;
+ stoppedBy?: "operator" | "shutdown";
+ keptParts?: KeptPart[];
+ removedParts?: RemovedPart[];
+ coverage?: StreamCoverage;
+ acknowledgedAt?: string;
+ acknowledgedBy?: string;
+ // The run (its jobId, else its startedAt) that later landed this id.
+ supersededBy?: string;
+};
+
+function fileOf(paths: Pick<Paths, "channelsDir">, slug: string): string {
+ return path.join(paths.channelsDir, slug, LIVE_RECORDINGS_FILENAME);
+}
+
+function coerceRow(raw: unknown): LiveRecordingRow | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as LiveRecordingRow;
+ if (typeof r.id !== "string" || typeof r.startedAt !== "string" || typeof r.status !== "string") return null;
+ return {
+ ...r,
+ url: typeof r.url === "string" ? r.url : "",
+ platform: typeof r.platform === "string" ? r.platform : "unknown",
+ fromStart: r.fromStart === true,
+ attempts: typeof r.attempts === "number" ? r.attempts : 0,
+ mustKeep: r.mustKeep === true,
+ parts: Array.isArray(r.parts) ? r.parts : [],
+ };
+}
+
+// A live-recordings.json that did not read, renamed aside by a write.
+export type SetAsideFile = {
+ // Its name beside live-recordings.json.
+ file: string;
+ at: string;
+ reason: "unreadable" | "unparseable";
+ acknowledgedAt?: string;
+ acknowledgedBy?: string;
+};
+
+export type LiveRecordingsFile = {
+ rows: LiveRecordingRow[];
+ setAside: SetAsideFile[];
+ // The file as it is now does not read (the next write sets it aside).
+ problem: "unreadable" | "unparseable" | null;
+};
+
+function coerceSetAside(raw: unknown): SetAsideFile[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.filter(
+ (x): x is SetAsideFile => !!x && typeof x === "object" && typeof (x as SetAsideFile).file === "string" && typeof (x as SetAsideFile).at === "string",
+ );
+}
+
+export async function loadLiveRecordingsFile(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingsFile> {
+ const read = await readJsonFile(fileOf(paths, slug));
+ if (!read.ok) return { rows: [], setAside: [], problem: read.reason === "absent" ? null : read.reason };
+ const value = read.value as { rows?: unknown; setAside?: unknown } | null;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { rows: [], setAside: [], problem: "unparseable" };
+ const rows = Array.isArray(value.rows) ? value.rows.map(coerceRow).filter((r): r is LiveRecordingRow => r !== null) : [];
+ return { rows, setAside: coerceSetAside(value.setAside), problem: null };
+}
+
+export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingRow[]> {
+ return (await loadLiveRecordingsFile(paths, slug)).rows;
+}
+
+// Needs a person, as the row stands (the listing adds `interrupted` for a
+// `recording` no job runs).
+// failed, interrupted always
+// cancelled when the stream was must-keep (a
+// person's Cancel of any other stream
+// is quiet)
+// recorded from the live edge the stream's start is lost
+// one stream missing it landed without video or audio
+// parts kept on disk (keptParts) until acknowledged, whatever lands
+// later: a later recording does not
+// decide what happens to them
+// Cleared by an acknowledgement; all but the kept parts also by a later
+// recording that holds the whole stream (supersededBy).
+export function rowNeedsAttention(
+ r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> &
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream">>,
+): boolean {
+ if (r.acknowledgedAt) return false;
+ if (r.keptParts && r.keptParts.length > 0) return true;
+ if (r.supersededBy) return false;
+ if (r.status === "failed" || r.status === "interrupted") return true;
+ if (r.status === "cancelled" && r.mustKeep === true) return true;
+ if (r.fallback === "live-edge") return true;
+ return r.missingStream !== undefined;
+}
+
+function cap(rows: LiveRecordingRow[]): LiveRecordingRow[] {
+ if (rows.length <= LIVE_RECORDINGS_MAX_ROWS) return rows;
+ const out = [...rows];
+ for (let i = 0; i < out.length && out.length > LIVE_RECORDINGS_MAX_ROWS; ) {
+ const r = out[i]!;
+ if (r.status !== "recording" && !rowNeedsAttention(r)) out.splice(i, 1);
+ else i++;
+ }
+ return out;
+}
+
+async function mutate<T>(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ // Returns its answer and whether it changed anything (nothing changed:
+ // nothing written).
+ fn: (rows: LiveRecordingRow[], setAside: SetAsideFile[]) => [T, boolean],
+ now: () => Date = () => new Date(),
+): Promise<T> {
+ const file = fileOf(paths, slug);
+ return withJsonFileLock(file, async () => {
+ const cur = await loadLiveRecordingsFile(paths, slug);
+ let forced = false;
+ if (cur.problem) {
+ // Never overwritten: renamed aside first (a failed rename throws, and
+ // nothing is written).
+ const at = now().toISOString();
+ const aside = `${LIVE_RECORDINGS_FILENAME}.corrupt-${at.replace(/[:.]/g, "-")}`;
+ await rename(file, path.join(path.dirname(file), aside));
+ cur.setAside.push({ file: aside, at, reason: cur.problem });
+ forced = true;
+ }
+ const [out, changed] = fn(cur.rows, cur.setAside);
+ if (changed || forced) {
+ await writeJsonAtomic(file, { rows: cap(cur.rows), ...(cur.setAside.length ? { setAside: cur.setAside } : {}) });
+ }
+ return out;
+ });
+}
+
+// The row a run's record makes.
+export function rowOfRecord(
+ id: string,
+ rec: LiveRecordingRecord,
+ extra: { note?: string; request?: Record<string, unknown> } = {},
+): Omit<LiveRecordingRow, "acknowledgedAt" | "acknowledgedBy" | "supersededBy"> {
+ return {
+ id,
+ url: rec.url,
+ platform: rec.platform,
+ startedAt: rec.startedAt,
+ ...(rec.endedAt ? { endedAt: rec.endedAt } : {}),
+ status: rec.status,
+ ...(rec.jobId ? { jobId: rec.jobId } : {}),
+ fromStart: rec.fromStart,
+ ...(rec.separate !== undefined ? { separate: rec.separate } : {}),
+ ...(rec.error ? { error: rec.error } : {}),
+ attempts: rec.attempts ?? rec.parts.length,
+ ...(rec.fallback ? { fallback: rec.fallback } : {}),
+ ...(rec.lost ? { lost: rec.lost } : {}),
+ mustKeep: rec.mustKeep === true,
+ ...(extra.note ? { note: extra.note } : {}),
+ ...(extra.request ? { request: extra.request } : {}),
+ ...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}),
+ parts: rec.parts.map((p) => ({ ...p })),
+ ...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}),
+ ...(rec.failureClass ? { failureClass: rec.failureClass } : {}),
+ ...(rec.missingStream ? { missingStream: rec.missingStream } : {}),
+ ...(rec.stoppedBy ? { stoppedBy: rec.stoppedBy } : {}),
+ ...(rec.keptParts && rec.keptParts.length ? { keptParts: rec.keptParts.map((k) => ({ ...k, files: k.files.map((f) => ({ ...f })) })) } : {}),
+ ...(rec.removedParts && rec.removedParts.length ? { removedParts: rec.removedParts.map((r) => ({ ...r })) } : {}),
+ ...(rec.coverage ? { coverage: { ...rec.coverage } } : {}),
+ };
+}
+
+// Whether a row holds the whole stream: landed, from its start, with video and
+// audio, and as long as the stream within the coverage's tolerance
+// (controller/recordLive.ts streamCoverage). Only such a run supersedes.
+export function rowCoversStream(r: Pick<LiveRecordingRow, "status" | "fromStart" | "fallback" | "missingStream" | "coverage">): boolean {
+ return r.status === "landed" && r.fromStart && !r.fallback && !r.missingStream && r.coverage?.covers === true;
+}
+
+// Writes (or rewrites) the run's row. A run that lands the WHOLE stream
+// (rowCoversStream) marks every earlier row of the same id that still needs a
+// person as superseded by it. A live-edge landing, a run asked not to start at
+// the start, or a short partial never does.
+export async function upsertLiveRecordingRow(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ row: Omit<LiveRecordingRow, "acknowledgedAt" | "acknowledgedBy" | "supersededBy">,
+): Promise<void> {
+ await mutate(paths, slug, (rows) => {
+ const i = rows.findIndex((r) => r.id === row.id && r.startedAt === row.startedAt);
+ const prev = i >= 0 ? rows[i]! : null;
+ const next: LiveRecordingRow = {
+ ...row,
+ ...(prev?.acknowledgedAt ? { acknowledgedAt: prev.acknowledgedAt } : {}),
+ ...(prev?.acknowledgedBy ? { acknowledgedBy: prev.acknowledgedBy } : {}),
+ ...(prev?.supersededBy ? { supersededBy: prev.supersededBy } : {}),
+ };
+ if (i >= 0) rows[i] = next;
+ else rows.push(next);
+ if (rowCoversStream(row)) {
+ const by = row.jobId ?? row.startedAt;
+ for (const r of rows) {
+ if (r === next || r.id !== row.id || r.supersededBy) continue;
+ if (r.status === "recording" || rowNeedsAttention(r)) r.supersededBy = by;
+ }
+ }
+ return [undefined, true];
+ });
+}
+
+// A person has seen it: every row of `id` that needs a person (or the one
+// run `startedAt` names) is acknowledged. The rows stay.
+export async function acknowledgeLiveRecordingRows(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ id: string,
+ opts: { by?: string; startedAt?: string; now?: Date; interrupted?: (r: LiveRecordingRow) => boolean } = {},
+): Promise<number> {
+ const at = (opts.now ?? new Date()).toISOString();
+ return mutate(paths, slug, (rows) => {
+ let n = 0;
+ for (const r of rows) {
+ if (r.id !== id || r.acknowledgedAt) continue;
+ if (opts.startedAt && r.startedAt !== opts.startedAt) continue;
+ if (!rowNeedsAttention(r) && !opts.interrupted?.(r)) continue;
+ r.acknowledgedAt = at;
+ if (opts.by) r.acknowledgedBy = opts.by;
+ n++;
+ }
+ return [n, n > 0];
+ });
+}
+
+// A person has seen a set-aside file (its name, or every one of the channel's
+// when `file` is not given). The file stays where it is.
+export async function acknowledgeSetAsideFiles(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ opts: { file?: string; by?: string; now?: Date } = {},
+): Promise<number> {
+ const at = (opts.now ?? new Date()).toISOString();
+ return mutate(paths, slug, (_rows, setAside) => {
+ let n = 0;
+ for (const f of setAside) {
+ if (f.acknowledgedAt || (opts.file && f.file !== opts.file)) continue;
+ f.acknowledgedAt = at;
+ if (opts.by) f.acknowledgedBy = opts.by;
+ n++;
+ }
+ return [n, n > 0];
+ });
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -29,6 +29,7 @@ import {
DIARIZATION_SETTINGS_FIELD_DOCS,
PACING_SETTINGS_FIELD_DOCS,
LIVE_PRECLIP_SETTINGS_FIELD_DOCS,
+ LIVE_RECORDING_SETTINGS_FIELD_DOCS,
PUBLISH_SETTINGS_FIELD_DOCS,
REPORT_SCHEDULE_SETTINGS_FIELD_DOCS,
DIGEST_SETTINGS_FIELD_DOCS,
@@ -168,6 +169,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.livePreclip),
},
],
+ liveRecording: [
+ {
+ path: "liveRecording",
+ docs: LIVE_RECORDING_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.liveRecording),
+ },
+ ],
pacing: [
{
path: "pacing",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -50,6 +50,7 @@ import type {
DigestSettings,
PacingSettingsBlock,
LivePreclipSettingsBlock,
+ LiveRecordingSettingsBlock,
PublishSettings,
ReportScheduleSettings,
ReportDebouncePreset,
@@ -88,6 +89,8 @@ type PreSchemaSiteSettings = {
sleepBetweenDownloadsSeconds: number;
// Live pre-clip (plans/live-preclip.md) — its defaults.
livePreclip: LivePreclipSettingsBlock;
+ // The live recordings' stall threshold (controller/liveRecordings.ts).
+ liveRecording: LiveRecordingSettingsBlock;
// Release 17 slice RL — the adaptive pace and the hold.
pacing: PacingSettingsBlock;
downloadFormat: DownloadFormatPreset;
@@ -150,7 +153,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 49 fields, in file order", () => {
+test("SiteSettings keeps its 50 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -163,6 +166,7 @@ test("SiteSettings keeps its 49 fields, in file order", () => {
"social",
"sleepBetweenDownloadsSeconds",
"livePreclip",
+ "liveRecording",
"pacing",
"downloadFormat",
"sourceVideoQuality",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -985,6 +985,24 @@ export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock {
};
}
+// LIVE RECORDINGS (controller/liveRecordings.ts): how the listing judges a
+// recording that is running. Each field is documented in
+// LIVE_RECORDING_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md).
+export type LiveRecordingSettingsBlock = {
+ stallMinutes: number;
+};
+
+export const LIVE_RECORDING_SETTINGS_FIELD_DOCS: FieldDocs<LiveRecordingSettingsBlock> = {
+ stallMinutes:
+ "Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, " +
+ "the banners) mark it `stalled`. Clamped 1–240; default 10.",
+};
+
+export function sanitizeLiveRecording(v: unknown): LiveRecordingSettingsBlock {
+ const r = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
+ return { stallMinutes: clampInt(r.stallMinutes, 1, 240, 10) };
+}
+
export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600;
export const SLEEP_BETWEEN_DOWNLOADS_DEFAULT_SECONDS = 10;
@@ -1974,6 +1992,9 @@ export const siteSettingsSchema = z.object({
livePreclip: settingsField((v): LivePreclipSettingsBlock => sanitizeLivePreclip(v)).describe(
"The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `\"preclip\": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.",
),
+ liveRecording: settingsField((v): LiveRecordingSettingsBlock => sanitizeLiveRecording(v)).describe(
+ "How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.",
+ ),
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
),
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -19,6 +19,28 @@
- Under the deck, a `--chrome-only` take picks up the change. The exception is an audio-only clip, whose poster
is part of its segment. A no-deck build re-encodes only the clips of the renamed channel (docs/knobs.md, "A
channel's name in the cut").
+- **A live recording that fails is retried, then recorded from the live edge, and its failure stays loud.**
+ - A from-start attempt that records nothing ("The downloaded file is empty") is tried again at +60 and +180 s, then
+ from the live edge at 0, +60 and +180 s. A fallback to the live edge says how much of the stream's start it lost.
+ - `pnpm ops get live-recordings` answers whether a stream is being recorded and growing, from the recording's own
+ record: status, bytes, last growth, stalled, attempts, what was lost. `record-live` answers with the command that
+ checks it, and `--wait-started` returns once media is being written.
+ - A failed, interrupted or start-losing recording is listed on /review with Record again and Acknowledge, shown as a
+ banner on /jobs and the channel and video pages, and said on stderr after every `pnpm ops` reply, until it is
+ acknowledged (`pnpm ops live-recording-ack`) or a later recording of it lands. Its row in
+ `channels/<slug>/live-recordings.json` is never removed for failing.
+ - Why an attempt failed decides what follows: a stream that has ended, gone private, is members-only, or a full
+ disk is not retried; a 429 or YouTube's bot check gets one more try after 15 minutes, then stops; the row says
+ which (`failureClass`). An attempt where only one of the two streams recorded is retried too.
+ - The landing no longer deletes a part it is not known to hold. When the landed file covers the whole stream from
+ its start (or is a platform VOD that does), the other parts go, listed on the row. Otherwise they stay in staging,
+ listed with their sizes, until acknowledged.
+ - An editor shutdown leaves a recording `interrupted` (it needs you), never `cancelled`; cancelling a must-keep
+ stream needs you too. A stalled recording is said beside the failures. Only a recording that holds the whole
+ stream from its start clears an earlier failure. `--wait-started` exits 3 when only the live edge records.
+ - A `live-recordings.json` that does not read is set aside under a new name, never overwritten.
+ - New setting `liveRecording.stallMinutes` (default 10).
+ - The recorder's job log no longer takes every progress line of a separate-streams recording (~1 MB a minute).
- **umtool: the gap mark's border is the deck's accent colour.**
- The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule
and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text
diff --git a/editor/app/api/ops/_attention.ts b/editor/app/api/ops/_attention.ts
@@ -0,0 +1,54 @@
+import type { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { liveRecordingsAttentionCounts } from "yt-dlp-transcript-common/controller/liveRecordings";
+
+// WHAT NEEDS A PERSON, ON EVERY REPLY OF THE OPS DOOR. An agent polling the
+// editor reads replies, not pages: a live recording that failed (or lost its
+// start, was interrupted, kept parts it did not land), and one that runs but
+// has stopped growing, is said in a header on every answer the door gives —
+// `ops()`, `readRoute()`, and the GET routes that check opsAuth themselves
+// (they wrap their answer in withAttention) —
+//
+// x-archilyzer-attention: live-recordings=<N>[, stalled=<M>]
+//
+// — only when N or M is above 0, and `pnpm ops` prints one stderr line for it.
+// The counts (controller/liveRecordings.ts) are cached 30 s: they read each
+// channel's live-recordings.json, and a reply must not wait for that every
+// time. A count that could not be read is not cached (and not said).
+
+export const ATTENTION_HEADER = "x-archilyzer-attention";
+const TTL_MS = 30_000;
+
+type Counts = { needsAttention: number; stalled: number };
+let cached: { at: number; counts: Counts } | null = null;
+
+export async function liveRecordingsAttention(now = Date.now()): Promise<Counts | null> {
+ if (cached && now - cached.at < TTL_MS) return cached.counts;
+ try {
+ const counts = await liveRecordingsAttentionCounts(getPaths());
+ cached = { at: now, counts };
+ return counts;
+ } catch {
+ return null;
+ }
+}
+
+// For a write that changed the answer (an acknowledgement): the next reply counts again.
+export function forgetAttention(): void {
+ cached = null;
+}
+
+export function attentionHeaderValue(c: Counts | null): string | null {
+ if (!c || (c.needsAttention <= 0 && c.stalled <= 0)) return null;
+ return `live-recordings=${c.needsAttention}${c.stalled > 0 ? `, stalled=${c.stalled}` : ""}`;
+}
+
+export async function withAttention<R extends Response | NextResponse>(res: R): Promise<R> {
+ try {
+ const v = attentionHeaderValue(await liveRecordingsAttention());
+ if (v) res.headers.set(ATTENTION_HEADER, v);
+ } catch {
+ /* a reply is never refused for its header */
+ }
+ return res;
+}
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -113,6 +113,7 @@ test("a traversing slug is refused at the door, on every route that takes one",
["find-clips", { slug: "../../escape", id: "abc123" }],
["import-media", { slug: "../../escape", path: "/tmp/ops-api-never.mp4", id: "abc123" }],
["record-live", { slug: "../../escape", url: "https://rumble.com/v1abcde-x.html" }],
+ ["live-recording-ack", { slug: "../../escape", id: "abc123" }],
["live-preclip", { slug: "../../escape", id: "abc123", action: "status" }],
["live-clip", { slug: "../../escape", id: "abc123", start: 1, end: 20 }],
["keep-videos", { slug: "../../escape", ids: ["abc123"] }],
diff --git a/editor/app/api/ops/_lib.ts b/editor/app/api/ops/_lib.ts
@@ -6,6 +6,7 @@ import { isValidSiteId, listSiteIds } from "yt-dlp-transcript-common/lib/site";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import type { QueueOutcome } from "../../channels/lib/queueForSlugs";
+import { withAttention } from "./_attention";
// THE OPS API IS ADAPTERS, AND NOTHING ELSE.
//
@@ -74,11 +75,12 @@ export async function ops(
}`,
);
}
+ // Every answer says what needs a person (./_attention.ts).
try {
- return await run(body as OpsBody);
+ return await withAttention(await run(body as OpsBody));
} catch (e) {
- if (e instanceof OpsInputError) return opsFail(e.message);
- return opsFail((e as Error).message, 500);
+ if (e instanceof OpsInputError) return withAttention(opsFail(e.message));
+ return withAttention(opsFail((e as Error).message, 500));
}
}
diff --git a/editor/app/api/ops/_liveRecordings.test.ts b/editor/app/api/ops/_liveRecordings.test.ts
@@ -0,0 +1,104 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { TOKEN, callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_liveRecordings.test.ts"
+//
+// THE LIVE RECORDINGS DOOR (lane live-recording-guard): `get live-recordings`
+// answers each run from its own row, `live-recording-ack` acknowledges, and
+// every ops reply carries the attention header while something needs a
+// person. A temp corpus; the row is written through the one writer.
+
+const corpus = await setupOpsCorpus(null);
+test.after(() => corpus.cleanup());
+
+const SLUG = "demo-live";
+await corpus.writeChannelConfig(SLUG, { platform: "youtube", url: "https://www.youtube.com/@Example" });
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { upsertLiveRecordingRow } = await import("yt-dlp-transcript-common/lib/liveRecordings-server");
+await upsertLiveRecordingRow(getPaths(), SLUG, {
+ id: "exampleid01",
+ url: "https://www.youtube.com/watch?v=exampleid01",
+ platform: "youtube",
+ startedAt: new Date().toISOString(),
+ endedAt: new Date().toISOString(),
+ status: "failed",
+ fromStart: true,
+ error: "nothing was recorded — 6 attempts (3 from its start, 3 from the live edge): ERROR: The downloaded file is empty",
+ attempts: 6,
+ mustKeep: true,
+ parts: [],
+});
+
+const list = (await import("./live-recordings/route")).GET as unknown as Parameters<typeof callGet>[0];
+const ack = (await import("./live-recording-ack/route")).POST as unknown as Parameters<typeof callPost>[0];
+const authed = { authorization: `Bearer ${TOKEN}` };
+
+test("get live-recordings lists the failure, and the reply carries the attention header", async () => {
+ const res = await list(new Request(`http://localhost/api/ops/live-recordings?slug=${SLUG}`, { headers: authed }), { params: Promise.resolve({}) });
+ assert.equal(res.status, 200);
+ assert.equal(res.headers.get("x-archilyzer-attention"), "live-recordings=1");
+ const body = (await res.json()) as { needsAttention: number; rows: { id: string; status: string; needsAttention: boolean; check: string }[] };
+ assert.equal(body.needsAttention, 1);
+ assert.equal(body.rows[0]?.status, "failed");
+ assert.equal(body.rows[0]?.check, `pnpm ops get live-recordings ${SLUG}/exampleid01`);
+ const bad = await callGet(list, "http://localhost/api/ops/live-recordings?id=exampleid01");
+ assert.equal(bad.status, 400, "an id needs its slug");
+ const unknown = await callGet(list, "http://localhost/api/ops/live-recordings?slugs=x");
+ assert.equal(unknown.status, 400);
+});
+
+test("live-recording-ack acknowledges it: listed still, counted no more, and the header goes", async () => {
+ const refused = await callPost(ack, { slug: SLUG, id: "nosuchid001" });
+ assert.equal(refused.status, 400);
+ const traversing = await callPost(ack, { slug: "../../escape", id: "exampleid01" });
+ assert.equal(traversing.status, 400);
+ assert.match(String(traversing.body.error), /is not a valid channel slug/);
+ const res = await ack(
+ new Request("http://localhost/api/ops/live-recording-ack", {
+ method: "POST",
+ headers: { ...authed, "content-type": "application/json" },
+ body: JSON.stringify({ slug: SLUG, id: "exampleid01", by: "test" }),
+ }),
+ );
+ assert.equal(res.status, 200);
+ assert.deepEqual(await res.json(), { ok: true, acknowledged: 1 });
+ assert.equal(res.headers.get("x-archilyzer-attention"), null);
+ const after = await callGet(list, `http://localhost/api/ops/live-recordings?slug=${SLUG}`);
+ const rows = after.body.rows as { needsAttention: boolean; acknowledgedBy?: string }[];
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0]?.needsAttention, false);
+ assert.equal(rows[0]?.acknowledgedBy, "test");
+});
+
+test("the attention header rides on the GET routes that check their own auth too: get job, get jobs", async () => {
+ await upsertLiveRecordingRow(getPaths(), SLUG, {
+ id: "exampleid02",
+ url: "https://www.youtube.com/watch?v=exampleid02",
+ platform: "youtube",
+ startedAt: new Date().toISOString(),
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [],
+ });
+ (await import("./_attention")).forgetAttention();
+ const job = (await import("./job/[id]/route")).GET as unknown as (r: Request, c: { params: Promise<{ id: string }> }) => Promise<Response>;
+ const res = await job(new Request("http://localhost/api/ops/job/nosuchjob", { headers: authed }), { params: Promise.resolve({ id: "nosuchjob" }) });
+ assert.equal(res.status, 404);
+ assert.equal(res.headers.get("x-archilyzer-attention"), "live-recordings=1", "a 404 says it too");
+ const jobs = (await import("./jobs/route")).GET as unknown as (r: Request) => Promise<Response>;
+ const list2 = await jobs(new Request("http://localhost/api/ops/jobs?active=1", { headers: authed }));
+ assert.equal(list2.headers.get("x-archilyzer-attention"), "live-recordings=1");
+});
+
+test("the header's value says stalled recordings beside those that need a person", async () => {
+ const { attentionHeaderValue } = await import("./_attention");
+ assert.equal(attentionHeaderValue(null), null);
+ assert.equal(attentionHeaderValue({ needsAttention: 0, stalled: 0 }), null);
+ assert.equal(attentionHeaderValue({ needsAttention: 2, stalled: 0 }), "live-recordings=2");
+ assert.equal(attentionHeaderValue({ needsAttention: 0, stalled: 1 }), "live-recordings=0, stalled=1");
+});
diff --git a/editor/app/api/ops/_read.ts b/editor/app/api/ops/_read.ts
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { opsAuth, opsFail } from "./_lib";
+import { withAttention } from "./_attention";
// THE READ SIDE'S DOOR (release 19, A3): `GET /api/ops/<noun>` routes that
// answer what an existing builder already builds for a page — settings, the
@@ -28,9 +29,9 @@ export async function readRoute(
}
try {
const out = await run(q);
- return out instanceof NextResponse ? out : NextResponse.json({ ok: true, ...out });
+ return withAttention(out instanceof NextResponse ? out : NextResponse.json({ ok: true, ...out }));
} catch (e) {
- return opsFail((e as Error).message, 500);
+ return withAttention(opsFail((e as Error).message, 500));
}
}
diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts
@@ -15,6 +15,7 @@ import {
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads";
import { opsAuth } from "../../_lib";
+import { withAttention } from "../../_attention";
export const dynamic = "force-dynamic";
@@ -38,7 +39,7 @@ export const dynamic = "force-dynamic";
// largest channel here. The report's totals answer the same question from a
// file, and a poll loop asking for them every few seconds must not be the thing
// that hammers the platter.
-export async function GET(
+async function get(
request: Request,
{ params }: { params: Promise<{ slug: string }> },
) {
@@ -122,3 +123,9 @@ export async function GET(
: null,
});
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request, ctx: { params: Promise<{ slug: string }> }) {
+ return withAttention(await get(request, ctx));
+}
diff --git a/editor/app/api/ops/channels/route.ts b/editor/app/api/ops/channels/route.ts
@@ -4,6 +4,7 @@ import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels
import { isRemoteOnlyChannel, isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { siteChannelIndex } from "yt-dlp-transcript-common/lib/site";
import { opsAuth } from "../_lib";
+import { withAttention } from "../_attention";
export const dynamic = "force-dynamic";
@@ -13,7 +14,7 @@ export const dynamic = "force-dynamic";
// other channel routes, and to see which sites carry it — a channel on no site
// is private to this editor. Config reads only (no report, no media probe, no
// directory walk); `get channel <slug>` is the deep read of one.
-export async function GET(request: Request) {
+async function get(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
const paths = getPaths();
@@ -44,3 +45,9 @@ export async function GET(request: Request) {
})),
});
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request) {
+ return withAttention(await get(request));
+}
diff --git a/editor/app/api/ops/job/[id]/route.ts b/editor/app/api/ops/job/[id]/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { opsAuth, opsFail } from "../../_lib";
import { readJob } from "../../_jobs";
+import { withAttention } from "../../_attention";
export const dynamic = "force-dynamic";
@@ -23,7 +24,7 @@ export const dynamic = "force-dynamic";
// An id neither the registry nor `.jobs/` knows is a 404 `{ ok: false }`.
const MAX_TAIL = 500;
-export async function GET(
+async function get(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
@@ -50,3 +51,9 @@ export async function GET(
if (!found) return opsFail(`no job "${id}"`, 404);
return NextResponse.json({ ok: true, ...found });
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) {
+ return withAttention(await get(request, ctx));
+}
diff --git a/editor/app/api/ops/jobs/route.ts b/editor/app/api/ops/jobs/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
import { opsAuth, opsFail } from "../_lib";
import { listJobs } from "../_jobs";
+import { withAttention } from "../_attention";
export const dynamic = "force-dynamic";
@@ -24,7 +25,7 @@ export const dynamic = "force-dynamic";
const KEYS = ["active", "failed", "kind", "slug", "limit"];
const MAX_LIMIT = 500;
-export async function GET(request: Request) {
+async function get(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
const q = new URL(request.url).searchParams;
@@ -61,3 +62,9 @@ export async function GET(request: Request) {
const page = await listJobs({ active, failed, kind, slug, limit });
return NextResponse.json({ ok: true, ...page });
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request) {
+ return withAttention(await get(request));
+}
diff --git a/editor/app/api/ops/live-recording-ack/route.ts b/editor/app/api/ops/live-recording-ack/route.ts
@@ -0,0 +1,33 @@
+import { NextResponse } from "next/server";
+import { acknowledgeLiveRecordingAction } from "../../../channels/[slug]/liveMediaActions";
+import { forgetAttention } from "../_attention";
+import { ops, opsFail, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, startedAt?, by? } | { slug, file, by? } -> { ok: true, acknowledged }
+//
+// A PERSON HAS SEEN IT (controller/liveRecordings.ts): every run of the record
+// that needs a person — failed, interrupted, or recorded from the live edge
+// with the stream's start lost — or the one run `startedAt` names, is
+// acknowledged. The rows stay in `get live-recordings`; they no longer count
+// in /review, the banners or the attention header. /review's Acknowledge.
+// `file` instead of `id`: a live-recordings.json that did not read and was set
+// aside under that name (the listing's `files`) has been seen — it stays.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "file", "startedAt", "by"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const file = typeof body.file === "string" && body.file.trim() ? body.file.trim() : undefined;
+ const id = file ? undefined : reqString(body, "id");
+ const r = await acknowledgeLiveRecordingAction({
+ slug,
+ ...(id ? { id } : {}),
+ ...(file ? { file } : {}),
+ ...(typeof body.startedAt === "string" ? { startedAt: body.startedAt } : {}),
+ by: typeof body.by === "string" && body.by.trim() ? body.by.trim() : "agent:ops",
+ });
+ if (!r.ok) return opsFail(r.error);
+ forgetAttention();
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/api/ops/live-recordings/route.ts b/editor/app/api/ops/live-recordings/route.ts
@@ -0,0 +1,33 @@
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { listLiveRecordings } from "yt-dlp-transcript-common/controller/liveRecordings";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?slug=<channel>[&id=<record id>]][&all=1]
+// -> { ok, needsAttention, stalled, stallMinutes, files: [{ slug, file,
+// state (set-aside | unreadable), reason, needsAttention, message }],
+// rows: [{ slug, id, url, status (recording | interrupted | landed |
+// failed | cancelled), job, bytes, lastGrowthAt, stalled,
+// streamElapsedSeconds, capturedSeconds, coverage?, attempts,
+// failureClass?, fallback?, lost?, missingStream?, keptParts?,
+// stoppedBy?, error?, mustKeep, needsAttention, reason, check,
+// parts (each its bytes and lastGrowthAt while recording), … }] }
+//
+// IS THIS STREAM BEING RECORDED, AND IS IT GROWING (controller/
+// liveRecordings.ts): each run from its own record, never from "a job for this
+// video id". Default: what is recording, what needs a person, and the last 7
+// days; `all=1` every run kept. Nothing is written.
+export async function GET(request: Request) {
+ return readRoute(request, ["slug", "id", "all"], async (q) => {
+ const slug = q.get("slug")?.trim() || undefined;
+ const id = q.get("id")?.trim() || undefined;
+ if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ if (id && !slug) return opsFail('"id" goes with "slug"');
+ if (id && !/^[\w.-]+$/.test(id)) return opsFail(`"${id}" is not a record id`);
+ const listing = await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}), all: q.get("all") === "1" });
+ return { ...listing };
+ });
+}
diff --git a/editor/app/api/ops/publish/route.ts b/editor/app/api/ops/publish/route.ts
@@ -15,6 +15,7 @@ import {
reqSiteIds,
type OpsBody,
} from "../_lib";
+import { withAttention } from "../_attention";
export const dynamic = "force-dynamic";
@@ -180,8 +181,14 @@ export async function POST(request: Request) {
});
}
-export async function GET(request: Request) {
+async function get(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
return NextResponse.json({ ok: true, ...(await readPublishStatus(getPaths())) });
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request) {
+ return withAttention(await get(request));
+}
diff --git a/editor/app/api/ops/record-live/route.ts b/editor/app/api/ops/record-live/route.ts
@@ -1,12 +1,18 @@
-import { RECORD_LIVE_BODY_KEYS } from "yt-dlp-transcript-common/controller/recordLive";
+import { NextResponse } from "next/server";
+import { RECORD_LIVE_BODY_KEYS, recordLiveCheckCommand } from "yt-dlp-transcript-common/controller/recordLive";
import { recordLiveAction } from "../../../channels/[slug]/liveMediaActions";
-import { jobResponse, ops, reqSlug } from "../_lib";
+import { ops, opsFail, reqSlug } from "../_lib";
export const dynamic = "force-dynamic";
// POST { slug, url? | id?, fromStart? (true), maxHeight? (720; null = tallest),
// separate? (YouTube true, else false), transcribe?, doNotClean?, note?,
-// dryRun? } -> { ok: true, jobId }
+// dryRun? } -> { ok: true, jobId, kind: "record-live", check }
+//
+// `check` is the command that answers for the recording afterwards (`pnpm ops
+// get live-recordings <slug>/<id>`): whether it records, grows, failed — from
+// its own record, never from "a job for this video id". `pnpm ops record-live
+// … --wait-started` polls it until media bytes are being written.
//
// A LIVE STREAM RECORDED UNTIL IT ENDS (controller/recordLive.ts;
// plans/live-capture.md): yt-dlp `--live-from-start` (Rumble's DVR playlist
@@ -19,7 +25,10 @@ export const dynamic = "force-dynamic";
// stops the recorders with SIGINT and lands what they have.
export async function POST(request: Request) {
return ops(request, RECORD_LIVE_BODY_KEYS, async (body) => {
- reqSlug(body, "slug");
- return jobResponse(await recordLiveAction(body));
+ const slug = reqSlug(body, "slug");
+ const result = await recordLiveAction(body);
+ if (!result.ok) return opsFail(result.error, 400, result.info ? { info: true } : undefined);
+ void result.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: result.jobId, kind: "record-live", check: recordLiveCheckCommand(slug, body) });
});
}
diff --git a/editor/app/api/ops/tags/route.ts b/editor/app/api/ops/tags/route.ts
@@ -8,6 +8,7 @@ import {
removeTagDefAction,
} from "../../../tags/actions";
import { OpsInputError, oneOf, ops, opsAuth, opsFail } from "../_lib";
+import { withAttention } from "../_attention";
export const dynamic = "force-dynamic";
@@ -21,7 +22,7 @@ export const dynamic = "force-dynamic";
// at every index build and its hits live on the records, so the only honest
// answer from a file read is "what somebody said". For the built numbers, read
// a site's published /tags.json after a build.
-export async function GET(request: Request) {
+async function get(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
const config = readGlobalTags(getPaths());
@@ -147,3 +148,9 @@ export async function POST(request: Request) {
: opsFail(result.error);
});
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request) {
+ return withAttention(await get(request));
+}
diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts
@@ -15,6 +15,7 @@ import { readXTrendingAccounts } from "yt-dlp-transcript-common/controller/xSear
import { X_TRENDING_ACCOUNTS_MAX } from "yt-dlp-transcript-common/lib/xTrending/accounts";
import { readXTrendingPublished } from "yt-dlp-transcript-common/lib/xTrending/published";
import { opsAuth, opsFail } from "../_lib";
+import { withAttention } from "../_attention";
export const dynamic = "force-dynamic";
@@ -92,7 +93,7 @@ export const dynamic = "force-dynamic";
const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail", "accounts"];
const FLAGS = new Set(["1", "true"]);
-export async function GET(request: Request) {
+async function get(request: Request) {
const denied = opsAuth(request);
if (denied) return denied;
const sp = new URL(request.url).searchParams;
@@ -212,3 +213,9 @@ export async function GET(request: Request) {
}
return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing });
}
+
+// Every answer says what needs a person (../_attention.ts), as ops() and
+// readRoute() do.
+export async function GET(request: Request) {
+ return withAttention(await get(request));
+}
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -32,6 +32,8 @@ import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/
import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport";
import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia";
import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive";
+import { acknowledgeLiveRecording } from "yt-dlp-transcript-common/controller/liveRecordings";
+import { loadLiveRecordingRows } from "yt-dlp-transcript-common/lib/liveRecordings-server";
import {
finalizeLivePreclip,
livePreclipStatus,
@@ -120,6 +122,51 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S
});
}
+// LIVE RECORDINGS THAT NEED A PERSON (controller/liveRecordings.ts):
+// acknowledgeLiveRecordingAction `pnpm ops live-recording-ack`, the
+// Acknowledge button on /review and the
+// banners: the rows stay listed, no longer
+// needing anyone.
+// recordLiveAgainAction the Record again button: record-live with
+// the run's own url and recording keys.
+export async function acknowledgeLiveRecordingAction(body: {
+ slug: string;
+ id?: string;
+ // A set-aside live-recordings.json (the listing's `files`), by its name.
+ file?: string;
+ startedAt?: string;
+ by?: string;
+}): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` };
+ if (body.file !== undefined) {
+ if (!/^live-recordings\.json\.corrupt-[\w-]+$/.test(body.file)) return { ok: false, error: `"${body.file}" is not a set-aside live-recordings file` };
+ } else if (!body.id || !/^[\w.-]+$/.test(body.id)) return { ok: false, error: `"${body.id ?? ""}" is not a record id` };
+ const r = await acknowledgeLiveRecording(getPaths(), {
+ slug: body.slug,
+ ...(body.file !== undefined ? { file: body.file } : { id: body.id! }),
+ ...(body.startedAt ? { startedAt: body.startedAt } : {}),
+ by: body.by ?? "editor",
+ });
+ if (r.ok) safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`, ...(body.id ? [`/channels/${body.slug}/videos/${body.id}`] : [])]);
+ return r;
+}
+
+export async function recordLiveAgainAction(body: {
+ slug: string;
+ id: string;
+ startedAt?: string;
+}): Promise<{ ok: true; jobId: string } | { ok: false; error: string; info?: boolean }> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` };
+ const rows = await loadLiveRecordingRows(getPaths(), body.slug);
+ const row = [...rows].reverse().find((r) => r.id === body.id && (!body.startedAt || r.startedAt === body.startedAt));
+ if (!row || !row.url) return { ok: false, error: `${body.slug}/${body.id} has no live recording to record again` };
+ const r = await recordLiveAction({ ...(row.request ?? { fromStart: row.fromStart }), slug: body.slug, url: row.url });
+ if (!r.ok) return { ok: false, error: r.error, ...(r.info ? { info: true } : {}) };
+ void r.stream.cancel();
+ safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`]);
+ return { ok: true, jobId: r.jobId };
+}
+
export type LivePreclipActionResult =
| { ok: true; action: "start"; jobId: string }
| { ok: true; action: "stop"; jobId: string }
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -1,4 +1,5 @@
import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server";
+import { LiveRecordingsAttention } from "../../components/LiveRecordingsAttention";
import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema";
import path from "node:path";
import { Suspense, type ReactNode } from "react";
@@ -993,6 +994,7 @@ export default async function ChannelDetailPage({
return (
<div className="flex flex-col gap-6">
{!existing && <NoReportYet slug={slug} />}
+ <LiveRecordingsAttention slug={slug} />
{/* MANUAL DOWNLOADS (lib/manualDownloads.ts): said at the top, so a
channel whose listing is mostly undownloaded is not read as stalled. */}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../../../../components/LiveRecordingsAttention";
import Link from "next/link";
import { notFound } from "next/navigation";
import path from "node:path";
@@ -342,6 +343,7 @@ export default async function VideoDetailPage({
<span>/</span>
<span className="font-mono">{id}</span>
</div>
+ <LiveRecordingsAttention slug={slug} id={id} />
<header className="flex flex-col gap-2">
{/* h2, not h1. The channel layout above this route owns the page's
diff --git a/editor/app/components/LiveRecordingActions.tsx b/editor/app/components/LiveRecordingActions.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+// THE TWO ANSWERS TO A LIVE RECORDING THAT NEEDS A PERSON (LiveRecordingsAttention):
+// Record again — record-live with the run's own url and recording keys — and
+// Acknowledge — seen; the row stays in `pnpm ops get live-recordings` and no
+// longer counts. A failed press says so.
+
+import { useState, useTransition } from "react";
+import {
+ acknowledgeLiveRecordingAction,
+ recordLiveAgainAction,
+} from "../channels/[slug]/liveMediaActions";
+
+export function LiveRecordingActions({
+ slug,
+ id,
+ startedAt,
+ file,
+ canRecordAgain,
+}: {
+ slug: string;
+ // A recording's run (id + startedAt), or a set-aside live-recordings.json.
+ id?: string;
+ startedAt?: string;
+ file?: string;
+ canRecordAgain: boolean;
+}): React.ReactNode {
+ const what = file ?? `${slug}/${id ?? ""}`;
+ const [pending, startTransition] = useTransition();
+ const [said, setSaid] = useState<{ error: boolean; text: string } | null>(null);
+ const press = (fn: () => Promise<{ ok: boolean; error?: string } & Record<string, unknown>>, done: (r: Record<string, unknown>) => string) =>
+ startTransition(async () => {
+ try {
+ const r = await fn();
+ setSaid(r.ok ? { error: false, text: done(r) } : { error: true, text: r.error ?? "failed" });
+ } catch (e) {
+ setSaid({ error: true, text: (e as Error).message });
+ }
+ });
+ const btn = "rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50";
+ return (
+ <span className="flex items-center gap-2 flex-wrap">
+ {canRecordAgain && id && (
+ <button
+ type="button"
+ aria-label={`record ${what} again`}
+ disabled={pending}
+ className={btn}
+ onClick={() => press(() => recordLiveAgainAction({ slug, id, ...(startedAt ? { startedAt } : {}) }), (r) => `Recording: job ${String(r.jobId)}`)}
+ >
+ Record again
+ </button>
+ )}
+ <button
+ type="button"
+ aria-label={`acknowledge ${what}`}
+ disabled={pending}
+ className={btn}
+ onClick={() =>
+ press(
+ () =>
+ acknowledgeLiveRecordingAction(file ? { slug, file } : { slug, ...(id ? { id } : {}), ...(startedAt ? { startedAt } : {}) }),
+ () => "Acknowledged",
+ )
+ }
+ >
+ Acknowledge
+ </button>
+ {said && (
+ <span role={said.error ? "alert" : "status"} className={`text-xs ${said.error ? "text-destructive" : "text-muted-foreground"}`}>
+ {said.text}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/editor/app/components/LiveRecordingsAttention.tsx b/editor/app/components/LiveRecordingsAttention.tsx
@@ -0,0 +1,122 @@
+import Link from "next/link";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ listLiveRecordings,
+ type LiveRecordingView,
+ type LiveRecordingsFileProblem,
+} from "yt-dlp-transcript-common/controller/liveRecordings";
+import { LiveRecordingActions } from "./LiveRecordingActions";
+
+// LIVE RECORDINGS THAT NEED A PERSON (controller/liveRecordings.ts): failed,
+// interrupted, cancelled when must-keep, recorded from the live edge with the
+// stream's start lost, one stream missing, parts kept on disk not landed — and
+// every recording that runs but has STOPPED GROWING (stalled: said here as a
+// failure is, with no Acknowledge, since it clears itself when the files grow
+// or the run ends), and a live-recordings.json that did not read.
+// One component for the four places it is said — /review's section, and the
+// banners on /jobs, the channel page and the video page (narrowed by `slug`,
+// `id`) — so all four say the same sentence. It stays until a person presses
+// Acknowledge or a later recording of the stream lands from its start.
+//
+// RENDERED ONLY WHEN THERE IS SOMETHING TO SAY, like /review's other sections.
+
+function when(iso: string): string {
+ return `${iso.slice(0, 16).replace("T", " ")} UTC`;
+}
+
+function Row({ r }: { r: LiveRecordingView }) {
+ return (
+ <li
+ aria-label={`live recording ${r.slug}/${r.id}`}
+ className="flex flex-col gap-1 border-t border-destructive/30 pt-2 first:border-t-0 first:pt-0"
+ >
+ <span className="flex items-center gap-2 flex-wrap">
+ <Link href={`/channels/${r.slug}/videos/${r.id}`} className="font-medium underline hover:text-foreground">
+ {r.slug}/{r.id}
+ </Link>
+ <span className="text-muted-foreground">
+ started {when(r.startedAt)} · {r.attempts} attempt{r.attempts === 1 ? "" : "s"}
+ {r.mustKeep ? " · must keep" : ""}
+ {r.job ? (
+ <>
+ {" · "}
+ <Link href={`/jobs/${r.job.id}`} className="underline hover:text-foreground">
+ job {r.job.status}
+ </Link>
+ </>
+ ) : null}
+ </span>
+ </span>
+ <span>{r.reason}</span>
+ {r.keptParts && r.keptParts.length > 0 ? (
+ <ul className="text-xs text-muted-foreground">
+ {r.keptParts.map((k) => (
+ <li key={k.stem}>
+ kept: <code>{k.stem}</code> · {Math.round(k.bytes / 1024 / 1024)} MB · {k.why}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ {r.needsAttention ? (
+ <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} />
+ ) : null}
+ </li>
+ );
+}
+
+function FileRow({ f }: { f: LiveRecordingsFileProblem }) {
+ return (
+ <li
+ aria-label={`live recordings file ${f.slug}/${f.file}`}
+ className="flex flex-col gap-1 border-t border-destructive/30 pt-2 first:border-t-0 first:pt-0"
+ >
+ <span>{f.message}</span>
+ {f.state === "set-aside" ? <LiveRecordingActions slug={f.slug} file={f.file} canRecordAgain={false} /> : null}
+ </li>
+ );
+}
+
+export async function LiveRecordingsAttention({
+ slug,
+ id,
+ heading = false,
+}: {
+ slug?: string;
+ id?: string;
+ // /review: a section with a heading; elsewhere a banner.
+ heading?: boolean;
+}) {
+ let rows: LiveRecordingView[];
+ let files: LiveRecordingsFileProblem[];
+ try {
+ const l = await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}) });
+ rows = l.rows.filter((r) => r.needsAttention || r.stalled);
+ files = l.files.filter((f) => f.needsAttention);
+ } catch {
+ return null;
+ }
+ if (rows.length === 0 && files.length === 0) return null;
+ const stalled = rows.filter((r) => r.stalled).length;
+ const title = `Live recordings that need you (${rows.length + files.length}${stalled ? `, ${stalled} not growing` : ""})`;
+ return (
+ <section
+ aria-label="live recordings that need you"
+ data-live-recordings-attention=""
+ role={heading ? undefined : "alert"}
+ className="flex flex-col gap-2 rounded-md border border-destructive/30 bg-destructive-soft px-3 py-2 text-sm"
+ >
+ {heading ? <h2 className="text-lg font-semibold">{title}</h2> : <strong>{title}</strong>}
+ <ul className="flex flex-col gap-2">
+ {rows.map((r) => (
+ <Row key={`${r.slug}/${r.id}/${r.startedAt}`} r={r} />
+ ))}
+ {files.map((f) => (
+ <FileRow key={`${f.slug}/${f.file}`} f={f} />
+ ))}
+ </ul>
+ <span className="text-xs text-muted-foreground">
+ <code>pnpm ops get live-recordings</code> lists every recording; <code>pnpm ops live-recording-ack</code> is Acknowledge.
+ </span>
+ </section>
+ );
+}
diff --git a/editor/app/jobs/page.tsx b/editor/app/jobs/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../components/LiveRecordingsAttention";
import { Suspense } from "react";
import Link from "next/link";
import {
@@ -82,6 +83,7 @@ export default async function JobsPage({
</div>
</div>
<RenderModeBanner />
+ <LiveRecordingsAttention />
<StreamErrorBoundary name="jobs-list" what="The job list">
<Suspense
fallback={
diff --git a/editor/app/review/page.tsx b/editor/app/review/page.tsx
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
+import { LiveRecordingsAttention } from "../components/LiveRecordingsAttention";
import Link from "next/link";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import {
@@ -45,6 +46,7 @@ export default async function ReviewPage() {
return (
<div className="flex flex-col gap-6">
<h1 className="text-2xl font-semibold">Review</h1>
+ <LiveRecordingsAttention heading />
<AutoPausedSection rows={review.autoPaused} />
<PausedWatchesSection rows={review.pausedWatches} />
<XRunConsole initial={xRun} />
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -63,6 +63,9 @@
// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'
// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'
// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'
+// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started
+// pnpm ops get live-recordings demo-yt/<videoId>
+// pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'
// pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'
// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait
// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'
@@ -395,6 +398,21 @@ const GETTERS = {
"generation-usage": (day) =>
day ? `/api/ops/generation-usage?day=${encodeURIComponent(day)}` : "/api/ops/generation-usage",
iterations: (article) => `/api/ops/iterations?article=${encodeURIComponent(article)}`,
+ // Every live recording, from its own record (controller/liveRecordings.ts):
+ // status (recording | interrupted | landed | failed | cancelled), bytes, last
+ // growth, stalled, attempts, a live-edge fallback and what it lost, and
+ // needsAttention. `<slug>` or `<slug>/<id>` narrows it; --all is every run kept.
+ "live-recordings": (arg, { all }) => {
+ const q = new URLSearchParams();
+ if (arg) {
+ const [slug, id] = String(arg).split("/");
+ if (slug) q.set("slug", slug);
+ if (id) q.set("id", id);
+ }
+ if (all) q.set("all", "1");
+ const s = q.toString();
+ return `/api/ops/live-recordings${s ? `?${s}` : ""}`;
+ },
};
// READS THAT ARE JOBS: the answer needs a request upstream, so the editor
@@ -436,6 +454,7 @@ const GET_ARG_OPTIONAL = new Set([
"render-mode",
"speakers",
"lookouts",
+ "live-recordings",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -446,6 +465,7 @@ const GET_FLAGS = {
trending: ["topic", "limit", "accounts"],
job: ["tail"],
jobs: ["active", "failed", "kind", "slug", "limit"],
+ "live-recordings": ["all"],
};
// The row buttons of /jobs (`POST /api/ops/job`), as `job <verb> <id…>`.
@@ -542,6 +562,10 @@ const ACTIONS = [
// clip, project?, replace?}).
"live-preclip",
"live-clip",
+ // A live recording that failed, was interrupted or lost its start, seen by
+ // a person ({slug, id, startedAt?, by?}): it stays in `get live-recordings`
+ // and no longer counts as needing anyone. /review's Acknowledge.
+ "live-recording-ack",
// A channel's saved containers remuxed losslessly into browser-playable
// copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}).
"prepare-playable",
@@ -886,6 +910,9 @@ export function parseArgs(argv) {
let counts = false;
let leads = false;
let accounts = false;
+ let all = false;
+ // record-live only: return once media bytes are being written.
+ let waitStarted = false;
let tail = 0;
// `job resume-interrupted` only: list what would be re-queued.
let dryRun = false;
@@ -932,6 +959,11 @@ export function parseArgs(argv) {
} else if (arg === "--accounts") {
accounts = true;
used.add("accounts");
+ } else if (arg === "--all") {
+ all = true;
+ used.add("all");
+ } else if (arg === "--wait-started") {
+ waitStarted = true;
} else if (arg === "--active" || arg === "--failed") {
jobs[arg.slice(2)] = true;
used.add(arg.slice(2));
@@ -987,6 +1019,9 @@ export function parseArgs(argv) {
}
}
if (positional.length === 0) return { help: true };
+ if (waitStarted && positional[0] !== "record-live") {
+ return { error: "--wait-started goes with record-live" };
+ }
if (dryRun && !(positional[0] === "job" && positional[1] === "resume-interrupted")) {
return { error: '--dry-run goes with "job resume-interrupted" (elsewhere, a body\'s "dryRun": true)' };
}
@@ -1048,7 +1083,7 @@ export function parseArgs(argv) {
}
return {
method: "GET",
- path: GETTERS[noun](positional[2], { counts, leads, accounts, tail, jobs }),
+ path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs }),
wait: false,
quiet,
waitTimeout,
@@ -1133,6 +1168,7 @@ export function parseArgs(argv) {
...(action === "x-run" ? { resultMarker: X_RUN_RESULT_MARKER } : {}),
...(action === "read-x-trending" ? { resultMarker: READ_X_TRENDING_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
+ ...(waitStarted ? { waitStarted: true } : {}),
wait,
quiet,
waitTimeout,
@@ -1161,6 +1197,125 @@ export function previewUrlsIn(payload) {
return [...new Set(urls)];
}
+// WHAT NEEDS A PERSON, said on every reply (editor/app/api/ops/_attention.ts):
+// the header `x-archilyzer-attention: live-recordings=<N>[, stalled=<M>]`
+// becomes one stderr line, so an agent that only ever reads replies still
+// hears of a live recording that failed, was interrupted, lost its start or
+// kept parts — and of one that runs and has stopped growing. Null when both
+// are 0.
+export function attentionLine(headerValue) {
+ const m = /live-recordings=(\d+)/.exec(headerValue ?? "");
+ const st = /stalled=(\d+)/.exec(headerValue ?? "");
+ const n = m ? Number(m[1]) : 0;
+ const s = st ? Number(st[1]) : 0;
+ if (n <= 0 && s <= 0) return null;
+ const said = [];
+ if (n > 0) said.push(`${n} live recording${n === 1 ? " needs" : "s need"} you`);
+ if (s > 0) said.push(`${s} live recording${s === 1 ? " is" : "s are"} NOT growing (stalled)`);
+ return `! ${said.join("; ")}: pnpm ops get live-recordings`;
+}
+
+// --wait-started: how often the recording is asked after, and for how long by
+// default (the attempts' schedule, 0/+60/+180 s twice over, is ~8 minutes).
+export const WAIT_STARTED_POLL_MS = 10_000;
+export const WAIT_STARTED_DEFAULT_SECONDS = 15 * 60;
+
+// The exit of `record-live --wait-started` when the recording runs, but only
+// from the live edge: the stream's start is lost (not a success, and not the
+// failure exit 1 is).
+export const WAIT_STARTED_EDGE_ONLY_EXIT = 3;
+
+// The bytes that count as "started": a run asked from its start counts only
+// its FROM-START parts (the listing gives each part's bytes while it
+// records); a run asked from now (fromStart: false) counts every part.
+export function startedBytes(row) {
+ if (!row) return null;
+ if (row.fromStart === false) return typeof row.bytes === "number" ? row.bytes : null;
+ if (Array.isArray(row.parts) && row.parts.some((p) => typeof p?.bytes === "number")) {
+ return row.parts.filter((p) => p?.fromStart).reduce((n, p) => n + (typeof p.bytes === "number" ? p.bytes : 0), 0);
+ }
+ return row.fallback === "live-edge" ? 0 : typeof row.bytes === "number" ? row.bytes : null;
+}
+
+// One poll's verdict on the run's row:
+// {ok: true} a from-start part's bytes grew since the poll
+// before (a run asked from now: any part's), or
+// it landed from its start
+// {ok: false, edgeOnly: true} it records (or landed) from the live edge
+// only: the stream's start is lost
+// (WAIT_STARTED_EDGE_ONLY_EXIT)
+// {ok: false, reason} it failed, was cancelled or interrupted
+// null ask again
+export function startedVerdict(row, prevBytes) {
+ if (!row) return null;
+ if (row.status === "failed" || row.status === "cancelled" || row.status === "interrupted") {
+ return { ok: false, reason: row.reason ?? row.status };
+ }
+ const edgeOnly = row.fromStart !== false && row.fallback === "live-edge";
+ const edgeReason = () => `recording from the live edge only: the stream's start is LOST — ${row.reason ?? row.status}`;
+ if (row.status === "landed") return edgeOnly ? { ok: false, edgeOnly: true, reason: edgeReason() } : { ok: true };
+ const now = startedBytes(row);
+ if (now !== null && now > 0 && prevBytes !== null && now > prevBytes) return { ok: true };
+ if (edgeOnly && typeof row.bytes === "number" && row.bytes > 0) return { ok: false, edgeOnly: true, reason: edgeReason() };
+ return null;
+}
+
+// RECORD-LIVE --wait-started: returns once the recording's own row (the run
+// whose jobId the reply named, in `get live-recordings`) shows media bytes
+// growing (a FROM-START part's, when it was asked from its start) — or fails
+// with the reason it gives, `edgeOnly` when it records from the live edge only
+// (the start lost). A job that ends with no row at all (a refusal before the
+// recording) fails with the job's status. Answers {ok, edgeOnly?, row?, reason?}.
+export async function waitStarted(reply, slug, opts = {}) {
+ const doFetch = opts.fetch ?? fetch;
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
+ const now = opts.now ?? (() => Date.now());
+ const say = opts.say ?? ((line) => process.stderr.write(`${line}\n`));
+ const base = opts.baseUrl ?? baseUrl();
+ const headers = opts.headers ?? authHeaders();
+ const seconds = opts.timeoutSeconds > 0 ? opts.timeoutSeconds : WAIT_STARTED_DEFAULT_SECONDS;
+ const deadline = now() + seconds * 1000;
+ const id = /live-recordings \S+\/(\S+)$/.exec(reply.check ?? "")?.[1];
+ const listing = GETTERS["live-recordings"](id ? `${slug}/${id}` : slug, { all: true });
+ let prevBytes = null;
+ let lastSaid = null;
+ for (;;) {
+ let row = null;
+ try {
+ const res = await doFetch(`${base}${listing}`, { headers });
+ const payload = await res.json();
+ row = (payload.rows ?? []).find((r) => r.jobId === reply.jobId) ?? null;
+ } catch {
+ row = null;
+ }
+ const verdict = startedVerdict(row, prevBytes);
+ if (verdict) return { ...verdict, row };
+ if (!row) {
+ try {
+ const res = await doFetch(`${base}/api/ops/job/${encodeURIComponent(reply.jobId)}`, { headers });
+ const job = (await res.json())?.job;
+ if (job && ["done", "failed", "cancelled"].includes(job.status)) {
+ return job.status === "done"
+ ? { ok: true, row: null }
+ : { ok: false, row: null, reason: `job ${reply.jobId} ended ${job.status} before it recorded anything` };
+ }
+ } catch {
+ /* asked again next poll */
+ }
+ }
+ if (row) {
+ const line = `[${reply.jobId}] ${row.reason}`;
+ if (line !== lastSaid) say(line);
+ lastSaid = line;
+ prevBytes = startedBytes(row) ?? prevBytes;
+ }
+ if (now() >= deadline) {
+ return { ok: false, row, reason: `--wait-started: no media bytes after ${seconds} s (${reply.check})` };
+ }
+ await sleep(WAIT_STARTED_POLL_MS);
+ }
+}
+
function printPreviewUrls(payload) {
for (const url of previewUrlsIn(payload)) console.error(`preview: ${url}`);
}
@@ -1231,6 +1386,8 @@ export function usage() {
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
" pnpm ops get generation-usage [<YYYY-MM-DD>] | iterations <article>",
+ " pnpm ops get live-recordings [<slug>[/<id>]] [--all]",
+ " pnpm ops record-live --json '<body>' --wait-started [--wait-timeout <seconds>]",
" pnpm ops list",
"",
`Actions: ${ACTIONS.join(", ")}`,
@@ -2410,6 +2567,49 @@ export function usage() {
' {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine",',
' "project"}, over settings.livePreclip) starts live-preclip once the first',
' part begins, and implies "transcribe".',
+ " A from-start attempt that records nothing (yt-dlp: \"The downloaded file",
+ " is empty\"), or only one of its two streams, is tried again at +60 and",
+ " +180 s, then from the live edge at 0, +60 and +180 s (each wait",
+ " jittered). The failure's class decides: ended, private/removed,",
+ " members-only/login and a full or unwritable disk are not retried; a 429",
+ " or the bot check gets ONE more try after 15 min, then stops; empty,",
+ " network and unknown failures keep the schedule; a Cancel ends it. The",
+ " row records the class (failureClass). A live-edge fallback says what it",
+ " lost (the first N min of the stream) and needs a person. The landing",
+ " never removes a part it is not known to contain (an earlier run's, one",
+ " from another point of the stream, one it cannot land): those are kept",
+ " in staging and listed (keptParts) until acknowledged. The reply is",
+ ' {jobId, kind, "check"}: the `get live-recordings` command that answers',
+ " for it. --wait-started returns once a FROM-START part's bytes grow (the",
+ " recording's row on stdout, exit 0; a run asked fromStart: false, any",
+ " part's), exit 3 when it records only from the live edge (the start is",
+ " lost), exit 1 with the reason it failed; 15 minutes by default,",
+ " --wait-timeout overrides.",
+ "",
+ "get live-recordings [<slug>[/<id>]] [--all] is THE answer to \"is this",
+ " stream being recorded, and is it growing\" — never a job for the video",
+ " id (a live-chat job is one too). Per run, from its own record: status",
+ " (recording | interrupted: no job runs it, or the editor shut down |",
+ " landed | failed | cancelled), job, bytes, lastGrowthAt, parts (each its",
+ " bytes and lastGrowthAt while recording), stalled (not grown for",
+ " settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,",
+ " capturedSeconds (once landed), coverage, attempts, failureClass,",
+ " fallback, lost, missingStream, keptParts, error, mustKeep,",
+ " needsAttention, reason, check; `files` names a live-recordings.json that",
+ " did not read (set aside, never overwritten). Default: what is recording,",
+ " what needs a person, the last 7 days; --all every run kept",
+ " (channels/<slug>/live-recordings.json, never pruned of a failure).",
+ " needsAttention — failed, interrupted, cancelled when must-keep, the",
+ " stream's start lost, a stream missing, parts kept — stays until",
+ " live-recording-ack, or (all but kept parts) a later recording that lands",
+ " the WHOLE stream from its start; /review, /jobs, the channel and video",
+ " pages show the same rows and the stalled ones, and every ops reply then",
+ " prints \"! N live recordings need you; M ... NOT growing\" on stderr.",
+ "",
+ 'live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every',
+ " run of the record that needs a person (or the one run startedAt names):",
+ ' listed still, counted no more. {"slug", "file"} acknowledges a set-aside',
+ " live-recordings.json (it stays where it is). /review's Acknowledge.",
"",
'live-preclip transcribes and mines a recording WHILE it records: {"slug",',
' "id", "action"?: "start" (default) | "stop" | "status" | "finalize"}, and',
@@ -3449,6 +3649,8 @@ async function main() {
...(parsed.method === "POST" ? { body: JSON.stringify(parsed.body) } : {}),
});
const text = await res.text();
+ const attention = attentionLine(res.headers?.get?.("x-archilyzer-attention"));
+ if (attention) console.error(attention);
let payload;
try {
payload = JSON.parse(text);
@@ -3462,8 +3664,16 @@ async function main() {
// A result-carrying action under --wait keeps stdout for the RESULT: the
// response goes to stderr with the log.
const resultMode = Boolean(parsed.wait && parsed.resultMarker);
- (resultMode ? console.error : console.log)(JSON.stringify(payload, null, 2));
+ (resultMode || parsed.waitStarted ? console.error : console.log)(JSON.stringify(payload, null, 2));
if (!res.ok || payload.ok === false) return 1;
+ if (parsed.waitStarted && payload.jobId) {
+ // stdout carries the recording's row once it is writing media.
+ const r = await waitStarted(payload, parsed.body.slug, { timeoutSeconds: parsed.waitTimeout ?? 0 });
+ if (r.row) console.log(JSON.stringify(r.row, null, 2));
+ if (!r.ok) console.error(r.reason);
+ else if (!r.row) console.error(`[${payload.jobId}] done`);
+ return r.ok ? 0 : r.edgeOnly ? WAIT_STARTED_EDGE_ONLY_EXIT : 1;
+ }
if (!parsed.wait) {
printPreviewUrls(payload);
return 0;
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -13,6 +13,7 @@ import {
TTS_RESULT_MARKER,
VOICE_RESULT_MARKER,
X_RUN_RESULT_MARKER,
+ attentionLine,
editorEnvFiles,
followJob,
loadEditorEnv,
@@ -21,8 +22,12 @@ import {
parseArgs,
parseDotenv,
previewUrlsIn,
+ startedVerdict,
+ startedBytes,
+ WAIT_STARTED_EDGE_ONLY_EXIT,
tokenHint,
usage,
+ waitStarted,
} from "./archilyzer-ops.mjs";
test("no arguments prints usage", () => {
@@ -1192,3 +1197,130 @@ test("watch-trending posts its body; its help says a watch runs only on a fresh
assert.match(usage(), /none while a trending read or capture of ANY\n\s+library waits its turn/);
assert.match(usage(), /pause it until the operator switches it on again/);
});
+
+// --- live recordings (lane live-recording-guard) --------------------------------
+
+test("get live-recordings reads the listing, narrowed by <slug>[/<id>], --all for every run", () => {
+ assert.equal(parseArgs(["get", "live-recordings"]).path, "/api/ops/live-recordings");
+ assert.equal(parseArgs(["get", "live-recordings", "demo-yt"]).path, "/api/ops/live-recordings?slug=demo-yt");
+ assert.equal(
+ parseArgs(["get", "live-recordings", "demo-yt/exampleid01", "--all"]).path,
+ "/api/ops/live-recordings?slug=demo-yt&id=exampleid01&all=1",
+ );
+ assert.match(parseArgs(["get", "channel", "x", "--all"]).error, /does not take --all/);
+ const ack = parseArgs(["live-recording-ack", "--json", '{"slug":"demo-yt","id":"exampleid01"}']);
+ assert.equal(ack.path, "/api/ops/live-recording-ack");
+ assert.match(usage(), /\nlive-recording-ack /);
+ assert.match(usage(), /\nget live-recordings /);
+});
+
+test("--wait-started goes with record-live only", () => {
+ const p = parseArgs(["record-live", "--json", '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=exampleid01"}', "--wait-started"]);
+ assert.equal(p.waitStarted, true);
+ assert.equal(p.wait, false);
+ assert.match(parseArgs(["sync", "--wait-started"]).error, /goes with record-live/);
+ assert.match(parseArgs(["get", "live-recordings", "--wait-started"]).error, /goes with record-live/);
+});
+
+test("the attention header becomes one stderr line, only when something needs a person", () => {
+ assert.equal(attentionLine(null), null);
+ assert.equal(attentionLine("live-recordings=0"), null);
+ assert.equal(attentionLine("live-recordings=1"), "! 1 live recording needs you: pnpm ops get live-recordings");
+ assert.equal(attentionLine("live-recordings=3"), "! 3 live recordings need you: pnpm ops get live-recordings");
+ assert.equal(attentionLine("live-recordings=0, stalled=1"), "! 1 live recording is NOT growing (stalled): pnpm ops get live-recordings");
+ assert.equal(
+ attentionLine("live-recordings=2, stalled=3"),
+ "! 2 live recordings need you; 3 live recordings are NOT growing (stalled): pnpm ops get live-recordings",
+ );
+});
+
+test("startedVerdict: growing bytes or a landing is started; failed, cancelled, interrupted are not", () => {
+ assert.equal(startedVerdict(null, null), null);
+ assert.equal(startedVerdict({ status: "recording", bytes: 0 }, null), null);
+ assert.equal(startedVerdict({ status: "recording", bytes: 500 }, null), null, "one sight of bytes is not growth yet");
+ assert.deepEqual(startedVerdict({ status: "recording", bytes: 900 }, 500), { ok: true });
+ assert.deepEqual(startedVerdict({ status: "landed", bytes: 900 }, null), { ok: true });
+ assert.deepEqual(startedVerdict({ status: "failed", reason: "failed: nothing was recorded" }, null), { ok: false, reason: "failed: nothing was recorded" });
+ assert.equal(startedVerdict({ status: "interrupted", reason: "interrupted" }, 5).ok, false);
+});
+
+test("startedVerdict: only a FROM-START part's growth is started; a live-edge fallback is edge-only (the start is lost)", () => {
+ const edge = {
+ status: "recording",
+ fromStart: true,
+ fallback: "live-edge",
+ bytes: 9000,
+ reason: "recording from the live edge: the first 2 h 0 min of the stream are NOT recorded",
+ parts: [
+ { fromStart: true, bytes: 0 },
+ { fromStart: false, bytes: 9000 },
+ ],
+ };
+ assert.equal(startedBytes(edge), 0);
+ const v = startedVerdict(edge, 0);
+ assert.equal(v.ok, false);
+ assert.equal(v.edgeOnly, true);
+ assert.match(v.reason, /start is LOST/);
+ assert.equal(startedVerdict({ ...edge, status: "landed" }, null).edgeOnly, true, "a landing from the live edge is not a success either");
+ const fs = { status: "recording", fromStart: true, bytes: 900, parts: [{ fromStart: true, bytes: 900 }] };
+ assert.deepEqual(startedVerdict(fs, 400), { ok: true });
+ assert.equal(startedVerdict(fs, 900), null, "not grown");
+ // Asked from now: any part's growth is the start it asked for.
+ assert.deepEqual(startedVerdict({ status: "recording", fromStart: false, bytes: 900, parts: [{ fromStart: false, bytes: 900 }] }, 100), { ok: true });
+});
+
+test("record-live --wait-started on a live-edge fallback: not ok, edgeOnly (exit 3), with the reason", async () => {
+ const edgeRow = { jobId: "job-1", status: "recording", fromStart: true, fallback: "live-edge", bytes: 5000, reason: "recording from the live edge", parts: [{ fromStart: false, bytes: 5000 }] };
+ const ed = fakeLiveEditor([[{ jobId: "job-1", status: "recording", fromStart: true, bytes: 0, reason: "recording", parts: [] }], [edgeRow]]);
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch });
+ assert.equal(r.ok, false);
+ assert.equal(r.edgeOnly, true);
+ assert.equal(WAIT_STARTED_EDGE_ONLY_EXIT, 3);
+});
+
+// A fake editor: the listing answers the rows given per poll, in turn.
+function fakeLiveEditor(listings, job = { status: "running" }) {
+ let n = 0;
+ const asked = [];
+ const fetch = async (url) => {
+ asked.push(url);
+ if (url.includes("/api/ops/job/")) return { json: async () => ({ ok: true, job }) };
+ const rows = listings[Math.min(n++, listings.length - 1)];
+ return { json: async () => ({ ok: true, rows }) };
+ };
+ return { fetch, asked };
+}
+const reply = { ok: true, jobId: "job-1", kind: "record-live", check: "pnpm ops get live-recordings demo-yt/exampleid01" };
+const quiet = { sleep: async () => {}, say: () => {}, baseUrl: "http://editor.test", headers: {} };
+
+test("record-live --wait-started returns once the run's bytes grow", async () => {
+ const ed = fakeLiveEditor([
+ [],
+ [{ jobId: "job-1", status: "recording", bytes: 0, reason: "recording" }],
+ [{ jobId: "job-1", status: "recording", bytes: 4096, reason: "recording" }],
+ [{ jobId: "job-1", status: "recording", bytes: 9000, reason: "recording" }],
+ ]);
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch });
+ assert.equal(r.ok, true);
+ assert.equal(r.row.bytes, 4096, "grown from the 0 the poll before saw");
+ assert.ok(ed.asked.some((u) => u.endsWith("/api/ops/live-recordings?slug=demo-yt&id=exampleid01&all=1")));
+});
+
+test("record-live --wait-started fails with the recording's own reason", async () => {
+ const ed = fakeLiveEditor([[{ jobId: "job-0", status: "landed" }, { jobId: "job-1", status: "failed", reason: "failed: nothing was recorded — 6 attempts" }]]);
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch });
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /6 attempts/);
+});
+
+test("record-live --wait-started: a job that ends with no row fails with its status; the bound is kept", async () => {
+ const gone = fakeLiveEditor([[]], { status: "failed" });
+ const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: gone.fetch });
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /ended failed before it recorded anything/);
+ let clock = 0;
+ const stuck = fakeLiveEditor([[{ jobId: "job-1", status: "recording", bytes: 0, reason: "recording" }]]);
+ const t = await waitStarted(reply, "demo-yt", { ...quiet, fetch: stuck.fetch, now: () => clock, sleep: async (ms) => void (clock += ms), timeoutSeconds: 60 });
+ assert.equal(t.ok, false);
+ assert.match(t.reason, /no media bytes after 60 s/);
+});
diff --git a/settings.json.example b/settings.json.example
@@ -16,6 +16,9 @@
"scan": true,
"mine": true
},
+ "liveRecording": {
+ "stallMinutes": 10
+ },
"pacing": {
"sleepRequestsCapSeconds": 16,
"decayAfterCleanUnits": 5,