import { test } from "node:test"; import assert from "node:assert/strict"; import { link, mkdir, mkdtemp, rm, stat, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "../lib/spaceSuggestions"; import { SPACE_MAX_SCAN_AGE_MS, SpaceHolds, clipWindowsDigest, liveRowHold, recheckSpaceRow, type SpaceHoldDeps, } from "./spaceHold"; // THE ONE HELD PREDICATE (review 1, B2) and THE CLICK-TIME RE-CHECK (B4): what // the scan holds back, asked again when the button is pressed, against the // disk as it is then. const NOW = new Date("2026-11-24T12:00:00.000Z"); const DAY = 86_400_000; async function put(file: string, bytes: number, ageDays = 0): Promise { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, Buffer.alloc(bytes, 7)); if (ageDays) { const t = new Date(NOW.getTime() - ageDays * DAY); await utimes(file, t, t); } } async function world() { const tmp = await mkdtemp(path.join(tmpdir(), "space-hold-")); const transcriptsDir = path.join(tmp, "transcripts"); const paths = { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels"), savedVideosDir: path.join(transcriptsDir, "saved-videos") } as Paths; await mkdir(paths.channelsDir, { recursive: true }); return { tmp, paths, data: (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id) }; } const noLive: SpaceHoldDeps = { liveRows: async () => [], jobs: () => [] }; test("live rows: anything not landed, failed, cancelled or superseded holds; must-keep and awaiting resume hold whatever the status", () => { const row = (r: Record) => liveRowHold({ id: "v", mustKeep: false, status: "landed", ...r } as never); assert.equal(row({}), null); assert.equal(row({ status: "failed" }), null); assert.equal(row({ status: "cancelled" }), null); assert.equal(row({ status: "recording", supersededBy: "x" }), null); assert.equal(row({ status: "recording" })?.kind, "live"); assert.equal(row({ status: "interrupted" })?.kind, "live"); assert.equal(row({ awaitingResume: ["p1"] })?.kind, "live"); assert.equal(row({ mustKeep: true })?.kind, "must-keep"); }); test("a video is held by do-not-clean, a live row, a job for it, or its channel's relocation marker; the store by its own marker", async () => { const w = await world(); try { await mkdir(w.data("c", "dnc"), { recursive: true }); await writeFile(path.join(w.data("c", "dnc"), "do-not-clean.json"), JSON.stringify({ setAt: "x" })); const holds = new SpaceHolds(w.paths, { liveRows: async (slug) => (slug === "c" ? [{ id: "rec", status: "interrupted", mustKeep: false }, { id: "keep", status: "landed", mustKeep: true }] : []), jobs: () => [ { id: "j1", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "busy" }, { id: "j2", kind: "compact-saved-videos", status: "queued", channelSlug: "c", spec: { kind: "compact-saved-videos", slug: "c", params: { ids: ["queued"] } } }, { id: "j3", kind: "sync", status: "running", channelSlug: "d" }, { id: "j4", kind: "transcribe-one", status: "done", channelSlug: "c", videoId: "free" }, ], }); assert.equal((await holds.video("c", "dnc"))?.kind, "do-not-clean"); assert.equal((await holds.video("c", "rec"))?.kind, "live"); assert.equal((await holds.video("c", "keep"))?.kind, "must-keep"); assert.equal((await holds.video("c", "busy"))?.kind, "job"); assert.equal((await holds.video("c", "queued"))?.kind, "job"); // A channel-wide writer (sync) holds every video of its channel. assert.equal((await holds.video("d", "any"))?.kind, "job"); assert.equal(await holds.video("c", "free"), null); await mkdir(path.join(w.paths.channelsDir, "m"), { recursive: true }); await writeFile(path.join(w.paths.channelsDir, "m", ".relocating.json"), JSON.stringify({ target: "/x/m/media", direction: "out", startedAt: "", phase: "copy", scope: "media" })); assert.equal((await new SpaceHolds(w.paths, noLive).video("m", "v"))?.kind, "moving"); assert.equal(await new SpaceHolds(w.paths, noLive).store(), null); await writeFile(path.join(w.paths.transcriptsDir, ".relocating-saved-videos.json"), JSON.stringify({ target: "/x/saved-videos", direction: "out", startedAt: "", phase: "copy" })); assert.equal((await new SpaceHolds(w.paths, noLive).store())?.kind, "store-moving"); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); function row(extra: Partial): SpaceSuggestion { return { key: "k", kind: "stale-partial", title: "", frees: { disk: "corpus", bytes: 1 }, basis: "measured", basisText: "", loss: "", ...extra }; } test("the re-check: a scan older than a day, a target changed, grown, gone or shared, a hold that appeared since — each refused and named", async () => { const w = await world(); try { const dir = w.data("c", "v1"); const part = path.join(dir, "audio.mp3.part"); 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(), 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); assert.match((await ask(good, noLive, new Date(NOW.getTime() + SPACE_MAX_SCAN_AGE_MS + 60_000)))!, /rescan first/); assert.match((await ask(good, { ...noLive, jobs: () => [{ id: "j", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "v1" }] }))!, /a job/); // Gone from its platform since: the partial may be the only copy. await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "deleted", checkedAt: NOW.toISOString(), checkedBy: "check" })); assert.match((await ask(good))!, /only copy/); await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); // Resumed since (it grew): changed. await writeFile(part, Buffer.alloc(2000, 1)); assert.match((await ask(good))!, /changed since the scan/); await rm(part); assert.match((await ask(good))!, /no longer there/); // Shared. const alt = path.join(dir, "alt.mp4"); await put(alt, 500); await link(alt, path.join(w.tmp, "other-link")); const ast = await stat(alt); assert.match((await ask(row({ kind: "drop-alternate", hold: { slug: "c", id: "v1", store: true }, targets: [{ path: alt, size: ast.size, mtimeMs: ast.mtimeMs }] })))!, /hard link/); // Marked do-not-clean since. await writeFile(path.join(dir, "do-not-clean.json"), JSON.stringify({ setAt: "x" })); assert.match((await ask(row({ kind: "drop-original", hold: { slug: "c", id: "v1", store: true } })))!, /do-not-clean/); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("a channel-wide eviction: refused when the set of old windows changed or a video holding windows is held now", async () => { const w = await world(); try { await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.mp4"), 300, 60); await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.json"), 10, 60); 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(), 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(), 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/); } finally { 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) => 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 }); } });