import { test } from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { JobSpec } from "../jobs/jobSpec"; import type { VerifyProbes } from "./verifyBeforeClean"; import { PLAN_LOST_SENTENCE, REPLAY_UNCHECKED_KEY_OFF, cleanAudioRequestFor, replayCleanSpec, runCleanAudioJob, type CleanJobOutcome, } from "./cleanAudioJob"; import { readChannelConfig } from "./channels"; import { jobSpecDetail } from "../jobs/jobDetail"; import { settleQueuedJobMetas } from "../jobs/bootQueuedJobs"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanReplay.test.ts // // REPLAYING A CLEAN (lane clean-unverified, review 2 ruling): the four replay // paths — a /jobs Retry, Retry all failed, `pnpm ops job retry`, and the boot's // re-queue — all reach replayCleanSpec (the editor's runJobSpec → // JOB_REPLAY_HANDLERS → replayClean; the boot's requeue is runJobSpec too). // Each path is driven here as its caller drives it, over the same composition // the editor's actions make: cleanAudioRequestFor on the config read at the // call, then the job body. On a KEY-ON channel a replay may run unchecked with // no count ("channel setting", no prune); a confirmed run needs its plan; on a // KEY-OFF channel nothing replays unchecked. const ROOT = await mkdtemp(path.join(tmpdir(), "clean-replay-")); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); const T0 = Date.parse("2026-11-21T03:00:00.000Z"); let n = 0; async function corpus(keyOn: boolean) { const dir = path.join(ROOT, `c${n++}`); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, savedVideosDir: path.join(dir, "saved"), jobsDir: path.join(dir, ".jobs"), ytdlpBin: path.join(dir, "no-ytdlp"), } as unknown as Paths; await mkdir(paths.jobsDir, { recursive: true }); await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); await writeFile( path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...(keyOn ? { cleanAudioWithoutChecking: true } : {}) }), ); for (const id of ["a", "b"]) { const v = path.join(paths.channelsDir, "ch", "data", id); await mkdir(v, { recursive: true }); await writeFile(path.join(v, "transcript.json"), "{}"); await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); } return paths; } type Ran = { kind: string; unchecked?: string; detail?: string; out: CleanJobOutcome; logs: string[]; asked: number }; // The editor's actions, composed as whisperActions composes them: the request // from the config read NOW, then the job body (its key read again at start). function actions(paths: Paths) { const ran: Ran[] = []; const run = async (explicit: "button" | undefined, slug: string, plan?: string[]) => { const req = cleanAudioRequestFor(await readChannelConfig(paths, slug), { ...(explicit ? { explicit } : {}), ...(plan ? { plan } : {}) }); const params = { ...(req.unchecked ? { unchecked: req.unchecked } : {}), ...(req.plan ? { plan: req.plan } : {}) }; let asked = 0; const probes: VerifyProbes = { quick: async () => (asked++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }), }; const logs: string[] = []; const out = await runCleanAudioJob({ channelSlug: slug, paths, jobId: `job-${ran.length}`, ...(req.unchecked ? { unchecked: req.unchecked } : {}), ...(req.plan ? { plan: req.plan } : {}), onLog: (m) => logs.push(m), deps: { probes, now: () => T0, cooldownRemainingMs: async () => 0, scheduleRetry: async () => ({ ok: false, error: "none" }) }, }); const r: Ran = { kind: req.kind, ...(req.unchecked ? { unchecked: req.unchecked } : {}), detail: jobSpecDetail(req.kind, { kind: req.kind, slug, params }), out, logs, asked }; ran.push(r); return { ok: true as const, jobId: `job-${ran.length - 1}` }; }; return { ran, deps: { readConfig: (slug: string) => readChannelConfig(paths, slug), clean: (slug: string, _q: string | undefined, plan?: string[]) => run(undefined, slug, plan), unchecked: (slug: string, _q: string | undefined, plan?: string[]) => run("button", slug, plan), }, }; } // The four paths, each as its caller drives replay. type Path = "retry" | "retry-all-failed" | "ops-job-retry" | "boot"; const PATHS: Path[] = ["retry", "retry-all-failed", "ops-job-retry", "boot"]; async function replayBy(via: Path, paths: Paths, spec: JobSpec, deps: ReturnType["deps"]) { if (via === "retry" || via === "ops-job-retry") return replayCleanSpec(spec, deps); if (via === "retry-all-failed") { // Every failed job with a spec, one after another. const out = []; for (const s of [spec]) out.push(await replayCleanSpec(s, deps)); return out[0]; } // The boot: a meta a restart caught queued, re-queued through its spec. const metaId = `M${n++}`; await writeFile( path.join(paths.jobsDir, `${metaId}.meta.json`), JSON.stringify({ id: metaId, kind: spec.kind, queueKey: "channel:ch", status: "queued", queuedAt: Date.now() - 60_000, channelSlug: "ch", spec }), ); let answer: unknown; const res = await settleQueuedJobMetas({ paths, bootedAt: Date.now() + 60_000, log: () => {}, requeue: async (s) => { const r = await replayCleanSpec(s, deps); answer = r; return r as { ok: true; jobId: string } | { ok: false; error: string }; }, }); if (!answer) return { ok: false, error: `not re-queued: ${JSON.stringify(res.cancelled)}` }; return answer; } const has = (paths: Paths, id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); const CHECKED_SPECS: JobSpec[] = [ { kind: "clean-audio-transcribed", slug: "ch", params: {} }, { kind: "clean-audio-retry", slug: "ch", params: { retry: { attempt: 1, of: "j", notBefore: 1, platform: "twitch", id: "j.retry1" } } }, { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "channel-setting" } }, ]; const BUTTON_WITH_PLAN: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a"] } }; const BUTTON_NO_PLAN: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button" } }; for (const via of PATHS) { test(`${via}, key OFF: no replay runs unchecked — the clean kinds run checked, a confirmed unchecked one is refused`, async () => { for (const spec of CHECKED_SPECS) { const paths = await corpus(false); const a = actions(paths); await replayBy(via, paths, spec, a.deps); // At boot a queued retry is not replayed at all: its schedule re-arms it. if (via === "boot" && spec.kind === "clean-audio-retry") { assert.equal(a.ran.length, 0); continue; } assert.equal(a.ran.length, 1, `${spec.kind}: replayed`); const [r] = a.ran; assert.equal(r.kind, "clean-audio-transcribed", `${spec.kind}: checked kind`); assert.equal(r.unchecked, undefined); assert.equal(r.asked, 1, `${spec.kind}: the source was asked`); assert.ok(!r.logs.some((l) => l.includes("without checking")), r.logs.join("\n")); } for (const spec of [BUTTON_WITH_PLAN, BUTTON_NO_PLAN]) { const paths = await corpus(false); const a = actions(paths); const out = (await replayBy(via, paths, spec, a.deps)) as { ok: boolean; error?: string }; assert.equal(a.ran.length, 0, "nothing ran"); assert.equal(out.ok, false); if (via !== "boot") assert.equal(out.error, REPLAY_UNCHECKED_KEY_OFF); assert.equal(await has(paths, "a"), true); assert.equal(await has(paths, "b"), true); } if (via === "boot") { // The boot pass closes a refused re-queue with the refusal. const paths = await corpus(false); const a = actions(paths); await replayBy(via, paths, BUTTON_WITH_PLAN, a.deps); const files = (await readdir(paths.jobsDir)).filter((f) => f.endsWith(".meta.json")); const metas = await Promise.all(files.map((f) => readFile(path.join(paths.jobsDir, f), "utf8"))); assert.ok(metas.some((m) => m.includes("re-queue refused") && m.includes("cleans checked now")), metas.join("\n")); } }); test(`${via}, key ON: a clean replays unchecked with no count ("channel setting", no prune); a confirmed one needs its plan`, async () => { for (const spec of CHECKED_SPECS) { const paths = await corpus(true); const a = actions(paths); await replayBy(via, paths, spec, a.deps); if (via === "boot" && spec.kind === "clean-audio-retry") { assert.equal(a.ran.length, 0, "a queued retry is re-armed by its schedule, never replayed at boot"); continue; } assert.equal(a.ran.length, 1); const [r] = a.ran; assert.equal(r.kind, "clean-audio-unchecked", `${spec.kind}`); assert.equal(r.unchecked, "channel-setting"); assert.equal(r.detail, "channel setting", "the title reads … without checking · channel setting"); assert.ok(r.logs[0]?.startsWith("Clean without checking (channel setting):"), r.logs.join("\n")); assert.ok(r.logs.some((l) => l.startsWith("Saved-video retention prune skipped")), r.logs.join("\n")); assert.equal(r.asked, 0, "the source was not asked"); assert.equal(r.out.end, "done"); } // A confirmed run with its plan: unchecked, at most the plan. { const paths = await corpus(true); const a = actions(paths); await replayBy(via, paths, BUTTON_WITH_PLAN, a.deps); assert.equal(a.ran[0]?.unchecked, "button"); assert.equal(a.ran[0]?.detail, "confirmed count"); assert.equal(await has(paths, "a"), false); assert.equal(await has(paths, "b"), true, "not in the carried plan"); } // A confirmed run without its plan: removes nothing, ends failed. { const paths = await corpus(true); const a = actions(paths); await replayBy(via, paths, BUTTON_NO_PLAN, a.deps); assert.deepEqual(a.ran[0]?.out, { end: "failed", sentence: PLAN_LOST_SENTENCE }); assert.equal(await has(paths, "a"), true); assert.equal(await has(paths, "b"), true); } }); }