Archilyzer · Source

archilyzer

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

commit a2354f80691db583b825af6fc9032db7c88143b0
parent 0be6ccdeb83dd73feb8dbe84dab5a5c02457d377
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 02:52:21 -0500

cleanup (review B1): clean after capture asks NOTHING of the network -- it reads a per-channel availability verdict (availability-verdict.json: the ids the quick availability check's last listing named, and when); listed in a fresh listing -> clean, not named -> held (maybe missing), no fresh listing -> held "awaiting an availability check" and at most ONE quick check of that channel is queued on its platform's queue per diarization.cleanVerdictMaxAgeHours (default 24), never while the platform is held

Before this, cleanAudioForVideo called verifyBeforeClean, whose tier B lists
the whole channel (fetchFlatPlaylistUrls) uncached -- one full listing per
cleaned video, outside every platform queue, gap, 429 hold and cookie alert.

- controller/availabilityVerdict.ts: the store (written by
  runQuickAvailabilityCheck beside maybe-missing.json), verdictFor (listed /
  absent / stale / none), requestAvailabilityCheck (no-url / platform-held via
  heldPlatformRefusal / already-requested within the max age, persisted as
  requestedAt BEFORE the start so a restart or two units cannot ask twice /
  requested), and startQuickAvailabilityCheckJob: the quick-availability-check
  kind on the channel's platform queue, so runManagedFunction's network guard
  applies as it does to the Quick check button.
- The per-video tier A stays: a video whose cached availability says it is
  gone is pinned do-not-clean, no spawn. verifyAvailabilityBeforeClean off
  still means no verification, as before. The manual Clean audio sweep keeps
  its live verifyBeforeClean, unchanged.
- Tests: five held videos of one channel -> one request; an old listing is no
  listing and is not re-requested inside the max age; a fresh listing cleans
  what it names and holds what it does not; a held platform -> held, nothing
  deleted, nothing requested, not even marked. maybe-missing.spec asserts the
  quick check writes the verdict. The per-video gate test's channel config
  now parses (it lacked `handling`, so it had been read as no config at all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
MSETTINGS.md | 4+++-
Acommon/controller/availabilityVerdict.ts | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/cleanAfterCapture.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/cleanAudioFromTranscribed.ts | 75++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcommon/controller/quickAvailabilityCheck.ts | 7++++++-
Mcommon/lib/settingsSchema.ts | 18++++++++++++++++++
Meditor/e2e/maybe-missing.spec.ts | 8++++++++
Msettings.json.example | 3++-
8 files changed, 365 insertions(+), 24 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -777,6 +777,7 @@ Speaker diarization captured right after transcription, while the audio is still | `maxAudioHours` | `0` | Videos longer than this are DEFERRED rather than diarized: reported as a third number that is never summed into reachable work, so a capped corpus can never read as finished.<br><br>THIS IS A STOPGAP AND IT IS NOT THE FIX. sherpa-onnx's clustering holds a pairwise distance matrix over speech-segment embeddings — O(n^2) in SEGMENT count — and speaker-turn density varies 40x across this corpus (33-1364 turns/hour), so duration does not actually predict the blowup: a sparse 7h42m video completed while a dense 6h12m one was OOM-killed. Duration is merely the only predictor available for free, from metadata already on disk, BEFORE spending 45 minutes to find out. n^2 at 30k segments is 6.7 GiB and at 40k is 11.9 GiB, which brackets the 10.6 GB and 9.6 GB peaks measured on this 16 GB box.<br><br>0 disables the cap. That is where this goes once windowed diarization lands: windowing divides per-window n by the window count, so the matrix falls by its square, and the cap stops being needed rather than being tuned. | | `cleanAfterCapture` | `false` | Delete a video's audio as soon as the Speakers lane has captured it.<br><br>When ON, a diarization unit that finishes with a complete set of voice fingerprints (diarization.json `voiceprints`) is followed at once by the per-video half of Clean audio, with every one of its gates: a transcript.json, outside the keep-latest window, not marked do-not-clean, and the availability check (a video gone upstream is pinned, not deleted). The bytes freed are logged and counted in the speakers readout. OFF by default: nothing deletes audio until the operator says so. | | `requireVoiceprints` | `true` | Hold a video's audio until its diarization.json carries voice fingerprints.<br><br>A fingerprint is the one part of a diarization that cannot be made again once the audio is gone, so with this ON (the default) Clean audio skips a diarized video whose sidecar has none, saying "awaiting voice fingerprint", and the Speakers lane adds them from the existing turns. Applies only while diarization is enabled, like the diarization guard itself. | +| `cleanVerdictMaxAgeHours` | `24` | How old the channel's last listing may be for clean-after-capture to trust it.<br><br>Clean after capture asks NOTHING of the network: it reads the channel's availability verdict (availability-verdict.json, written by the quick availability check) — a video named in a listing younger than this is cleaned, one not named is held (maybe missing). With no fresh listing the video is held and ONE quick check of the channel is queued on its platform's queue, at most once per this many hours, never while the platform is held. The manual Clean audio sweep keeps its own live check. | Default: @@ -796,7 +797,8 @@ Default: "concurrency": 1, "maxAudioHours": 0, "cleanAfterCapture": false, - "requireVoiceprints": true + "requireVoiceprints": true, + "cleanVerdictMaxAgeHours": 24 } ``` diff --git a/common/controller/availabilityVerdict.ts b/common/controller/availabilityVerdict.ts @@ -0,0 +1,194 @@ +// A CHANNEL'S AVAILABILITY VERDICT, cached: which videos its source listed the +// last time the quick availability check asked, and when. Written by that check +// (controller/quickAvailabilityCheck.ts, one flat-playlist listing on the +// channel's platform queue); READ by clean-after-capture, which must never ask +// the network itself (lane/speakers-run review, B1: one full listing per +// cleaned video, outside every queue, gap and hold). +// +// The per-video question (verdictFor) has four answers: +// listed — the channel's fresh listing names the video: safe to clean; +// absent — a fresh listing does NOT name it: maybe deleted, maybe unlisted +// (unlisted videos legitimately drop out of a listing). Held; the +// manual "check maybe missing" resolves which; +// stale — the newest listing is older than diarization.cleanVerdictMaxAgeHours; +// none — the channel has never been listed by the check. +// Stale and none hold the video "awaiting an availability check", and +// requestAvailabilityCheck asks for at most one check of that channel per +// max age, on its platform's own queue. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { heldPlatformRefusal } from "../jobs/downloadBackoff"; +import { detectPlatform, platformQueueKey, queueKeyForUrl } from "../lib/platform"; +import { resolveQueueKey } from "../lib/queueKeys"; +import { readChannelConfig } from "./channels"; +import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; + +export const AVAILABILITY_VERDICT_FILENAME = "availability-verdict.json"; + +export type AvailabilityVerdictRecord = { + version: 1; + // ISO 8601 of the listing, or null before the first one. + checkedAt: string | null; + // Canonical ids (data-dir names) the listing named, sorted. + ids: string[]; + // ISO 8601 of the last check REQUESTED by clean-after-capture, so a lane that + // holds a hundred videos of one channel asks once, and a restart does not + // ask again inside the max age. + requestedAt?: string; +}; + +export function availabilityVerdictPath(paths: Pick<Paths, "channelsDir">, slug: string): string { + return path.join(paths.channelsDir, slug, AVAILABILITY_VERDICT_FILENAME); +} + +function coerce(value: unknown): AvailabilityVerdictRecord | null { + const v = value as Partial<AvailabilityVerdictRecord> | null; + if (!v || typeof v !== "object" || !Array.isArray(v.ids)) return null; + return { + version: 1, + checkedAt: typeof v.checkedAt === "string" ? v.checkedAt : null, + ids: v.ids.filter((x): x is string => typeof x === "string"), + ...(typeof v.requestedAt === "string" ? { requestedAt: v.requestedAt } : {}), + }; +} + +export async function readAvailabilityVerdict( + paths: Pick<Paths, "channelsDir">, + slug: string, +): Promise<AvailabilityVerdictRecord | null> { + const read = await readJsonFile(availabilityVerdictPath(paths, slug)); + return read.ok ? coerce(read.value) : null; +} + +async function update( + paths: Pick<Paths, "channelsDir">, + slug: string, + fn: (r: AvailabilityVerdictRecord) => AvailabilityVerdictRecord, +): Promise<void> { + const file = availabilityVerdictPath(paths, slug); + await withJsonFileLock(file, async () => { + const cur = (await readAvailabilityVerdict(paths, slug)) ?? { version: 1, checkedAt: null, ids: [] }; + await writeJsonAtomic(file, fn(cur)); + }); +} + +// The quick check's half: what the listing named, and when. +export function writeAvailabilityVerdict( + paths: Pick<Paths, "channelsDir">, + slug: string, + listing: { checkedAt: string; ids: Iterable<string> }, +): Promise<void> { + return update(paths, slug, (r) => ({ + ...r, + checkedAt: listing.checkedAt, + ids: [...new Set(listing.ids)].sort(), + })); +} + +export function markAvailabilityCheckRequested( + paths: Pick<Paths, "channelsDir">, + slug: string, + at: string, +): Promise<void> { + return update(paths, slug, (r) => ({ ...r, requestedAt: at })); +} + +export type VideoVerdict = "listed" | "absent" | "stale" | "none"; + +const HOUR = 3_600_000; + +// PURE. +export function verdictFor( + record: AvailabilityVerdictRecord | null, + videoId: string, + maxAgeHours: number, + now: number = Date.now(), +): VideoVerdict { + if (!record?.checkedAt) return "none"; + const at = Date.parse(record.checkedAt); + if (!Number.isFinite(at) || now - at > maxAgeHours * HOUR) return "stale"; + return record.ids.includes(videoId) ? "listed" : "absent"; +} + +// PURE: may clean-after-capture ask for another check of this channel now? +// Not when one was asked for within the max age (it is queued, running, or +// failed — and a failure is not a reason to ask again sooner). +export function mayRequestCheck( + record: AvailabilityVerdictRecord | null, + maxAgeHours: number, + now: number = Date.now(), +): boolean { + const at = record?.requestedAt ? Date.parse(record.requestedAt) : NaN; + return !Number.isFinite(at) || now - at > maxAgeHours * HOUR; +} + +// --------------------------------------------------------------------------- +// Asking for a check — never doing one. + + +// The quick availability check as a job on the channel's PLATFORM queue — the +// one the channel page's Quick check button runs (kind +// quick-availability-check, network: so runManagedFunction's network guard +// applies: never unqueued, and an X job only on a fresh jar with no alert up). +export async function startQuickAvailabilityCheckJob(opts: { + paths: Paths; + slug: string; + queueKey?: string; + onDone?: () => void; +}): Promise<StreamActionResult> { + const config = await readChannelConfig(opts.paths, opts.slug); + const defaultQueue = config?.platform + ? platformQueueKey(config.platform) + : queueKeyForUrl(config?.url); + return runManagedFunction({ + kind: "quick-availability-check", + queueKey: resolveQueueKey(defaultQueue, opts.queueKey), + paths: opts.paths, + channelSlug: opts.slug, + fn: async (onLog, signal) => { + await runQuickAvailabilityCheck({ channelSlug: opts.slug, paths: opts.paths, onLog, signal }); + opts.onDone?.(); + }, + }); +} + +export type CheckRequestDeps = { + start?: (paths: Paths, slug: string) => Promise<StreamActionResult>; + platformRefusal?: (platform: string) => Promise<string | null>; + now?: () => number; +}; + +export type CheckRequest = + | { status: "requested"; jobId?: string } + | { status: "already-requested"; at: string } + | { status: "platform-held"; why: string } + | { status: "refused"; why: string } + | { status: "no-url" }; + +// At most one check per channel per max age, and none while its platform is +// held: a hold is the platform asking us to stop, and a check is a request. +export async function requestAvailabilityCheck( + paths: Paths, + slug: string, + maxAgeHours: number, + deps: CheckRequestDeps = {}, +): Promise<CheckRequest> { + const now = deps.now?.() ?? Date.now(); + const config = await readChannelConfig(paths, slug); + if (!config?.url) return { status: "no-url" }; + const platform = config.platform ?? detectPlatform(config.url) ?? "unknown"; + const held = await (deps.platformRefusal ?? ((p: string) => heldPlatformRefusal(p, "An availability check", paths)))(platform); + if (held) return { status: "platform-held", why: held }; + const record = await readAvailabilityVerdict(paths, slug); + if (!mayRequestCheck(record, maxAgeHours, now)) { + return { status: "already-requested", at: record!.requestedAt! }; + } + // Marked BEFORE the start, so two units finishing at once cannot both ask. + await markAvailabilityCheckRequested(paths, slug, new Date(now).toISOString()); + const started = await (deps.start ?? ((p: Paths, s: string) => startQuickAvailabilityCheckJob({ paths: p, slug: s })))(paths, slug); + if (!started.ok) return { status: "refused", why: started.error ?? "the check could not be queued" }; + return { status: "requested", jobId: started.jobId }; +} diff --git a/common/controller/cleanAfterCapture.test.ts b/common/controller/cleanAfterCapture.test.ts @@ -8,6 +8,15 @@ import type { Operation } from "../lib/operations"; import { cleanAudioForVideo, cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; import { runOperationUnit, type OperationRun } from "./operationBatch"; import { readSpeakersLedger } from "../lib/speakersLedger-server"; +import { readAvailabilityVerdict, writeAvailabilityVerdict, type CheckRequestDeps } from "./availabilityVerdict"; + +// Any test that reaches the request path without saying otherwise fails loudly. +const NO_NETWORK: CheckRequestDeps = { + start: async () => { + throw new Error("a test asked for a real availability check"); + }, + platformRefusal: async () => null, +}; import { defaultSiteSettings, getSettings } from "../lib/settings"; // Run with: @@ -53,7 +62,7 @@ async function corpus() { ytdlpBin: path.join(dir, "no-such-ytdlp"), } as unknown as Paths; await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); - await writeFile(path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ name: "ch" })); + await writeFile(path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch" })); const video = async ( id: string, o: { transcript?: boolean; diarization?: "none" | "plain" | "voiceprints"; doNotClean?: boolean; gone?: boolean; bytes?: number } = {}, @@ -116,8 +125,8 @@ test("cleanAudioForVideo keeps every gate of the channel sweep", async () => { await video("plain", { diarization: "plain" }); const gone = await video("gone", { diarization: "voiceprints", gone: true }); const ok = await video("ok", { diarization: "voiceprints", bytes: 2048 }); - await writeFile(path.join(ok, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "public" })); - const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {} }); + await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["ok", "gone"] }); + const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {}, checkDeps: NO_NETWORK }); assert.deepEqual(await one("untranscribed"), { outcome: "held", gate: "no-transcript", removedFiles: 0, bytesFreed: 0 }); assert.equal((await one("pinned")).gate, "do-not-clean"); assert.equal((await one("nodiar")).gate, "awaiting-diarization"); @@ -209,7 +218,7 @@ test("cleanAudioForVideo: an unmounted media drive keeps the audio link where it await rm(path.join(v, "audio.mp3")); const channelDir = path.join(paths.channelsDir, "ch"); const target = path.join(ROOT, "platter-not-mounted", "ch", "media"); - await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ name: "ch", mediaDir: target })); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch", mediaDir: target })); await symlink(target, path.join(channelDir, "media")); await symlink("../../media/v1/audio.mp3", path.join(v, "audio.mp3")); const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} }); @@ -232,6 +241,69 @@ test("cleanAudioForVideo removes the audio and nothing else: no source media, cl assert.equal(await readFile(path.join(v, "clips", "10.00-20.00.m4a"), "utf8"), "clip"); }); +// ---- B1: the availability verdict cache, never a listing per video ------------ + +test("no fresh listing: N captured videos of one channel are held, and at most ONE check is asked for", async () => { + await settings({}, { verifyAvailabilityBeforeClean: true }); + const { paths, video } = await corpus(); + const ids = ["a1", "a2", "a3", "a4", "a5"]; + for (const id of ids) await video(id, { diarization: "voiceprints" }); + const started: string[] = []; + const deps: CheckRequestDeps = { + start: async (_p, slug) => { + started.push(slug); + return { ok: true, jobId: "job-1" } as never; + }, + platformRefusal: async () => null, + }; + for (const id of ids) { + const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: () => {}, checkDeps: deps }); + assert.equal(out.gate, "awaiting-availability", id); + } + assert.deepEqual(started, ["ch"], "one check, on the channel, for five videos"); + for (const id of ids) assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")), true); + assert.equal(typeof (await readAvailabilityVerdict(paths, "ch"))?.requestedAt, "string"); + + // An OLD listing is no listing: still held, and the request is not repeated + // inside the max age. + await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(), ids }); + assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).gate, "awaiting-availability"); + assert.equal(started.length, 1); + + // The check lands (a fresh listing naming them): cleaned, nothing asked. + await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["a1", "a2"] }); + assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).outcome, "cleaned"); + // A fresh listing that does NOT name a video holds it: maybe missing. + assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a3", onLog: () => {}, checkDeps: deps })).gate, "maybe-missing"); + assert.equal(started.length, 1); +}); + +test("a held platform: the video is held, nothing deleted, nothing requested", async () => { + await settings({}, { verifyAvailabilityBeforeClean: true }); + const { paths, video } = await corpus(); + const v = await video("v1", { diarization: "voiceprints" }); + let started = 0; + const logs: string[] = []; + const out = await cleanAudioForVideo({ + channelSlug: "ch", + paths, + videoId: "v1", + onLog: (m) => logs.push(m), + checkDeps: { + start: async () => { + started++; + return { ok: true, jobId: "x" } as never; + }, + platformRefusal: async (platform) => `${platform} is held after a 429`, + }, + }); + assert.equal(out.gate, "awaiting-availability"); + assert.equal(started, 0); + assert.equal(await exists(path.join(v, "audio.mp3")), true); + assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined, "not even marked as asked"); + assert.ok(logs.some((l) => l.includes("youtube is held after a 429")), logs.join("\n")); +}); + test.after(() => rm(ROOT, { recursive: true, force: true })); test("concurrency stays 1: one diarization at a time, one backfill unit at a time", () => { diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -1,4 +1,13 @@ import { removeMediaFile } from "../lib/mediaTier-server"; +import { isPermanentlyGone } from "../lib/availability"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; +import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import { + readAvailabilityVerdict, + requestAvailabilityCheck, + verdictFor, + type CheckRequestDeps, +} from "./availabilityVerdict"; import { assertChannelMediaReachable } from "../lib/channelMedia"; import path from "node:path"; import fs from "fs-extra"; @@ -77,7 +86,13 @@ export type AudioCleanGate = | "awaiting-voiceprint" // cleanAudioForVideo only: the channel's media drive is not answering. The // channel sweep is covered by its job kind's needsMedia guard instead. - | "media-unreachable"; + | "media-unreachable" + // cleanAudioForVideo only, from the channel's availability verdict cache + // (controller/availabilityVerdict.ts): no listing within + // diarization.cleanVerdictMaxAgeHours (a check is requested), or a fresh + // listing that does not name the video (maybe deleted, maybe unlisted). + | "awaiting-availability" + | "maybe-missing"; export async function audioCleanGate( videoDir: string, @@ -278,22 +293,31 @@ export type CleanOneOptions = { verifyAvailability?: boolean; onLog?: (msg: string) => void; signal?: AbortSignal; + // Test seam: how a check is asked for (never run) — see availabilityVerdict.ts. + checkDeps?: CheckRequestDeps; }; export type CleanOneResult = { // cleaned: the audio is gone. held: a gate kept it (`gate` says which). - // pinned / unverified: the availability check kept it (gone upstream — now - // do-not-clean — or could not be resolved). - outcome: "cleaned" | "held" | "pinned" | "unverified"; + // pinned: its cached availability says it is gone upstream — now + // do-not-clean, kept. + outcome: "cleaned" | "held" | "pinned"; gate?: AudioCleanGate; removedFiles: number; bytesFreed: number; }; // THE PER-VIDEO HALF of cleanAudioFromTranscribed, for clean-after-capture: the -// same gates in the same order (audioCleanGate), the same availability check -// (a gone-upstream video is pinned, not deleted), the same removeMediaFile. -// Nothing about it is looser than the channel sweep; it only asks about one id. +// same gates in the same order (audioCleanGate) and the same removeMediaFile. +// +// ITS AVAILABILITY CHECK ASKS NOTHING OF THE NETWORK (review B1). The channel +// sweep's verifyBeforeClean lists the whole channel per call; called once per +// captured video that is a full listing per video, outside every platform +// queue, gap and hold. Here: a video whose cached per-video availability says +// it is gone is pinned (verifyBeforeClean's tier A, no spawn); otherwise the +// channel's verdict cache decides — listed in a fresh listing → clean; not named +// → held (maybe missing); no fresh listing → held, and ONE quick check of the +// channel is requested on its platform's queue, at most once per max age. // No saved-video prune: that is the channel sweep's retention pass. export async function cleanAudioForVideo({ channelSlug, @@ -302,6 +326,7 @@ export async function cleanAudioForVideo({ verifyAvailability, onLog, signal, + checkDeps, }: CleanOneOptions): Promise<CleanOneResult> { const log = onLog ?? ((m: string) => console.log(m)); const held = (gate: AudioCleanGate): CleanOneResult => ({ @@ -336,18 +361,34 @@ export async function cleanAudioForVideo({ } const verify = verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean; if (verify) { - const verdicts = await verifyBeforeClean({ - channelSlug, - paths, - candidateIds: [videoId], - onLog: log, - signal, - }); - if (verdicts.pinned.has(videoId) || verdicts.alreadyGone.has(videoId)) { + const cached = await resolveEffectiveAvailability(videoDir); + if (isPermanentlyGone(cached)) { + if (!(await loadDoNotClean(videoDir))) { + await setDoNotClean(videoDir, true, `deleted from source (pre-clean check): ${cached}`); + log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`); + } return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 }; } - if (excludedIds(verdicts).has(videoId)) { - return { outcome: "unverified", removedFiles: 0, bytesFreed: 0 }; + const maxAge = diarization.cleanVerdictMaxAgeHours; + const verdict = verdictFor(await readAvailabilityVerdict(paths, channelSlug), videoId, maxAge); + if (verdict === "absent") { + log(`Kept ${videoId}'s audio: the channel's last listing does not name it (maybe missing — Check maybe missing resolves it).`); + return held("maybe-missing"); + } + if (verdict !== "listed") { + const asked = await requestAvailabilityCheck(paths, channelSlug, maxAge, checkDeps); + const why = + asked.status === "requested" + ? "a quick availability check of the channel is queued" + : asked.status === "already-requested" + ? `a check was requested at ${asked.at}` + : asked.status === "platform-held" + ? `its platform is held, so no check is asked: ${asked.why}` + : asked.status === "refused" + ? `the check was refused: ${asked.why}` + : "the channel has no source URL to list"; + log(`Kept ${videoId}'s audio: awaiting an availability check (${verdict === "none" ? "never listed" : `no listing in ${maxAge} h`}; ${why}).`); + return held("awaiting-availability"); } } if (signal?.aborted) return held(gate); diff --git a/common/controller/quickAvailabilityCheck.ts b/common/controller/quickAvailabilityCheck.ts @@ -9,6 +9,7 @@ import { seedRosterIfAbsent, } from "./rosterStore"; import type { Paths } from "../lib/paths"; +import { writeAvailabilityVerdict } from "./availabilityVerdict"; // The record itself lives in the dependency-free ./maybeMissingStore so // runYtdlp's full sweep can write it too (this module imports runYtdlp, so the @@ -102,11 +103,15 @@ export async function runQuickAvailabilityCheck({ const maybeMissing = diffMaybeMissing(knownIds, freshIds); + const checkedAt = new Date().toISOString(); await writeMaybeMissing(paths, channelSlug, { - checkedAt: new Date().toISOString(), + checkedAt, freshPlaylistCount: freshIds.size, ids: maybeMissing, }); + // What the listing NAMED, for clean-after-capture's verdict cache (an id is + // safe to clean only while a fresh listing names it). + await writeAvailabilityVerdict(paths, channelSlug, { checkedAt, ids: freshIds }); log( `Quick availability: ${knownIds.length} known, ${freshIds.size} in fresh playlist, ${maybeMissing.length} maybe-missing.`, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -335,6 +335,7 @@ export type DiarizationSettings = { maxAudioHours: number; cleanAfterCapture: boolean; requireVoiceprints: boolean; + cleanVerdictMaxAgeHours: number; }; export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = { @@ -456,6 +457,16 @@ export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = { "fingerprint\", and the Speakers lane adds them from the existing turns. " + "Applies only while diarization is enabled, like the diarization guard " + "itself.", + cleanVerdictMaxAgeHours: + "How old the channel's last listing may be for clean-after-capture to " + + "trust it.\n\n" + + "Clean after capture asks NOTHING of the network: it reads the channel's " + + "availability verdict (availability-verdict.json, written by the quick " + + "availability check) — a video named in a listing younger than this is " + + "cleaned, one not named is held (maybe missing). With no fresh listing the " + + "video is held and ONE quick check of the channel is queued on its " + + "platform's queue, at most once per this many hours, never while the " + + "platform is held. The manual Clean audio sweep keeps its own live check.", }; // Configuration for the derived-corpus digest layer. Local-first by decision: @@ -1581,6 +1592,7 @@ export function defaultDiarization(): DiarizationSettings { maxAudioHours: 0, cleanAfterCapture: false, requireVoiceprints: true, + cleanVerdictMaxAgeHours: 24, }; } @@ -1626,6 +1638,12 @@ export function sanitizeDiarization(value: unknown): DiarizationSettings { cleanAfterCapture: r.cleanAfterCapture === true, // ON unless explicitly switched off: the safe direction is to keep audio. requireVoiceprints: r.requireVoiceprints !== false, + cleanVerdictMaxAgeHours: + typeof r.cleanVerdictMaxAgeHours === "number" && + Number.isFinite(r.cleanVerdictMaxAgeHours) && + r.cleanVerdictMaxAgeHours > 0 + ? r.cleanVerdictMaxAgeHours + : d.cleanVerdictMaxAgeHours, }; } diff --git a/editor/e2e/maybe-missing.spec.ts b/editor/e2e/maybe-missing.spec.ts @@ -124,6 +124,14 @@ test("quick check flags videos missing from the fresh playlist", async ({ `${channelRoot}/maybe-missing.json`, ); expect(record.ids.sort()).toEqual(["viddeleted1", "vidunlisted1"].sort()); + // …and what the listing NAMED, with when: the verdict cache + // clean-after-capture reads instead of listing the channel itself. + const verdict = await readJson<{ checkedAt: string; ids: string[] }>( + `${channelRoot}/availability-verdict.json`, + ); + expect(verdict.ids).toContain(BASELINE_IDS.find((id) => id !== "viddeleted1")!); + expect(verdict.ids).not.toContain("viddeleted1"); + expect(Date.now() - Date.parse(verdict.checkedAt)).toBeLessThan(10 * 60_000); // The job arms a debounced (~1s) snapshot regen that re-surfaces the // maybe-missing set into snapshot.json. Wait for it before reloading. diff --git a/settings.json.example b/settings.json.example @@ -185,7 +185,8 @@ "concurrency": 1, "maxAudioHours": 0, "cleanAfterCapture": false, - "requireVoiceprints": true + "requireVoiceprints": true, + "cleanVerdictMaxAgeHours": 24 }, "backfill": { "concurrency": 1,