// 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//live-recordings.json, // lib/liveRecordings-server.ts), cross-checked: // // status the record's own (data//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 & { 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[]; }; export function liveRecordingCheckCommand(slug: string, id: string): string { return `pnpm ops get live-recordings ${slug}/${id}`; } // settings.liveRecording.stallMinutes (record-live's watchdog reads it too). // settings.liveRecording.insuranceWhenBehind (default true). export function liveInsuranceWhenBehind(): boolean { try { return getSettings().liveRecording?.insuranceWhenBehind !== false; } catch { return true; } } export function liveStallMinutes(): 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 { 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"]); // A boot restart still `starting` after this long never went on. export const LIVE_BOOT_STARTING_STALE_MS = 10 * 60_000; function reasonOf(v: Omit, 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 rs = v.startRecovery; if (rs) { const words: Record = { waiting: `start recovery: ${rs.tries} of ${rs.max} tries made, the next within ${spanWords(rs.everyMs / 1000)}`, trying: `start recovery: try ${rs.tries} of ${rs.max} records now`, recorded: `start recovery: try ${rs.tries} recorded from its start (not proven whole)`, recovered: "start recovered: a from-start try holds the whole stream", "gave-up": `start recovery gave up after ${rs.tries} tries${rs.failureClass ? ` [${rs.failureClass}]` : ""}`, exhausted: `start recovery: all ${rs.max} tries failed`, stopped: `start recovery stopped after ${rs.tries} tries (the live edge ended first)`, }; extra.unshift(words[rs.state] ?? `start recovery: ${rs.state}`); } if (v.insurance) { const ins = v.insurance; const w: Record = { waiting: "the insurance recorder waits for the from-start recording to begin", recording: `the insurance recorder records the live edge beside it${ins.mode === "whole" ? " (the whole stream)" : " until it catches up"}`, "caught-up": "the insurance recorder stopped: the from-start recording caught up", ended: "the insurance recorder recorded the live edge to the end", stalled: "the insurance recorder stalled and was stopped", died: `the insurance recorder DIED before the start caught up${ins.reason ? ` (${ins.reason})` : ""}`, stopped: `the insurance recorder was stopped${ins.reason ? ` (${ins.reason})` : ""}`, failed: `the insurance recorder recorded nothing${ins.reason ? ` (${ins.reason})` : ""}`, "not-started": `no insurance recorder${ins.reason ? ` (${ins.reason})` : ""}`, }; extra.push(w[ins.state] ?? `insurance: ${ins.state}`); } if (v.joins && v.joins.length) { const gaps = v.joins.filter((j) => j.kind === "gap"); extra.push( `landed as ${v.joins.length + 1} parts joined` + (gaps.length ? ` — ${gaps.length} GAP${gaps.length === 1 ? "" : "S"} of about ${gaps.map((g) => spanWords(g.seconds)).join(", ")} (by the clock) NOT recorded` : ", each join checked by its sound"), ); } if (v.endedBy?.class === "private") { const held = (v.parts ?? []).reduce((n, p) => Math.max(n, p.seconds ?? 0), 0); extra.unshift(`the stream went private or was removed while recording (${v.endedBy.message})${held ? `; ${spanWords(held)} are held` : "; what was recorded is held"}`); } if (v.awaitingResume && v.awaitingResume.length) { extra.push( `${v.awaitingResume.length} part(s) wait in staging, with their state, to be resumed` + (v.status === "interrupted" ? "" : " — not resumed by this run: a person decides"), ); } if (v.status === "landed" && v.coverage?.basis === "duration" && v.coverage.covers === false && v.coverage.capturedSeconds !== null && v.coverage.streamSeconds !== null) { extra.unshift( `landed ${spanWords(v.coverage.capturedSeconds)} of the ended stream's ${spanWords(v.coverage.streamSeconds)}: the rest is in no file — download the VOD now`, ); } if (v.landedWhileLive) { const u = v.landedWhileLive.unrecordedSeconds; extra.unshift( `LANDED WHILE THE STREAM WAS STILL LIVE (${v.landedWhileLive.why})${u !== null ? `: about ${spanWords(u)} of it, by the clock, were in no landed file at that moment` : ""} — what is landed is the stream SO FAR, not the whole`, ); } if (v.offline) extra.unshift(`the stream's state cannot be read since ${v.offline.since} (the network?): NOTHING is recording; read again every few minutes (${v.offline.reads} so far), and resumed in place once it reads`); for (const p of v.parts ?? []) { if (p.resumeDamaged) extra.unshift(`${p.stem ?? "a part"}: after a resume it is NOT its kept fragments (${p.resumeDamaged}) — kept as it is, never removed`); if (p.behindUnknown) extra.push(`${p.stem ?? "a part"}: how far behind the live edge it was could not be told (${p.behindUnknown}): no live-edge insurance by the behind rule`); if (p.failureClass === "went-private") extra.push(`${p.stem ?? "a part"}: its fragment requests were answered 403 Forbidden and the stream reads private or removed — it went private while it was recorded; what is on disk is landed and nothing is removed`); if (p.failureClass === "url-refresh") extra.push(`${p.stem ?? "a part"}: yt-dlp could not refresh the stream's URL (the platform stopped serving the format — DVR switched off?) and ended by itself`); if (p.reused) extra.push(`${p.stem ?? "a part"} was resumed after it had ended, reusing ${p.reused.fragments} fragments already downloaded (only what came since was fetched)`); } if (v.skippedFragments?.count) { extra.unshift(`the landed file is missing ${v.skippedFragments.count} fragment(s) yt-dlp could not fetch${v.skippedFragments.positions.length ? ` (positions ${v.skippedFragments.positions.slice(0, 10).join(", ")}${v.skippedFragments.positions.length > 10 ? ", …" : ""})` : ""}: a HOLE`); } for (const p of v.parts ?? []) { if (p.fragmentsDropped) extra.push(`${p.stem ?? "a part"} lost its kept fragments (${p.fragmentsDropped}): it could not be resumed in place`); } if (v.verification?.state === "failed") extra.unshift(`the landed file is NOT verified whole (${v.verification.why ?? "?"}): the stream files it was made from are kept`); else if (v.verification?.state === "pending") extra.push("the landed file is not yet verified against its stream files"); if (v.transcriptRedo) { const t = v.transcriptRedo; extra.push( t.verdict === "shorter" ? `the transcript was the replaced shorter file's (${t.why}): ${t.jobId ? `transcription asked again (job ${t.jobId})` : `transcription NOT asked again${t.error ? ` (${t.error})` : ""} — a person decides`}` : `the transcript may be the replaced shorter file's — not known (${t.why}): a person decides whether to transcribe again`, ); } if (v.spaceHeld && v.spaceHeld.length) extra.push(`NOT started for want of disk: ${v.spaceHeld.map((x) => x.what).join(", ")}`); if (v.restarts && v.restarts.count > 0) extra.push(`its recorder was restarted ${v.restarts.count} time${v.restarts.count === 1 ? "" : "s"} (stalled or died while live)`); if (v.restarts?.refused) extra.push(`NOT restarted again though the stream was live: ${v.restarts.refused}`); if (v.restarts?.waiting) extra.push(`NOT recording until ${v.restarts.waiting.until}: the restart bound (${v.restarts.waiting.why}) is waited out, then it goes on`); else if (v.restarts?.waited) extra.push(`waited out the restart bound ${v.restarts.waited} time${v.restarts.waited === 1 ? "" : "s"} (nothing recorded while it waited)`); if (v.lost && !v.fallback && v.startRecovery?.state !== "recovered") { const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`; extra.unshift( v.lost.toSeconds !== null ? `hours ${hm(v.lost.fromSeconds)}-${hm(v.lost.toSeconds)} are in no part yet (${spanWords(v.lost.toSeconds - v.lost.fromSeconds)})` : "what lies before the live edge may be in no part (the stream's start time is not known)", ); } 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": { const r = v.restart; const boot = r ? { // REVIEW-5 note 12: `starting` past 10 min is an editor that died // mid-pass — the restart never went on: a person. starting: Date.now() - Date.parse(r.at) > LIVE_BOOT_STARTING_STALE_MS ? `the automatic restart began at ${r.at} and never got going (the editor stopped mid-pass?) — it needs a person: Record again if the stream is still live` : "being restarted automatically", asked: `restarted automatically as job ${r.jobId ?? "?"}: it reads the stream's state first`, restarted: `restarted automatically (job ${r.jobId ?? "?"}): the stream was still live`, landing: `${r.reason ?? "the stream had ended by the restart"}: what this run left is being landed (job ${r.jobId ?? "?"})`, landed: `${r.reason ?? "the stream had ended by the restart"}: what this run left was landed (job ${r.jobId ?? "?"})`, ended: "the stream had ended by the restart, and nothing was left to land — the end of the stream is NOT recorded", unknown: `NOT restarted: the stream's state could not be read${r.reason ? ` (${r.reason})` : ""} — Record again if it is still live`, refused: `NOT restarted automatically: ${r.reason ?? "refused"} — Record again if the stream is still live`, failed: `the automatic restart failed: ${r.reason ?? "no job"} — Record again if the stream is still live`, }[r.state] : null; const head = v.stoppedBy === "shutdown" ? "interrupted: the editor shut down while it recorded" : v.stoppedBy === "crash" ? "interrupted: the editor stopped (a crash?) while it recorded" : "interrupted: its record says recording, and no record-live job runs it (an editor restart?)"; return `${head} — ${boot ?? "Record again if the stream is still live"}${tail}`; } case "cancelled": return `cancelled${v.mustKeep ? " (a must-keep stream: is that what you wanted?)" : ""}${tail}`; case "landed": return ( (v.fallback === "live-edge" && rs?.state !== "recovered" ? `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): 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 { const now = (opts.now ?? new Date()).getTime(); const stallMinutes = opts.stallMinutes ?? liveStallMinutes(); 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//) 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 = { ...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 } : {}), ...(own?.startRecovery ? { startRecovery: own.startRecovery } : {}), ...(own?.restarts ? { restarts: own.restarts } : {}), ...(own?.insurance ? { insurance: own.insurance } : {}), ...(own?.joins ? { joins: own.joins } : {}), ...(own?.spaceHeld ? { spaceHeld: own.spaceHeld } : {}), ...(own?.endedBy ? { endedBy: own.endedBy } : {}), ...(own?.awaitingResume ? { awaitingResume: own.awaitingResume } : {}), ...(own?.transcriptRedo ? { transcriptRedo: own.transcriptRedo } : {}), ...(own?.verification ? { verification: own.verification } : {}), ...(own?.skippedFragments ? { skippedFragments: own.skippedFragments } : {}), ...(own?.landedWhileLive ? { landedWhileLive: own.landedWhileLive } : {}), ...(own?.offline ? { offline: own.offline } : {}), 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, startRecovery: own?.startRecovery ?? row.startRecovery, restarts: own?.restarts ?? row.restarts, joins: own?.joins ?? row.joins, lost: own?.lost ?? row.lost, endedBy: own?.endedBy ?? row.endedBy, spaceHeld: own?.spaceHeld ?? row.spaceHeld, awaitingResume: own?.awaitingResume ?? row.awaitingResume, transcriptRedo: own?.transcriptRedo ?? row.transcriptRedo, verification: own?.verification ?? row.verification, skippedFragments: own?.skippedFragments ?? row.skippedFragments, parts: own?.parts ?? row.parts, landedWhileLive: own?.landedWhileLive ?? row.landedWhileLive, coverage: own?.coverage ?? row.coverage, offline: own?.offline ?? row.offline, }), }; 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) }); } } // AN INTERRUPTION THE BOOT PASS RESTARTED (REVIEW-1 1.3 of live-guard-2) is // quiet only while the NEW run (its row's resumeOf) records and its part // grows; a new run that failed, ended short or never began leaves it loud, // and says so. A new run that holds the whole stream supersedes it anyway. for (const v of out) { if (v.status !== "interrupted" || v.restart?.state !== "restarted" || v.acknowledgedAt || v.supersededBy) continue; const nv = out.find((x) => x.slug === v.slug && x.id === v.id && x.resumeOf === v.startedAt); const growing = nv && nv.status === "recording" && !nv.stalled && (nv.bytes ?? 0) > 0; if (growing && !(v.keptParts && v.keptParts.length)) { v.needsAttention = false; v.reason = `${v.reason} — the new run records (${Math.round((nv.bytes ?? 0) / 1024 / 1024)} MB, growing)`; } else if (!nv) { v.reason = `${v.reason} — but no new run has recorded anything yet`; } else if (nv.status === "recording" || nv.status === "interrupted") { v.reason = `${v.reason} — but the new run is ${nv.stalled ? "NOT growing" : nv.status === "interrupted" ? "interrupted too" : "not recording yet"}`; } else { v.reason = `${v.reason} — but the new run ${nv.status === "failed" ? `failed: ${nv.error ?? "no reason recorded"}` : `ended ${nv.status}${nv.coverage && !nv.coverage.covers ? " without the whole stream" : ""}`}`; } } 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 { 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 }; }