commit bd45e863ce8578f1fbde5fcc2853705822168dea
parent eeef3cf3613c36145d0f6d2fdd2e504670ff829f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 24 Nov 2026 16:31:11 -0500
space-suggestions: the space scan (controller/spaceScan.ts, the space-scan job kind)
Every disk the archive writes to, by device: allocated bytes, each inode once,
hard-linked files never counted as freed, tier links on their target's disk, an
unmounted or stalled location unknown and never empty. Suggestions through the
existing writers only (compress-text, cleanup, relocate, evict-clips,
delete-file, compact-saved-videos, drop-saved-alternate, kept-failed-encodes,
live-recording-verify); held and unmanaged bytes named with their owner. One
result file, transcripts/.space-suggestions.json; nothing else is written.
Never calls previewRelocation (it tiers a classic channel in place).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
4 files changed, 1688 insertions(+), 2 deletions(-)
diff --git a/common/controller/spaceScan.test.ts b/common/controller/spaceScan.test.ts
@@ -0,0 +1,479 @@
+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<void> {
+ 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<void> {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify(value));
+}
+
+function snapshot(buckets: Partial<ChannelSnapshot["buckets"]>, extra: Partial<ChannelSnapshot> = {}): 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 <tmp>/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<World> {
+ 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/<id>/ 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
+ // 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: "" }],
+ });
+ // 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<ChannelBrief> => ({
+ 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<ChannelSnapshot>,
+ )),
+ briefOf("relocated", snapshot({ transcribedWithAudio: ["r1"] })),
+ briefOf("moving", null),
+ briefOf("legacy", null),
+ briefOf("offline", 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,
+ ],
+ busy: () => null,
+ reportsRoot: reports,
+ };
+ return { tmp, paths, settings, deps, platter, storeDir };
+}
+
+async function listAll(dir: string): Promise<string[]> {
+ 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 {
+ 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" } }]);
+ 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);
+ } 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, so the channel's eviction is per video: v1's (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", olderThanDays: 30 } }]);
+ 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));
+ } 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");
+ 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");
+ assert.deepEqual(alts.map((s) => `${s.id}/${s.file}`), ["v5/source-media.alt-480p-20261001000000.mp4"]);
+ assert.ok(r.held.some((h) => /pinned/.test(h.why) && (h.bytes ?? 0) >= 500_000));
+ 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];
+ assert.equal(landing.frees!.disk, "platter");
+ assert.ok(landing.frees!.bytes >= 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 });
+ const clipRows = kinds(r, "evict-clips").filter((s) => s.slug === "classic");
+ assert.equal(clipRows.length, 50);
+ const over = r.overflow.find((o) => o.kind === "evict-clips")!;
+ assert.equal(over.count, 301 - 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);
+});
diff --git a/common/controller/spaceScan.ts b/common/controller/spaceScan.ts
@@ -0,0 +1,1193 @@
+// THE SPACE SCAN (lane space-suggestions; the `space-scan` job, `pnpm ops
+// space-scan`): every disk the archive writes to, how much of each is the
+// archive's, and what would free space on each — through the writers that
+// already exist. The result is ONE file, `transcripts/.space-suggestions.json`
+// (lib/spaceSuggestions.ts is its shape); /cleanup/space and `pnpm ops get
+// space-suggestions` read it and never compute.
+//
+// IT ONLY READS. No file is removed, moved, tiered or written but the result;
+// no platform is asked; previewRelocation is NOT called (for a classic channel
+// it tiers the media in place first, which writes).
+//
+// HOW BYTES ARE COUNTED. A disk is a filesystem (`st_dev`); a file counts as
+// its allocated bytes (`st_blocks × 512`, what df counts), each inode once. A
+// file with more than one hard link frees nothing when one name goes, so a
+// suggestion never counts it — it is "shared" (umtool's takes, record-live's
+// insurance links). A tier link counts on the disk its target is on. A
+// channel whose media drive is not mounted or not answering has its text
+// walked and its media UNKNOWN, never empty; a legacy channel, one mid-move or
+// inconsistent is not walked for suggestions and is named.
+//
+// THE COST. A walk of every video dir (an lstat per entry), the storage
+// locations' trees through the drive watchdog, the store's pointers, and —
+// unless `compaction: false` — one ffprobe per saved container, remembered
+// across scans by (path, size, mtime). It runs in the editor's process and
+// gives the event loop back every few milliseconds.
+
+import path from "node:path";
+import { lstat, readdir, realpath, stat, statfs } from "node:fs/promises";
+import type { Stats } from "node:fs";
+import { homedir } from "node:os";
+import type { Paths } from "../lib/paths";
+import type { SiteSettings } from "../lib/settings";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { StorageLocation, StorageSettings } from "../lib/storageLocations";
+import type { SavedVideoCompactionSettings } from "../lib/savedVideoCompaction";
+import { inspectChannelMedia, type ChannelMediaLocation } from "../lib/channelMedia";
+import { CLIPS_DIR, LIVE_CHAT_MEDIA_FILENAME, isKeptChatCapture, isScratchEntry, isTierable } from "../lib/mediaTier";
+import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles";
+import { isStoredCaptionName } from "../lib/storedText";
+import { DO_NOT_CLEAN_FILENAME } from "../lib/doNotClean";
+import { isDoNotClean } from "../lib/doNotClean-server";
+import { SAVED_VIDEO_POINTER_FILENAME, savedVideoRoot } from "../lib/savedVideo";
+import { formatBytes } from "../lib/format";
+import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
+import { isDriveNotAnswering, onDrive, stalledLocation } from "../lib/storageHealth";
+import { probeLocationMemo } from "../lib/storageVolumes";
+import { STORAGE_STATUS_LABEL } from "../views/storage";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import {
+ SPACE_CLIP_AGE_DAYS,
+ SPACE_PARTIAL_AGE_DAYS,
+ SPACE_SCAN_JOB_KIND,
+ SPACE_SCAN_QUEUE,
+ SPACE_SCAN_VERSION,
+ SPACE_SUGGESTIONS_FILENAME,
+ alternateDisposition,
+ capPerKind,
+ compressSaving,
+ moveFit,
+ refusalGroup,
+ type SpaceArchiveShare,
+ type SpaceDisk,
+ type SpaceDiskStatus,
+ type SpaceHeld,
+ type SpaceProbeMemo,
+ type SpaceRefused,
+ type SpaceScanResult,
+ type SpaceSuggestion,
+ type SpaceUnmanaged,
+} from "../lib/spaceSuggestions";
+import { listChannelBriefs, type ChannelBrief } from "./channels";
+import { CAPTION_RATIO_ESTIMATE, CHAT_RATIO_ESTIMATE } from "./compressText";
+import { listSavedVideos, type SavedVideoEntry } from "./savedVideoInventory";
+import {
+ listCompactionReview,
+ listKeptFailedEncodes,
+ planCompaction,
+ type CompactPlan,
+ type CompactionReviewRow,
+ type KeptFailedEncodeRow,
+} from "./compactSavedVideos";
+import { listLiveRecordings, type LiveRecordingView } from "./liveRecordings";
+import { ARCHIVE_ORG_STAGING_DIR } from "./archiveOrgDownload";
+import { probeCompactionSource, type SourceProbe } from "../lib/compactMedia-server";
+
+const DAY_MS = 86_400_000;
+const SLICE_MS = 15;
+const LSTAT_BATCH = 32;
+const EXAMPLES_PER_GROUP = 5;
+
+// 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
+// run's `.retire-<pid>` (possibly the only copy), a `.landed-kept` or
+// `.corrupt-kept` container, a tier hook's temp are somebody's kept bytes.
+const PARTIAL_RES: readonly RegExp[] = [
+ /\.part$/,
+ /\.ytdl$/,
+ /\.part-Frag\d+$/,
+ /\.part\.(good|testing)$/,
+ /\.stored\.part\.json$/,
+ /^\.syncthing\..*\.tmp$/,
+ /^audio\.tmp-\d+\./,
+ /\.temp\./,
+];
+
+export function isAbandonablePartial(name: string): boolean {
+ return PARTIAL_RES.some((re) => re.test(name));
+}
+
+export type SpaceScanSettings = Pick<SiteSettings, "minFreeDiskGB"> & {
+ storage: Pick<StorageSettings, "locations" | "defaultLocationId" | "savedVideosLocationId">;
+ savedVideoCompaction: SavedVideoCompactionSettings;
+};
+
+export type SpaceFsInfo = { dev: string; mountpoint: string; sizeBytes: number; freeBytes: number };
+
+export type SpaceScanDeps = {
+ now?: () => Date;
+ // The device a path is on (default: its st_dev). Tests name two.
+ deviceOf?: (absPath: string, st: Stats) => string;
+ filesystemOf?: (dir: string) => Promise<SpaceFsInfo | null>;
+ briefs?: () => Promise<ChannelBrief[]>;
+ inspect?: (slug: string, config: ChannelConfig) => Promise<ChannelMediaLocation>;
+ locationStatus?: (loc: StorageLocation) => Promise<{ status: SpaceDiskStatus; detail?: string }>;
+ savedVideos?: () => Promise<SavedVideoEntry[]>;
+ compactionPlan?: (memo: SpaceProbeMemo) => Promise<{ plan: CompactPlan; probes: SpaceProbeMemo }>;
+ compactionReview?: () => Promise<CompactionReviewRow[]>;
+ keptFailedEncodes?: () => Promise<KeptFailedEncodeRow[]>;
+ liveRecordings?: () => Promise<LiveRecordingView[]>;
+ busy?: (slug: string, id: string) => string | null;
+ isDoNotClean?: (videoDir: string) => Promise<boolean>;
+ // umtool's report projects (null: not measured).
+ reportsRoot?: string | null;
+};
+
+export type SpaceScanOptions = {
+ paths: Paths;
+ settings: SpaceScanSettings;
+ deps?: SpaceScanDeps;
+ // false: the ffprobe pass is not run; the last scan's compaction rows carry.
+ compaction?: boolean;
+ previous?: SpaceScanResult | null;
+ jobId?: string;
+ onLog?: (line: string) => void;
+ onProgress?: (done: number, of: number) => void;
+ signal?: AbortSignal;
+};
+
+export function spaceSuggestionsPath(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, SPACE_SUGGESTIONS_FILENAME);
+}
+
+// The last scan, or null (none yet, or a file of another version).
+export async function readSpaceSuggestions(paths: Pick<Paths, "transcriptsDir">): Promise<SpaceScanResult | null> {
+ const read = await readJsonFile(spaceSuggestionsPath(paths));
+ if (!read.ok || !read.value || typeof read.value !== "object") return null;
+ const v = read.value as SpaceScanResult;
+ return v.version === SPACE_SCAN_VERSION && typeof v.computedAt === "string" ? 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.
+export function defaultReportsRoot(env: NodeJS.ProcessEnv = process.env): string {
+ return path.resolve(env.SPACE_SCAN_REPORTS_DIR ?? env.REPORTS_DIR ?? path.join(homedir(), "reports"));
+}
+
+// --- the accounting ----------------------------------------------------------------
+
+function allocated(st: Stats): number {
+ return typeof st.blocks === "number" && st.blocks >= 0 ? st.blocks * 512 : st.size;
+}
+
+function emptyShare(): SpaceArchiveShare {
+ return { media: 0, text: 0, clips: 0, store: 0, playable: 0, builds: 0, reports: 0, other: 0 };
+}
+
+type Fact = { bytes: number; nlink: number; dev: string; mtimeMs: number };
+
+class Accounting {
+ private seen = new Set<string>();
+ readonly byDev = new Map<string, SpaceArchiveShare>();
+ readonly devDir = new Map<string, string>();
+ constructor(private readonly deviceOf: (p: string, st: Stats) => string) {}
+ fact(abs: string, st: Stats): Fact {
+ return { bytes: allocated(st), nlink: st.nlink, dev: this.deviceOf(abs, st), mtimeMs: st.mtimeMs };
+ }
+ // Counted once per inode; returns the fact either way.
+ add(abs: string, st: Stats, cat: keyof SpaceArchiveShare): Fact {
+ const f = this.fact(abs, st);
+ if (!this.devDir.has(f.dev)) this.devDir.set(f.dev, path.dirname(abs));
+ if (st.nlink > 1) {
+ const k = `${f.dev}:${st.ino}`;
+ if (this.seen.has(k)) return f;
+ this.seen.add(k);
+ }
+ let s = this.byDev.get(f.dev);
+ if (!s) this.byDev.set(f.dev, (s = emptyShare()));
+ s[cat] += f.bytes;
+ return f;
+ }
+ noteDir(abs: string, st: Stats): string {
+ const dev = this.deviceOf(abs, st);
+ if (!this.devDir.has(dev)) this.devDir.set(dev, abs);
+ return dev;
+ }
+}
+
+type Through = <T>(call: () => Promise<T>) => Promise<T>;
+const direct: Through = (call) => call();
+
+class Ticker {
+ private last = Date.now();
+ constructor(private readonly signal?: AbortSignal) {}
+ async tick(): Promise<void> {
+ if (this.signal?.aborted) throw new Error("cancelled");
+ if (Date.now() - this.last >= SLICE_MS) {
+ await new Promise((r) => setImmediate(r));
+ this.last = Date.now();
+ }
+ }
+}
+
+async function lstatAll(dir: string, names: string[], through: Through): Promise<Array<[string, Stats | null]>> {
+ const out: Array<[string, Stats | null]> = [];
+ for (let i = 0; i < names.length; i += LSTAT_BATCH) {
+ const batch = names.slice(i, i + LSTAT_BATCH);
+ const sts = await Promise.all(batch.map((n) => through(() => lstat(path.join(dir, n))).catch((e) => {
+ if (isDriveNotAnswering(e)) throw e;
+ return null;
+ })));
+ batch.forEach((n, j) => out.push([n, sts[j]]));
+ }
+ return out;
+}
+
+async function readNames(dir: string, through: Through): Promise<string[]> {
+ return through(() => readdir(dir)).catch((e) => {
+ if (isDriveNotAnswering(e)) throw e;
+ return [] as string[];
+ });
+}
+
+// Every regular file under `root` (symlinks never followed), to `onFile`.
+async function walkTree(
+ root: string,
+ onFile: (abs: string, st: Stats) => void,
+ o: { through?: Through; skip?: (abs: string) => boolean; ticker: Ticker },
+): Promise<void> {
+ const through = o.through ?? direct;
+ const stack = [root];
+ while (stack.length) {
+ const dir = stack.pop()!;
+ for (const [name, st] of await lstatAll(dir, await readNames(dir, through), through)) {
+ await o.ticker.tick();
+ if (!st) continue;
+ const abs = path.join(dir, name);
+ if (st.isDirectory()) {
+ if (!o.skip?.(abs)) stack.push(abs);
+ } else if (st.isFile()) onFile(abs, st);
+ }
+ }
+}
+
+// A file's tier for the archive's share: the big files (mediaTier's media and
+// scratch, a source container) against the text.
+function mediaByName(name: string): boolean {
+ return isTierable(name) || isSourceMediaFile(name) || isScratchEntry(name) || isKeptChatCapture(name);
+}
+
+function under(p: string, root: string): boolean {
+ const rel = path.relative(root, p);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
+async function defaultFilesystemOf(dir: string): Promise<SpaceFsInfo | null> {
+ try {
+ const st = await stat(dir);
+ let mount = path.resolve(dir);
+ for (;;) {
+ const parent = path.dirname(mount);
+ if (parent === mount) break;
+ const p = await stat(parent).catch(() => null);
+ if (!p || p.dev !== st.dev) break;
+ mount = parent;
+ }
+ const fs = await statfs(dir);
+ return { dev: String(st.dev), mountpoint: mount, sizeBytes: fs.blocks * fs.bsize, freeBytes: fs.bavail * fs.bsize };
+ } catch {
+ return null;
+ }
+}
+
+async function defaultLocationStatus(loc: StorageLocation, paths: Paths): Promise<{ status: SpaceDiskStatus; detail?: string }> {
+ if (stalledLocation(loc)) return { status: "not-answering", detail: "its drive is not answering" };
+ const probe = await probeLocationMemo(loc, paths);
+ if (probe.status === "available") return { status: "ok" };
+ if (probe.status === "stalled") return { status: "not-answering", detail: STORAGE_STATUS_LABEL[probe.status] };
+ return { status: "not-mounted", detail: STORAGE_STATUS_LABEL[probe.status] };
+}
+
+// --- per channel -----------------------------------------------------------------
+
+type PerDev = Map<string, { bytes: number; count: number; shared: number; sharedBytes: number }>;
+function bump(m: PerDev, f: Fact, count = 1): void {
+ let e = m.get(f.dev);
+ if (!e) m.set(f.dev, (e = { bytes: 0, count: 0, shared: 0, sharedBytes: 0 }));
+ if (f.nlink > 1) {
+ e.shared += count;
+ e.sharedBytes += f.bytes;
+ } else {
+ e.bytes += f.bytes;
+ e.count += count;
+ }
+}
+
+type ChannelTally = {
+ captions: PerDev;
+ chat: PerDev;
+ audio: PerDev;
+ extra: PerDev;
+ move: { bytes: number; files: number };
+ clips: { id: string; bytes: number; count: number; dev: string }[];
+ clipsDncVideos: number;
+ partials: { id: string; file: string; fact: Fact }[];
+ strays: { id: string; file: string; fact: Fact }[];
+};
+
+function newTally(): ChannelTally {
+ return {
+ captions: new Map(),
+ chat: new Map(),
+ audio: new Map(),
+ extra: new Map(),
+ move: { bytes: 0, files: 0 },
+ clips: [],
+ clipsDncVideos: 0,
+ partials: [],
+ strays: [],
+ };
+}
+
+type HeldTally = Map<string, SpaceHeld>;
+function hold(h: HeldTally, key: string, base: Omit<SpaceHeld, "key" | "bytes" | "count">, bytes: number | null, count = 1): void {
+ const e = h.get(key);
+ if (e) {
+ e.count += count;
+ if (bytes !== null) e.bytes = (e.bytes ?? 0) + bytes;
+ return;
+ }
+ h.set(key, { key, ...base, bytes, count });
+}
+
+type Unmanaged = Map<string, SpaceUnmanaged>;
+function unmanaged(u: Unmanaged, key: string, base: Omit<SpaceUnmanaged, "key" | "bytes" | "count">, bytes: number, count = 1): void {
+ const e = u.get(key);
+ if (e) {
+ e.bytes += bytes;
+ e.count = (e.count ?? 0) + count;
+ return;
+ }
+ u.set(key, { key, ...base, bytes, count });
+}
+
+// --- the scan ---------------------------------------------------------------------
+
+export async function scanSpace(opts: SpaceScanOptions): Promise<SpaceScanResult> {
+ const { paths, settings } = opts;
+ const deps = opts.deps ?? {};
+ const now = (deps.now ?? (() => new Date()))();
+ const started = Date.now();
+ const log = opts.onLog ?? (() => {});
+ const deviceOf = deps.deviceOf ?? ((_p: string, st: Stats) => String(st.dev));
+ const filesystemOf = deps.filesystemOf ?? defaultFilesystemOf;
+ const acc = new Accounting(deviceOf);
+ const ticker = new Ticker(opts.signal);
+ const held: HeldTally = new Map();
+ const um: Unmanaged = new Map();
+ const suggestions: SpaceSuggestion[] = [];
+ const notScanned: { slug: string; why: string }[] = [];
+ const floorBytes = Math.max(0, settings.minFreeDiskGB) * 1024 ** 3;
+ const locations = settings.storage.locations;
+ const busy = deps.busy ?? ((s: string, i: string) => {
+ // Lazily: the registry is the editor's, and a test names its own.
+ return busyReason?.(s, i) ?? null;
+ });
+ let busyReason: ((s: string, i: string) => string | null) | null = null;
+ if (!deps.busy) busyReason = (await import("./videoBusy")).videoPersistBusyReason;
+ const dnc = deps.isDoNotClean ?? isDoNotClean;
+
+ // THE DEVICES' IDS. The corpus disk is `corpus`; a location's disk takes the
+ // first location on it; anything else `fs-<dev>`.
+ const corpusStat = await stat(paths.channelsDir);
+ const corpusDev = acc.noteDir(paths.channelsDir, corpusStat);
+ const locState = new Map<string, { status: SpaceDiskStatus; detail?: string; dev?: string }>();
+ for (const loc of locations) {
+ const s = await (deps.locationStatus ? deps.locationStatus(loc) : defaultLocationStatus(loc, paths));
+ let dev: string | undefined;
+ if (s.status === "ok") {
+ try {
+ const st = await onDrive(loc, () => stat(loc.root));
+ dev = acc.noteDir(loc.root, st);
+ } catch (e) {
+ locState.set(loc.id, { status: isDriveNotAnswering(e) ? "not-answering" : "not-mounted", detail: (e as Error).message });
+ continue;
+ }
+ }
+ locState.set(loc.id, { ...s, ...(dev ? { dev } : {}) });
+ }
+ const diskIdOf = (dev: string): string => {
+ if (dev === corpusDev) return "corpus";
+ const loc = locations.find((l) => locState.get(l.id)?.dev === dev);
+ return loc ? loc.id : `fs-${dev}`;
+ };
+
+ // THE STORE'S REAL DIR, and the playable copies beside it.
+ const storeReal = await realpath(paths.savedVideosDir).catch(() => paths.savedVideosDir);
+ const playableRoot = path.join(path.dirname(storeReal), "playable");
+
+ // LIVE RECORDINGS FIRST: what is recording is never proposed.
+ const liveRows = await (deps.liveRecordings ?? (async () => (await listLiveRecordings(paths, { all: true })).rows))().catch(() => [] as LiveRecordingView[]);
+ const recording = new Set(liveRows.filter((r) => r.status === "recording").map((r) => `${r.slug}/${r.id}`));
+ for (const r of liveRows) {
+ if (r.status === "recording") {
+ hold(held, `recording:${r.slug}/${r.id}`, { what: `${r.slug}/${r.id}`, disk: null, why: "a live recording is running: nothing of it is proposed", link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Video page" } }, null, 1);
+ }
+ }
+
+ // --- the channels -------------------------------------------------------------
+ const briefs = await (deps.briefs ?? (() => listChannelBriefs(paths)))();
+ const inspect = deps.inspect ?? ((slug: string, config: ChannelConfig) => inspectChannelMedia(paths, slug, config, { fresh: true }));
+ const moveCandidates: { slug: string; bytes: number; files: number }[] = [];
+ const configOf = new Map(briefs.map((b) => [b.slug, b.config]));
+ let done = 0;
+ for (const brief of briefs) {
+ opts.onProgress?.(done, briefs.length);
+ done += 1;
+ const { slug, config } = brief;
+ const channelDir = path.join(paths.channelsDir, slug);
+ const loc = await inspect(slug, config);
+ if (loc.status === "legacy" || loc.status === "in-transition" || loc.status === "inconsistent") {
+ notScanned.push({ slug, why: loc.detail ?? loc.status });
+ if (loc.status === "in-transition") {
+ hold(held, `moving:${slug}`, { what: slug, disk: null, why: `a relocation is in flight: ${loc.detail ?? "its marker is present"}`, link: { href: `/channels/${slug}`, label: "Storage panel" } }, null, 1);
+ }
+ // Its corpus-disk bytes still count as the archive's (never following a link).
+ if (loc.text.readable || loc.status !== "legacy") {
+ await walkTree(channelDir, (abs, st) => acc.add(abs, st, mediaByName(path.basename(abs)) ? "media" : "text"), { ticker }).catch(() => {});
+ }
+ continue;
+ }
+ const mediaReadable = loc.status === "ok" || loc.status === "in-place";
+ if (!mediaReadable) {
+ hold(held, `media-unknown:${slug}`, { what: `${slug}: its media`, disk: null, why: `${loc.detail ?? loc.status}: its media is unknown here, not empty`, link: { href: "/storage", label: "Storage" } }, null, 1);
+ }
+ const through: Through = loc.relocated && loc.target ? (call) => onDrive(loc.target!, call) : direct;
+ const tally = newTally();
+ const buckets = brief.snapshot?.buckets;
+ const cleanIds = new Set(buckets?.transcribedWithAudio ?? []);
+ const extraIds = new Set(buckets?.multipleAudioFormats ?? []);
+ const target = config.audioFormat ? `audio.${config.audioFormat}` : null;
+ const inPlace = loc.status === "in-place";
+ try {
+ // The channel dir's own entries; `media/` a real dir is the media tier in place.
+ for (const [name, st] of await lstatAll(channelDir, await readNames(channelDir, direct), direct)) {
+ if (!st || name === "data") continue;
+ const abs = path.join(channelDir, name);
+ if (st.isDirectory()) {
+ await walkTree(abs, (a, s) => {
+ acc.add(a, s, name === "media" ? "media" : "text");
+ if (name === "media" && inPlace && isTierable(path.basename(a)) && s.nlink === 1) {
+ tally.move.bytes += allocated(s);
+ tally.move.files += 1;
+ }
+ }, { ticker });
+ } else if (st.isFile()) acc.add(abs, st, "text");
+ }
+ const dataDir = path.join(channelDir, "data");
+ for (const id of await readNames(dataDir, direct)) {
+ await ticker.tick();
+ const dir = path.join(dataDir, id);
+ const dst = await lstat(dir).catch(() => null);
+ if (!dst?.isDirectory()) continue;
+ await scanVideo({ slug, id, dir, through, mediaReadable, inPlace, cleanIds, extraIds, target, tally });
+ }
+ } catch (e) {
+ if (!isDriveNotAnswering(e)) throw e;
+ hold(held, `media-unknown:${slug}`, { what: `${slug}: its media`, disk: null, why: `${(e as Error).message}: the rest of its media is unknown here`, link: { href: "/storage", label: "Storage" } }, null, 1);
+ }
+ channelSuggestions(slug, brief, tally);
+ if (inPlace && tally.move.bytes > 0) moveCandidates.push({ slug, bytes: tally.move.bytes, files: tally.move.files });
+ }
+ opts.onProgress?.(briefs.length, briefs.length);
+
+ async function scanVideo(v: {
+ slug: string;
+ id: string;
+ dir: string;
+ through: Through;
+ mediaReadable: boolean;
+ inPlace: boolean;
+ cleanIds: Set<string>;
+ extraIds: Set<string>;
+ target: string | null;
+ tally: ChannelTally;
+ }): Promise<void> {
+ const { slug, id, dir, tally } = v;
+ const names = await readNames(dir, direct);
+ const set = new Set(names);
+ const isRecording = recording.has(`${slug}/${id}`);
+ let dncMemo: boolean | null = null;
+ const isDnc = async () => (dncMemo ??= set.has(DO_NOT_CLEAN_FILENAME) ? await dnc(dir) : false);
+ const hasPointer = set.has(SAVED_VIDEO_POINTER_FILENAME);
+ const audio: { name: string; fact: Fact }[] = [];
+ let clipOld = 0;
+ let clipOldCount = 0;
+ let clipDev = corpusDev;
+ for (const [name, st] of await lstatAll(dir, names, direct)) {
+ await ticker.tick();
+ if (!st) continue;
+ const abs = path.join(dir, name);
+ if (st.isSymbolicLink()) {
+ if (!v.mediaReadable || !isTierable(name)) continue;
+ const real = await v.through(() => realpath(abs)).catch((e) => {
+ if (isDriveNotAnswering(e)) throw e;
+ return null;
+ });
+ const tst = real ? await v.through(() => stat(real)).catch(() => null) : null;
+ if (!real || !tst?.isFile()) continue;
+ // Counted where the target is, by the walk of its own tree (a
+ // location's root, or `media/` in place) — here only for the row.
+ const f = acc.fact(real, tst);
+ if (isRealAudioFile(name)) audio.push({ name, fact: f });
+ else if (name === LIVE_CHAT_MEDIA_FILENAME) bump(tally.chat, f);
+ continue;
+ }
+ if (st.isDirectory()) {
+ if (name === CLIPS_DIR) {
+ await walkTree(abs, (a, s) => {
+ const f = acc.add(a, s, "clips");
+ clipDev = f.dev;
+ if (now.getTime() - f.mtimeMs < SPACE_CLIP_AGE_DAYS * DAY_MS) return;
+ if (f.nlink > 1) {
+ hold(held, "clips-shared", { what: "Clip windows linked into a umtool take", disk: diskIdOf(f.dev), why: "shared (another hard link holds the same bytes): evicting one frees nothing" }, f.bytes, 1);
+ return;
+ }
+ clipOld += f.bytes;
+ clipOldCount += 1;
+ }, { ticker });
+ } else if (name === ARCHIVE_ORG_STAGING_DIR) {
+ let bytes = 0;
+ let dev = corpusDev;
+ await walkTree(abs, (a, s) => {
+ const f = acc.add(a, s, "media");
+ bytes += f.nlink > 1 ? 0 : f.bytes;
+ dev = f.dev;
+ }, { ticker });
+ unmanaged(um, `archiveorg:${slug}`, { what: `${slug}: archive.org downloads left in staging`, disk: diskIdOf(dev), owner: "the archive.org download, which resumes from it and removes it when it finishes", link: { href: `/channels/${slug}`, label: "Channel page" } }, bytes, 1);
+ } else {
+ await walkTree(abs, (a, s) => acc.add(a, s, isScratchEntry(name) ? "media" : "text"), { ticker });
+ }
+ continue;
+ }
+ if (!st.isFile()) continue;
+ const f = acc.add(abs, st, mediaByName(name) ? "media" : "text");
+ if (isStoredCaptionName(name)) bump(tally.captions, f);
+ else if (name === LIVE_CHAT_MEDIA_FILENAME) bump(tally.chat, f);
+ else if (name === "metadata.info.json") unmanaged(um, `metadata:${f.dev}`, { what: "Video metadata (metadata.info.json)", disk: diskIdOf(f.dev), owner: "no writer compresses it yet" }, f.bytes);
+ else if (name === "transcript.json") unmanaged(um, `asr:${f.dev}`, { what: "Raw transcriber output (transcript.json)", disk: diskIdOf(f.dev), owner: "no writer compresses it yet" }, f.bytes);
+ else if (name === "transcript.cues.json") unmanaged(um, `cues:${f.dev}`, { what: "Cue files (transcript.cues.json)", disk: diskIdOf(f.dev), owner: "derived and rebuildable (build-cues); nothing removes them" }, f.bytes);
+ if (isRealAudioFile(name)) audio.push({ name, fact: f });
+ if (v.inPlace && (isTierable(name)) && f.nlink === 1) {
+ tally.move.bytes += f.bytes;
+ tally.move.files += 1;
+ }
+ if (isSourceMediaFile(name) && !hasPointer) {
+ if (isRecording) hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(f.dev), why: "a live recording is running" }, f.bytes, 1);
+ else if (await isDnc()) hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(f.dev), why: "do-not-clean: nothing of it is proposed" }, f.bytes, 1);
+ else if (!busy(slug, id)) tally.strays.push({ id, file: name, fact: f });
+ } else if (isAbandonablePartial(name) && now.getTime() - f.mtimeMs >= SPACE_PARTIAL_AGE_DAYS * DAY_MS) {
+ if (isRecording) hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(f.dev), why: "a live recording is running" }, f.bytes, 1);
+ else if (await isDnc()) hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(f.dev), why: "do-not-clean: nothing of it is proposed" }, f.bytes, 1);
+ else if (f.nlink === 1 && !busy(slug, id)) tally.partials.push({ id, file: name, fact: f });
+ }
+ }
+ if (clipOld > 0) {
+ if (await isDnc()) {
+ tally.clipsDncVideos += 1;
+ hold(held, "dnc-files", { what: "Files of do-not-clean videos", disk: diskIdOf(clipDev), why: "do-not-clean: nothing of it is proposed" }, clipOld, clipOldCount);
+ } else if (isRecording) {
+ hold(held, "recording-files", { what: "Files of a live recording", disk: diskIdOf(clipDev), why: "a live recording is running" }, clipOld, clipOldCount);
+ } else tally.clips.push({ id, bytes: clipOld, count: clipOldCount, dev: clipDev });
+ }
+ // The cleanup sweeps' targets: the report's buckets (already net of
+ // do-not-clean, keep-latest and the diarization hold), measured now.
+ if (audio.length && !isRecording && !(await isDnc())) {
+ 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);
+ }
+ }
+
+ function channelSuggestions(slug: string, brief: ChannelBrief, t: ChannelTally): void {
+ const name = brief.config.name ?? slug;
+ for (const [dev, e] of t.captions) {
+ if (e.bytes <= 0) continue;
+ suggestions.push({
+ key: `compress-captions:${slug}:${dev}`,
+ kind: "compress-captions",
+ slug,
+ title: `${name}: ${e.count.toLocaleString("en-US")} caption track(s), ${formatBytes(e.bytes)}`,
+ frees: { disk: diskIdOf(dev), bytes: compressSaving(e.bytes, CAPTION_RATIO_ESTIMATE) },
+ basis: "estimate",
+ basisText: `estimate: ${formatBytes(e.bytes)} of plain caption tracks × (1 − ${CAPTION_RATIO_ESTIMATE}), compress-text's own ratio; the job measures each file`,
+ loss: "nothing: each track is written compressed, read back and hashed before the plain one goes; compress-text restore puts them back",
+ actions: [{ op: "compress-text", body: { slugs: [slug], kinds: ["captions"] } }],
+ ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}),
+ });
+ }
+ for (const [dev, e] of t.chat) {
+ if (e.bytes <= 0) continue;
+ suggestions.push({
+ key: `compress-live-chat:${slug}:${dev}`,
+ kind: "compress-live-chat",
+ slug,
+ title: `${name}: ${e.count.toLocaleString("en-US")} raw live chat(s), ${formatBytes(e.bytes)}`,
+ frees: { disk: diskIdOf(dev), bytes: compressSaving(e.bytes, CHAT_RATIO_ESTIMATE) },
+ basis: "estimate",
+ basisText: `estimate: ${formatBytes(e.bytes)} of raw live chats × (1 − ${CHAT_RATIO_ESTIMATE}), compress-text's own ratio`,
+ loss: "nothing: each chat is written compressed and verified before the plain one goes; compress-text restore puts them back",
+ actions: [{ op: "compress-text", body: { slugs: [slug] } }],
+ ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}),
+ });
+ }
+ const report = brief.snapshot?.generatedAt ? ` (report of ${String(brief.snapshot.generatedAt).slice(0, 10)})` : "";
+ for (const [dev, e] of t.audio) {
+ if (e.bytes <= 0) continue;
+ const atRisk = brief.snapshot?.reclaimableAtRiskBytes ?? 0;
+ suggestions.push({
+ key: `clean-audio:${slug}:${dev}`,
+ kind: "clean-audio",
+ slug,
+ title: `${name}: audio kept beside ${e.count.toLocaleString("en-US")} transcribed video(s)`,
+ frees: { disk: diskIdOf(dev), bytes: e.bytes },
+ basis: "measured",
+ basisText: `measured now: the audio files of the report's transcribed-with-audio bucket${report}`,
+ loss:
+ "the audio; every transcript stays; re-fetchable while each video is on its platform" +
+ (atRisk > 0 ? ` (~${formatBytes(atRisk)} of it the pre-clean check may refuse: gone or needs sign-in)` : ""),
+ actions: [{ op: "cleanup", body: { slug, sweep: "transcribed" } }],
+ ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}),
+ });
+ }
+ for (const [dev, e] of t.extra) {
+ if (e.bytes <= 0) continue;
+ suggestions.push({
+ key: `clean-extra-formats:${slug}:${dev}`,
+ kind: "clean-extra-formats",
+ slug,
+ title: `${name}: ${e.count.toLocaleString("en-US")} audio file(s) beside the ${brief.config.audioFormat} copy`,
+ frees: { disk: diskIdOf(dev), bytes: e.bytes },
+ basis: "measured",
+ basisText: `measured now: the report's extra-formats bucket${report}`,
+ loss: `the extra formats; the ${brief.config.audioFormat} copy stays (overlaps the clean-audio row of this channel)`,
+ actions: [{ op: "cleanup", body: { slug, sweep: "extra-formats" } }],
+ });
+ }
+ // Clip windows: one eviction for the channel, or — when a do-not-clean
+ // video holds old windows — one per video, so its windows are not touched.
+ const clipRows = t.clips.length && t.clipsDncVideos === 0
+ ? [{ id: undefined as string | undefined, bytes: t.clips.reduce((n, c) => n + c.bytes, 0), count: t.clips.reduce((n, c) => n + c.count, 0), dev: t.clips[0].dev }]
+ : t.clips.map((c) => ({ ...c, id: c.id as string | undefined }));
+ for (const c of clipRows) {
+ suggestions.push({
+ key: `evict-clips:${slug}:${c.id ?? "*"}`,
+ kind: "evict-clips",
+ slug,
+ ...(c.id ? { id: c.id } : {}),
+ title: `${name}${c.id ? ` ${c.id}` : ""}: ${c.count.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`,
+ frees: { disk: diskIdOf(c.dev), bytes: c.bytes },
+ basis: "measured",
+ basisText: "measured now: windows not modified for the cutoff",
+ loss: "re-fetchable: an evicted window costs a fetch, not data. By age only: nothing here knows whether a umtool report still cites one",
+ actions: [{ op: "evict-clips", body: c.id ? { slug, id: c.id, olderThanDays: SPACE_CLIP_AGE_DAYS } : { olderThanDays: SPACE_CLIP_AGE_DAYS, slug } }],
+ });
+ }
+ for (const p of t.partials) {
+ suggestions.push({
+ key: `stale-partial:${slug}:${p.id}:${p.file}`,
+ kind: "stale-partial",
+ slug,
+ id: p.id,
+ file: p.file,
+ title: `${name} ${p.id}: ${p.file}, untouched ${Math.floor((now.getTime() - p.fact.mtimeMs) / DAY_MS)} days`,
+ frees: { disk: diskIdOf(p.fact.dev), bytes: p.fact.bytes },
+ basis: "measured",
+ basisText: "measured now",
+ loss: "an abandoned partial download; running the download again starts over",
+ actions: [{ op: "delete-file", body: { slug, id: p.id, file: p.file } }],
+ });
+ }
+ for (const s of t.strays) {
+ suggestions.push({
+ key: `unstored-container:${slug}:${s.id}:${s.file}`,
+ kind: "unstored-container",
+ slug,
+ id: s.id,
+ file: s.file,
+ title: `${name} ${s.id}: ${s.file} is not in the saved-video store`,
+ frees: { disk: diskIdOf(s.fact.dev), bytes: s.fact.bytes },
+ basis: "measured",
+ basisText: "measured now",
+ loss: "the only copy on this machine: decide on the video page (its Files list; Persist source video)",
+ link: { href: `/channels/${slug}/videos/${s.id}`, label: "Video page" },
+ });
+ }
+ }
+
+ // --- the rest of transcripts/, the locations, the store, builds, reports ------
+ const resultFile = spaceSuggestionsPath(paths);
+ let storeWalked = false;
+ for (const [name, st] of await lstatAll(paths.transcriptsDir, await readNames(paths.transcriptsDir, direct), direct)) {
+ if (!st) continue;
+ const abs = path.join(paths.transcriptsDir, name);
+ if (abs === paths.channelsDir || abs === resultFile) continue;
+ if (st.isDirectory()) {
+ if (under(storeReal, abs) && abs === storeReal) continue;
+ await walkTree(abs, (a, s) => acc.add(a, s, under(a, storeReal) ? "store" : "other"), { ticker });
+ if (under(storeReal, abs)) storeWalked = true;
+ } else if (st.isFile()) {
+ const f = acc.add(abs, st, "other");
+ if (name === "index.mdb") unmanaged(um, "index", { what: "The transcript index (index.mdb)", disk: diskIdOf(f.dev), owner: "rebuilt by build-index; it does not shrink on its own" }, f.bytes);
+ }
+ }
+ let playableBytes = 0;
+ let playableDev: string | null = null;
+ const walkedRoots: string[] = [];
+ for (const loc of [...locations].sort((a, b) => a.root.length - b.root.length)) {
+ const s = locState.get(loc.id);
+ if (!s?.dev) continue;
+ if (walkedRoots.some((r) => under(loc.root, r))) continue;
+ walkedRoots.push(loc.root);
+ try {
+ await walkTree(loc.root, (a, st) => {
+ const cat = under(a, storeReal) ? "store" : under(a, playableRoot) ? "playable" : "media";
+ const f = acc.add(a, st, cat);
+ if (cat === "playable") {
+ playableBytes += f.bytes;
+ playableDev = f.dev;
+ }
+ }, { ticker, through: (call) => onDrive(loc, call) });
+ } catch (e) {
+ if (!isDriveNotAnswering(e)) throw e;
+ locState.set(loc.id, { ...s, detail: `stopped answering during the scan: its figures are partial (${(e as Error).message})` });
+ }
+ }
+ if (!storeWalked && !walkedRoots.some((r) => under(storeReal, r))) {
+ await walkTree(storeReal, (a, st) => {
+ const f = acc.add(a, st, "store");
+ void f;
+ }, { ticker }).catch(() => {});
+ }
+ if (!walkedRoots.some((r) => under(playableRoot, r))) {
+ await walkTree(playableRoot, (a, st) => {
+ const f = acc.add(a, st, "playable");
+ playableBytes += f.bytes;
+ playableDev = f.dev;
+ }, { ticker }).catch(() => {});
+ }
+ if (playableBytes > 0) {
+ unmanaged(um, "playable", { what: "Browser-playable copies (prepare-playable)", disk: playableDev ? diskIdOf(playableDev) : null, owner: "rebuildable by prepare-playable; no remover exists" }, playableBytes);
+ }
+ const buildRoots = [paths.exportBuildsDir, paths.exportPublicDir, path.join(paths.monorepoRoot, "homepage", "out")].filter(Boolean);
+ for (const root of buildRoots) {
+ let bytes = 0;
+ let dev: string | null = null;
+ await walkTree(root, (a, st) => {
+ const f = acc.add(a, st, "builds");
+ bytes += f.bytes;
+ dev = f.dev;
+ }, { ticker }).catch(() => {});
+ if (bytes > 0) {
+ unmanaged(um, `builds:${root}`, { what: `Site builds (${path.relative(paths.monorepoRoot, root) || root})`, disk: dev ? diskIdOf(dev) : null, owner: "the publish stages; no pruner exists" }, bytes);
+ }
+ }
+ const reportsRoot = deps.reportsRoot === undefined ? defaultReportsRoot() : deps.reportsRoot;
+ if (reportsRoot) {
+ let bytes = 0;
+ let dev: string | null = null;
+ await walkTree(reportsRoot, (a, st) => {
+ const f = acc.add(a, st, "reports");
+ bytes += f.bytes;
+ dev = f.dev;
+ }, { ticker }).catch(() => {});
+ if (bytes > 0) {
+ unmanaged(um, "reports", { what: "umtool's report projects", disk: dev ? diskIdOf(dev) : null, owner: "umtool (its takes' work files, by policy); a dry run lists what it would prune, --yes prunes", command: "umtool prune --all" }, bytes);
+ }
+ }
+
+ // --- the disks ---------------------------------------------------------------------
+ const disks: SpaceDisk[] = [];
+ const devs = new Set<string>([...acc.byDev.keys(), corpusDev, ...[...locState.values()].map((s) => s.dev).filter((d): d is string => !!d)]);
+ const storeDev = await stat(storeReal).then((st) => deviceOf(storeReal, st), () => null);
+ for (const dev of devs) {
+ const dir = dev === corpusDev ? paths.channelsDir : acc.devDir.get(dev);
+ const onLoc = locations.filter((l) => locState.get(l.id)?.dev === dev);
+ const fs = dir ? await (onLoc.length ? onDrive(onLoc[0], () => filesystemOf(dir)).catch(() => null) : filesystemOf(dir)) : null;
+ const share = acc.byDev.get(dev) ?? emptyShare();
+ const roles: string[] = [];
+ if (dev === corpusDev) roles.push("corpus disk");
+ for (const l of onLoc) roles.push(`location ${l.label || l.id}`);
+ if (storeDev === dev) roles.push("saved-video store");
+ if (share.builds > 0) roles.push("site builds");
+ if (share.reports > 0) roles.push("umtool reports");
+ const partial = onLoc.map((l) => locState.get(l.id)?.detail).find(Boolean);
+ disks.push({
+ id: diskIdOf(dev),
+ label: dev === corpusDev ? "Corpus disk" : onLoc.length ? onLoc.map((l) => l.label || l.id).join(" + ") : fs?.mountpoint ?? `device ${dev}`,
+ mountpoint: fs?.mountpoint ?? null,
+ status: "ok",
+ ...(partial ? { detail: partial } : {}),
+ roles,
+ locationIds: onLoc.map((l) => l.id),
+ sizeBytes: fs?.sizeBytes ?? null,
+ freeBytes: fs?.freeBytes ?? null,
+ archive: share,
+ archiveBytes: Object.values(share).reduce((a, b) => a + b, 0),
+ });
+ }
+ for (const loc of locations) {
+ const s = locState.get(loc.id);
+ if (!s || s.dev) continue;
+ disks.push({
+ id: loc.id,
+ label: loc.label || loc.id,
+ mountpoint: loc.volume?.mountpoint ?? null,
+ status: s.status === "ok" ? "not-mounted" : s.status,
+ detail: `${s.detail ?? s.status}: not scanned; its channels' media is unknown here, not empty`,
+ roles: [`location ${loc.label || loc.id}`],
+ locationIds: [loc.id],
+ sizeBytes: null,
+ freeBytes: null,
+ archive: null,
+ archiveBytes: null,
+ });
+ }
+ const diskById = new Map(disks.map((d) => [d.id, d]));
+
+ // --- moves ---------------------------------------------------------------------------
+ const targetLoc =
+ [settings.storage.defaultLocationId, ...locations.map((l) => l.id)]
+ .map((id) => locations.find((l) => l.id === id))
+ .find((l) => l && locState.get(l.id)?.dev && locState.get(l.id)!.dev !== corpusDev) ?? null;
+ if (moveCandidates.length && !targetLoc) {
+ hold(held, "no-target", { what: "Channels whose media is on the corpus disk", disk: "corpus", why: "no storage location on another disk is mounted to move them to", link: { href: "/storage", label: "Storage" } }, moveCandidates.reduce((n, m) => n + m.bytes, 0), moveCandidates.length);
+ }
+ if (targetLoc) {
+ const tDisk = diskById.get(diskIdOf(locState.get(targetLoc.id)!.dev!));
+ let used = 0;
+ for (const m of moveCandidates.sort((a, b) => b.bytes - a.bytes)) {
+ const fit = moveFit(tDisk?.freeBytes === null || tDisk?.freeBytes === undefined ? null : tDisk.freeBytes - used, m.bytes, floorBytes);
+ if (fit.fits) used += m.bytes;
+ const name = configOf.get(m.slug)?.name ?? m.slug;
+ suggestions.push({
+ key: `move-media:${m.slug}`,
+ kind: "move-media",
+ slug: m.slug,
+ title: `${name}: ${m.files.toLocaleString("en-US")} media file(s) to ${targetLoc.label || targetLoc.id}`,
+ frees: { disk: "corpus", bytes: m.bytes },
+ fills: { disk: tDisk?.id ?? targetLoc.id, bytes: m.bytes, fits: fit.fits, freeAfter: fit.freeAfter },
+ basis: "measured",
+ basisText: "measured now: the media tier's files on the corpus disk (audio, raw live chat, kept chat captures)",
+ loss: "nothing: the media moves and the text stays on the corpus disk; relocate-back brings it back. A classic channel is first tiered in place (same-disk renames)",
+ actions: [{ op: "relocate", body: { slugs: [m.slug], locationId: targetLoc.id } }],
+ ...(fit.fits ? {} : { disabled: `does not fit on ${targetLoc.label || targetLoc.id} with its floor kept (after the bigger moves above): free space there first` }),
+ });
+ }
+ }
+ if (storeDev === corpusDev && targetLoc) {
+ const share = acc.byDev.get(corpusDev)?.store ?? 0;
+ if (share > 0) {
+ suggestions.push({
+ key: "move-store",
+ kind: "move-store",
+ title: `The saved-video store to ${targetLoc.label || targetLoc.id}`,
+ frees: { disk: "corpus", bytes: share },
+ fills: { disk: diskIdOf(locState.get(targetLoc.id)!.dev!), bytes: share, ...moveFit(diskById.get(diskIdOf(locState.get(targetLoc.id)!.dev!))?.freeBytes ?? null, share, floorBytes) },
+ basis: "measured",
+ basisText: "measured now: the store's tree",
+ loss: "nothing: the store moves whole and is verified before the swap; it can be moved back",
+ link: { href: "/storage", label: "Storage: the store's card" },
+ });
+ }
+ }
+
+ // --- the store ------------------------------------------------------------------------
+ const entries = await (deps.savedVideos ?? (() => listSavedVideos({ paths, notAnswering: [] })))().catch(() => [] as SavedVideoEntry[]);
+ const entryOf = new Map(entries.map((e) => [`${e.slug}/${e.videoId}`, e]));
+ const statFile = async (file: string): Promise<Fact | null> => {
+ const st = await stat(file).catch(() => null);
+ return st?.isFile() ? acc.fact(file, st) : null;
+ };
+ for (const e of entries) {
+ const name = configOf.get(e.slug)?.name ?? e.slug;
+ for (const alt of e.pointer.alternates ?? []) {
+ const disp = alternateDisposition(e.pointer, alt);
+ if (alt.keptAs === "original") continue;
+ const f = await statFile(path.join(e.pointer.dir, alt.file));
+ if (!f) continue;
+ if (!disp.offer) {
+ hold(held, `alt:${disp.why}`, { what: "Saved alternates", disk: diskIdOf(f.dev), why: disp.why, link: { href: "/saved-videos", label: "Saved videos" } }, f.bytes, 1);
+ continue;
+ }
+ suggestions.push({
+ key: `drop-alternate:${e.slug}:${e.videoId}:${alt.file}`,
+ kind: "drop-alternate",
+ slug: e.slug,
+ id: e.videoId,
+ file: alt.file,
+ title: `${name} ${e.videoId}: ${alt.file}${alt.height ? ` (${alt.height}p)` : ""} beside the active copy`,
+ frees: { disk: diskIdOf(f.dev), bytes: f.nlink > 1 ? 0 : f.bytes },
+ basis: "measured",
+ basisText: "measured now",
+ loss: alt.keptAs === "former-original" ? "a former original: a copy of the source bytes no longer active" : "the alternate copy; the active copy stays",
+ actions: [{ op: "drop-saved-alternate", body: { slug: e.slug, id: e.videoId, file: alt.file, ...(disp.confirmFormerOriginal ? { confirmFormerOriginal: true } : {}) } }],
+ ...(disp.confirmFormerOriginal ? { tick: "I mean the former original" } : {}),
+ ...(f.nlink > 1 ? { shared: { files: 1, bytes: f.bytes } } : {}),
+ link: { href: `/channels/${e.slug}/videos/${e.videoId}`, label: "Video page" },
+ });
+ }
+ }
+
+ // Compaction (ruling 2: it follows the compaction rules, which pick the
+ // deliberately stored — pinned — videos and keep the original).
+ let compactionAt: string | null = null;
+ let probes: SpaceProbeMemo = opts.previous?.probes ?? {};
+ let refused: SpaceRefused[] = [];
+ if (opts.compaction === false && opts.previous) {
+ compactionAt = opts.previous.compactionAt;
+ refused = opts.previous.refused;
+ suggestions.push(...opts.previous.suggestions.filter((s) => s.kind === "compact"));
+ } else if (opts.compaction !== false) {
+ log("Planning compaction (one ffprobe per saved container not seen unchanged before) …");
+ const planned = await (deps.compactionPlan ?? ((memo: SpaceProbeMemo) => defaultCompactionPlan(paths, settings.savedVideoCompaction, memo)))(probes);
+ probes = planned.probes;
+ compactionAt = now.toISOString();
+ const groups = new Map<string, SpaceRefused>();
+ for (const item of planned.plan.items) {
+ const e = entryOf.get(`${item.slug}/${item.id}`);
+ const f = e ? await statFile(path.join(e.pointer.dir, e.pointer.file)) : null;
+ const bytes = f?.bytes ?? item.source?.bytes ?? e?.pointer.bytes ?? 0;
+ const disk = f ? diskIdOf(f.dev) : e ? diskIdOf(storeDev ?? corpusDev) : null;
+ if (item.compact && item.estimate) {
+ const src = item.source?.bytes ?? bytes;
+ const name = configOf.get(item.slug)?.name ?? item.slug;
+ const when = settings.savedVideoCompaction.dropOriginal === "after-verify"
+ ? "when its original is dropped: after the verify if it is on its platform, else after a person's review"
+ : "when its original is dropped (dropOriginal: keep): review it, then drop it here";
+ suggestions.push({
+ key: `compact:${item.slug}:${item.id}`,
+ kind: "compact",
+ slug: item.slug,
+ id: item.id,
+ title: `${name} ${item.id}: ${formatBytes(src)}${item.source?.height ? ` ${item.source.height}p` : ""}${item.source?.videoMbps ? ` ${item.source.videoMbps.toFixed(1)} Mbit/s` : ""} → AV1`,
+ frees: null,
+ later: { disk: disk ?? "corpus", low: Math.max(0, src - item.estimate.bytes[1]), high: Math.max(0, src - item.estimate.bytes[0]), when },
+ basis: "estimate",
+ basisText: `estimate: the measured crf share for its bitrate (${item.estimate.share.toFixed(2)}) ± 20 %; ${item.estimate.hours[0].toFixed(1)}–${item.estimate.hours[1].toFixed(1)} h of encoding`,
+ loss: "nothing at this step: the original is kept beside the verified copy",
+ actions: [{ op: "compact-saved-videos", body: { items: [{ slug: item.slug, id: item.id }] } }],
+ detail: item.line,
+ link: { href: `/channels/${item.slug}/videos/${item.id}`, label: "Video page" },
+ });
+ continue;
+ }
+ if (item.compact) continue;
+ const group = refusalGroup(item.reason ?? "");
+ if (!group) continue;
+ let g = groups.get(group);
+ if (!g) groups.set(group, (g = { group, count: 0, bytes: 0, disk, examples: [] }));
+ g.count += 1;
+ g.bytes += bytes;
+ g.examples.push({ slug: item.slug, id: item.id, bytes, reason: item.reason ?? "" });
+ }
+ refused = [...groups.values()].map((g) => ({ ...g, examples: g.examples.sort((a, b) => b.bytes - a.bytes).slice(0, EXAMPLES_PER_GROUP) })).sort((a, b) => b.bytes - a.bytes);
+ }
+
+ // Compacted originals: where the space actually comes back.
+ const review = await (deps.compactionReview ?? (() => listCompactionReview({ paths, settings: settings.savedVideoCompaction, notAnswering: [] })))().catch(() => [] as CompactionReviewRow[]);
+ for (const r of review) {
+ const e = entryOf.get(`${r.slug}/${r.id}`);
+ const dir = e?.pointer.dir;
+ const name = configOf.get(r.slug)?.name ?? r.slug;
+ const files: { file: string; interrupted: boolean }[] = [];
+ if (r.original && r.state !== "dropped") files.push({ file: r.original.file, interrupted: false });
+ if (r.leftover) files.push({ file: path.basename(r.leftover), interrupted: true });
+ for (const { file, interrupted } of files) {
+ const f = dir ? await statFile(path.join(dir, file)) : r.leftover ? await statFile(r.leftover) : null;
+ if (!f) continue;
+ const awaiting = r.state === "awaiting-review" && !interrupted;
+ suggestions.push({
+ key: `drop-original:${r.slug}:${r.id}:${file}`,
+ kind: "drop-original",
+ slug: r.slug,
+ id: r.id,
+ file,
+ title: `${name} ${r.id}: ${interrupted ? "an interrupted drop of " : ""}the original (${r.state.replace("-", " ")})`,
+ frees: { disk: diskIdOf(f.dev), bytes: f.nlink > 1 ? 0 : f.bytes },
+ basis: "measured",
+ basisText: "measured now",
+ loss: `the original source bytes; the compacted copy (its checks passed) stays active; re-fetchable only while the video is on its platform (${r.presence || (r.onPlatform ? "on its platform" : "not known to be")})`,
+ ...(awaiting
+ ? { link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Review the compacted copy first (watch it)" } }
+ : {
+ actions: [{ op: "drop-saved-alternate", body: { slug: r.slug, id: r.id, file, confirmOriginal: true } }],
+ link: { href: `/channels/${r.slug}/videos/${r.id}`, label: "Video page" },
+ }),
+ ...(f.nlink > 1 ? { shared: { files: 1, bytes: f.bytes } } : {}),
+ });
+ }
+ }
+ const failed = await (deps.keptFailedEncodes ?? (() => listKeptFailedEncodes(paths)))().catch(() => [] as KeptFailedEncodeRow[]);
+ for (const r of failed) {
+ const bytes = r.kept?.bytes ?? r.bytes ?? 0;
+ if (bytes <= 0) continue;
+ const dst = await stat(r.dir).catch(() => null);
+ const dev = dst ? deviceOf(r.dir, dst) : storeDev ?? corpusDev;
+ suggestions.push({
+ key: `failed-encode:${r.slug}:${r.id}`,
+ kind: "failed-encode",
+ slug: r.slug,
+ id: r.id,
+ title: `${configOf.get(r.slug)?.name ?? r.slug} ${r.id}: ${r.orphaned ? "an orphaned compaction scratch" : `a failed encode (${r.reason})`}`,
+ frees: { disk: diskIdOf(dev), bytes },
+ basis: "measured",
+ basisText: r.kept ? "as the compaction recorded it" : "measured now",
+ loss: "a re-verify's head start: compacting it again encodes it again",
+ actions: [{ op: "kept-failed-encodes", body: { clear: { slug: r.slug, id: r.id } } }],
+ });
+ }
+ // Live landings whose check failed or never ran: Verify again removes the
+ // stream files only if the landed file checks out against them.
+ let keptPartsBytes = 0;
+ let keptPartsCount = 0;
+ for (const r of liveRows) {
+ for (const k of r.keptParts ?? []) {
+ keptPartsBytes += k.bytes;
+ keptPartsCount += 1;
+ }
+ const v = r.verification;
+ if (r.status === "recording" || !v || v.state === "verified" || !v.against?.length) continue;
+ const staging = path.join(await realpath(savedVideoRoot(paths, configOf.get(r.slug) ?? null)).catch(() => savedVideoRoot(paths, configOf.get(r.slug) ?? null)), r.slug);
+ let bytes = 0;
+ let dev: string | null = null;
+ for (const n of v.against) {
+ const f = await statFile(path.join(staging, n));
+ if (!f) continue;
+ if (f.nlink === 1) bytes += f.bytes;
+ dev = f.dev;
+ }
+ if (!dev) continue;
+ suggestions.push({
+ key: `reverify-landing:${r.slug}:${r.id}:${r.startedAt}`,
+ kind: "reverify-landing",
+ slug: r.slug,
+ id: r.id,
+ title: `${configOf.get(r.slug)?.name ?? r.slug} ${r.id}: a landing whose check ${v.state === "failed" ? "failed" : "never ran"} (${v.against.length} stream file(s))`,
+ frees: { disk: diskIdOf(dev), bytes },
+ basis: "measured",
+ basisText: "measured now: the stream files the landing is checked against",
+ loss: "nothing unless it verifies: the stream files go only when the landed file checks out against them and the stream is done",
+ actions: [{ op: "live-recording-verify", body: { slug: r.slug, id: r.id, startedAt: r.startedAt } }],
+ });
+ }
+ if (keptPartsBytes > 0) {
+ unmanaged(um, "kept-parts", { what: "Live recordings' kept parts", disk: storeDev ? diskIdOf(storeDev) : null, owner: "a person decides; nothing removes them (pnpm ops get live-recordings)" }, keptPartsBytes, keptPartsCount);
+ }
+ // Audio the cleanup sweeps hold, from the reports: decided on /cleanup.
+ const heldAudio = { noTranscript: 0, keepLatest: 0, doNotClean: 0, awaitingDiarization: 0 };
+ for (const b of briefs) {
+ const h = b.snapshot?.heldAudioBytes;
+ if (!h) continue;
+ heldAudio.noTranscript += h.noTranscript;
+ heldAudio.keepLatest += h.keepLatest;
+ heldAudio.doNotClean += h.doNotClean;
+ heldAudio.awaitingDiarization += h.awaitingDiarization;
+ }
+ const heldAudioWhy: Record<keyof typeof heldAudio, string> = {
+ noTranscript: "no transcript yet: transcribing releases it",
+ keepLatest: "the channels' keep-latest window",
+ doNotClean: "do-not-clean",
+ awaitingDiarization: "waiting for the Speakers lane",
+ };
+ for (const [k, bytes] of Object.entries(heldAudio) as [keyof typeof heldAudio, number][]) {
+ if (bytes > 0) hold(held, `audio:${k}`, { what: "Audio the cleanup sweeps hold (from the reports)", disk: null, why: heldAudioWhy[k], link: { href: "/cleanup", label: "Audio cleanup" } }, bytes, 0);
+ }
+
+ const { kept, overflow } = capPerKind(suggestions);
+ const overflowLink: Partial<Record<SpaceSuggestion["kind"], { href: string; label: string }>> = {
+ compact: { href: "/saved-videos", label: "Saved videos" },
+ "drop-original": { href: "/saved-videos", label: "Saved videos" },
+ "drop-alternate": { href: "/saved-videos", label: "Saved videos" },
+ "evict-clips": { href: "/storage", label: "Storage: clip windows" },
+ "clean-audio": { href: "/cleanup", label: "Audio cleanup" },
+ };
+ const result: SpaceScanResult = {
+ version: SPACE_SCAN_VERSION,
+ computedAt: now.toISOString(),
+ tookMs: Date.now() - started,
+ ...(opts.jobId ? { jobId: opts.jobId } : {}),
+ floorBytes,
+ disks,
+ suggestions: kept,
+ overflow: overflow.map((o) => ({ ...o, ...(overflowLink[o.kind] ? { link: overflowLink[o.kind] } : {}) })),
+ held: [...held.values()].sort((a, b) => (b.bytes ?? 0) - (a.bytes ?? 0)),
+ refused,
+ unmanaged: [...um.values()].sort((a, b) => b.bytes - a.bytes),
+ notScanned,
+ compactionAt,
+ probes,
+ };
+ await writeJsonAtomic(resultFile, result);
+ return result;
+}
+
+// The selector's plan, each ffprobe remembered by (path, size, mtime).
+async function defaultCompactionPlan(
+ paths: Paths,
+ settings: SavedVideoCompactionSettings,
+ memo: SpaceProbeMemo,
+): Promise<{ plan: CompactPlan; probes: SpaceProbeMemo }> {
+ const fresh: SpaceProbeMemo = {};
+ const plan = await planCompaction({
+ paths,
+ settings,
+ select: true,
+ deps: {
+ probe: async (file) => {
+ const st = await stat(file).catch(() => null);
+ const hit = memo[file];
+ if (st && hit && hit.size === st.size && hit.mtimeMs === st.mtimeMs) {
+ fresh[file] = hit;
+ return hit.probe as SourceProbe | null;
+ }
+ const p = await probeCompactionSource(paths.ffprobeBin, file);
+ if (st) fresh[file] = { size: st.size, mtimeMs: st.mtimeMs, probe: p };
+ return p;
+ },
+ },
+ });
+ return { plan, probes: fresh };
+}
+
+// --- the job ---------------------------------------------------------------------
+
+export const SPACE_SCAN_BODY_KEYS = ["compaction"] as const;
+
+export async function enqueueSpaceScan(opts: {
+ paths: Paths;
+ settings: () => SpaceScanSettings;
+ compaction?: boolean;
+ onDone?: () => void;
+}): Promise<StreamActionResult> {
+ return runManagedFunction({
+ kind: SPACE_SCAN_JOB_KIND,
+ queueKey: SPACE_SCAN_QUEUE,
+ paths: opts.paths,
+ network: false,
+ fn: async (onLog, signal, setProgress, ctx) => {
+ onLog("Scanning the disks the archive writes to. Nothing is removed, moved or fetched; the result is .space-suggestions.json.");
+ const previous = await readSpaceSuggestions(opts.paths);
+ const result = await scanSpace({
+ paths: opts.paths,
+ settings: opts.settings(),
+ compaction: opts.compaction !== false,
+ previous,
+ jobId: ctx.jobId,
+ onLog,
+ signal,
+ onProgress: (done, of) => setProgress({ metric: "channels", initial: 0, target: of, current: done }),
+ });
+ for (const d of result.disks) {
+ onLog(
+ `${d.label} (${d.id}): ${d.status === "ok" ? `${d.freeBytes === null ? "?" : formatBytes(d.freeBytes)} free of ${d.sizeBytes === null ? "?" : formatBytes(d.sizeBytes)}, the archive's ${formatBytes(d.archiveBytes ?? 0)}` : d.detail ?? d.status}`,
+ );
+ }
+ onLog(
+ `${result.suggestions.length} suggestion(s)${result.overflow.length ? ` (+${result.overflow.reduce((n, o) => n + o.count, 0)} more counted)` : ""}, ` +
+ `${result.held.length} held, ${result.notScanned.length} channel(s) not scanned, in ${Math.round(result.tookMs / 1000)} s.`,
+ );
+ opts.onDone?.();
+ },
+ });
+}
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -1477,6 +1477,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsText: true,
},
+ // THE SPACE SCAN (lane space-suggestions, controller/spaceScan.ts; `pnpm ops
+ // space-scan`, /cleanup/space's Refresh): every disk the archive writes to
+ // and what would free space on each, into transcripts/.space-suggestions.json.
+ // It only reads. Corpus-wide, so no channelSlug and neither guard: it asks
+ // inspectChannelMedia of each channel itself and names the ones it skips.
+ // Its own machine-wide queue, one at a time. Not replayable: Refresh again.
+ "space-scan": {
+ kind: "space-scan",
+ label: "Scan for space",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ network: false,
+ },
// The audio audit (release 31, lane A): a tolerant decode of each audio
// file a channel holds, its verdict in `audio-integrity.json` beside it —
// `pnpm ops audio-audit`, one job per channel on `audio-audit`. OPENS EVERY
diff --git a/common/lib/spaceSuggestions.ts b/common/lib/spaceSuggestions.ts
@@ -323,8 +323,8 @@ export function refusalGroup(reason: string): string | null {
// compaction rules (drop-original rows); a former original needs the person's
// own word (`confirmFormerOriginal`).
export function alternateDisposition(
- pointer: Pick<SavedVideoPointer, "keepReason">,
- alt: Pick<SavedVideoAlternate, "keptAs">,
+ pointer: SavedVideoPointer,
+ alt: SavedVideoAlternate,
): { offer: true; confirmFormerOriginal?: true } | { offer: false; why: string } {
if (alt.keptAs === "original") return { offer: false, why: "an original a compacted copy was made from (see Drop compacted originals)" };
if (alt.keptAs === "proxy") return { offer: false, why: "kept on purpose as the lower-quality proxy" };