import { test } from "node:test"; import assert from "node:assert/strict"; import { link, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChannelBrief } from "./channels"; import type { ChannelSnapshot } from "./channelSnapshot"; import type { CompactPlan, CompactionReviewRow, KeptFailedEncodeRow } from "./compactSavedVideos"; import type { LiveRecordingView } from "./liveRecordings"; import { DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS } from "../lib/savedVideoCompaction"; import { SPACE_SUGGESTIONS_FILENAME, type SpaceScanResult } from "../lib/spaceSuggestions"; import { readSpaceSuggestions, scanSpace, type SpaceScanDeps, type SpaceScanSettings } from "./spaceScan"; const DAY = 86_400_000; const NOW = new Date("2026-11-24T12:00:00.000Z"); 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 json(file: string, value: unknown): Promise { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, JSON.stringify(value)); } function snapshot(buckets: Partial, extra: Partial = {}): ChannelSnapshot { return { generatedAt: NOW.toISOString(), buckets: { ...buckets }, ...extra } as unknown as ChannelSnapshot; } type World = { tmp: string; paths: Paths; settings: SpaceScanSettings; deps: SpaceScanDeps; platter: string; storeDir: string; }; // Two "disks": everything under /platter is device P, the rest device C // (a temp dir cannot make a second st_dev, so the device is a dep). async function world(): Promise { const tmp = await mkdtemp(path.join(tmpdir(), "space-scan-")); const transcriptsDir = path.join(tmp, "transcripts"); const channelsDir = path.join(transcriptsDir, "channels"); const platter = path.join(tmp, "platter"); const platterRoot = path.join(platter, "archilyzer-media"); const storeDir = path.join(platterRoot, "saved-videos"); const paths = { transcriptsDir, channelsDir, savedVideosDir: path.join(transcriptsDir, "saved-videos"), exportBuildsDir: path.join(tmp, "repo", "export", ".export-builds"), exportPublicDir: path.join(tmp, "repo", "export", "public"), monorepoRoot: path.join(tmp, "repo"), } as Paths; await mkdir(storeDir, { recursive: true }); await mkdir(channelsDir, { recursive: true }); await symlink(storeDir, paths.savedVideosDir); await put(path.join(transcriptsDir, "index.mdb"), 50_000); // A CLASSIC channel: its media real files in data// on the corpus disk. const classic = path.join(channelsDir, "classic"); await json(path.join(classic, "config.json"), { name: "Classic", audioFormat: "mp3" }); const v1 = path.join(classic, "data", "v1"); await put(path.join(v1, "audio.mp3"), 100_000); await put(path.join(v1, "audio.m4a"), 40_000); await put(path.join(v1, "transcript.en.vtt"), 200_000); await put(path.join(v1, "transcript.en-orig.vtt"), 200_000); await put(path.join(v1, "metadata.info.json"), 30_000); await put(path.join(v1, "transcript.json"), 20_000); await put(path.join(v1, "clips", "10.00-20.00.mp4"), 60_000, 60); await put(path.join(v1, "clips", "30.00-40.00.mp4"), 60_000, 1); // Do-not-clean: nothing of it is proposed. const v2 = path.join(classic, "data", "v2"); await put(path.join(v2, "audio.mp3"), 100_000); await json(path.join(v2, "do-not-clean.json"), { enabled: true, by: "person", at: NOW.toISOString() }); await put(path.join(v2, "clips", "1.00-2.00.mp4"), 70_000, 90); await put(path.join(v2, "source-media.mp4"), 300_000); await put(path.join(v2, "audio.mp3.part"), 9_000, 30); // An abandoned partial, and an unstored container. const v3 = path.join(classic, "data", "v3"); await put(path.join(v3, "audio.mp3.part"), 80_000, 30); await put(path.join(v3, "audio.mp3.ytdl"), 100, 30); await put(path.join(v3, "audio.mp3.part-recent"), 1); // not a partial name await put(path.join(v3, "source-media.mp4"), 500_000); await put(path.join(v3, ".transcript.live_chat.json.retire-123"), 5_000, 30); // the stored-text run's: never proposed await json(path.join(v3, "availability.json"), { availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" }); await put(path.join(v3, "clips", "50.00-60.00.mp4"), 40_000, 60); // A partial of a video not known to be on its platform: it may be the only copy. await put(path.join(classic, "data", "v9", "audio.mp3.part"), 70_000, 30); // A clip window hard-linked into a take: shared, frees nothing. const v4 = path.join(classic, "data", "v4"); await put(path.join(v4, "clips", "5.00-9.00.mp4"), 90_000, 60); await mkdir(path.join(tmp, "takes"), { recursive: true }); await link(path.join(v4, "clips", "5.00-9.00.mp4"), path.join(tmp, "takes", "w.mp4")); // A saved video: its pointer here, its container (and an alternate, a // compacted original, a proxy) in the store on the platter. const v5 = path.join(classic, "data", "v5"); const s5 = path.join(storeDir, "classic", "v5"); await put(path.join(s5, "source-media.compact-av1-20261101000000.mp4"), 400_000); await put(path.join(s5, "source-media.mp4"), 1_200_000); await put(path.join(s5, "source-media.alt-480p-20261001000000.mp4"), 300_000); await json(path.join(v5, "saved-video.json"), { storedAt: "2026-10-01T00:00:00Z", dir: s5, file: "source-media.compact-av1-20261101000000.mp4", bytes: 400_000, keepReason: "override", explicit: true, alternates: [ { file: "source-media.mp4", bytes: 1_200_000, storedAt: "", setAsideAt: "", keptAs: "original", sha256: "a" }, { file: "source-media.alt-480p-20261001000000.mp4", bytes: 300_000, storedAt: "", setAsideAt: "" }, ], }); // A pinned video's alternate: kept (ruling 2). const v6 = path.join(classic, "data", "v6"); const s6 = path.join(storeDir, "classic", "v6"); await put(path.join(s6, "source-media.mkv"), 600_000); await put(path.join(s6, "source-media.alt-720p-20261001000000.mkv"), 500_000); await json(path.join(v6, "saved-video.json"), { storedAt: "", dir: s6, file: "source-media.mkv", bytes: 600_000, keepReason: "pin", alternates: [{ file: "source-media.alt-720p-20261001000000.mkv", bytes: 500_000, storedAt: "", setAsideAt: "" }], }); // Saved alternates of a do-not-clean video, a must-keep recording's and an // interrupted recording's: held (review 1, B2). A former original: a row // with a link to the video page only (ruling B1). for (const id of ["v10", "v11", "v12", "v13"]) { const sd = path.join(storeDir, "classic", id); await put(path.join(sd, "source-media.mp4"), 100_000); await put(path.join(sd, "source-media.alt-480p-20261001000000.mp4"), 200_000); await json(path.join(classic, "data", id, "saved-video.json"), { storedAt: "", dir: sd, file: "source-media.mp4", bytes: 100_000, keepReason: "override", alternates: [{ file: "source-media.alt-480p-20261001000000.mp4", bytes: 200_000, storedAt: "", setAsideAt: "", ...(id === "v13" ? { keptAs: "former-original" } : {}) }], }); } await json(path.join(classic, "data", "v10", "do-not-clean.json"), { setAt: NOW.toISOString() }); // Two channels of clip windows: one with nothing held (one eviction for the // channel), one whose other video is recording (per video). await json(path.join(channelsDir, "clipsy", "config.json"), { name: "Clipsy" }); await put(path.join(channelsDir, "clipsy", "data", "c1", "clips", "1.00-2.00.mp4"), 10_000, 60); await put(path.join(channelsDir, "clipsy", "data", "c2", "clips", "3.00-4.00.h1080.mp4"), 10_000, 45); await json(path.join(channelsDir, "clipsrec", "config.json"), { name: "Clipsrec" }); await put(path.join(channelsDir, "clipsrec", "data", "k1", "clips", "1.00-2.00.mp4"), 10_000, 60); await put(path.join(channelsDir, "clipsrec", "data", "k2", "clips", "1.00-2.00.mp4"), 10_000, 2); // A live landing whose check failed, its stream file in the store's staging. await put(path.join(storeDir, "classic", "live.part1.mp4"), 250_000); // A RELOCATED channel: its audio a tier link onto the platter. const rel = path.join(channelsDir, "relocated"); const relMedia = path.join(platterRoot, "relocated", "media"); await json(path.join(rel, "config.json"), { name: "Relocated", mediaDir: relMedia }); await put(path.join(relMedia, "r1", "audio.mp3"), 2_000_000); await put(path.join(relMedia, "r1", "transcript.live_chat.json"), 400_000); await symlink(relMedia, path.join(rel, "media")); const r1 = path.join(rel, "data", "r1"); await mkdir(r1, { recursive: true }); await symlink("../../media/r1/audio.mp3", path.join(r1, "audio.mp3")); await symlink("../../media/r1/transcript.live_chat.json", path.join(r1, "transcript.live_chat.json")); await put(path.join(r1, "transcript.en.vtt"), 100_000); // A channel MID-MOVE, a LEGACY one, and one whose drive is NOT MOUNTED. const moving = path.join(channelsDir, "moving"); await json(path.join(moving, "config.json"), { name: "Moving" }); await json(path.join(moving, ".relocating.json"), { target: path.join(platterRoot, "moving", "media"), direction: "out", startedAt: "", phase: "copy", scope: "media" }); await put(path.join(moving, "data", "m1", "audio.mp3"), 700_000); const legacy = path.join(channelsDir, "legacy"); await json(path.join(legacy, "config.json"), { name: "Legacy", dataDir: path.join(tmp, "elsewhere", "legacy", "data") }); const offline = path.join(channelsDir, "offline"); const goneRoot = path.join(tmp, "gone", "root"); await json(path.join(offline, "config.json"), { name: "Offline", mediaDir: path.join(goneRoot, "offline", "media") }); await symlink(path.join(goneRoot, "offline", "media"), path.join(offline, "media")); await mkdir(path.join(offline, "data", "o1"), { recursive: true }); await symlink("../../media/o1/audio.mp3", path.join(offline, "data", "o1", "audio.mp3")); await put(path.join(offline, "data", "o1", "transcript.en.vtt"), 10_000); // Builds and umtool's reports, measured only. await put(path.join(paths.exportBuildsDir, "site-a", "x.json"), 120_000); const reports = path.join(tmp, "reports"); await put(path.join(reports, "proj", "take.mp4"), 80_000); const settings: SpaceScanSettings = { minFreeDiskGB: 0, storage: { locations: [ { id: "platter", label: "Platter", root: platterRoot, autoRepoint: false }, { id: "gone", label: "Gone drive", root: goneRoot, autoRepoint: false }, ], defaultLocationId: "platter", savedVideosLocationId: "platter", }, savedVideoCompaction: DEFAULT_SAVED_VIDEO_COMPACTION_SETTINGS, }; const briefOf = async (slug: string, snap: ChannelSnapshot | null): Promise => ({ slug, config: JSON.parse(await readFile(path.join(channelsDir, slug, "config.json"), "utf8")) as ChannelBrief["config"], snapshot: snap, }); const deps: SpaceScanDeps = { now: () => NOW, deviceOf: (p) => (p.startsWith(platter) ? "P" : "C"), filesystemOf: async (dir) => dir.startsWith(platter) ? { dev: "P", mountpoint: platter, sizeBytes: 1_800_000_000_000, freeBytes: 200_000_000_000 } : { dev: "C", mountpoint: tmp, sizeBytes: 1_500_000_000_000, freeBytes: 20_000_000_000 }, locationStatus: async (loc) => (loc.id === "gone" ? { status: "not-mounted", detail: "the drive is not mounted" } : { status: "ok" }), briefs: async () => Promise.all([ briefOf("classic", snapshot( { transcribedWithAudio: ["v1", "v2"], multipleAudioFormats: ["v1"] }, { reclaimableAtRiskBytes: 0, heldAudioBytes: { noTranscript: 0, keepLatest: 0, doNotClean: 100_000, awaitingDiarization: 0, diarizationNeverClears: 0 } } as Partial, )), briefOf("relocated", snapshot({ transcribedWithAudio: ["r1"] })), briefOf("moving", null), briefOf("legacy", null), briefOf("offline", null), briefOf("clipsy", null), briefOf("clipsrec", null), ]), compactionPlan: async () => ({ plan: { items: [ { slug: "classic", id: "v6", compact: true, platform: "kick", onPlatform: true, availability: "public", source: { file: "source-media.mkv", bytes: 600_000, vcodec: "h264", height: 1080, fps: 60, seconds: 3600, videoMbps: 6 }, estimate: { bytes: [200_000, 300_000], hours: [1, 2], share: 0.5 }, line: "classic/v6: would compact" }, { slug: "classic", id: "v9", compact: false, reason: "an automatic keep-latest container (compaction is for deliberately stored videos only)", platform: "twitch", onPlatform: true, availability: "public", line: "" }, { slug: "classic", id: "v5", compact: false, reason: "already compacted", platform: "kick", onPlatform: true, availability: "public", line: "" }, ], willCompact: 1, totals: { bytes: 600_000, estimate: [200_000, 300_000], hours: [1, 2] }, lines: [], } as CompactPlan, probes: { "/x": { size: 1, mtimeMs: 1, probe: null } }, }), compactionReview: async () => [ { slug: "classic", id: "v5", state: "reviewed", line: "", availability: "public", onPlatform: false, presence: "gone", original: { file: "source-media.mp4", bytes: 1_200_000, storedAt: "", setAsideAt: "", keptAs: "original", sha256: "a" }, compactedAt: "", bytes: 400_000, sourceBytes: 1_200_000, checksPassed: true, watch: { compacted: "", command: "" }, } as CompactionReviewRow, ], keptFailedEncodes: async () => [ { slug: "classic", id: "v6", dir: path.join(s6, ".compact-scratch"), at: "", reason: "ssim", failedChunks: [], kept: { chunks: 2, bytes: 90_000, copy: null } } as KeptFailedEncodeRow, ], liveRecordings: async () => [ { slug: "classic", id: "v7", status: "landed", verification: { state: "failed", at: "", against: ["live.part1.mp4"] }, startedAt: "2026-11-20T00:00:00Z", mustKeep: false, parts: [], keptParts: [{ stem: "k", files: [], bytes: 33_000, seconds: null, fromStart: null, run: "earlier", why: "" }] } as unknown as LiveRecordingView, { slug: "classic", id: "v3", status: "recording", startedAt: "2026-11-24T11:00:00Z", mustKeep: true, parts: [] } as unknown as LiveRecordingView, { slug: "classic", id: "v11", status: "landed", startedAt: "2026-11-01T00:00:00Z", mustKeep: true, parts: [] } as unknown as LiveRecordingView, { slug: "classic", id: "v12", status: "interrupted", startedAt: "2026-11-23T00:00:00Z", mustKeep: false, parts: [] } as unknown as LiveRecordingView, { slug: "clipsrec", id: "k2", status: "interrupted", startedAt: "2026-11-23T00:00:00Z", mustKeep: false, parts: [] } as unknown as LiveRecordingView, ], holds: { jobs: () => [] }, reportsRoot: reports, }; return { tmp, paths, settings, deps, platter, storeDir }; } async function listAll(dir: string): Promise { const out: string[] = []; for (const e of await readdir(dir, { withFileTypes: true, recursive: true })) { out.push(path.join(e.parentPath, e.name)); } return out.sort(); } async function scanned(): Promise<{ w: World; r: SpaceScanResult; before: string[]; after: string[] }> { const w = await world(); const before = await listAll(w.tmp); const r = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps }); const after = await listAll(w.tmp); return { w, r, before, after }; } const kinds = (r: SpaceScanResult, kind: string) => r.suggestions.filter((s) => s.kind === kind); test("the scan writes its one file and nothing else, and reads it back", async () => { const { w, r, before, after } = await scanned(); try { const written = after.filter((f) => !before.includes(f)); assert.deepEqual(written.map((f) => path.relative(w.tmp, f)), [path.join("transcripts", SPACE_SUGGESTIONS_FILENAME)]); const back = await readSpaceSuggestions(w.paths); assert.equal(back?.computedAt, NOW.toISOString()); assert.equal(back?.suggestions.length, r.suggestions.length); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("disks: the corpus disk and the platter by device, the unmounted location never empty", async () => { const { w, r } = await scanned(); try { const corpus = r.disks.find((d) => d.id === "corpus")!; const platter = r.disks.find((d) => d.id === "platter")!; const gone = r.disks.find((d) => d.id === "gone")!; assert.equal(corpus.status, "ok"); assert.ok(corpus.roles.includes("corpus disk")); assert.ok(platter.roles.includes("saved-video store")); assert.equal(gone.status, "not-mounted"); assert.equal(gone.archiveBytes, null); assert.equal(gone.freeBytes, null); // The relocated channel's audio counts on the platter, its text on the corpus disk. assert.ok(platter.archive!.media >= 2_000_000); assert.ok(corpus.archive!.text >= 400_000); assert.ok(corpus.archive!.builds >= 120_000); assert.ok(corpus.archive!.reports >= 80_000); assert.ok(corpus.archive!.other >= 50_000); // index.mdb assert.ok(platter.archive!.store >= 1_200_000); // A hard-linked file is counted once. assert.equal(corpus.archiveBytes, Object.values(corpus.archive!).reduce((a, b) => a + b, 0)); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("channels the scan cannot read are named, never counted as empty", async () => { const { w, r } = await scanned(); try { const why = Object.fromEntries(r.notScanned.map((n) => [n.slug, n.why])); assert.match(why.moving, /relocation/); assert.match(why.legacy, /migrate-tier/); assert.ok(r.held.some((h) => /offline/.test(h.what) && /not mounted|not reachable|unknown/i.test(h.why))); assert.ok(!r.suggestions.some((s) => s.slug === "moving" || s.slug === "legacy")); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("captions: compress-text per channel, at its ratio, an estimate; the corpus disk", async () => { const { w, r } = await scanned(); try { const rows = kinds(r, "compress-captions"); const classic = rows.find((s) => s.slug === "classic")!; assert.equal(classic.frees!.disk, "corpus"); assert.ok(classic.frees!.bytes > 0.79 * 400_000 && classic.frees!.bytes <= 0.8 * 409_600); assert.equal(classic.basis, "estimate"); assert.deepEqual(classic.actions, [{ op: "compress-text", body: { slugs: ["classic"], kinds: ["captions"] } }]); // The relocated channel's raw chat is on the platter: its compression frees the platter. const chat = kinds(r, "compress-live-chat").find((s) => s.slug === "relocated")!; assert.equal(chat.frees!.disk, "platter"); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); 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 { // 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"); assert.deepEqual(relocated.actions, [{ op: "cleanup", body: { slug: "relocated", sweep: "transcribed" } }]); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("moves: a classic channel's media to the default location, its fit on the target said", async () => { const { w, r } = await scanned(); try { const move = kinds(r, "move-media").find((s) => s.slug === "classic")!; assert.equal(move.frees!.disk, "corpus"); assert.equal(move.fills!.disk, "platter"); assert.equal(move.fills!.fits, true); assert.deepEqual(move.actions, [{ op: "relocate", body: { slugs: ["classic"], locationId: "platter" } }]); // Text never moves: only the media tier (audio here), not captions or metadata. assert.ok(move.frees!.bytes < 400_000); assert.ok(!kinds(r, "move-media").some((s) => s.slug === "relocated")); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("clip windows: older than the cutoff, a shared window frees nothing, a do-not-clean video's are targeted around", async () => { const { w, r } = await scanned(); try { const rows = kinds(r, "evict-clips").filter((s) => s.slug === "classic"); // v2 is do-not-clean and v3 recording, so the channel's eviction is per // video: v1's, naming its old window (v4's is shared). assert.equal(rows.length, 1); assert.equal(rows[0].id, "v1"); assert.deepEqual(rows[0].actions, [{ op: "evict-clips", body: { slug: "classic", id: "v1", windows: ["10.00-20.00"], olderThanDays: 30 } }]); assert.deepEqual(rows[0].hold, { slug: "classic", id: "v1" }); assert.equal(rows[0].targets?.length, 1); assert.ok(rows[0].frees!.bytes >= 60_000 && rows[0].frees!.bytes < 70_000); assert.ok(r.held.some((h) => /shared|hard link/i.test(h.why) && (h.bytes ?? 0) >= 90_000)); // Nothing held in clipsy: one eviction for the channel, its windows digested. const clipsy = kinds(r, "evict-clips").filter((s) => s.slug === "clipsy"); assert.equal(clipsy.length, 1); assert.deepEqual(clipsy[0].actions, [{ op: "evict-clips", body: { olderThanDays: 30, slug: "clipsy" } }]); assert.equal(clipsy[0].digest?.count, 2); // clipsrec's k2 (a young window) is recording: k1 alone, never the channel. assert.deepEqual(kinds(r, "evict-clips").filter((s) => s.slug === "clipsrec").map((s) => s.id), ["k1"]); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("partials and unstored containers: abandoned downloads via delete-file; a recording's and a do-not-clean video's left alone; a container is a link only", async () => { const { w, r } = await scanned(); try { const partials = kinds(r, "stale-partial"); // v3 is recording: nothing of it. v2 is do-not-clean. assert.deepEqual(partials, []); const stray = kinds(r, "unstored-container"); assert.deepEqual(stray.map((s) => s.id), []); assert.ok(r.held.some((h) => /recording/i.test(h.why))); assert.ok(r.held.some((h) => /do-not-clean/i.test(h.why))); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("partials and unstored containers once nothing holds them", async () => { const w = await world(); try { w.deps.liveRecordings = async () => []; const r = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps }); const partials = kinds(r, "stale-partial").filter((s) => s.id === "v3"); assert.deepEqual(partials.map((s) => s.file).sort(), ["audio.mp3.part", "audio.mp3.ytdl"]); assert.deepEqual(partials[0].actions![0].op, "delete-file"); assert.deepEqual(partials[0].hold, { slug: "classic", id: "v3" }); assert.equal(partials[0].targets?.length, 1); // v9 is not known to be on its platform: held, the partial may be the only copy. assert.equal(kinds(r, "stale-partial").filter((s) => s.id === "v9").length, 0); assert.ok(r.held.some((h) => /only copy/.test(h.why) && (h.bytes ?? 0) >= 70_000)); const stray = kinds(r, "unstored-container"); assert.deepEqual(stray.map((s) => s.id), ["v3"]); assert.equal(stray[0].actions, undefined); assert.equal(stray[0].link!.href, "/channels/classic/videos/v3"); assert.match(stray[0].loss, /only copy/); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("the store: compaction frees the platter later, a reviewed original now; refusals grouped; a pin's alternate kept", async () => { const { w, r } = await scanned(); try { const compact = kinds(r, "compact")[0]; assert.equal(compact.frees, null); assert.equal(compact.later!.disk, "platter"); assert.equal(compact.later!.low, 300_000); assert.equal(compact.later!.high, 400_000); assert.deepEqual(compact.actions, [{ op: "compact-saved-videos", body: { items: [{ slug: "classic", id: "v6" }] } }]); const drop = kinds(r, "drop-original")[0]; assert.equal(drop.frees!.disk, "platter"); assert.ok(drop.frees!.bytes >= 1_200_000); assert.deepEqual(drop.actions, [{ op: "drop-saved-alternate", body: { slug: "classic", id: "v5", file: "source-media.mp4", confirmOriginal: true } }]); const alts = kinds(r, "drop-alternate"); // v10 (do-not-clean), v11 (must-keep) and v12 (interrupted recording) are held; // v13's former original is a row with a link only. assert.deepEqual(alts.map((s) => `${s.id}/${s.file}`).sort(), ["v13/source-media.alt-480p-20261001000000.mp4", "v5/source-media.alt-480p-20261001000000.mp4"]); const former = alts.find((s) => s.id === "v13")!; assert.equal(former.actions, undefined); assert.equal(former.link?.href, "/channels/classic/videos/v13"); const v5alt = alts.find((s) => s.id === "v5")!; assert.deepEqual(v5alt.hold, { slug: "classic", id: "v5", store: true }); assert.equal(v5alt.targets?.length, 1); assert.ok(r.held.some((h) => /pinned/.test(h.why) && (h.bytes ?? 0) >= 500_000)); assert.ok(r.held.some((h) => /do-not-clean/.test(h.why) && (h.bytes ?? 0) >= 200_000)); assert.ok(r.held.some((h) => /must-keep/.test(h.why))); assert.ok(r.held.some((h) => /interrupted/.test(h.why))); assert.deepEqual(r.refused.map((g) => g.group), ["keep-latest (not deliberately stored)"]); const failed = kinds(r, "failed-encode")[0]; assert.deepEqual(failed.actions, [{ op: "kept-failed-encodes", body: { clear: { slug: "classic", id: "v6" } } }]); const landing = kinds(r, "reverify-landing")[0]; // It frees nothing unless it verifies. assert.equal(landing.frees, null); assert.equal(landing.later!.disk, "platter"); assert.ok(landing.later!.low >= 250_000); assert.deepEqual(landing.actions, [{ op: "live-recording-verify", body: { slug: "classic", id: "v7", startedAt: "2026-11-20T00:00:00Z" } }]); assert.ok(r.unmanaged.some((u) => /kept parts/i.test(u.what) && u.bytes === 33_000)); assert.ok(r.unmanaged.some((u) => /umtool/i.test(u.what) && u.command === "umtool prune --all")); assert.ok(r.unmanaged.some((u) => /builds/i.test(u.what))); assert.deepEqual(r.probes, { "/x": { size: 1, mtimeMs: 1, probe: null } }); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("a scan without the compaction pass carries the last one's rows and says when they are from", async () => { const w = await world(); try { const first = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps }); let asked = false; w.deps.compactionPlan = async () => { asked = true; throw new Error("not asked"); }; w.deps.now = () => new Date(NOW.getTime() + DAY); const second = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps, compaction: false, previous: first }); assert.equal(asked, false); assert.equal(second.compactionAt, first.compactionAt); assert.deepEqual(kinds(second, "compact").map((s) => s.id), ["v6"]); assert.deepEqual(second.refused, first.refused); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("the result stays small: thousands of clip windows are counted, fifty listed", async () => { const w = await world(); try { const base = path.join(w.paths.channelsDir, "classic", "data"); for (let i = 0; i < 300; i++) await put(path.join(base, `x${i}`, "clips", "1.00-2.00.mp4"), 1_000 + i, 60); const r = await scanSpace({ paths: w.paths, settings: w.settings, deps: w.deps }); // classic's 301 per-video rows, clipsy's one and clipsrec's one: 50 kept. const clipRows = kinds(r, "evict-clips"); assert.equal(clipRows.length, 50); const over = r.overflow.find((o) => o.kind === "evict-clips")!; assert.equal(over.count, 303 - 50); const file = await stat(path.join(w.paths.transcriptsDir, SPACE_SUGGESTIONS_FILENAME)); assert.ok(file.size < 200_000, `${file.size} bytes`); } finally { await rm(w.tmp, { recursive: true, force: true }); } }); test("the job kind: its own queue, no network, no channel guard (the scan guards each channel itself), a person starts it", async () => { const { getJobKind, kindIsNetwork, kindNeedsMedia, kindNeedsText } = await import("../jobs/jobKinds"); const meta = getJobKind("space-scan"); assert.equal(meta?.label, "Scan for space"); assert.equal(meta?.network, false); assert.equal(kindIsNetwork("space-scan"), false); assert.equal(kindNeedsMedia("space-scan"), false); assert.equal(kindNeedsText("space-scan"), false); assert.equal(meta?.resumeOnBoot, undefined); assert.equal(meta?.drainable, false); });