Archilyzer · Source

archilyzer

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

commit 07c7ea2e07155bfa60af756767805f3280aa7c6d
parent f3d6688ae886fc13580a2c69dbe2e5a3dd896347
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 24 Nov 2026 20:22:57 -0500

space-suggestions REVIEW-2 F1, F2, F3, F6: sweeps per video, rows name their subject, fail closed

F1: the channel-wide audio sweeps (clean-audio, clean-extra-formats) are
offered only when no video of the channel is held; otherwise listed as held
with the first held video's reason. The click asks the held predicate of every
video of the channel. F2: a row with actions and no hold is refused at the
click; SPACE_SCAN_VERSION is 2 and a file of another version is "rescan
first". F3: a scan dated more than 5 minutes ahead is refused. F6: a
do-not-clean mark or a channel's live-recordings.json that is there but cannot
be read or parsed holds, naming the error.

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

Diffstat:
Mcommon/controller/spaceHold.test.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/spaceHold.ts | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/controller/spaceScan.test.ts | 18+++++++++++-------
Mcommon/controller/spaceScan.ts | 45++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/spaceSuggestions.ts | 4+++-
Meditor/app/api/ops/space-suggestions/route.test.ts | 2+-
Meditor/app/cleanup/space/actions.ts | 5+++--
Meditor/app/cleanup/space/lib/runSpaceAction.test.ts | 8++++++++
Meditor/app/cleanup/space/lib/runSpaceAction.ts | 12+++++++++---
9 files changed, 208 insertions(+), 34 deletions(-)

diff --git a/common/controller/spaceHold.test.ts b/common/controller/spaceHold.test.ts @@ -4,7 +4,7 @@ import { link, mkdir, mkdtemp, rm, stat, utimes, writeFile } from "node:fs/promi import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; -import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; +import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "../lib/spaceSuggestions"; import { SPACE_MAX_SCAN_AGE_MS, SpaceHolds, @@ -97,7 +97,7 @@ test("the re-check: a scan older than a day, a target changed, grown, gone or sh await put(part, 1000, 30); await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); const st = await stat(part); - const result = { computedAt: NOW.toISOString() } as SpaceScanResult; + const result = { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult; const good = row({ slug: "c", id: "v1", file: "audio.mp3.part", hold: { slug: "c", id: "v1" }, targets: [{ path: part, size: st.size, mtimeMs: st.mtimeMs }] }); const ask = (r: SpaceSuggestion, deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); assert.equal(await ask(good), null); @@ -134,13 +134,13 @@ test("a channel-wide eviction: refused when the set of old windows changed or a await put(path.join(w.data("c", "b"), "clips", "1.00-2.00.mp4"), 300, 2); const digest = await clipWindowsDigest(w.paths, "c", 30, NOW); assert.equal(digest.count, 1); - const result = { computedAt: NOW.toISOString() } as SpaceScanResult; + const result = { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult; const r = row({ kind: "evict-clips", slug: "c", hold: { slug: "c" }, digest: { olderThanDays: 30, count: digest.count, sha1: digest.sha1 } }); const ask = (deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); assert.equal(await ask(), null); // b's window turns 30 days old (a scan an hour old then): the set grew. const later = new Date(NOW.getTime() + 29 * DAY); - const fresh = await recheckSpaceRow({ paths: w.paths, result: { computedAt: new Date(later.getTime() - 3_600_000).toISOString() } as SpaceScanResult, row: r, now: later, holds: new SpaceHolds(w.paths, noLive) }); + const fresh = await recheckSpaceRow({ paths: w.paths, result: { computedAt: new Date(later.getTime() - 3_600_000).toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult, row: r, now: later, holds: new SpaceHolds(w.paths, noLive) }); assert.match(fresh!, /changed since the scan/); // b (holding a young window) is recording now. assert.match((await ask({ ...noLive, liveRows: async () => [{ id: "b", status: "recording", mustKeep: false }] }))!, /live recording/); @@ -148,3 +148,61 @@ test("a channel-wide eviction: refused when the set of old windows changed or a await rm(w.tmp, { recursive: true, force: true }); } }); + +test("fail closed (review 2, F6): a do-not-clean or live-recordings file that cannot be read holds, and the hold names the error", async () => { + const w = await world(); + try { + // do-not-clean.json a directory: not absent, not readable. + await mkdir(path.join(w.data("c", "a"), "do-not-clean.json"), { recursive: true }); + await mkdir(w.data("c", "b"), { recursive: true }); + await writeFile(path.join(w.data("c", "b"), "do-not-clean.json"), "{not json"); + const holds = new SpaceHolds(w.paths, { jobs: () => [] }); + const a = await holds.video("c", "a"); + assert.equal(a?.kind, "do-not-clean"); + assert.match(a!.why, /could not be read/); + assert.match((await holds.video("c", "b"))!.why, /could not be read/); + // The channel's live-recordings.json unreadable: every video of it holds. + await mkdir(path.join(w.paths.channelsDir, "d", "live-recordings.json"), { recursive: true }); + const d = await new SpaceHolds(w.paths, { jobs: () => [] }).video("d", "any"); + assert.equal(d?.kind, "live"); + assert.match(d!.why, /live-recordings\.json could not be read/); + // A dep that throws holds the same way. + const t = await new SpaceHolds(w.paths, { jobs: () => [], liveRows: async () => { throw new Error("EIO"); } }).video("e", "v"); + assert.match(t!.why, /could not be read.*EIO/); + // Absent files hold nothing. + assert.equal(await new SpaceHolds(w.paths, { jobs: () => [] }).video("e", "v"), null); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("review 2: a row with actions and no subject, a scan of another version, a scan dated in the future — refused", async () => { + const w = await world(); + try { + const ask = (r: SpaceSuggestion, result: Partial<SpaceScanResult>) => + recheckSpaceRow({ paths: w.paths, result: { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION, ...result } as SpaceScanResult, row: r, now: NOW, holds: new SpaceHolds(w.paths, noLive) }); + const acting = row({ kind: "evict-clips", actions: [{ op: "evict-clips", body: { slug: "c", olderThanDays: 30 } }] }); + assert.match((await ask(acting, {}))!, /names nothing to check: rescan first/); + const ok = row({ kind: "compress-captions", hold: { slug: "c" }, actions: [{ op: "compress-text", body: { slugs: ["c"] } }] }); + assert.equal(await ask(ok, {}), null); + assert.match((await ask(ok, { version: 1 as never }))!, /older format.*rescan first/); + assert.match((await ask(ok, { computedAt: new Date(NOW.getTime() + 10 * 60_000).toISOString() }))!, /dated in the future/); + assert.equal(await ask(ok, { computedAt: new Date(NOW.getTime() + 60_000).toISOString() }), null); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("review 2, F1: a channel-wide audio sweep is refused when any video of the channel is held now", async () => { + const w = await world(); + try { + await mkdir(w.data("c", "v1"), { recursive: true }); + await mkdir(w.data("c", "v2"), { recursive: true }); + const sweep = row({ kind: "clean-audio", slug: "c", hold: { slug: "c" }, actions: [{ op: "cleanup", body: { slug: "c", sweep: "transcribed" } }] }); + const ask = (deps: SpaceHoldDeps) => recheckSpaceRow({ paths: w.paths, result: { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult, row: sweep, now: NOW, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(noLive), null); + assert.match((await ask({ ...noLive, liveRows: async () => [{ id: "v2", status: "landed", mustKeep: true }] }))!, /v2: a must-keep live recording/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); diff --git a/common/controller/spaceHold.ts b/common/controller/spaceHold.ts @@ -30,15 +30,20 @@ import { lstat, readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { getRegistry, type JobRecord } from "../jobs/registry"; import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; + import { readRelocationMarker } from "../lib/channelMedia"; import { readSavedVideosMarker } from "../lib/savedVideoStore"; -import { isDoNotClean } from "../lib/doNotClean-server"; +import { doNotCleanPath } from "../lib/doNotClean-server"; +import { readJsonFile } from "../lib/jsonFile-server"; import { resolveEffectiveAvailability } from "../lib/availability-server"; import { CLIPS_DIR_NAME, parseAnyClipWindowName, parseDesyncedClipWindowName, clipWindowStem } from "../lib/clipWindow"; -import { loadLiveRecordingRows, type LiveRecordingRow } from "../lib/liveRecordings-server"; +import { LIVE_RECORDINGS_FILENAME, loadLiveRecordingsFile, type LiveRecordingRow } from "../lib/liveRecordings-server"; +import { SPACE_SCAN_VERSION } from "../lib/spaceSuggestions"; import { VIDEO_WRITING_KINDS } from "./videoBusy"; export const SPACE_MAX_SCAN_AGE_MS = 24 * 60 * 60 * 1000; +// A scan dated further ahead than this was written by a wrong clock or by hand. +export const SPACE_MAX_SCAN_FUTURE_MS = 5 * 60 * 1000; // A downloader's partial: what `delete-file` may be asked to remove once it is // abandoned. NARROWER than mediaTier's scratch on purpose — a stored-text @@ -95,8 +100,27 @@ export function liveRowHold(r: LiveRowLike): SpaceHold | null { type JobLike = Pick<JobRecord, "id" | "kind" | "status"> & Partial<Pick<JobRecord, "channelSlug" | "videoId" | "spec">>; +// FAIL CLOSED (review 2, F6): a do-not-clean file that is there but cannot be +// read or parsed holds its video, and says so. Absent holds nothing. A file +// that parses is a mark whatever it holds (doNotClean-server's rule). +export async function readDoNotCleanHold(videoDir: string): Promise<SpaceHold | null> { + const read = await readJsonFile(doNotCleanPath(videoDir)); + if (read.ok) return { kind: "do-not-clean", why: "do-not-clean" }; + if (read.reason === "absent") return null; + return { kind: "do-not-clean", why: `its do-not-clean mark could not be read (${read.reason}): held` }; +} + +// A channel's live rows off its own file; a file there that cannot be read or +// parsed THROWS, so every video of the channel is held (F6). +async function liveRowsOffDisk(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRowLike[]> { + const f = await loadLiveRecordingsFile(paths, slug); + if (f.problem) throw new Error(f.problem); + return f.rows; +} + export type SpaceHoldDeps = { - isDoNotClean?: (videoDir: string) => Promise<boolean>; + // A do-not-clean hold for a video dir (default: readDoNotCleanHold). + doNotClean?: (videoDir: string) => Promise<SpaceHold | null>; liveRows?: (slug: string) => Promise<LiveRowLike[]>; jobs?: () => readonly JobLike[]; }; @@ -107,7 +131,7 @@ function jobIds(j: JobLike): string[] | null { } export class SpaceHolds { - private readonly live = new Map<string, Promise<LiveRowLike[]>>(); + private readonly live = new Map<string, Promise<LiveRowLike[] | { error: string }>>(); private readonly markers = new Map<string, Promise<SpaceHold | null>>(); private storeMemo: Promise<SpaceHold | null> | null = null; private jobList: readonly JobLike[] | null = null; @@ -141,10 +165,11 @@ export class SpaceHolds { return this.storeMemo; } - private liveRows(slug: string): Promise<LiveRowLike[]> { + // The rows, or the error the file gave (held, F6). + private liveRows(slug: string): Promise<LiveRowLike[] | { error: string }> { let p = this.live.get(slug); if (!p) { - p = (this.deps.liveRows ?? ((s: string) => loadLiveRecordingRows(this.paths, s)))(slug).catch(() => []); + p = (this.deps.liveRows ?? ((s: string) => liveRowsOffDisk(this.paths, s)))(slug).catch((e: Error) => ({ error: e.message || String(e) })); this.live.set(slug, p); } return p; @@ -161,14 +186,22 @@ export class SpaceHolds { return null; } - async video(slug: string, id: string): Promise<SpaceHold | null> { + // `opts.noDoNotCleanFile`: the caller listed the dir and saw no + // do-not-clean file (the scan), so it is not read. + async video(slug: string, id: string, opts: { noDoNotCleanFile?: boolean } = {}): Promise<SpaceHold | null> { const moving = await this.channel(slug); if (moving) return moving; const dir = path.join(this.paths.channelsDir, slug, "data", id); - if (await (this.deps.isDoNotClean ?? isDoNotClean)(dir).catch(() => false)) { - return { kind: "do-not-clean", why: "do-not-clean" }; + if (!opts.noDoNotCleanFile) { + const dnc = await (this.deps.doNotClean ?? readDoNotCleanHold)(dir).catch((e: Error) => ({ + kind: "do-not-clean" as const, + why: `its do-not-clean mark could not be read (${e.message}): held`, + })); + if (dnc) return dnc; } - for (const r of await this.liveRows(slug)) { + const rows = await this.liveRows(slug); + if (!Array.isArray(rows)) return { kind: "live", why: `the channel's ${LIVE_RECORDINGS_FILENAME} could not be read (${rows.error}): held` }; + for (const r of rows) { if (r.id !== id) continue; const h = liveRowHold(r); if (h) return h; @@ -233,23 +266,43 @@ export async function clipWindowsDigest( return { count: old.length, sha1: digestOf(old), videosWithWindows: videos, shared }; } +// The first held video of a channel (every video dir asked), or null. +export async function heldInChannel( + paths: Pick<Paths, "channelsDir">, + slug: string, + holds: SpaceHolds, +): Promise<(SpaceHold & { id: string }) | null> { + for (const id of await readdir(path.join(paths.channelsDir, slug, "data")).catch(() => [] as string[])) { + const h = await holds.video(slug, id); + if (h) return { ...h, id }; + } + return null; +} + // --- the re-check ---------------------------------------------------------------------- export async function recheckSpaceRow(opts: { paths: Pick<Paths, "channelsDir" | "transcriptsDir">; - result: Pick<SpaceScanResult, "computedAt">; + result: Pick<SpaceScanResult, "computedAt" | "version">; row: SpaceSuggestion; now?: Date; holds: SpaceHolds; availability?: (videoDir: string) => Promise<string | null>; }): Promise<string | null> { const now = opts.now ?? new Date(); + if (opts.result.version !== SPACE_SCAN_VERSION) { + return `the last scan is of an older format (version ${String(opts.result.version ?? "none")}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`; + } const age = now.getTime() - Date.parse(opts.result.computedAt); + if (age < -SPACE_MAX_SCAN_FUTURE_MS) return "the last scan is dated in the future (a wrong clock?): rescan first"; if (!(age <= SPACE_MAX_SCAN_AGE_MS)) { return `the last scan is ${Number.isFinite(age) ? `${Math.round(age / 3_600_000)} h` : "of an unknown"} old: rescan first`; } const { row, holds } = opts; const h = row.hold; + // A row that would act names what to check (F2): one that does not is + // refused, never run unchecked. + if (row.actions?.length && !h?.slug && !h?.store) return "the row names nothing to check: rescan first"; if (h?.store) { const s = await holds.store(); if (s) return `held: ${s.why}`; @@ -269,6 +322,13 @@ export async function recheckSpaceRow(opts: { const a = await (opts.availability ?? resolveEffectiveAvailability)(path.join(opts.paths.channelsDir, h.slug, "data", h.id)).catch(() => null); if (partialMayBeOnlyCopy(a)) return `held: the video is not known to be on its platform (${a ?? "unknown"}): the partial may be the only copy`; } + // A CHANNEL-WIDE AUDIO SWEEP (review 2, F1): the sweep knows do-not-clean + // and keep-latest by its own rules, not a must-keep or unfinished live + // recording — so every video of the channel is asked again. + if ((row.kind === "clean-audio" || row.kind === "clean-extra-formats") && h?.slug) { + const held = await heldInChannel(opts.paths, h.slug, holds); + if (held) return `held: ${held.id}: ${held.why}`; + } if (row.digest && h?.slug) { const d = await clipWindowsDigest(opts.paths, h.slug, row.digest.olderThanDays, now); if (d.count !== row.digest.count || d.sha1 !== row.digest.sha1) return "the channel's old clip windows changed since the scan: rescan"; diff --git a/common/controller/spaceScan.test.ts b/common/controller/spaceScan.test.ts @@ -348,15 +348,19 @@ test("captions: compress-text per channel, at its ratio, an estimate; the corpus test("audio: the report's bucket measured now, do-not-clean left out, on the disk the audio is on", async () => { const { w, r } = await scanned(); try { - const classic = kinds(r, "clean-audio").find((s) => s.slug === "classic")!; - assert.equal(classic.frees!.disk, "corpus"); - // v1's two audio files (v2 is do-not-clean); blocks, so at least the bytes. - assert.ok(classic.frees!.bytes >= 140_000 && classic.frees!.bytes < 200_000); - assert.deepEqual(classic.actions, [{ op: "cleanup", body: { slug: "classic", sweep: "transcribed" } }]); + // classic holds videos (v2 do-not-clean, v3 recording, v11 must-keep): its + // channel-wide sweeps are held, not offered (review 2, F1), with v1's bytes. + assert.equal(kinds(r, "clean-audio").find((s) => s.slug === "classic"), undefined); + assert.equal(kinds(r, "clean-extra-formats").find((s) => s.slug === "classic"), undefined); + const sweepHeld = r.held.filter((h) => /Classic: the audio sweeps/.test(h.what)); + assert.ok(sweepHeld.length >= 1); + assert.match(sweepHeld[0].why, /a channel-wide sweep is not offered while a video of the channel is held/); + // v1's two audio files; blocks, so at least the bytes. + assert.ok((sweepHeld.find((h) => /transcribed/.test(h.what))?.bytes ?? 0) >= 140_000); + // relocated holds nothing: its sweep is offered, on the disk its audio is on. const relocated = kinds(r, "clean-audio").find((s) => s.slug === "relocated")!; assert.equal(relocated.frees!.disk, "platter"); - const extra = kinds(r, "clean-extra-formats").find((s) => s.slug === "classic")!; - assert.ok(extra.frees!.bytes >= 40_000 && extra.frees!.bytes < 60_000); + assert.deepEqual(relocated.actions, [{ op: "cleanup", body: { slug: "relocated", sweep: "transcribed" } }]); } finally { await rm(w.tmp, { recursive: true, force: true }); } diff --git a/common/controller/spaceScan.ts b/common/controller/spaceScan.ts @@ -37,6 +37,7 @@ import { inspectChannelMedia, type ChannelMediaLocation } from "../lib/channelMe import { CLIPS_DIR, isKeptChatCapture, isScratchEntry, isTierable } from "../lib/mediaTier"; import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; import { isStoredCaptionName, isStoredTextName } from "../lib/storedText"; +import { DO_NOT_CLEAN_FILENAME } from "../lib/doNotClean"; // The raw live chat in its PLAIN form, by the stored-text rules // (lib/storedText.ts): a declared stored-text name that is not a caption @@ -163,6 +164,14 @@ export async function readSpaceSuggestions(paths: Pick<Paths, "transcriptsDir">) return v.version === SPACE_SCAN_VERSION && typeof v.computedAt === "string" ? v : null; } +// The version the file on disk says, whatever it is (null: none, or no file): +// the button names an older format "rescan first" (review 2, F2). +export async function readSpaceSuggestionsVersion(paths: Pick<Paths, "transcriptsDir">): Promise<number | null> { + const read = await readJsonFile(spaceSuggestionsPath(paths)); + const v = read.ok && read.value && typeof read.value === "object" ? (read.value as { version?: unknown }).version : null; + return typeof v === "number" ? v : null; +} + // umtool's REPORTS_ROOT, as umtool/lib/paths.mjs resolves it. // `SPACE_SCAN_REPORTS_DIR` is the scan's own name for it (an e2e server's // fixture), so nothing else that reads REPORTS_DIR changes. @@ -334,6 +343,9 @@ type ChannelTally = { // Every video holding a clip window: its old (unshared) windows, whether // it is held, and whether one of its old windows has another link. clipVideos: { id: string; old: ClipWindowFile[]; held: SpaceHold | null; shared: number; dev: string }[]; + // The first video of the channel the held predicate holds: a channel-wide + // audio sweep is not offered while there is one (review 2, F1). + firstHeld: (SpaceHold & { id: string }) | null; partials: { id: string; file: string; fact: Fact; path: string }[]; strays: { id: string; file: string; fact: Fact }[]; }; @@ -346,6 +358,7 @@ function newTally(): ChannelTally { extra: new Map(), move: { bytes: 0, files: 0 }, clipVideos: [], + firstHeld: null, partials: [], strays: [], }; @@ -427,15 +440,17 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult // video, a relocation marker — asked of every video a row would touch, the // store's rows included, and asked again at the click. const liveRows = await (deps.liveRecordings ?? (async () => (await listLiveRecordings(paths, { all: true })).rows))().catch(() => [] as LiveRecordingView[]); + // The held predicate's live rows: a test's listing when it names one, else + // each channel's own file, which FAILS CLOSED when it cannot be read. const holds = new SpaceHolds(paths, { - liveRows: async (slug) => liveRows.filter((r) => r.slug === slug), + ...(deps.liveRecordings ? { liveRows: async (slug: string) => liveRows.filter((r) => r.slug === slug) } : {}), ...deps.holds, }); const heldMemo = new Map<string, Promise<SpaceHold | null>>(); - const heldVideo = (slug: string, id: string): Promise<SpaceHold | null> => { + const heldVideo = (slug: string, id: string, o: { noDoNotCleanFile?: boolean } = {}): Promise<SpaceHold | null> => { const k = `${slug}/${id}`; let p = heldMemo.get(k); - if (!p) heldMemo.set(k, (p = holds.video(slug, id))); + if (!p) heldMemo.set(k, (p = holds.video(slug, id, o))); return p; }; // A held file's bytes, under its hold's kind. @@ -523,7 +538,7 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult const { slug, id, dir, tally } = v; const names = await readNames(dir, direct); const set = new Set(names); - const heldNow = () => heldVideo(slug, id); + const heldNow = () => heldVideo(slug, id, { noDoNotCleanFile: !set.has(DO_NOT_CLEAN_FILENAME) }); const hasPointer = set.has(SAVED_VIDEO_POINTER_FILENAME); const audio: { name: string; fact: Fact }[] = []; let clipDev = corpusDev; @@ -617,7 +632,9 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult // The cleanup sweeps' targets: the report's buckets (already net of // do-not-clean, keep-latest and the diarization hold), measured now, and // left out for a video the held predicate holds. - if (audio.length && !(await heldNow())) { + const videoHeld = await heldNow(); + if (videoHeld && !tally.firstHeld) tally.firstHeld = { ...videoHeld, id }; + if (audio.length && !videoHeld) { if (v.cleanIds.has(id)) for (const a of audio) bump(v.tally.audio, a.fact); if (v.extraIds.has(id) && v.target) for (const a of audio) if (a.name !== v.target) bump(v.tally.extra, a.fact); } @@ -658,8 +675,22 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult }); } const report = brief.snapshot?.generatedAt ? ` (report of ${String(brief.snapshot.generatedAt).slice(0, 10)})` : ""; + // THE AUDIO SWEEPS ARE CHANNEL-WIDE and know do-not-clean and keep-latest + // by their own rules, not a must-keep or unfinished live recording: while + // any video of the channel is held they are held, never offered (F1). + const sweepHeld = (what: string, dev: string, bytes: number, count: number) => + hold(held, `sweep:${what}:${slug}:${dev}`, { + what: `${name}: the audio sweeps (${what})`, + disk: diskIdOf(dev), + why: `${t.firstHeld!.id}: ${t.firstHeld!.why}: a channel-wide sweep is not offered while a video of the channel is held`, + link: { href: `/channels/${slug}`, label: "Channel page" }, + }, bytes, count); for (const [dev, e] of t.audio) { if (e.bytes <= 0) continue; + if (t.firstHeld) { + sweepHeld("transcribed", dev, e.bytes, e.count); + continue; + } const atRisk = brief.snapshot?.reclaimableAtRiskBytes ?? 0; suggestions.push({ key: `clean-audio:${slug}:${dev}`, @@ -679,6 +710,10 @@ export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult } for (const [dev, e] of t.extra) { if (e.bytes <= 0) continue; + if (t.firstHeld) { + sweepHeld("extra formats", dev, e.bytes, e.count); + continue; + } suggestions.push({ key: `clean-extra-formats:${slug}:${dev}`, kind: "clean-extra-formats", diff --git a/common/lib/spaceSuggestions.ts b/common/lib/spaceSuggestions.ts @@ -15,7 +15,9 @@ import { formatBytes } from "./format"; import type { SavedVideoAlternate, SavedVideoPointer } from "./savedVideo"; -export const SPACE_SCAN_VERSION = 1; +// 2 (review 2, F2): rows carry what the click re-checks (hold, targets, +// digest); a file of another version is refused at the click ("rescan first"). +export const SPACE_SCAN_VERSION = 2; export const SPACE_SUGGESTIONS_FILENAME = ".space-suggestions.json"; export const SPACE_SCAN_JOB_KIND = "space-scan"; export const SPACE_SCAN_QUEUE = "space-scan"; diff --git a/editor/app/api/ops/space-suggestions/route.test.ts b/editor/app/api/ops/space-suggestions/route.test.ts @@ -58,7 +58,7 @@ async function seed(): Promise<void> { await writeFile( path.join(corpus.transcripts, ".space-suggestions.json"), JSON.stringify({ - version: 1, + version: 2, computedAt: new Date().toISOString(), tookMs: 1, floorBytes: 0, diff --git a/editor/app/cleanup/space/actions.ts b/editor/app/cleanup/space/actions.ts @@ -1,7 +1,7 @@ "use server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { readSpaceSuggestions } from "yt-dlp-transcript-common/controller/spaceScan"; +import { readSpaceSuggestions, readSpaceSuggestionsVersion } from "yt-dlp-transcript-common/controller/spaceScan"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { enqueueSpaceScanJob } from "./lib/spaceJob"; @@ -20,7 +20,8 @@ export async function runSpaceSuggestionAction( opts: { dryRun?: boolean } = {}, ): Promise<SpaceRunOutcome> { const result = await readSpaceSuggestions(getPaths()); - const out = await runSpaceSuggestion({ result, key, dryRun: opts.dryRun === true }); + const fileVersion = result ? null : await readSpaceSuggestionsVersion(getPaths()); + const out = await runSpaceSuggestion({ result, fileVersion, key, dryRun: opts.dryRun === true }); if (!out.dryRun && out.ok) safeRevalidate(["/cleanup", "/cleanup/space"]); return out; } diff --git a/editor/app/cleanup/space/lib/runSpaceAction.test.ts b/editor/app/cleanup/space/lib/runSpaceAction.test.ts @@ -95,3 +95,11 @@ test("a failing action stops the rest and says so", async () => { assert.equal(out.ok, false); assert.deepEqual(out.lines, ["refused: drive not answering", "1 more not run"]); }); + +test("review 2: a scan file of another version is refused with rescan first, not run", async () => { + const { calls, runners } = recorder(); + const out = await runSpaceSuggestion({ result: null, fileVersion: 1, key: "p", dryRun: false, runners, recheck: async () => null }); + assert.equal(out.ok, false); + assert.match(out.lines[0], /older format \(version 1,.*rescan first/); + assert.equal(calls.length, 0); +}); diff --git a/editor/app/cleanup/space/lib/runSpaceAction.ts b/editor/app/cleanup/space/lib/runSpaceAction.ts @@ -1,4 +1,4 @@ -import type { SpaceScanResult, SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; @@ -139,7 +139,7 @@ export function bodyShapeProblem(body: Record<string, unknown>): string | null { // The click-time re-check (controller/spaceHold.ts), loaded lazily so a test // that names its own never reaches the registry or the disk. -async function defaultRecheck(result: Pick<SpaceScanResult, "computedAt">, row: SpaceSuggestion): Promise<string | null> { +async function defaultRecheck(result: Pick<SpaceScanResult, "computedAt" | "version">, row: SpaceSuggestion): Promise<string | null> { const { recheckSpaceRow, SpaceHolds } = await import("yt-dlp-transcript-common/controller/spaceHold"); const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); const paths = getPaths(); @@ -147,13 +147,19 @@ async function defaultRecheck(result: Pick<SpaceScanResult, "computedAt">, row: } export async function runSpaceSuggestion(opts: { - result: Pick<SpaceScanResult, "suggestions" | "computedAt"> | null; + result: Pick<SpaceScanResult, "suggestions" | "computedAt" | "version"> | null; + // The version the file on disk says, when it did not parse as this + // editor's (`result` null): an older format is "rescan first" (F2). + fileVersion?: number | null; key: string; dryRun: boolean; runners?: Record<string, SpaceRunner>; recheck?: (row: SpaceSuggestion) => Promise<string | null>; }): Promise<SpaceRunOutcome> { const runners = opts.runners ?? SPACE_RUNNERS; + if (!opts.result && typeof opts.fileVersion === "number" && opts.fileVersion !== SPACE_SCAN_VERSION) { + return fail(`the last scan is of an older format (version ${opts.fileVersion}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`); + } const s = opts.result?.suggestions.find((x) => x.key === opts.key); if (!s || !opts.result) return fail(`no suggestion "${opts.key}" in the last scan: refresh the page`); if (!s.actions?.length) return fail(`nothing to run here: ${s.link ? `see ${s.link.label}` : "this row is for information"}`);