import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { platformCooldownRemainingMs } from "../jobs/downloadBackoff"; import { cleanAudioFromTranscribed, type CleanAudioResult, type UncheckedReason, } from "./cleanAudioFromTranscribed"; import { readChannelConfig } from "./channels"; import type { VerifyProbes } from "./verifyBeforeClean"; // THE CLEAN-AUDIO JOB'S BODY (lane clean-unverified): what the channel sweep // does inside its job, and how that job ENDS. // // A CHECKED CLEAN THE SOURCE RATE-LIMITED (operator ruling, 21 Nov 2026). The // gate fails closed — nothing it could not verify is deleted — and the job // used to end a plain `done` that did nothing (a Rumble listing answered 429: // 0 of 350 cleaned, `done`). Now: // - rate-limited, retries left: the job ends DEFERRED (JobRecord.deferred, // the job system's own state, drawn "deferred" on /jobs) with the counts, // and ONE retry is scheduled (off-queue, below), not before // max(now + CLEAN_RETRY_PAUSE_MS, the platform's recorded cooldown end); // - the third rate limit in a row (the request and its 2 retries): FAILED, // "Gave up: rate-limited …" — a person decides; // - any other failure to verify (a network error, an extractor break): // FAILED, "Could not verify availability …", no retry (only a rate limit // is retried — nothing else here suggests waiting helps). // The retry's wait is OFF-QUEUE (review 1 F4–F6): a durable record and a // timer (controller/cleanRetrySchedule.ts) that queues the retry job only at // its not-before time, so it holds no queue and no job slot meanwhile. // Cancelling the deferred job cancels the retry. A person's Retry of any of // these jobs starts a fresh chain. // // An UNCHECKED clean asks nothing, so none of this applies to it. // The pause before a rate-limited clean is retried. The repo's per-platform // cooldown (jobs/platformBackoff.ts) starts at 1 minute and doubles — a floor // for downloads, too short to be a pause for a cleanup nobody is waiting on — // so the retry waits whichever is later: this, or that cooldown's end. export const CLEAN_RETRY_PAUSE_MS = 15 * 60_000; // Automatic retries per original request; the next rate limit gives up. export const CLEAN_RATE_LIMIT_MAX_RETRIES = 2; // A retry of a rate-limited clean, carried in its record and its job's spec // params. `of` is the ORIGINAL request's job id (the chain's), `attempt` // 1-based, `platform` the key the rate limit was recorded under (its cooldown), // `id` the schedule record's (cleanRetrySchedule.ts) once it has one. export type CleanRetry = { attempt: number; of: string; notBefore: number; platform: string; id?: string }; export type CleanJobOutcome = | { end: "done"; result: CleanAudioResult } | { end: "deferred"; until: number; sentence: string; retryId: string; result: CleanAudioResult } | { end: "failed"; sentence: string; result?: CleanAudioResult } | { end: "cancelled" }; export type CleanJobDeps = { // Schedule the retry OFF-QUEUE (the action: cleanRetrySchedule's record and // timer, which queue a clean-audio-retry job at `notBefore`). scheduleRetry: (retry: CleanRetry) => Promise<{ ok: true; id: string } | { ok: false; error: string }>; now?: () => number; cooldownRemainingMs?: (platform: string) => Promise; probes?: VerifyProbes; // Test seam for the sweep's guard immediately before it removes anything. assertReachable?: (paths: Paths, slug: string) => Promise; }; // THE SENTENCE OF A CONFIRMED UNCHECKED JOB WHOSE PLAN IS GONE (ruling 5): a // "Clean without checking" removes at most what a person confirmed, so a job // that has no plan to carry (a spec from before plans, or one a restart // re-queued without it) removes nothing and asks for the confirmation again. export const PLAN_LOST_SENTENCE = "Confirmed plan lost; confirm again: this clean without checking carries no list of what a person confirmed, so it removed nothing. Run Clean without checking again and confirm its count."; // The channel key's verdict for a sweep the operator did not explicitly ask to // run unchecked: "channel-setting" when `cleanAudioWithoutChecking` is on. export function uncheckedReasonFor(config: ChannelConfig | null | undefined): UncheckedReason | undefined { return config?.cleanAudioWithoutChecking === true ? "channel-setting" : undefined; } // WHAT A CLEAN REQUEST QUEUES — the job kind (so the job list's title is // truthful) and what its spec carries. The one rule the action, the ops twin // and replay share: // - "button" (a person confirmed a counted plan, or `cleanup {"unchecked": // true}` computed one at the call): unchecked, the plan carried; // - the channel's key on: unchecked by "channel-setting", with the plan when // a person confirmed one, else discovered at start; the key is re-read // when the job starts (runCleanAudioJob); // - otherwise the checked clean (bounded by a plan when one was confirmed). // - `sourceGone` (the opt-in "also remove audio kept only because the source // was gone", lane mark-provenance) rides ONLY on an explicit "button" // request: never implied by the channel key, never on a checked clean. export type CleanAudioRequest = { kind: "clean-audio-transcribed" | "clean-audio-unchecked"; unchecked?: UncheckedReason; plan?: string[]; sourceGone?: string[]; }; export function cleanAudioRequestFor( config: ChannelConfig | null | undefined, opts: { explicit?: "button"; plan?: readonly string[]; sourceGone?: readonly string[] } = {}, ): CleanAudioRequest { const plan = opts.plan ? [...opts.plan] : undefined; const reason: UncheckedReason | undefined = opts.explicit ?? uncheckedReasonFor(config); if (reason) { const sourceGone = opts.explicit === "button" && opts.sourceGone ? [...opts.sourceGone] : undefined; return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}), ...(sourceGone ? { sourceGone } : {}) }; } return { kind: "clean-audio-transcribed", ...(plan ? { plan } : {}) }; } // A spec's carried plan, or undefined for anything that is not a list of ids. export function planFromParams(p: Record | undefined): string[] | undefined { const v = p?.plan; return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; } // A spec's carried source-gone ids (the opt-in), or undefined. Read only by the // job that carries them — no replay passes them on (below). export function sourceGoneFromParams(p: Record | undefined): string[] | undefined { const v = p?.sourceGone; return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; } // HOW A CLEAN JOB IS REPLAYED — by every replay path alike: a /jobs Retry, // Retry all failed, `pnpm ops job retry`, and the boot's re-queue of a job a // restart caught queued (all four go through the editor's runJobSpec). Operator // ruling (review 2): the channel key is the operator's standing consent for // that channel, so on a KEY-ON channel a replay may run unchecked WITHOUT a // new count, like any key-driven job (the key read at start, "without // checking (channel setting)" in its title and first line, no prune). But a // replay never becomes a person-confirmed unchecked run without its plan, and // on a KEY-OFF channel no replay runs unchecked at all: // - clean-audio-transcribed, clean-audio-retry (a FRESH chain: a scheduled // retry is re-armed from its own record, never replayed) and a // "channel-setting" clean-audio-unchecked → Clean audio again, the key as // it is now decides (a carried plan, if any, still bounds it); // - a "button" clean-audio-unchecked (a person confirmed a count) → on a // key-on channel, unchecked again WITH ITS CARRIED PLAN only; with no plan // it replays into a job that removes nothing and ends failed, "Confirmed // plan lost; confirm again". On a key-OFF channel it is REFUSED: it would // be an unchecked run nobody asked for now; // - anything else is refused. // THE OPT-IN IS NEVER REPLAYED (lane mark-provenance): a replay carries the // plan only, so audio kept because the source was gone is removed only by the // run a person confirmed it for. export type CleanReplay = | { ok: true; call: "clean" | "unchecked"; plan?: string[] } | { ok: false; error: string; info?: boolean }; export const REPLAY_UNCHECKED_KEY_OFF = "This was a clean without checking, and this channel cleans checked now: a Retry does not run it unchecked. Run Clean without checking again and confirm its count, or Clean audio."; export function cleanReplayFor( kind: string, params: Record | undefined, keyOn: boolean, ): CleanReplay { const plan = planFromParams(params); if (kind === "clean-audio-transcribed") return { ok: true, call: "clean", ...(plan ? { plan } : {}) }; if (kind === "clean-audio-retry") return { ok: true, call: "clean" }; if (kind === "clean-audio-unchecked") { if (params?.unchecked === "button") { if (!keyOn) return { ok: false, info: true, error: REPLAY_UNCHECKED_KEY_OFF }; return { ok: true, call: "unchecked", ...(plan ? { plan } : {}) }; } if (params?.unchecked === "channel-setting") return { ok: true, call: "clean", ...(plan ? { plan } : {}) }; return { ok: false, error: "This clean without checking carries no unchecked flag to replay it with — run Clean audio or Clean without checking instead.", }; } return { ok: false, error: `not a clean-audio kind: ${kind}` }; } // The replay itself, over the actions it calls (the editor's cleanAudioAction // and cleanAudioUncheckedAction): the channel's key is read NOW. export async function replayCleanSpec( spec: { kind: string; slug: string; params?: Record }, deps: { readConfig: (slug: string) => Promise; clean: (slug: string, queueKey: string | undefined, plan?: string[]) => Promise; unchecked: (slug: string, queueKey: string | undefined, plan?: string[]) => Promise; }, ): Promise { const p = spec.params ?? {}; const queueKey = typeof p.queueKey === "string" ? p.queueKey : undefined; const keyOn = uncheckedReasonFor(await deps.readConfig(spec.slug).catch(() => null)) !== undefined; const r = cleanReplayFor(spec.kind, p, keyOn); if (!r.ok) return r; return r.call === "unchecked" ? deps.unchecked(spec.slug, queueKey, r.plan) : deps.clean(spec.slug, queueKey, r.plan); } // What the plan counted, as the job's log states it before anything is removed // (and `pnpm ops cleanup {"unchecked": true}` answers it). export type CleanPlanCountsLog = { files: number; bytes: number; videos: number; protected: number; awaitingDiarization: number; awaitingVoiceprint: number; // The opt-in's group as counted, when it was confirmed. sourceGone?: { videos: number; files: number; bytes: number; inferred: { videos: number; files: number; bytes: number } }; }; export function planCountsLine(c: CleanPlanCountsLog): string { const g = c.sourceGone; return ( `Plan counted when this clean was asked for: ${c.files} audio file(s) (${c.bytes} bytes) from ${c.videos} video(s); ` + `kept: ${g ? c.protected - g.videos : c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + `${c.awaitingVoiceprint} awaiting voice fingerprint.` + (g ? ` Also, kept only because the source was gone: ${g.files} audio file(s) (${g.bytes} bytes) from ${g.videos} video(s)` + ` (${g.inferred.videos} of them with marks inferred from the records: ${g.inferred.files} file(s), ${g.inferred.bytes} bytes).` : "") ); } function clock(ms: number): string { return new Date(ms).toISOString().slice(11, 16) + " UTC"; } export async function runCleanAudioJob({ channelSlug, paths, jobId, unchecked, plan, planCounts, sourceGone, retry, onLog, signal, deps, }: { channelSlug: string; paths: Paths; jobId: string; // Why the job was queued unchecked. "button": a person confirmed a counted // plan (`plan` required). "channel-setting": the channel's key — RE-READ // HERE, when the job starts (ruling 3). unchecked?: UncheckedReason; // The confirmed plan's video ids: the run removes at most these. plan?: readonly string[]; // The plan's counts, logged before anything is removed (an ops call). planCounts?: CleanPlanCountsLog; // The opt-in's confirmed ids: honoured only while the job runs as "button". sourceGone?: readonly string[]; retry?: CleanRetry; onLog: (m: string) => void; signal?: AbortSignal; deps: CleanJobDeps; }): Promise { const now = deps.now ?? (() => Date.now()); const cooldown = deps.cooldownRemainingMs ?? ((pf: string) => platformCooldownRemainingMs(pf, paths)); const config = await readChannelConfig(paths, channelSlug); // --- Unchecked, decided NOW -------------------------------------------------- let mode: UncheckedReason | undefined = unchecked; if (mode === "button" && !plan) { return { end: "failed", sentence: PLAN_LOST_SENTENCE }; } if (mode === "channel-setting" && !uncheckedReasonFor(config)) { onLog( "This channel's cleanAudioWithoutChecking was turned off after this clean was queued: it runs CHECKED (the source is asked, as Clean audio does).", ); mode = undefined; } // A retry is the continuation of a CHECKED request: it stays checked even if // the channel's key was turned on since (nobody confirmed an unchecked run). if (retry) mode = undefined; // --- A retry never runs before its time -------------------------------------- // The schedule queues it only at its not-before; a spec replayed by hand // earlier than that asks nothing. if (retry && now() < retry.notBefore) { return { end: "failed", sentence: `This retry was started before its time (not before ${clock(retry.notBefore)}): nothing was asked or cleaned.`, }; } if (plan && planCounts) onLog(planCountsLine(planCounts)); if (retry) { onLog(`Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} of rate-limited clean ${retry.of}.`); } const result = await cleanAudioFromTranscribed({ channelSlug, paths, onLog, signal, ...(mode ? { unchecked: mode } : {}), ...(plan ? { onlyIds: plan } : {}), ...(sourceGone ? { sourceGone } : {}), jobId, ...(deps.probes ? { probes: deps.probes } : {}), ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}), }); if (signal?.aborted) return { end: "cancelled" }; // The chain makes progress each attempt, and says how much. if (retry && result.verdictsAtStart !== undefined) { onLog( `Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES}: started with ${result.verdictsAtStart} verdict(s) earlier attempts and stored listings had earned, ` + `added ${result.verdictsAdded ?? 0}; ${result.unverified} unverified remain.`, ); } const stop = result.stopped; if (!stop) return { end: "done", result }; // A partial listing (verifyBeforeClean): what it verified is cleaned, and // the sentence says how much of the listing that came from. const partial = result.partial ? `verified ${result.partial.verified} from a partial listing of ${result.partial.entries} entries; ${result.partial.unverified} unverified remain; ` : ""; const counts = `${partial}${result.cleanedDirs} cleaned, ${result.unverified} left unverified`; if (stop.kind === "error") { return { end: "failed", sentence: `Could not verify availability (${stop.message}): ${counts}. Nothing unverified was deleted, and no retry is queued ` + `(only a rate limit is retried) — run Clean audio again once the source answers.`, result, }; } const attempt = retry?.attempt ?? 0; if (attempt >= CLEAN_RATE_LIMIT_MAX_RETRIES) { return { end: "failed", sentence: `Gave up: rate-limited by ${stop.platform} ${attempt + 1} times in a row (this request and ${CLEAN_RATE_LIMIT_MAX_RETRIES} automatic retries; ` + `${counts}). Nothing unverified was deleted. It needs a person: run Clean audio again later, or Clean without checking.`, result, }; } const t = now(); const notBefore = Math.max(t + CLEAN_RETRY_PAUSE_MS, t + (await cooldown(stop.platform).catch(() => 0))); const next: CleanRetry = { attempt: attempt + 1, of: retry?.of ?? jobId, notBefore, platform: stop.platform }; const scheduled = await deps.scheduleRetry(next); if (!scheduled.ok) { return { end: "failed", sentence: `Rate-limited by ${stop.platform} (${counts}); the retry could not be scheduled: ${scheduled.error}`, result, }; } return { end: "deferred", until: notBefore, retryId: scheduled.id, sentence: `Rate-limited by ${stop.platform} (${stop.message}): ${counts}; nothing unverified was deleted. ` + `Retry ${next.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} is scheduled, not before ${clock(notBefore)}; it waits off the queue. ` + `Cancel this job to cancel it (or Cancel retry on the channel's Cleanup stage).`, result, }; }