Archilyzer · Source

archilyzer

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

commit 48eef435363ba21d0e047f121559d0729577a723
parent b1cbc3b4906d263db85a9401557886d02f7cf92a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 24 Nov 2026 20:31:29 -0500

Merge lane/space-suggestions: /cleanup/space suggests what frees space, disk by disk

A space-scan job (started by a person, read-only, one at a time) measures every disk the archive writes to and writes transcripts/.space-suggestions.json. The page ranks suggestions by bytes freed on the disk that needs it most: caption and chat compression, audio sweeps, moving a channel's media to a storage location, clip-window eviction, compaction and compacted originals, saved alternates, failed encodes, partials and landings to verify again. Each says which disk it frees (and fills), how much, how that was measured and what is lost. A button runs only an existing writer, and only after re-checking at the click: a scan under 24 h old of this version, the same size, mtime and single link on every target, and no hold (do-not-clean, mustKeep, a pin, an unfinished live recording, a job, a relocation). Unreadable marks hold. Hard-linked files never count as freed. pnpm ops space-scan and get space-suggestions give agents the same list.

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

Diffstat:
MCOMMANDS.md | 11+++++++++++
MENVIRONMENT.md | 3++-
MOPERATING.md | 26++++++++++++++++++++++++++
Acommon/controller/spaceHold.test.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/spaceHold.ts | 342+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/spaceScan.test.ts | 542+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/spaceScan.ts | 1366+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 14++++++++++++++
Mcommon/lib/envVars.ts | 3++-
Acommon/lib/spaceSuggestions.test.ts | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/spaceSuggestions.ts | 414+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 27+++++++++++++++++++++++++++
Aeditor/app/api/ops/space-scan/route.test.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/space-scan/route.ts | 31+++++++++++++++++++++++++++++++
Aeditor/app/api/ops/space-suggestions/route.test.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/space-suggestions/route.ts | 40++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cleanup/components/CleanupTabs.tsx | 24++++++++++++++++++++++++
Meditor/app/cleanup/page.tsx | 14++++++++++++++
Aeditor/app/cleanup/space/actions.ts | 27+++++++++++++++++++++++++++
Aeditor/app/cleanup/space/components/SpaceRefresh.tsx | 31+++++++++++++++++++++++++++++++
Aeditor/app/cleanup/space/components/SpaceRow.tsx | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cleanup/space/lib/loadSpace.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cleanup/space/lib/runSpaceAction.test.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cleanup/space/lib/runSpaceAction.ts | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/cleanup/space/lib/spaceJob.ts | 26++++++++++++++++++++++++++
Aeditor/app/cleanup/space/page.tsx | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/lib/nav.ts | 2+-
Meditor/e2e/servers.ts | 3+++
Aeditor/e2e/space-suggestions.spec.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 40++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.test.mjs | 11+++++++++++
31 files changed, 4420 insertions(+), 3 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -162,6 +162,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | | `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | | `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | | +| `space-scan` | space-scan measures every disk the archive writes to: {"compaction"?} -&gt; {jobId}. The corpus disk, each storage location, the saved-video store's, the site builds' and umtool's reports' disks, by device: allocated bytes, each inode once, a file with other hard links never counted as freed, a tier link on its target's disk, a drive not mounted or not answering unknown (never empty). Then what would free space on each through the writers that exist — compress-text (captions, live chats), the cleanup sweeps, relocate, evict-clips, delete-file (abandoned partials), compact-saved-videos, drop-saved-alternate (compacted originals, alternates), kept-failed-encodes, live-recording-verify — with what is held (do-not-clean, a pin's copies, a live recording, a move in flight) and why. It only reads: nothing is removed, moved or fetched. Written to transcripts/.space-suggestions.json; get space-suggestions reads it. "compaction": false skips the selector's pass (one ffprobe per saved container not seen unchanged before) and keeps the last scan's rows. While a scan is queued or running, nothing more is queued: the answer is that job ({jobId, alreadyQueued: true}). | `pnpm ops space-scan --json '{"compaction":false}' --wait` | | `compress-text` | compress-text stores big text files compressed (zstd, level 9): the raw live-chat replays (transcript.live\_chat.json -&gt; .zst, kind live-chat, the default) and the caption tracks (every transcript.&lt;lang&gt;.vtt -&gt; .zst, on the corpus disk: "kinds": \["captions"\], only when named). Read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat", "captions"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. A caption's dry run also counts the en / en-orig pairs of equal size (compressed each as it is, never deduped). One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused, both kept and listed once (recorded per channel; not visited again until a form changes): nothing removes a stored copy because a different one arrived. A file a writer replaces during the run is kept and read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "dryRun": true answers per channel and kind the files, their bytes, the stored ones, the estimate after (about 5 % for a chat, 20 % for a caption: estimates) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored file of the kinds put back into its plain form, verified the same way in reverse (decoded beside, fsynced, read back against a fresh decode, the same times, then the .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat or caption (OPERATING.md). | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | @@ -274,6 +275,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get network [--probe] pnpm ops get saved-alternates [<slug>] pnpm ops get compaction-review [<slug>] + pnpm ops get space-suggestions [<disk>] pnpm ops get kept-originals [<slug>] pnpm ops get marks <slug> pnpm ops get services @@ -347,6 +349,15 @@ get compaction-review [<slug>] lists every compacted saved video and what availability and why, the original's entry, sizes, checks, the re-check, "watch" (both files and an smplayer command that plays them) and any "leftover" of an interrupted drop. +get space-suggestions [<disk>] answers the last space scan (space-scan): + every disk the archive writes to, most in need first, each with its size, + free space and how much of it is the archive's; and one disk's + suggestions (default the fullest), biggest saving first. Each says what + it frees and where (measured, or an estimate and from what), what a move + fills, what is lost, and its "actions": the existing ops call that does + it. Then what is held and why, the compaction selector's refusals by + rule, and the archive's bytes no writer here removes, with their owner. + It reads the file only: computedAt null means no scan yet. get marks <slug> lists the channel's do-not-clean marks and who set each one and when, as the video page says it ("setBy": "availability check, 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -97,8 +97,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `NITTER_INSTANCES` | a built-in list | Comma-separated Nitter instances for the X fallback fetcher, in order of preference. | common/social/xNitterFetcher.ts | | `ARCHILYZER_X_BROWSER` | the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium | The Chromium-family browser /settings' "Connect X account" opens (a path, or a name looked up on PATH), and a forum-thread channel's "Connect forum session" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser. | common/social/xBrowser.ts | | `UMTOOL_MEDIA_DIR` | unset (no media root: a project link's target is kept) | umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md). | common/lib/report/delete.ts, umtool (lib/paths.mjs) | -| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs) | +| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, common/controller/spaceScan.ts, umtool (lib/paths.mjs) | | `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does). | common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs) | +| `SPACE_SCAN_REPORTS_DIR` | `REPORTS_DIR`, else `~/reports` | umtool's reports root as the space scan sizes it (measured only: the archive's share of its disk). The e2e servers point it at their own data, so a scan never walks the operator's reports. | common/controller/spaceScan.ts | | `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it. | mcp/src/sources.ts | | `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES` | off | `1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only). | common/controller/remoteArchives.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -2277,6 +2277,32 @@ file and leaves it stored), looked at again (size and hash), and only then is th again (the dry run says how much): about 20 times the stored size. Kept earlier captures (`chat-capture-kept.*.json.zst`) are not restored: an older checkout ignores them, and they stay where they are. +### Free up space (which disk, and what frees it) + +```sh +pnpm ops space-scan --wait # measure every disk the archive writes to (reads only) +pnpm ops space-scan --json '{"compaction":false}' --wait # the same without the compaction selector's ffprobe pass +pnpm ops get space-suggestions # the fullest disk's list, biggest saving first +pnpm ops get space-suggestions platter # another disk's +``` + +The editor's `/cleanup/space` is the same list. A `space-scan` job measures the corpus disk, each storage location, +and the disks of the saved-video store, the site builds and umtool's reports. It counts allocated bytes, each inode +once; a file with another hard link is never counted as freed, and a tier link counts on its target's disk. It writes +`transcripts/.space-suggestions.json` and nothing else. + +Each suggestion carries `actions`, the existing ops call that does it: compress-text (caption tracks first on the +corpus disk), the cleanup sweeps, relocate, evict-clips, delete-file for abandoned partials, compact-saved-videos, +drop-saved-alternate for compacted originals and alternates, kept-failed-encodes, and live-recording-verify. Run that +call, or press the row's button. The button first checks the row again: it refuses a scan older than a day, a +video held now (do-not-clean, a must-keep or unfinished live recording, a job, a move), and a target file +that changed, went or gained a hard link. A call run by hand gets only its writer's own refusals. Two things to know: +- A compaction frees the store's disk only, and only once its original is dropped. +- A move frees only the media tier, never the text. + +Held (do-not-clean, a pinned video's copies, a live recording, a move in flight), the selector's refusals and the +archive's bytes no writer here removes are listed with their reason or owner. + ### Compact saved videos ```sh diff --git a/common/controller/spaceHold.test.ts b/common/controller/spaceHold.test.ts @@ -0,0 +1,208 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { link, mkdir, mkdtemp, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "../lib/spaceSuggestions"; +import { + SPACE_MAX_SCAN_AGE_MS, + SpaceHolds, + clipWindowsDigest, + liveRowHold, + recheckSpaceRow, + type SpaceHoldDeps, +} from "./spaceHold"; + +// THE ONE HELD PREDICATE (review 1, B2) and THE CLICK-TIME RE-CHECK (B4): what +// the scan holds back, asked again when the button is pressed, against the +// disk as it is then. + +const NOW = new Date("2026-11-24T12:00:00.000Z"); +const DAY = 86_400_000; + +async function put(file: string, bytes: number, ageDays = 0): Promise<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 world() { + const tmp = await mkdtemp(path.join(tmpdir(), "space-hold-")); + const transcriptsDir = path.join(tmp, "transcripts"); + const paths = { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels"), savedVideosDir: path.join(transcriptsDir, "saved-videos") } as Paths; + await mkdir(paths.channelsDir, { recursive: true }); + return { tmp, paths, data: (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id) }; +} + +const noLive: SpaceHoldDeps = { liveRows: async () => [], jobs: () => [] }; + +test("live rows: anything not landed, failed, cancelled or superseded holds; must-keep and awaiting resume hold whatever the status", () => { + const row = (r: Record<string, unknown>) => liveRowHold({ id: "v", mustKeep: false, status: "landed", ...r } as never); + assert.equal(row({}), null); + assert.equal(row({ status: "failed" }), null); + assert.equal(row({ status: "cancelled" }), null); + assert.equal(row({ status: "recording", supersededBy: "x" }), null); + assert.equal(row({ status: "recording" })?.kind, "live"); + assert.equal(row({ status: "interrupted" })?.kind, "live"); + assert.equal(row({ awaitingResume: ["p1"] })?.kind, "live"); + assert.equal(row({ mustKeep: true })?.kind, "must-keep"); +}); + +test("a video is held by do-not-clean, a live row, a job for it, or its channel's relocation marker; the store by its own marker", async () => { + const w = await world(); + try { + await mkdir(w.data("c", "dnc"), { recursive: true }); + await writeFile(path.join(w.data("c", "dnc"), "do-not-clean.json"), JSON.stringify({ setAt: "x" })); + const holds = new SpaceHolds(w.paths, { + liveRows: async (slug) => (slug === "c" ? [{ id: "rec", status: "interrupted", mustKeep: false }, { id: "keep", status: "landed", mustKeep: true }] : []), + jobs: () => [ + { id: "j1", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "busy" }, + { id: "j2", kind: "compact-saved-videos", status: "queued", channelSlug: "c", spec: { kind: "compact-saved-videos", slug: "c", params: { ids: ["queued"] } } }, + { id: "j3", kind: "sync", status: "running", channelSlug: "d" }, + { id: "j4", kind: "transcribe-one", status: "done", channelSlug: "c", videoId: "free" }, + ], + }); + assert.equal((await holds.video("c", "dnc"))?.kind, "do-not-clean"); + assert.equal((await holds.video("c", "rec"))?.kind, "live"); + assert.equal((await holds.video("c", "keep"))?.kind, "must-keep"); + assert.equal((await holds.video("c", "busy"))?.kind, "job"); + assert.equal((await holds.video("c", "queued"))?.kind, "job"); + // A channel-wide writer (sync) holds every video of its channel. + assert.equal((await holds.video("d", "any"))?.kind, "job"); + assert.equal(await holds.video("c", "free"), null); + await mkdir(path.join(w.paths.channelsDir, "m"), { recursive: true }); + await writeFile(path.join(w.paths.channelsDir, "m", ".relocating.json"), JSON.stringify({ target: "/x/m/media", direction: "out", startedAt: "", phase: "copy", scope: "media" })); + assert.equal((await new SpaceHolds(w.paths, noLive).video("m", "v"))?.kind, "moving"); + assert.equal(await new SpaceHolds(w.paths, noLive).store(), null); + await writeFile(path.join(w.paths.transcriptsDir, ".relocating-saved-videos.json"), JSON.stringify({ target: "/x/saved-videos", direction: "out", startedAt: "", phase: "copy" })); + assert.equal((await new SpaceHolds(w.paths, noLive).store())?.kind, "store-moving"); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +function row(extra: Partial<SpaceSuggestion>): SpaceSuggestion { + return { key: "k", kind: "stale-partial", title: "", frees: { disk: "corpus", bytes: 1 }, basis: "measured", basisText: "", loss: "", ...extra }; +} + +test("the re-check: a scan older than a day, a target changed, grown, gone or shared, a hold that appeared since — each refused and named", async () => { + const w = await world(); + try { + const dir = w.data("c", "v1"); + const part = path.join(dir, "audio.mp3.part"); + await put(part, 1000, 30); + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); + const st = await stat(part); + const result = { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult; + const good = row({ slug: "c", id: "v1", file: "audio.mp3.part", hold: { slug: "c", id: "v1" }, targets: [{ path: part, size: st.size, mtimeMs: st.mtimeMs }] }); + const ask = (r: SpaceSuggestion, deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(good), null); + assert.match((await ask(good, noLive, new Date(NOW.getTime() + SPACE_MAX_SCAN_AGE_MS + 60_000)))!, /rescan first/); + assert.match((await ask(good, { ...noLive, jobs: () => [{ id: "j", kind: "download-one-pipeline", status: "running", channelSlug: "c", videoId: "v1" }] }))!, /a job/); + // Gone from its platform since: the partial may be the only copy. + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "deleted", checkedAt: NOW.toISOString(), checkedBy: "check" })); + assert.match((await ask(good))!, /only copy/); + await writeFile(path.join(dir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: NOW.toISOString(), checkedBy: "check" })); + // Resumed since (it grew): changed. + await writeFile(part, Buffer.alloc(2000, 1)); + assert.match((await ask(good))!, /changed since the scan/); + await rm(part); + assert.match((await ask(good))!, /no longer there/); + // Shared. + const alt = path.join(dir, "alt.mp4"); + await put(alt, 500); + await link(alt, path.join(w.tmp, "other-link")); + const ast = await stat(alt); + assert.match((await ask(row({ kind: "drop-alternate", hold: { slug: "c", id: "v1", store: true }, targets: [{ path: alt, size: ast.size, mtimeMs: ast.mtimeMs }] })))!, /hard link/); + // Marked do-not-clean since. + await writeFile(path.join(dir, "do-not-clean.json"), JSON.stringify({ setAt: "x" })); + assert.match((await ask(row({ kind: "drop-original", hold: { slug: "c", id: "v1", store: true } })))!, /do-not-clean/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("a channel-wide eviction: refused when the set of old windows changed or a video holding windows is held now", async () => { + const w = await world(); + try { + await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.mp4"), 300, 60); + await put(path.join(w.data("c", "a"), "clips", "10.00-20.00.json"), 10, 60); + await put(path.join(w.data("c", "b"), "clips", "1.00-2.00.mp4"), 300, 2); + const digest = await clipWindowsDigest(w.paths, "c", 30, NOW); + assert.equal(digest.count, 1); + const result = { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult; + const r = row({ kind: "evict-clips", slug: "c", hold: { slug: "c" }, digest: { olderThanDays: 30, count: digest.count, sha1: digest.sha1 } }); + const ask = (deps: SpaceHoldDeps = noLive, at = NOW) => recheckSpaceRow({ paths: w.paths, result, row: r, now: at, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(), null); + // b's window turns 30 days old (a scan an hour old then): the set grew. + const later = new Date(NOW.getTime() + 29 * DAY); + const fresh = await recheckSpaceRow({ paths: w.paths, result: { computedAt: new Date(later.getTime() - 3_600_000).toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult, row: r, now: later, holds: new SpaceHolds(w.paths, noLive) }); + assert.match(fresh!, /changed since the scan/); + // b (holding a young window) is recording now. + assert.match((await ask({ ...noLive, liveRows: async () => [{ id: "b", status: "recording", mustKeep: false }] }))!, /live recording/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("fail closed (review 2, F6): a do-not-clean or live-recordings file that cannot be read holds, and the hold names the error", async () => { + const w = await world(); + try { + // do-not-clean.json a directory: not absent, not readable. + await mkdir(path.join(w.data("c", "a"), "do-not-clean.json"), { recursive: true }); + await mkdir(w.data("c", "b"), { recursive: true }); + await writeFile(path.join(w.data("c", "b"), "do-not-clean.json"), "{not json"); + const holds = new SpaceHolds(w.paths, { jobs: () => [] }); + const a = await holds.video("c", "a"); + assert.equal(a?.kind, "do-not-clean"); + assert.match(a!.why, /could not be read/); + assert.match((await holds.video("c", "b"))!.why, /could not be read/); + // The channel's live-recordings.json unreadable: every video of it holds. + await mkdir(path.join(w.paths.channelsDir, "d", "live-recordings.json"), { recursive: true }); + const d = await new SpaceHolds(w.paths, { jobs: () => [] }).video("d", "any"); + assert.equal(d?.kind, "live"); + assert.match(d!.why, /live-recordings\.json could not be read/); + // A dep that throws holds the same way. + const t = await new SpaceHolds(w.paths, { jobs: () => [], liveRows: async () => { throw new Error("EIO"); } }).video("e", "v"); + assert.match(t!.why, /could not be read.*EIO/); + // Absent files hold nothing. + assert.equal(await new SpaceHolds(w.paths, { jobs: () => [] }).video("e", "v"), null); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("review 2: a row with actions and no subject, a scan of another version, a scan dated in the future — refused", async () => { + const w = await world(); + try { + const ask = (r: SpaceSuggestion, result: Partial<SpaceScanResult>) => + recheckSpaceRow({ paths: w.paths, result: { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION, ...result } as SpaceScanResult, row: r, now: NOW, holds: new SpaceHolds(w.paths, noLive) }); + const acting = row({ kind: "evict-clips", actions: [{ op: "evict-clips", body: { slug: "c", olderThanDays: 30 } }] }); + assert.match((await ask(acting, {}))!, /names nothing to check: rescan first/); + const ok = row({ kind: "compress-captions", hold: { slug: "c" }, actions: [{ op: "compress-text", body: { slugs: ["c"] } }] }); + assert.equal(await ask(ok, {}), null); + assert.match((await ask(ok, { version: 1 as never }))!, /older format.*rescan first/); + assert.match((await ask(ok, { computedAt: new Date(NOW.getTime() + 10 * 60_000).toISOString() }))!, /dated in the future/); + assert.equal(await ask(ok, { computedAt: new Date(NOW.getTime() + 60_000).toISOString() }), null); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); + +test("review 2, F1: a channel-wide audio sweep is refused when any video of the channel is held now", async () => { + const w = await world(); + try { + await mkdir(w.data("c", "v1"), { recursive: true }); + await mkdir(w.data("c", "v2"), { recursive: true }); + const sweep = row({ kind: "clean-audio", slug: "c", hold: { slug: "c" }, actions: [{ op: "cleanup", body: { slug: "c", sweep: "transcribed" } }] }); + const ask = (deps: SpaceHoldDeps) => recheckSpaceRow({ paths: w.paths, result: { computedAt: NOW.toISOString(), version: SPACE_SCAN_VERSION } as SpaceScanResult, row: sweep, now: NOW, holds: new SpaceHolds(w.paths, deps) }); + assert.equal(await ask(noLive), null); + assert.match((await ask({ ...noLive, liveRows: async () => [{ id: "v2", status: "landed", mustKeep: true }] }))!, /v2: a must-keep live recording/); + } finally { + await rm(w.tmp, { recursive: true, force: true }); + } +}); diff --git a/common/controller/spaceHold.ts b/common/controller/spaceHold.ts @@ -0,0 +1,342 @@ +// WHAT FREE UP SPACE NEVER OFFERS, AND THE CHECK AT THE CLICK (lane +// space-suggestions, review 1 B2 and B4). +// +// ONE HELD PREDICATE. The scan (controller/spaceScan.ts) asks it of every +// video a row would touch, the store rows included, and the page's button asks +// it again before anything runs (editor/app/cleanup/space/lib/runSpaceAction.ts). +// A video is held by: +// - do-not-clean; +// - a live recording of it that is must-keep, or whose run is not over +// (anything but landed, failed, cancelled or superseded; interrupted and +// awaiting a resume hold); +// - a job queued or running for it (or a channel-wide writer on its channel); +// - its channel's relocation marker. +// The store's rows are held, too, by the store's own relocation marker. A pin +// keeps every copy of its video (ruling 2): that rule is alternateDisposition's +// (lib/spaceSuggestions.ts), for the one kind that removes a copy of it. +// +// THE RE-CHECK (rulings for B4, orchestrator's, 24 Nov). A scan older than a +// day is refused ("rescan first"). Then, for the row's own subject: the held +// predicate, as it is now; every target file still there with the size and +// mtime the scan saw, and one link; a channel-wide clip eviction's whole set +// of old windows the same as at the scan, and no video holding a window held. +// A partial is also refused when its video is not known to be on its platform +// (it may be the only copy of those bytes). Any mismatch refuses the row and +// says why. Reads only. + +import path from "node:path"; +import { createHash } from "node:crypto"; +import { lstat, readdir } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { getRegistry, type JobRecord } from "../jobs/registry"; +import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; + +import { readRelocationMarker } from "../lib/channelMedia"; +import { readSavedVideosMarker } from "../lib/savedVideoStore"; +import { doNotCleanPath } from "../lib/doNotClean-server"; +import { readJsonFile } from "../lib/jsonFile-server"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; +import { CLIPS_DIR_NAME, parseAnyClipWindowName, parseDesyncedClipWindowName, clipWindowStem } from "../lib/clipWindow"; +import { LIVE_RECORDINGS_FILENAME, loadLiveRecordingsFile, type LiveRecordingRow } from "../lib/liveRecordings-server"; +import { SPACE_SCAN_VERSION } from "../lib/spaceSuggestions"; +import { VIDEO_WRITING_KINDS } from "./videoBusy"; + +export const SPACE_MAX_SCAN_AGE_MS = 24 * 60 * 60 * 1000; +// A scan dated further ahead than this was written by a wrong clock or by hand. +export const SPACE_MAX_SCAN_FUTURE_MS = 5 * 60 * 1000; + +// A downloader's partial: what `delete-file` may be asked to remove once it is +// abandoned. NARROWER than mediaTier's scratch on purpose — a stored-text +// 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)); +} + +// On its platform by the record's word (public or unlisted). Anything else — +// gone, private, unknown — and a partial may be the only copy. +export function partialMayBeOnlyCopy(availability: string | null): boolean { + return availability !== "public" && availability !== "unlisted"; +} + +export type SpaceHoldKind = "do-not-clean" | "must-keep" | "live" | "job" | "moving" | "store-moving"; +export type SpaceHold = { kind: SpaceHoldKind; why: string }; + +export const SPACE_HOLD_LABELS: Record<SpaceHoldKind, string> = { + "do-not-clean": "Videos marked do-not-clean", + "must-keep": "Must-keep live recordings", + live: "Videos with a live recording not over", + job: "Videos a job is working on", + moving: "Channels mid-relocation", + "store-moving": "The saved-video store, mid-move", +}; + +type LiveRowLike = Pick<LiveRecordingRow, "id" | "mustKeep"> & { + status: string; + supersededBy?: string; + awaitingResume?: string[]; +}; + +const TERMINAL = new Set(["landed", "failed", "cancelled"]); + +export function liveRowHold(r: LiveRowLike): SpaceHold | null { + if (r.mustKeep) return { kind: "must-keep", why: "a must-keep live recording" }; + if (r.awaitingResume?.length) return { kind: "live", why: "a live recording awaiting a resume" }; + if (r.supersededBy) return null; + if (!TERMINAL.has(r.status)) return { kind: "live", why: `a live recording (${r.status})` }; + return null; +} + +type JobLike = Pick<JobRecord, "id" | "kind" | "status"> & Partial<Pick<JobRecord, "channelSlug" | "videoId" | "spec">>; + +// FAIL CLOSED (review 2, F6): a do-not-clean file that is there but cannot be +// read or parsed holds its video, and says so. Absent holds nothing. A file +// that parses is a mark whatever it holds (doNotClean-server's rule). +export async function readDoNotCleanHold(videoDir: string): Promise<SpaceHold | null> { + const read = await readJsonFile(doNotCleanPath(videoDir)); + if (read.ok) return { kind: "do-not-clean", why: "do-not-clean" }; + if (read.reason === "absent") return null; + return { kind: "do-not-clean", why: `its do-not-clean mark could not be read (${read.reason}): held` }; +} + +// A channel's live rows off its own file; a file there that cannot be read or +// parsed THROWS, so every video of the channel is held (F6). +async function liveRowsOffDisk(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRowLike[]> { + const f = await loadLiveRecordingsFile(paths, slug); + if (f.problem) throw new Error(f.problem); + return f.rows; +} + +export type SpaceHoldDeps = { + // A do-not-clean hold for a video dir (default: readDoNotCleanHold). + doNotClean?: (videoDir: string) => Promise<SpaceHold | null>; + liveRows?: (slug: string) => Promise<LiveRowLike[]>; + jobs?: () => readonly JobLike[]; +}; + +function jobIds(j: JobLike): string[] | null { + const ids = (j.spec?.params as { ids?: unknown } | undefined)?.ids; + return Array.isArray(ids) ? ids.filter((x): x is string => typeof x === "string") : null; +} + +export class SpaceHolds { + private readonly live = new Map<string, Promise<LiveRowLike[] | { error: string }>>(); + private readonly markers = new Map<string, Promise<SpaceHold | null>>(); + private storeMemo: Promise<SpaceHold | null> | null = null; + private jobList: readonly JobLike[] | null = null; + constructor( + private readonly paths: Pick<Paths, "channelsDir" | "transcriptsDir">, + private readonly deps: SpaceHoldDeps = {}, + ) {} + + private jobs(): readonly JobLike[] { + if (!this.jobList) { + this.jobList = (this.deps.jobs ?? defaultJobs)().filter((j) => j.status === "queued" || j.status === "running"); + } + return this.jobList; + } + + channel(slug: string): Promise<SpaceHold | null> { + let m = this.markers.get(slug); + if (!m) { + m = readRelocationMarker(this.paths, slug).then((marker) => + marker ? { kind: "moving" as const, why: `a relocation is in flight (${marker.direction}, phase ${marker.phase})` } : null, + ); + this.markers.set(slug, m); + } + return m; + } + + store(): Promise<SpaceHold | null> { + this.storeMemo ??= readSavedVideosMarker(this.paths).then((marker) => + marker ? { kind: "store-moving" as const, why: `the saved-video store is being moved (${marker.direction}, phase ${marker.phase})` } : null, + ); + return this.storeMemo; + } + + // The rows, or the error the file gave (held, F6). + private liveRows(slug: string): Promise<LiveRowLike[] | { error: string }> { + let p = this.live.get(slug); + if (!p) { + p = (this.deps.liveRows ?? ((s: string) => liveRowsOffDisk(this.paths, s)))(slug).catch((e: Error) => ({ error: e.message || String(e) })); + this.live.set(slug, p); + } + return p; + } + + job(slug: string, id: string): SpaceHold | null { + for (const j of this.jobs()) { + if (j.kind === "space-scan") continue; + if (j.channelSlug && j.channelSlug !== slug) continue; + const ids = jobIds(j); + const forIt = j.videoId ? j.videoId === id : ids ? ids.includes(id) : !!j.channelSlug && VIDEO_WRITING_KINDS.has(j.kind); + if (forIt) return { kind: "job", why: `a job is working on it (${j.kind}, ${j.status})` }; + } + return null; + } + + // `opts.noDoNotCleanFile`: the caller listed the dir and saw no + // do-not-clean file (the scan), so it is not read. + async video(slug: string, id: string, opts: { noDoNotCleanFile?: boolean } = {}): Promise<SpaceHold | null> { + const moving = await this.channel(slug); + if (moving) return moving; + const dir = path.join(this.paths.channelsDir, slug, "data", id); + if (!opts.noDoNotCleanFile) { + const dnc = await (this.deps.doNotClean ?? readDoNotCleanHold)(dir).catch((e: Error) => ({ + kind: "do-not-clean" as const, + why: `its do-not-clean mark could not be read (${e.message}): held`, + })); + if (dnc) return dnc; + } + const rows = await this.liveRows(slug); + if (!Array.isArray(rows)) return { kind: "live", why: `the channel's ${LIVE_RECORDINGS_FILENAME} could not be read (${rows.error}): held` }; + for (const r of rows) { + if (r.id !== id) continue; + const h = liveRowHold(r); + if (h) return h; + } + return this.job(slug, id); + } +} + +function defaultJobs(): readonly JobLike[] { + return getRegistry().list(); +} + +// --- clip windows --------------------------------------------------------------------- + +export type ClipWindowFile = { id: string; name: string; stem: string; path: string; size: number; mtimeMs: number; nlink: number; blocks: number }; + +// One video dir's clip windows (the media, never the sidecars), as the +// evictor reads them. +export async function clipWindowsOf(videoDir: string, id: string): Promise<ClipWindowFile[]> { + const dir = path.join(videoDir, CLIPS_DIR_NAME); + const out: ClipWindowFile[] = []; + for (const name of await readdir(dir).catch(() => [] as string[])) { + const span = parseAnyClipWindowName(name) ?? parseDesyncedClipWindowName(name); + if (!span) continue; + const p = path.join(dir, name); + const st = await lstat(p).catch(() => null); + if (!st?.isFile()) continue; + out.push({ id, name, stem: clipWindowStem(span.from, span.to, span.tier), path: p, size: st.size, mtimeMs: st.mtimeMs, nlink: st.nlink, blocks: st.blocks * 512 }); + } + return out; +} + +export function digestOf(files: readonly Pick<ClipWindowFile, "id" | "name" | "size" | "mtimeMs">[]): string { + const h = createHash("sha1"); + for (const line of files.map((f) => `${f.id}/${f.name}\u0000${f.size}\u0000${f.mtimeMs}`).sort()) h.update(line + "\n"); + return h.digest("hex"); +} + +// A channel's windows not touched for `olderThanDays` at `now`, digested, and +// every video that holds any window (old or not). +export async function clipWindowsDigest( + paths: Pick<Paths, "channelsDir">, + slug: string, + olderThanDays: number, + now: Date, +): Promise<{ count: number; sha1: string; videosWithWindows: string[]; shared: number }> { + const data = path.join(paths.channelsDir, slug, "data"); + const cutoff = now.getTime() - olderThanDays * 86_400_000; + const old: ClipWindowFile[] = []; + const videos: string[] = []; + let shared = 0; + for (const id of await readdir(data).catch(() => [] as string[])) { + const w = await clipWindowsOf(path.join(data, id), id); + if (!w.length) continue; + videos.push(id); + for (const f of w) { + if (f.mtimeMs > cutoff) continue; + old.push(f); + if (f.nlink > 1) shared += 1; + } + } + return { count: old.length, sha1: digestOf(old), videosWithWindows: videos, shared }; +} + +// The first held video of a channel (every video dir asked), or null. +export async function heldInChannel( + paths: Pick<Paths, "channelsDir">, + slug: string, + holds: SpaceHolds, +): Promise<(SpaceHold & { id: string }) | null> { + for (const id of await readdir(path.join(paths.channelsDir, slug, "data")).catch(() => [] as string[])) { + const h = await holds.video(slug, id); + if (h) return { ...h, id }; + } + return null; +} + +// --- the re-check ---------------------------------------------------------------------- + +export async function recheckSpaceRow(opts: { + paths: Pick<Paths, "channelsDir" | "transcriptsDir">; + result: Pick<SpaceScanResult, "computedAt" | "version">; + row: SpaceSuggestion; + now?: Date; + holds: SpaceHolds; + availability?: (videoDir: string) => Promise<string | null>; +}): Promise<string | null> { + const now = opts.now ?? new Date(); + if (opts.result.version !== SPACE_SCAN_VERSION) { + return `the last scan is of an older format (version ${String(opts.result.version ?? "none")}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`; + } + const age = now.getTime() - Date.parse(opts.result.computedAt); + if (age < -SPACE_MAX_SCAN_FUTURE_MS) return "the last scan is dated in the future (a wrong clock?): rescan first"; + if (!(age <= SPACE_MAX_SCAN_AGE_MS)) { + return `the last scan is ${Number.isFinite(age) ? `${Math.round(age / 3_600_000)} h` : "of an unknown"} old: rescan first`; + } + const { row, holds } = opts; + const h = row.hold; + // A row that would act names what to check (F2): one that does not is + // refused, never run unchecked. + if (row.actions?.length && !h?.slug && !h?.store) return "the row names nothing to check: rescan first"; + if (h?.store) { + const s = await holds.store(); + if (s) return `held: ${s.why}`; + } + if (h?.slug) { + const held = h.id ? await holds.video(h.slug, h.id) : await holds.channel(h.slug); + if (held) return `held: ${held.why}`; + } + for (const t of row.targets ?? []) { + const st = await lstat(t.path).catch(() => null); + if (!st?.isFile()) return `${path.basename(t.path)} is no longer there: rescan`; + if (st.size !== t.size || st.mtimeMs !== t.mtimeMs) return `${path.basename(t.path)} changed since the scan: rescan`; + if (st.nlink !== 1) return `${path.basename(t.path)} has another hard link now: removing it would free nothing`; + } + if (row.kind === "stale-partial" && h?.slug && h.id) { + if (!row.file || !isAbandonablePartial(row.file)) return `${row.file ?? "?"} is not a partial download`; + const a = await (opts.availability ?? resolveEffectiveAvailability)(path.join(opts.paths.channelsDir, h.slug, "data", h.id)).catch(() => null); + if (partialMayBeOnlyCopy(a)) return `held: the video is not known to be on its platform (${a ?? "unknown"}): the partial may be the only copy`; + } + // A CHANNEL-WIDE AUDIO SWEEP (review 2, F1): the sweep knows do-not-clean + // and keep-latest by its own rules, not a must-keep or unfinished live + // recording — so every video of the channel is asked again. + if ((row.kind === "clean-audio" || row.kind === "clean-extra-formats") && h?.slug) { + const held = await heldInChannel(opts.paths, h.slug, holds); + if (held) return `held: ${held.id}: ${held.why}`; + } + if (row.digest && h?.slug) { + const d = await clipWindowsDigest(opts.paths, h.slug, row.digest.olderThanDays, now); + if (d.count !== row.digest.count || d.sha1 !== row.digest.sha1) return "the channel's old clip windows changed since the scan: rescan"; + if (d.shared) return "a window has another hard link now: rescan"; + for (const id of d.videosWithWindows) { + const held = await holds.video(h.slug, id); + if (held) return `held: ${id}: ${held.why}`; + } + } + return null; +} diff --git a/common/controller/spaceScan.test.ts b/common/controller/spaceScan.test.ts @@ -0,0 +1,542 @@ +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 + 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<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), + 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<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 { + // 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); +}); diff --git a/common/controller/spaceScan.ts b/common/controller/spaceScan.ts @@ -0,0 +1,1366 @@ +// 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, isKeptChatCapture, isScratchEntry, isTierable } from "../lib/mediaTier"; +import { isRealAudioFile, isSourceMediaFile } from "../lib/mediaFiles"; +import { isStoredCaptionName, isStoredTextName } from "../lib/storedText"; +import { DO_NOT_CLEAN_FILENAME } from "../lib/doNotClean"; + +// The raw live chat in its PLAIN form, by the stored-text rules +// (lib/storedText.ts): a declared stored-text name that is not a caption +// track. A listing's entry is only classified here, never opened; its stored +// form (.zst) is already compressed and is not proposed. +function isPlainRawChat(name: string): boolean { + return isStoredTextName(name) && !isStoredCaptionName(name); +} +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 { 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"; +import { + SPACE_HOLD_LABELS, + SpaceHolds, + clipWindowsOf, + digestOf, + isAbandonablePartial, + partialMayBeOnlyCopy, + type ClipWindowFile, + type SpaceHold, + type SpaceHoldDeps, +} from "./spaceHold"; +import { resolveEffectiveAvailability } from "../lib/availability-server"; + +const DAY_MS = 86_400_000; +const SLICE_MS = 15; +const LSTAT_BATCH = 32; +const EXAMPLES_PER_GROUP = 5; + +// The partial-name rule lives with the held predicate (controller/spaceHold.ts), +// which the click asks again. +export { isAbandonablePartial } from "./spaceHold"; + +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[]>; + // The held predicate's sources (controller/spaceHold.ts). Its live rows + // default to `liveRecordings` below, by channel. + holds?: SpaceHoldDeps; + // A video's availability, for a partial (default: the record's). + availability?: (videoDir: string) => Promise<string | null>; + // 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; +} + +// The version the file on disk says, whatever it is (null: none, or no file): +// the button names an older format "rescan first" (review 2, F2). +export async function readSpaceSuggestionsVersion(paths: Pick<Paths, "transcriptsDir">): Promise<number | null> { + const read = await readJsonFile(spaceSuggestionsPath(paths)); + const v = read.ok && read.value && typeof read.value === "object" ? (read.value as { version?: unknown }).version : null; + return typeof v === "number" ? v : null; +} + +// umtool's REPORTS_ROOT, as umtool/lib/paths.mjs resolves it. +// `SPACE_SCAN_REPORTS_DIR` is the scan's own name for it (an e2e server's +// fixture), so nothing else that reads REPORTS_DIR changes. +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; size: 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), size: st.size, 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: "its drive is not answering" }; + const why: Record<string, string> = { + "mounted-elsewhere": "its disk is mounted somewhere else (re-point it on /storage)", + unmounted: "its disk is attached but not mounted", + absent: "its disk is not attached", + missing: "its root does not exist", + }; + return { status: "not-mounted", detail: why[probe.status] ?? 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 }; + // Every video holding a clip window: its old (unshared) windows, whether + // it is held, and whether one of its old windows has another link. + clipVideos: { id: string; old: ClipWindowFile[]; held: SpaceHold | null; shared: number; dev: string }[]; + // The first video of the channel the held predicate holds: a channel-wide + // audio sweep is not offered while there is one (review 2, F1). + firstHeld: (SpaceHold & { id: string }) | null; + partials: { id: string; file: string; fact: Fact; path: string }[]; + strays: { id: string; file: string; fact: Fact }[]; +}; + +function newTally(): ChannelTally { + return { + captions: new Map(), + chat: new Map(), + audio: new Map(), + extra: new Map(), + move: { bytes: 0, files: 0 }, + clipVideos: [], + firstHeld: null, + 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 availabilityOf = deps.availability ?? ((dir: string) => resolveEffectiveAvailability(dir)); + + // 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, and THE ONE HELD PREDICATE (controller/spaceHold.ts): + // do-not-clean, a must-keep or unfinished live recording, a job for the + // video, a relocation marker — asked of every video a row would touch, the + // store's rows included, and asked again at the click. + const liveRows = await (deps.liveRecordings ?? (async () => (await listLiveRecordings(paths, { all: true })).rows))().catch(() => [] as LiveRecordingView[]); + // The held predicate's live rows: a test's listing when it names one, else + // each channel's own file, which FAILS CLOSED when it cannot be read. + const holds = new SpaceHolds(paths, { + ...(deps.liveRecordings ? { liveRows: async (slug: string) => liveRows.filter((r) => r.slug === slug) } : {}), + ...deps.holds, + }); + const heldMemo = new Map<string, Promise<SpaceHold | null>>(); + const heldVideo = (slug: string, id: string, o: { noDoNotCleanFile?: boolean } = {}): Promise<SpaceHold | null> => { + const k = `${slug}/${id}`; + let p = heldMemo.get(k); + if (!p) heldMemo.set(k, (p = holds.video(slug, id, o))); + return p; + }; + // A held file's bytes, under its hold's kind. + const holdBytes = (h: SpaceHold, disk: string | null, bytes: number, count = 1) => + hold(held, `video:${h.kind}:${h.kind === "live" || h.kind === "job" ? h.why : ""}`, { what: SPACE_HOLD_LABELS[h.kind], disk, why: `${h.why}: nothing of it is proposed` }, bytes, count); + + // --- 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 heldNow = () => heldVideo(slug, id, { noDoNotCleanFile: !set.has(DO_NOT_CLEAN_FILENAME) }); + const hasPointer = set.has(SAVED_VIDEO_POINTER_FILENAME); + const audio: { name: string; fact: Fact }[] = []; + let clipDev = corpusDev; + let hasClips = false; + 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 (isPlainRawChat(name)) bump(tally.chat, f); + continue; + } + if (st.isDirectory()) { + if (name === CLIPS_DIR) { + await walkTree(abs, (a, s) => { + clipDev = acc.add(a, s, "clips").dev; + }, { ticker }); + hasClips = true; + } 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 (isPlainRawChat(name)) 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) { + const h = await heldNow(); + if (h) holdBytes(h, diskIdOf(f.dev), f.bytes); + else tally.strays.push({ id, file: name, fact: f }); + } else if (isAbandonablePartial(name) && now.getTime() - f.mtimeMs >= SPACE_PARTIAL_AGE_DAYS * DAY_MS) { + const h = await heldNow(); + if (h) holdBytes(h, diskIdOf(f.dev), f.bytes); + else if (f.nlink > 1) hold(held, "partial-shared", { what: "Partial downloads with another hard link", disk: diskIdOf(f.dev), why: "shared: removing one name frees nothing" }, f.bytes, 1); + else { + // A video not known to be on its platform: the partial may be the + // only copy of those bytes (ruling, review 1). + const a = await availabilityOf(dir).catch(() => null); + if (partialMayBeOnlyCopy(a)) { + hold(held, "partial-only-copy", { what: "Partial downloads of videos not known to be on their platform", disk: diskIdOf(f.dev), why: "gone from its platform or its availability unknown: the partial may be the only copy" }, f.bytes, 1); + } else tally.partials.push({ id, file: name, fact: f, path: abs }); + } + } + } + if (hasClips) { + const windows = await clipWindowsOf(dir, id); + if (windows.length) { + const cutoff = now.getTime() - SPACE_CLIP_AGE_DAYS * DAY_MS; + const old = windows.filter((w) => w.mtimeMs <= cutoff); + const h = await heldNow(); + let shared = 0; + for (const w of old) { + if (w.nlink > 1) { + shared += 1; + hold(held, "clips-shared", { what: "Clip windows linked into a umtool take", disk: diskIdOf(clipDev), why: "shared (another hard link holds the same bytes): evicting one frees nothing" }, w.blocks, 1); + } + } + if (h && old.length) holdBytes(h, diskIdOf(clipDev), old.reduce((n, w) => n + w.blocks, 0), old.length); + tally.clipVideos.push({ id, old, held: h, shared, dev: clipDev }); + } + } + // The cleanup sweeps' targets: the report's buckets (already net of + // do-not-clean, keep-latest and the diarization hold), measured now, and + // left out for a video the held predicate holds. + const videoHeld = await heldNow(); + if (videoHeld && !tally.firstHeld) tally.firstHeld = { ...videoHeld, id }; + if (audio.length && !videoHeld) { + if (v.cleanIds.has(id)) for (const a of audio) bump(v.tally.audio, a.fact); + if (v.extraIds.has(id) && v.target) for (const a of audio) if (a.name !== v.target) bump(v.tally.extra, a.fact); + } + } + + 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"] } }], + hold: { slug }, + ...(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] } }], + hold: { slug }, + ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}), + }); + } + const report = brief.snapshot?.generatedAt ? ` (report of ${String(brief.snapshot.generatedAt).slice(0, 10)})` : ""; + // THE AUDIO SWEEPS ARE CHANNEL-WIDE and know do-not-clean and keep-latest + // by their own rules, not a must-keep or unfinished live recording: while + // any video of the channel is held they are held, never offered (F1). + const sweepHeld = (what: string, dev: string, bytes: number, count: number) => + hold(held, `sweep:${what}:${slug}:${dev}`, { + what: `${name}: the audio sweeps (${what})`, + disk: diskIdOf(dev), + why: `${t.firstHeld!.id}: ${t.firstHeld!.why}: a channel-wide sweep is not offered while a video of the channel is held`, + link: { href: `/channels/${slug}`, label: "Channel page" }, + }, bytes, count); + for (const [dev, e] of t.audio) { + if (e.bytes <= 0) continue; + if (t.firstHeld) { + sweepHeld("transcribed", dev, e.bytes, e.count); + continue; + } + const atRisk = brief.snapshot?.reclaimableAtRiskBytes ?? 0; + suggestions.push({ + key: `clean-audio:${slug}:${dev}`, + 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" } }], + hold: { slug }, + ...(e.shared ? { shared: { files: e.shared, bytes: e.sharedBytes } } : {}), + }); + } + for (const [dev, e] of t.extra) { + if (e.bytes <= 0) continue; + if (t.firstHeld) { + sweepHeld("extra formats", dev, e.bytes, e.count); + continue; + } + suggestions.push({ + key: `clean-extra-formats:${slug}:${dev}`, + kind: "clean-extra-formats", + 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" } }], + hold: { slug }, + }); + } + // Clip windows (review 1, B3): ONE eviction for the channel only when no + // video holding a window is held and no old window has another link — + // its whole set of old windows digested, so the click can tell it is the + // same set. Otherwise one per unheld video, naming its old windows. + const clipLoss = "re-fetchable: an evicted window costs a fetch, not data. By age only: nothing here knows whether a umtool report still cites one"; + const withOld = t.clipVideos.filter((c) => c.old.some((w) => w.nlink === 1)); + const channelWide = withOld.length > 0 && t.clipVideos.every((c) => !c.held && c.shared === 0); + if (channelWide) { + const old = t.clipVideos.flatMap((c) => c.old); + suggestions.push({ + key: `evict-clips:${slug}:*`, + kind: "evict-clips", + slug, + title: `${name}: ${old.length.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`, + frees: { disk: diskIdOf(withOld[0].dev), bytes: old.reduce((n, w) => n + w.blocks, 0) }, + basis: "measured", + basisText: "measured now: windows not modified for the cutoff", + loss: clipLoss, + actions: [{ op: "evict-clips", body: { olderThanDays: SPACE_CLIP_AGE_DAYS, slug } }], + hold: { slug }, + digest: { olderThanDays: SPACE_CLIP_AGE_DAYS, count: old.length, sha1: digestOf(old) }, + }); + } else { + for (const c of withOld) { + if (c.held) continue; + const sharedStems = new Set(c.old.filter((w) => w.nlink > 1).map((w) => w.stem)); + const own = c.old.filter((w) => w.nlink === 1 && !sharedStems.has(w.stem)); + if (!own.length) continue; + suggestions.push({ + key: `evict-clips:${slug}:${c.id}`, + kind: "evict-clips", + slug, + id: c.id, + title: `${name} ${c.id}: ${own.length.toLocaleString("en-US")} clip window(s) untouched ${SPACE_CLIP_AGE_DAYS}+ days`, + frees: { disk: diskIdOf(c.dev), bytes: own.reduce((n, w) => n + w.blocks, 0) }, + basis: "measured", + basisText: "measured now: windows not modified for the cutoff", + loss: clipLoss, + actions: [{ op: "evict-clips", body: { slug, id: c.id, windows: [...new Set(own.map((w) => w.stem))], olderThanDays: SPACE_CLIP_AGE_DAYS } }], + hold: { slug, id: c.id }, + targets: own.map((w) => ({ path: w.path, size: w.size, mtimeMs: w.mtimeMs })), + }); + } + } + 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 } }], + hold: { slug, id: p.id }, + targets: [{ path: p.path, size: p.fact.size, mtimeMs: p.fact.mtimeMs }], + }); + } + 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 } }], + hold: { slug: m.slug }, + ...(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 ------------------------------------------------------------------------ + // Every store row asks the held predicate of its video and the store's own + // relocation marker (review 1, B2). A store file is statted through the + // drive watchdog; a channel or a store not answering is "unknown", not missing. + const notAnswering: string[] = []; + const entries = await (deps.savedVideos ?? (() => listSavedVideos({ paths, notAnswering })))().catch(() => [] as SavedVideoEntry[]); + for (const slug of new Set(notAnswering)) { + hold(held, `store-unknown:${slug}`, { what: `${slug}: its saved videos`, disk: null, why: "its drive is not answering: unknown here, not missing", link: { href: "/storage", label: "Storage" } }, null, 1); + } + const entryOf = new Map(entries.map((e) => [`${e.slug}/${e.videoId}`, e])); + let storeUnknown = false; + const statFile = async (file: string): Promise<Fact | null> => { + try { + const st = await onDrive(file, () => stat(file)); + return st.isFile() ? acc.fact(file, st) : null; + } catch (e) { + if (isDriveNotAnswering(e)) storeUnknown = true; + return null; + } + }; + const storeHold = await holds.store(); + // The held predicate for a store row: the store's marker, then the video's. + const storeRowHold = async (slug: string, id: string): Promise<SpaceHold | null> => storeHold ?? (await heldVideo(slug, id)); + const sharedHold = (disk: string, bytes: number) => + hold(held, "store-shared", { what: "Saved-video files with another hard link", disk, why: "shared: removing one name frees nothing" }, bytes, 1); + 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 file = path.join(e.pointer.dir, alt.file); + const f = await statFile(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; + } + const h = await storeRowHold(e.slug, e.videoId); + if (h) { + holdBytes(h, diskIdOf(f.dev), f.bytes); + continue; + } + if (f.nlink > 1) { + sharedHold(diskIdOf(f.dev), f.bytes); + continue; + } + // A FORMER ORIGINAL is the person's to drop, on the video page (ruling + // B1): a row with its bytes and a link, no button here. + const former = disp.formerOriginal === true; + 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${former ? " (a former original)" : ""}`, + frees: { disk: diskIdOf(f.dev), bytes: f.bytes }, + basis: "measured", + basisText: "measured now", + loss: former + ? "a former original: a copy of the source bytes no longer active. Its review and drop are on the video page" + : "the alternate copy; the active copy stays", + ...(former ? {} : { actions: [{ op: "drop-saved-alternate", body: { slug: e.slug, id: e.videoId, file: alt.file } }] }), + hold: { slug: e.slug, id: e.videoId, store: true }, + targets: [{ path: file, size: f.size, mtimeMs: f.mtimeMs }], + link: { href: `/channels/${e.slug}/videos/${e.videoId}`, label: former ? "Video page: review and drop it there" : "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; + for (const row of opts.previous.suggestions.filter((x) => x.kind === "compact")) { + const h = row.slug && row.id ? await storeRowHold(row.slug, row.id) : null; + if (!h) suggestions.push(row); + } + } 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 h = await storeRowHold(item.slug, item.id); + if (h) { + holdBytes(h, disk, bytes); + continue; + } + 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 }] } }], + hold: { slug: item.slug, id: item.id, store: true }, + 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 abs = dir ? path.join(dir, file) : r.leftover ?? null; + const f = abs ? await statFile(abs) : null; + if (!f || !abs) continue; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(f.dev), f.bytes); + continue; + } + if (f.nlink > 1) { + sharedHold(diskIdOf(f.dev), f.bytes); + 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.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" }, + }), + hold: { slug: r.slug, id: r.id, store: true }, + targets: [{ path: abs, size: f.size, mtimeMs: f.mtimeMs }], + }); + } + } + 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 onDrive(r.dir, () => stat(r.dir)).catch((e) => { + if (isDriveNotAnswering(e)) storeUnknown = true; + return null; + }); + const dev = dst ? deviceOf(r.dir, dst) : storeDev ?? corpusDev; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(dev), bytes); + continue; + } + 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 } } }], + hold: { slug: r.slug, id: r.id, store: true }, + }); + } + // Live landings whose check failed or never ran: Verify again removes the + // stream files only if the landed file checks out against them, so the row + // frees nothing now (review 1, not blocking 3). + 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; + const targets: { path: string; size: number; mtimeMs: number }[] = []; + for (const n of v.against) { + const file = path.join(staging, n); + const f = await statFile(file); + if (!f) continue; + if (f.nlink === 1) bytes += f.bytes; + dev = f.dev; + targets.push({ path: file, size: f.size, mtimeMs: f.mtimeMs }); + } + if (!dev) continue; + const h = await storeRowHold(r.slug, r.id); + if (h) { + holdBytes(h, diskIdOf(dev), bytes); + 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: null, + later: { disk: diskIdOf(dev), low: bytes, high: bytes, when: "only if it verifies against them" }, + basis: "measured", + basisText: "measured now: the stream files the landing is checked against, freed only if it verifies", + 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 } }], + hold: { slug: r.slug, id: r.id, store: true }, + targets, + }); + } + if (storeHold) { + hold(held, "store-moving", { what: "The saved-video store", disk: storeDev ? diskIdOf(storeDev) : null, why: `${storeHold.why}: none of its rows is proposed`, link: { href: "/storage", label: "Storage" } }, null, 1); + } + if (storeUnknown) { + hold(held, "store-not-answering", { what: "Saved-video files", disk: storeDev ? diskIdOf(storeDev) : null, why: "a drive did not answer: those files are unknown here, not missing", link: { href: "/storage", label: "Storage" } }, null, 1); + } + 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); + // A FAILED PROBE IS NOT REMEMBERED (review 1, 12): one transient + // failure must not make a container "unreadable" on every later scan. + if (st && p) 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/envVars.ts b/common/lib/envVars.ts @@ -133,8 +133,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "NITTER_INSTANCES", audience: "runtime", default: "a built-in list", readBy: "common/social/xNitterFetcher.ts", doc: "Comma-separated Nitter instances for the X fallback fetcher, in order of preference." }, { name: "ARCHILYZER_X_BROWSER", audience: "runtime", default: "the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium", readBy: "common/social/xBrowser.ts", doc: "The Chromium-family browser /settings' \"Connect X account\" opens (a path, or a name looked up on PATH), and a forum-thread channel's \"Connect forum session\" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser." }, { name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." }, - { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, + { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, common/controller/spaceScan.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does)." }, + { name: "SPACE_SCAN_REPORTS_DIR", audience: "runtime", default: "`REPORTS_DIR`, else `~/reports`", readBy: "common/controller/spaceScan.ts", doc: "umtool's reports root as the space scan sizes it (measured only: the archive's share of its disk). The e2e servers point it at their own data, so a scan never walks the operator's reports." }, { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it." }, { name: "ARCHILYZER_ALLOW_PRIVATE_ARCHIVES", audience: "runtime", default: "off", readBy: "common/controller/remoteArchives.ts", doc: "`1` lets the editor connect an archive whose host is this machine or its network (loopback, private, link-local, a `.local` name, or a name resolving to such an address), which is refused otherwise: umtool, which can connect one, is open on the LAN. TRANSCRIPT_SITE_URL's archive, and one already written in settings.json, are connected without it. The check is made once, when the archive is connected: a name re-pointed at a private address afterwards is not rechecked (the archive is still read on its own origin only)." }, diff --git a/common/lib/spaceSuggestions.test.ts b/common/lib/spaceSuggestions.test.ts @@ -0,0 +1,188 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + SPACE_ITEMS_PER_KIND, + alternateDisposition, + capPerKind, + compressSaving, + diskNeedOrder, + diskSuggestedBytes, + fullestDiskId, + groupSuggestions, + leadKindsFor, + moveFit, + refusalGroup, + spaceSummaryLine, + suggestionsForDisk, + type SpaceDisk, + type SpaceScanResult, + type SpaceSuggestion, +} from "./spaceSuggestions"; + +const GB = 1024 ** 3; + +function disk(id: string, size: number, free: number, extra: Partial<SpaceDisk> = {}): SpaceDisk { + return { + id, + label: id, + mountpoint: `/${id}`, + status: "ok", + roles: [], + locationIds: [], + sizeBytes: size * GB, + freeBytes: free * GB, + archive: null, + archiveBytes: null, + ...extra, + }; +} + +function sug(kind: SpaceSuggestion["kind"], diskId: string, bytes: number | null, extra: Partial<SpaceSuggestion> = {}): SpaceSuggestion { + return { + key: `${kind}:${diskId}:${bytes}:${Math.random()}`, + kind, + title: kind, + frees: bytes === null ? null : { disk: diskId, bytes: bytes * GB }, + basis: "measured", + basisText: "measured", + loss: "nothing", + ...extra, + }; +} + +test("disk need: below the floor first, then the smallest free share; unmounted and not answering last", () => { + const disks = [ + disk("platter", 1800, 202), + disk("gone", 0, 0, { status: "not-mounted", sizeBytes: null, freeBytes: null }), + disk("corpus", 1500, 24), + disk("roomy", 100, 5), + disk("tiny", 4000, 40), + ]; + // floor 30 GB: corpus (24) and roomy (5) are under it, and of those the smaller share free first. + const order = diskNeedOrder(disks, 30 * GB).map((d) => d.id); + assert.deepEqual(order, ["corpus", "roomy", "tiny", "platter", "gone"]); + assert.equal(fullestDiskId(disks, 30 * GB), "corpus"); + // No floor: by share alone. + assert.deepEqual(diskNeedOrder(disks, 0).map((d) => d.id), ["tiny", "corpus", "roomy", "platter", "gone"]); +}); + +test("suggestions for a disk: only what frees bytes there, biggest first; a compaction (frees nothing now) after every saving", () => { + const result = { + suggestions: [ + sug("evict-clips", "corpus", 9), + sug("compress-captions", "corpus", 62), + sug("compact", "platter", null, { later: { disk: "platter", low: 40 * GB, high: 60 * GB, when: "after its original is dropped" } }), + sug("drop-original", "platter", 30), + sug("move-media", "corpus", 21, { fills: { disk: "platter", bytes: 21 * GB, fits: true, freeAfter: 181 * GB } }), + ], + } as Pick<SpaceScanResult, "suggestions">; + assert.deepEqual( + suggestionsForDisk(result, "corpus").map((s) => s.kind), + ["compress-captions", "move-media", "evict-clips"], + ); + assert.deepEqual(suggestionsForDisk(result, "platter").map((s) => s.kind), ["drop-original", "compact"]); +}); + +test("groups: by kind, subtotal of what each frees, the biggest group first; caption compression leads the corpus disk", () => { + const list = [ + sug("clean-audio", "corpus", 10), + sug("clean-audio", "corpus", 11), + sug("compress-captions", "corpus", 30), + sug("compress-captions", "corpus", 32), + sug("unstored-container", "corpus", 23), + ]; + const groups = groupSuggestions(list); + assert.deepEqual(groups.map((g) => g.kind), ["compress-captions", "unstored-container", "clean-audio"]); + assert.equal(groups[0].bytes, 62 * GB); + assert.equal(groups[0].rows[0].frees!.bytes, 32 * GB); +}); + +test("move fit: the target keeps its floor plus a margin, or the move is shown as not fitting", () => { + assert.deepEqual(moveFit(200 * GB, 21 * GB, 30 * GB), { fits: true, freeAfter: 179 * GB }); + assert.equal(moveFit(40 * GB, 21 * GB, 30 * GB).fits, false); + assert.equal(moveFit(null, 21 * GB, 30 * GB).fits, false); + assert.equal(moveFit(null, 21 * GB, 30 * GB).freeAfter, null); +}); + +test("compress saving: what the plain files lose at the controller's ratio", () => { + assert.equal(compressSaving(1000, 0.2), 800); + assert.equal(compressSaving(0, 0.2), 0); +}); + +test("cap per kind and disk: at most N rows each, the rest counted exactly", () => { + const many = Array.from({ length: SPACE_ITEMS_PER_KIND + 7 }, (_, i) => sug("evict-clips", "corpus", i + 1)); + const other = [sug("compress-captions", "corpus", 1)]; + const { kept, overflow } = capPerKind([...many, ...other]); + assert.equal(kept.filter((s) => s.kind === "evict-clips").length, SPACE_ITEMS_PER_KIND); + assert.equal(kept.filter((s) => s.kind === "compress-captions").length, 1); + assert.equal(overflow.length, 1); + assert.equal(overflow[0].kind, "evict-clips"); + assert.equal(overflow[0].count, 7); + // The seven smallest are the ones left out: 1..7 GB. + assert.equal(overflow[0].bytes, (1 + 2 + 3 + 4 + 5 + 6 + 7) * GB); +}); + +test("refusal groups: a selector refusal reads as its rule, numbers left out", () => { + assert.equal(refusalGroup("1.20 Mbit/s video is below minVideoMbps 3"), "below the bitrate floor"); + assert.equal(refusalGroup("480p is below minHeight 720"), "below the height floor"); + assert.equal(refusalGroup("platform youtube is not selected"), "platform not selected"); + assert.equal( + refusalGroup("an automatic keep-latest container (compaction is for deliberately stored videos only)"), + "keep-latest (not deliberately stored)", + ); + assert.equal(refusalGroup('kept as "override" with no record that a person asked for it (persist-kept…)'), "override (not known to be deliberate)"); + assert.equal(refusalGroup("no keep reason recorded (a legacy pointer): not known to be kept on purpose"), "legacy pointer"); + assert.equal(refusalGroup("already AV1"), "already AV1"); + assert.equal(refusalGroup("the channel opts out (excludeFromCompaction)"), "channel opts out"); + assert.equal(refusalGroup("its last compaction failed its checks on 2026-11-01: x"), "last compaction failed"); + assert.equal(refusalGroup("something new"), "other"); + assert.equal(refusalGroup("already compacted"), null); +}); + +test("alternates: a pin keeps every copy; a proxy is kept on purpose; an original is the compaction's; a former original needs its own word", () => { + const base = { storedAt: "", dir: "/s", file: "a.mp4", bytes: 1 }; + const alt = { file: "b.mp4", bytes: 1, storedAt: "", setAsideAt: "" }; + assert.deepEqual(alternateDisposition({ ...base, keepReason: "override" }, alt), { offer: true }); + assert.equal(alternateDisposition({ ...base, keepReason: "pin" }, alt).offer, false); + assert.equal(alternateDisposition(base, { ...alt, keptAs: "proxy" }).offer, false); + assert.equal(alternateDisposition(base, { ...alt, keptAs: "original" }).offer, false); + const former = alternateDisposition(base, { ...alt, keptAs: "former-original" }); + assert.equal(former.offer, true); + assert.ok(former.offer && former.formerOriginal); +}); + +test("summary line: the fullest disk, its free space and what the scan suggests there", () => { + const result = { + computedAt: "2026-11-24T10:00:00.000Z", + floorBytes: 0, + disks: [disk("corpus", 1500, 24, { label: "Corpus disk" }), disk("platter", 1800, 202)], + suggestions: [sug("compress-captions", "corpus", 62), sug("evict-clips", "corpus", 9), sug("drop-original", "platter", 30)], + } as unknown as SpaceScanResult; + const line = spaceSummaryLine(result, { corpus: 25 * GB }); + assert.match(line!, /^Corpus disk: 25\.00 GB free \(98 % used\) · ~71\.00 GB suggested there/); + assert.equal(spaceSummaryLine(null, {}), null); +}); + +test("groups: a lead kind goes first whatever its subtotal (caption compression on the corpus disk)", () => { + const list = [sug("unstored-container", "corpus", 30), sug("compress-captions", "corpus", 20), sug("evict-clips", "corpus", 25)]; + assert.deepEqual(groupSuggestions(list).map((g) => g.kind), ["unstored-container", "evict-clips", "compress-captions"]); + assert.deepEqual(groupSuggestions(list, { lead: ["compress-captions"] }).map((g) => g.kind), ["compress-captions", "unstored-container", "evict-clips"]); + assert.deepEqual(groupSuggestions([sug("evict-clips", "corpus", 1)], { lead: ["compress-captions"] }).map((g) => g.kind), ["evict-clips"]); + assert.deepEqual(leadKindsFor("corpus"), ["compress-captions"]); + assert.deepEqual(leadKindsFor("platter"), []); +}); + +test("a disk's suggested total counts each file once: one channel's overlapping kinds are the larger, a move that does not fit is left out", () => { + const list = [ + sug("clean-audio", "corpus", 10, { slug: "a" }), + sug("clean-extra-formats", "corpus", 4, { slug: "a" }), + sug("move-media", "corpus", 12, { slug: "a" }), + sug("compress-live-chat", "corpus", 3, { slug: "a" }), + sug("clean-audio", "corpus", 5, { slug: "b" }), + sug("move-media", "corpus", 50, { slug: "c", disabled: "does not fit" }), + sug("compress-captions", "corpus", 20, { slug: "a" }), + sug("evict-clips", "corpus", 1, { slug: "a" }), + ]; + // a: max(10, 4, 12, 3) = 12; b: 5; c's move left out; captions 20 and clips 1 add. + assert.equal(diskSuggestedBytes(list), (12 + 5 + 20 + 1) * GB); +}); diff --git a/common/lib/spaceSuggestions.ts b/common/lib/spaceSuggestions.ts @@ -0,0 +1,414 @@ +// FREE UP SPACE: the pure half (lane space-suggestions). The scan +// (controller/spaceScan.ts, the `space-scan` job) measures the disks and writes +// `transcripts/.space-suggestions.json`; this module is the shape of that file +// and every rule that orders, groups and bounds it. The page +// (/cleanup/space), the ops read (`get space-suggestions`) and the /cleanup +// summary line read the file through these functions. Pure: no fs, so a page +// and a test call it alike. +// +// THE PAGE ONLY PROPOSES. Every suggestion's `actions` is the existing ops +// call that does it (compress-text, cleanup, relocate, evict-clips, +// delete-file, compact-saved-videos, drop-saved-alternate, +// kept-failed-encodes, live-recording-verify) — there is no new way to delete +// or move here, and the writer refuses whatever it refuses when it runs. + +import { formatBytes } from "./format"; +import type { SavedVideoAlternate, SavedVideoPointer } from "./savedVideo"; + +// 2 (review 2, F2): rows carry what the click re-checks (hold, targets, +// digest); a file of another version is refused at the click ("rescan first"). +export const SPACE_SCAN_VERSION = 2; +export const SPACE_SUGGESTIONS_FILENAME = ".space-suggestions.json"; +export const SPACE_SCAN_JOB_KIND = "space-scan"; +export const SPACE_SCAN_QUEUE = "space-scan"; +// Rows kept per kind per disk; past it the file counts the rest exactly. +export const SPACE_ITEMS_PER_KIND = 50; +// The age past which a clip window is proposed for eviction (by age only). +export const SPACE_CLIP_AGE_DAYS = 30; +// The age past which a downloader's partial counts as abandoned. +export const SPACE_PARTIAL_AGE_DAYS = 7; +// What a move must leave on its target beyond the free-space floor. +export const SPACE_MOVE_MARGIN_BYTES = 5 * 1024 ** 3; + +export type SpaceDiskStatus = "ok" | "not-mounted" | "not-answering"; + +// What of a disk is the archive's, by what it is. Every figure is allocated +// bytes (st_blocks × 512, what df counts), each inode once. +export type SpaceArchiveShare = { + // Audio, raw live chat and kept chat captures (the media tier). + media: number; + // Transcripts, captions, metadata, sidecars: channels' text. + text: number; + // Fetched clip windows (`data/<id>/clips/`). + clips: number; + // The saved-video store (containers, alternates, staging, scratch). + store: number; + // Browser-playable copies (prepare-playable). + playable: number; + // Site builds (export/.export-builds, export/public, homepage/out). + builds: number; + // umtool's report projects (its REPORTS_DIR). + reports: number; + // Everything else under transcripts/ (index.mdb, .jobs, export, …). + other: number; +}; + +export type SpaceDisk = { + id: string; + label: string; + mountpoint: string | null; + status: SpaceDiskStatus; + detail?: string; + // "corpus disk", "location <label>", "saved-video store", "site builds", "umtool reports". + roles: string[]; + locationIds: string[]; + sizeBytes: number | null; + // Available to an unprivileged write (statfs bavail), at scan time. + freeBytes: number | null; + archive: SpaceArchiveShare | null; + archiveBytes: number | null; +}; + +export type SpaceKind = + | "compress-captions" + | "compress-live-chat" + | "clean-audio" + | "clean-extra-formats" + | "move-media" + | "move-store" + | "evict-clips" + | "stale-partial" + | "compact" + | "drop-original" + | "failed-encode" + | "drop-alternate" + | "reverify-landing" + | "unstored-container"; + +export const SPACE_KIND_LABELS: Record<SpaceKind, string> = { + "compress-captions": "Compress caption tracks", + "compress-live-chat": "Compress raw live chats", + "clean-audio": "Clean audio of transcribed videos", + "clean-extra-formats": "Clean extra audio formats", + "move-media": "Move a channel's media to a location", + "move-store": "Move the saved-video store", + "evict-clips": "Evict old clip windows", + "stale-partial": "Remove abandoned partial downloads", + compact: "Compact saved videos", + "drop-original": "Drop compacted originals", + "failed-encode": "Clear failed encodes", + "drop-alternate": "Drop saved alternates", + "reverify-landing": "Verify live landings again", + "unstored-container": "Source containers not in the store", +}; + +// The existing ops call that does it (`pnpm ops <op> --json <body>`), which is +// also what the page's button posts. +export type SpaceAction = { op: string; body: Record<string, unknown> }; +export type SpaceLink = { href: string; label: string }; + +export type SpaceSuggestion = { + key: string; + kind: SpaceKind; + slug?: string; + id?: string; + file?: string; + title: string; + // What it frees NOW, on which disk. Null: nothing yet (a compaction keeps + // its original until a separate drop). + frees: { disk: string; bytes: number } | null; + // What it may free later, and when. + later?: { disk: string; low: number; high: number; when: string }; + // For a move: what it fills, and whether that leaves the target its floor. + fills?: { disk: string; bytes: number; fits: boolean; freeAfter: number | null }; + basis: "measured" | "estimate"; + basisText: string; + // What is lost or kept: re-fetchable? the only copy? reversible? + loss: string; + actions?: SpaceAction[]; + link?: SpaceLink; + // WHAT THE CLICK RE-CHECKS (controller/spaceHold.ts recheckSpaceRow): the + // subject the held predicate is asked of again (a channel, a video of it, + // and the store for a store row), each target file as the scan saw it + // (still there, same size and mtime, one link), and for a channel-wide clip + // eviction the digest of its whole set of old windows. + hold?: { slug?: string; id?: string; store?: true }; + targets?: { path: string; size: number; mtimeMs: number }[]; + digest?: { olderThanDays: number; count: number; sha1: string }; + // Files with other hard links: removing this name frees nothing of them. + shared?: { files: number; bytes: number }; + detail?: string; + // Shown but not to be run (a move that does not fit): why. + disabled?: string; +}; + +// Not offered, and why. +export type SpaceHeld = { + key: string; + what: string; + disk: string | null; + bytes: number | null; + count: number; + why: string; + link?: SpaceLink; +}; + +// Containers the compaction selector refuses, by its rule. +export type SpaceRefused = { + group: string; + count: number; + bytes: number; + disk: string | null; + examples: { slug: string; id: string; bytes: number; reason: string }[]; +}; + +// The archive's bytes nothing in the editor removes: sized, with the owner. +export type SpaceUnmanaged = { + key: string; + what: string; + disk: string | null; + bytes: number; + count?: number; + owner: string; + command?: string; + link?: SpaceLink; +}; + +export type SpaceOverflow = { kind: SpaceKind; disk: string | null; count: number; bytes: number; link?: SpaceLink }; + +export type SpaceProbeMemo = Record<string, { size: number; mtimeMs: number; probe: unknown }>; + +export type SpaceScanResult = { + version: typeof SPACE_SCAN_VERSION; + computedAt: string; + tookMs: number; + jobId?: string; + // settings.minFreeDiskGB, in bytes (0 = no floor). + floorBytes: number; + disks: SpaceDisk[]; + suggestions: SpaceSuggestion[]; + overflow: SpaceOverflow[]; + held: SpaceHeld[]; + refused: SpaceRefused[]; + unmanaged: SpaceUnmanaged[]; + // Channels the scan did not walk, and why (legacy, moving, inconsistent). + notScanned: { slug: string; why: string }[]; + // Whether the compaction pass ran this time (false: carried from `compactionAt`). + compactionAt: string | null; + // ffprobe answers by container path, reused while size and mtime match. + probes: SpaceProbeMemo; +}; + +// --- ordering ------------------------------------------------------------------ + +function freeShare(d: SpaceDisk): number { + if (!d.sizeBytes || d.freeBytes === null) return Number.POSITIVE_INFINITY; + return d.freeBytes / d.sizeBytes; +} + +// Most in need first: a disk under the floor, then the smallest share free. +// A disk the scan could not read (not mounted, not answering) is last. +export function diskNeedOrder(disks: readonly SpaceDisk[], floorBytes: number): SpaceDisk[] { + const under = (d: SpaceDisk) => floorBytes > 0 && d.freeBytes !== null && d.freeBytes < floorBytes; + return [...disks].sort((a, b) => { + const ra = a.status === "ok" ? 0 : 1; + const rb = b.status === "ok" ? 0 : 1; + if (ra !== rb) return ra - rb; + const ua = under(a) ? 0 : 1; + const ub = under(b) ? 0 : 1; + if (ua !== ub) return ua - ub; + return freeShare(a) - freeShare(b); + }); +} + +export function fullestDiskId(disks: readonly SpaceDisk[], floorBytes: number): string | null { + const first = diskNeedOrder(disks, floorBytes)[0]; + return first && first.status === "ok" ? first.id : null; +} + +function freesNow(s: SpaceSuggestion): number { + return s.frees?.bytes ?? 0; +} + +// Every suggestion that frees bytes on `diskId` (or will, for a compaction), +// biggest first; one that frees nothing now after every one that does. +export function suggestionsForDisk( + result: Pick<SpaceScanResult, "suggestions">, + diskId: string, +): SpaceSuggestion[] { + return result.suggestions + .filter((s) => s.frees?.disk === diskId || (!s.frees && s.later?.disk === diskId)) + .sort((a, b) => freesNow(b) - freesNow(a) || (b.later?.low ?? 0) - (a.later?.low ?? 0)); +} + +export type SpaceGroup = { kind: SpaceKind; label: string; bytes: number; laterLow: number; laterHigh: number; rows: SpaceSuggestion[] }; + +// The kinds that lead a disk's list whatever their subtotal. On the corpus +// disk: caption compression (orchestrator's default, 24 Nov) — lossless, +// reversible, and there the biggest real win (77 GB of plain tracks measured +// on 24 Nov, about 62 GB back at compress-text's ratio). +export function leadKindsFor(diskId: string): SpaceKind[] { + return diskId === "corpus" ? ["compress-captions"] : []; +} + +// By kind, each with what it frees in total; a `lead` kind first, then the +// group that frees most. +export function groupSuggestions(list: readonly SpaceSuggestion[], opts: { lead?: readonly SpaceKind[] } = {}): SpaceGroup[] { + const by = new Map<SpaceKind, SpaceGroup>(); + for (const s of list) { + let g = by.get(s.kind); + if (!g) { + g = { kind: s.kind, label: SPACE_KIND_LABELS[s.kind], bytes: 0, laterLow: 0, laterHigh: 0, rows: [] }; + by.set(s.kind, g); + } + g.rows.push(s); + g.bytes += freesNow(s); + g.laterLow += s.later?.low ?? 0; + g.laterHigh += s.later?.high ?? 0; + } + const groups = [...by.values()]; + for (const g of groups) g.rows.sort((a, b) => freesNow(b) - freesNow(a) || (b.later?.low ?? 0) - (a.later?.low ?? 0)); + const lead = (k: SpaceKind) => { + const i = opts.lead?.indexOf(k) ?? -1; + return i < 0 ? Number.POSITIVE_INFINITY : i; + }; + return groups.sort((a, b) => lead(a.kind) - lead(b.kind) || b.bytes - a.bytes || b.laterLow - a.laterLow); +} + +// --- bounds and rules ------------------------------------------------------------ + +// The target keeps its floor plus a margin after the move, or it does not fit. +export function moveFit(targetFree: number | null, bytes: number, floorBytes: number): { fits: boolean; freeAfter: number | null } { + if (targetFree === null) return { fits: false, freeAfter: null }; + const freeAfter = targetFree - bytes; + return { fits: freeAfter >= floorBytes + SPACE_MOVE_MARGIN_BYTES, freeAfter }; +} + +// What compressing `plainBytes` at the controller's ratio gives back. +export function compressSaving(plainBytes: number, ratio: number): number { + return Math.max(0, Math.round(plainBytes * (1 - ratio))); +} + +// At most SPACE_ITEMS_PER_KIND rows per kind and disk, biggest kept; the rest +// counted exactly so a total never shrinks. +export function capPerKind(list: readonly SpaceSuggestion[], n = SPACE_ITEMS_PER_KIND): { kept: SpaceSuggestion[]; overflow: SpaceOverflow[] } { + const by = new Map<string, SpaceSuggestion[]>(); + for (const s of list) { + const k = `${s.kind}\u0000${s.frees?.disk ?? s.later?.disk ?? ""}`; + (by.get(k) ?? by.set(k, []).get(k)!).push(s); + } + const kept: SpaceSuggestion[] = []; + const overflow: SpaceOverflow[] = []; + for (const rows of by.values()) { + rows.sort((a, b) => freesNow(b) - freesNow(a) || (b.later?.low ?? 0) - (a.later?.low ?? 0)); + kept.push(...rows.slice(0, n)); + const rest = rows.slice(n); + if (rest.length) { + overflow.push({ + kind: rest[0].kind, + disk: rest[0].frees?.disk ?? rest[0].later?.disk ?? null, + count: rest.length, + bytes: rest.reduce((t, s) => t + freesNow(s), 0), + }); + } + } + return { kept, overflow }; +} + +// The compaction selector's refusal (controller/compactSavedVideos.ts planOne) +// as its rule, numbers left out; null for one that is not a refusal of a +// container (already compacted: its original is a drop-original row). +export function refusalGroup(reason: string): string | null { + const r = reason.toLowerCase(); + if (r.startsWith("already compacted")) return null; + if (r.includes("minvideombps")) return "below the bitrate floor"; + if (r.includes("minheight")) return "below the height floor"; + if (/^platform .* is not selected/.test(r)) return "platform not selected"; + if (r.includes("keep-latest")) return "keep-latest (not deliberately stored)"; + if (r.includes('"override"')) return "override (not known to be deliberate)"; + if (r.includes("legacy pointer")) return "legacy pointer"; + if (r.startsWith("already av1")) return "already AV1"; + if (r.includes("excludefromcompaction")) return "channel opts out"; + if (r.includes("last compaction failed")) return "last compaction failed"; + if (r.includes("keeps an original")) return "keeps an earlier original"; + if (r.includes("not in the store")) return "container missing from the store"; + if (r.includes("ffprobe could not read")) return "unreadable container"; + if (r.includes("no video stream")) return "audio-only container"; + if (r.includes("length is unknown")) return "length unknown"; + return "other"; +} + +// May a non-original alternate be proposed for a drop? A pin keeps every copy +// of its video (ruling 2, orchestrator's default 24 Nov: a pin bars removing +// the pinned copy); a proxy is kept on purpose; an original belongs to the +// compaction rules (drop-original rows); a former original is the person's +// to drop on the video page (ruling B1): offered as a row with a link only. +export function alternateDisposition( + pointer: SavedVideoPointer, + alt: SavedVideoAlternate, +): { offer: true; formerOriginal?: 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" }; + if (pointer.keepReason === "pin") return { offer: false, why: "the video is pinned: its copies are kept" }; + if (alt.keptAs === "former-original") return { offer: true, formerOriginal: true }; + return { offer: true }; +} + +// THE KINDS THAT COUNT THE SAME FILES: a channel's audio is what the clean +// sweeps remove and what a move carries; its raw live chat is what a move +// carries and what compression shrinks. +const OVERLAPPING: ReadonlySet<SpaceKind> = new Set(["clean-audio", "clean-extra-formats", "move-media", "compress-live-chat"]); + +// What a disk's list frees, each file once (review 1, not blocking 2): of one +// channel's overlapping kinds the larger, never the sum; a row that cannot +// run (a move that does not fit) left out; what frees nothing now counts 0. +export function diskSuggestedBytes(list: readonly SpaceSuggestion[]): number { + let total = 0; + const overlap = new Map<string, number>(); + for (const s of list) { + if (s.disabled || !s.frees) continue; + if (OVERLAPPING.has(s.kind) && s.slug) { + const k = `${s.slug}\u0000${s.frees.disk}`; + overlap.set(k, Math.max(overlap.get(k) ?? 0, s.frees.bytes)); + } else total += s.frees.bytes; + } + for (const v of overlap.values()) total += v; + return total; +} + +// --- words ----------------------------------------------------------------------- + +export function usedPercent(d: Pick<SpaceDisk, "sizeBytes" | "freeBytes">, free = d.freeBytes): number | null { + if (!d.sizeBytes || free === null) return null; + return Math.round(((d.sizeBytes - free) / d.sizeBytes) * 100); +} + +export function ageText(computedAt: string, now = Date.now()): string { + const s = Math.max(0, Math.round((now - Date.parse(computedAt)) / 1000)); + if (!Number.isFinite(s)) return "at an unknown time"; + if (s < 90) return "just now"; + const m = Math.round(s / 60); + if (m < 90) return `${m} min ago`; + const h = Math.round(m / 60); + if (h < 48) return `${h} h ago`; + return `${Math.round(h / 24)} days ago`; +} + +// The /cleanup page's one line: the fullest disk, its free space now (`live`, +// by disk id, when the caller has it) and what the scan suggests there. +export function spaceSummaryLine( + result: Pick<SpaceScanResult, "disks" | "suggestions" | "floorBytes" | "computedAt"> | null, + live: Record<string, number | undefined>, +): string | null { + if (!result) return null; + const id = fullestDiskId(result.disks, result.floorBytes); + const d = result.disks.find((x) => x.id === id); + if (!d) return null; + const free = live[d.id] ?? d.freeBytes; + const pct = usedPercent(d, free ?? null); + const suggested = diskSuggestedBytes(suggestionsForDisk(result, d.id)); + return ( + `${d.label}: ${free === null || free === undefined ? "free space unknown" : `${formatBytes(free)} free`}` + + `${pct === null ? "" : ` (${pct} % used)`} · ~${formatBytes(suggested)} suggested there` + ); +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,33 @@ # Changelog ## [Unreleased] +- **Free up space: `/cleanup/space`, every disk the archive writes to and what frees space on each.** + - The disks, the fullest first and marked: each one's size, free space now, how much of it is the archive's (by + kind: media, text, clip windows, saved videos, playable copies, site builds, umtool reports, the index) and how + much is not. An unmounted or unanswering location reads "not scanned", never empty. + - The disk picked lists what would free space on it, by kind, the biggest first, with caption compression leading + the corpus disk. Each row says how much it frees and where (measured, or an estimate and from what), what a move + fills and whether it fits, and what is lost. + - The kinds: compressing caption tracks or raw live chats, the cleanup sweeps, moving a channel's media to a + location, evicting clip windows untouched for 30 days, abandoned partial downloads, compacting saved videos, and + dropping compacted originals, alternates and failed encodes. Also live landings to verify again, and source + containers left outside the store (a link to the video page only). + - Every button runs the existing writer for its kind (compress-text, cleanup, relocate, evict-clips, delete-file, + compact-saved-videos, drop-saved-alternate, kept-failed-encodes, live-recording-verify). It offers a dry run where + the writer answers one at once. Before anything runs the row is checked again: a scan older than a day is + refused, then the held rules, then each target file's size, mtime and single link. A former original is a link + to the video page, never a button here. + - Compaction frees nothing until the original is dropped, and the row says so. + - Held and why, for every row the store's included: do-not-clean, a pinned video's copies, a must-keep or + unfinished live recording, a job for the video, a move in flight (the channel's or the store's), and a partial of + a video not known to be on its platform. A mark or a live-recordings file that cannot be read holds too. The + channel-wide audio sweeps are held while any video of the channel is held. Then the compaction + selector's refusals by rule, and the archive's bytes no writer here removes, with their owner (umtool's reports: + `umtool prune --all`). + - The numbers come from a scan, a `space-scan` job (Refresh; `pnpm ops space-scan`), into + `transcripts/.space-suggestions.json`. It only reads: allocated bytes, each inode once, and a hard-linked file is + never counted as freed. `pnpm ops get space-suggestions [<disk>]` answers the same list. `/cleanup` gets the two + tabs and a one-line summary. - **A live recording keeps itself alive: the start retried beside the live edge, stalls restarted, an insurance recorder, a restart after the editor's, and parts joined.** - A from-start recorder that dies, stalls or is stopped by an editor shutdown is RESUMED in place from yt-dlp's diff --git a/editor/app/api/ops/space-scan/route.test.ts b/editor/app/api/ops/space-scan/route.test.ts @@ -0,0 +1,74 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/space-scan/route.test.ts" +// +// The space scan as a job: refusals before any job, then one run over a temp +// corpus that writes the result file and nothing else in the corpus. + +const corpus = await setupOpsCorpus(null); +const reports = await mkdtemp(path.join(os.tmpdir(), "space-scan-reports-")); +process.env.SPACE_SCAN_REPORTS_DIR = reports; +await corpus.writeChannelConfig("demo", { url: "https://www.youtube.com/@demo" }); +const video = path.join(corpus.transcripts, "channels", "demo", "data", "vid00000001"); +await mkdir(video, { recursive: true }); +await writeFile(path.join(video, "transcript.en.vtt"), Buffer.alloc(9_000, 65)); + +const { POST } = await import("./route"); +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +const { quiesceJobs, settleJob } = await import("yt-dlp-transcript-common/testing/jobs/quiesce.js"); +test.after(async () => { + await quiesceJobs(); + await corpus.cleanup(); + await rm(reports, { recursive: true, force: true }); +}); + +test("refusals: unknown keys and a non-boolean compaction queue nothing", async () => { + const before = await corpus.listJobIds(); + const a = await callPost(POST, { force: true }); + assert.equal(a.status, 400); + assert.match(a.body.error!, /unknown key\(s\): force/); + const b = await callPost(POST, { compaction: "no" }); + assert.equal(b.status, 400); + assert.match(b.body.error!, /"compaction" must be a boolean/); + assert.deepEqual(await corpus.listJobIds(), before); +}); + +test("a scan runs as a job and writes .space-suggestions.json", async () => { + const r = await callPost(POST, { compaction: false }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + const jobId = r.body.jobId as string; + await settleJob(jobId); + assert.equal(getRegistry().get(jobId)?.status, "done"); + const names = await readdir(corpus.transcripts); + assert.ok(names.includes(".space-suggestions.json"), names.join(", ")); + const { readSpaceSuggestions } = await import("yt-dlp-transcript-common/controller/spaceScan"); + const result = await readSpaceSuggestions({ transcriptsDir: corpus.transcripts }); + assert.equal(result?.jobId, jobId); + assert.ok(result?.suggestions.some((s) => s.kind === "compress-captions" && s.slug === "demo")); + assert.equal(result?.compactionAt, null); +}); + +test("a scan already queued or running is the answer: no second one is queued", async () => { + const { newJobId } = await import("yt-dlp-transcript-common/jobs/registry"); + const record = { id: newJobId(), kind: "space-scan", queueKey: "space-scan-held", status: "queued" as const, queuedAt: Date.now(), logPath: "/dev/null" }; + getRegistry().register(record); + getRegistry().enqueue(record, { start: () => {}, onCancel: () => {} }); + const before = await corpus.listJobIds(); + const r = await callPost(POST, {}); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.jobId, record.id); + assert.equal(r.body.alreadyQueued, true); + assert.deepEqual(await corpus.listJobIds(), before); + const { startSpaceScanAction } = await import("../../../cleanup/space/actions"); + const ui = await startSpaceScanAction(); + assert.equal(ui.ok, false); + assert.ok(!ui.ok && ui.info); + assert.match(!ui.ok ? ui.error : "", new RegExp(record.id)); + getRegistry().cancel?.(record.id); +}); diff --git a/editor/app/api/ops/space-scan/route.ts b/editor/app/api/ops/space-scan/route.ts @@ -0,0 +1,31 @@ +import { SPACE_SCAN_BODY_KEYS } from "yt-dlp-transcript-common/controller/spaceScan"; +import { enqueueSpaceScanJob } from "../../../cleanup/space/lib/spaceJob"; +import { NextResponse } from "next/server"; +import { spaceScanJob } from "../../../cleanup/space/lib/loadSpace"; +import { jobResponse, ops, optBool } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { compaction? } -> { ok: true, jobId } +// +// The space scan (lane space-suggestions, controller/spaceScan.ts) as a +// `space-scan` job on its own machine-wide queue: every disk the archive +// writes to — the corpus disk, each storage location, the saved-video store's, +// the site builds' and umtool's reports' — measured (allocated bytes, each +// inode once, a hard-linked file never counted as freed, an unmounted or +// unanswering drive unknown and never empty), and what would free space on +// each through the writers that already exist, into +// `transcripts/.space-suggestions.json` (`get space-suggestions` reads it). +// It only reads: nothing is removed, moved or fetched. `"compaction": false` +// skips the compaction selector's pass (one ffprobe per saved container not +// seen unchanged before) and carries the last scan's compaction rows. While a +// scan is queued or running nothing more is queued: the answer is that job, +// `{ok: true, jobId, alreadyQueued: true}`. +export async function POST(request: Request) { + return ops(request, SPACE_SCAN_BODY_KEYS, async (body) => { + const compaction = optBool(body, "compaction"); + const there = spaceScanJob(); + if (there) return NextResponse.json({ ok: true, jobId: there.jobId, alreadyQueued: true, status: there.status }); + return jobResponse(await enqueueSpaceScanJob(compaction === false ? { compaction: false } : {})); + }); +} diff --git a/editor/app/api/ops/space-suggestions/route.test.ts b/editor/app/api/ops/space-suggestions/route.test.ts @@ -0,0 +1,76 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callGet } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/space-suggestions/route.test.ts" +// +// The read of the space scan's file: it never computes. No scan yet is an +// answer, not an error; a disk names whose suggestions come back. + +const corpus = await setupOpsCorpus(null); +const { GET } = await import("./route"); +test.after(() => corpus.cleanup()); + +const URL_BASE = "http://localhost/api/ops/space-suggestions"; + +test("no scan yet: computedAt null, nothing computed", async () => { + const r = await callGet(GET, URL_BASE); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.ok, true); + assert.equal(r.body.computedAt, null); +}); + +test("refusals: an unknown query key, a disk the scan does not know", async () => { + await seed(); + assert.equal((await callGet(GET, `${URL_BASE}?disc=corpus`)).status, 400); + const r = await callGet(GET, `${URL_BASE}?disk=nowhere`); + assert.equal(r.status, 400); + assert.match(r.body.error!, /no disk "nowhere".*corpus, platter/); +}); + +test("the fullest disk's suggestions by default, another disk's when named; the probe memo left out", async () => { + await seed(); + const r = await callGet(GET, URL_BASE); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.disk, "corpus"); + assert.deepEqual((r.body.disks as { id: string }[]).map((d) => d.id), ["corpus", "platter"]); + assert.deepEqual((r.body.suggestions as { kind: string }[]).map((s) => s.kind), ["compress-captions", "evict-clips"]); + assert.equal("probes" in r.body, false); + // The page's groups: caption compression leads the corpus disk. + assert.deepEqual((r.body.groups as { kind: string }[]).map((g) => g.kind), ["compress-captions", "evict-clips"]); + const p = await callGet(GET, `${URL_BASE}?disk=platter`); + assert.deepEqual((p.body.suggestions as { kind: string }[]).map((s) => s.kind), ["drop-original"]); + assert.ok(typeof p.body.ageSeconds === "number"); +}); + +async function seed(): Promise<void> { + const GB = 1024 ** 3; + const disk = (id: string, size: number, free: number) => ({ + id, label: id, mountpoint: `/${id}`, status: "ok", roles: [], locationIds: id === "platter" ? ["platter"] : [], + sizeBytes: size * GB, freeBytes: free * GB, archive: null, archiveBytes: null, + }); + const sug = (kind: string, disk: string, bytes: number) => ({ + key: `${kind}:${disk}`, kind, title: kind, frees: { disk, bytes: bytes * GB }, basis: "measured", basisText: "", loss: "", + }); + await writeFile( + path.join(corpus.transcripts, ".space-suggestions.json"), + JSON.stringify({ + version: 2, + computedAt: new Date().toISOString(), + tookMs: 1, + floorBytes: 0, + disks: [disk("platter", 1800, 202), disk("corpus", 1500, 24)], + suggestions: [sug("evict-clips", "corpus", 9), sug("drop-original", "platter", 30), sug("compress-captions", "corpus", 62)], + overflow: [], + held: [], + refused: [], + unmanaged: [], + notScanned: [], + compactionAt: null, + probes: { "/x": { size: 1, mtimeMs: 1, probe: null } }, + }), + ); +} diff --git a/editor/app/api/ops/space-suggestions/route.ts b/editor/app/api/ops/space-suggestions/route.ts @@ -0,0 +1,40 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readSpaceSuggestions } from "yt-dlp-transcript-common/controller/spaceScan"; +import { diskNeedOrder } from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import { spaceScanJob, spaceView } from "../../../cleanup/space/lib/loadSpace"; +import { readRoute } from "../_read"; +import { opsFail } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// GET [?disk=<id>] +// -> { ok, computedAt, ageSeconds, tookMs, jobId?, scan: {jobId, status} | null, +// floorBytes, disks (most in need first), disk, groups (the page's +// order: caption compression leads the corpus disk, then by subtotal), +// suggestions (for `disk`, default the fullest, biggest saving first), +// overflow, held, refused, +// unmanaged, notScanned, compactionAt } +// +// /cleanup/space's list (lane space-suggestions): what the last space scan +// (`space-scan`, controller/spaceScan.ts) found — every disk the archive +// writes to, how much of it is the archive's, and what would free space on +// each, each suggestion with its `actions` (the existing ops call that does +// it: `pnpm ops <op> --json <body>`), its `basis` (measured or an estimate, +// and from what) and what it loses. It READS THE FILE ONLY; with no scan yet +// it answers `computedAt: null`. `space-scan` runs one. +export async function GET(request: Request) { + return readRoute(request, ["disk"], async (q) => { + const result = await readSpaceSuggestions(getPaths()); + const scan = spaceScanJob(); + if (!result) return { computedAt: null, scan }; + const disk = q.get("disk")?.trim() || null; + if (disk && !result.disks.some((d) => d.id === disk)) { + return opsFail(`no disk "${disk}" in the last scan — it knows ${diskNeedOrder(result.disks, result.floorBytes).map((d) => d.id).join(", ")}`); + } + return { + ...spaceView(result, disk), + ageSeconds: Math.max(0, Math.round((Date.now() - Date.parse(result.computedAt)) / 1000)), + scan, + }; + }); +} diff --git a/editor/app/cleanup/components/CleanupTabs.tsx b/editor/app/cleanup/components/CleanupTabs.tsx @@ -0,0 +1,24 @@ +import Link from "next/link"; + +// The two halves of /cleanup: the audio sweeps and their holds, and Free up +// space (every disk, every writer that frees bytes on it). +export function CleanupTabs({ active }: { active: "audio" | "space" }) { + const tab = (href: string, id: "audio" | "space", label: string) => ( + <Link + href={href} + aria-current={active === id ? "page" : undefined} + className={ + "rounded-md px-3 py-1.5 text-sm " + + (active === id ? "bg-secondary font-medium text-foreground" : "text-muted-foreground hover:text-foreground") + } + > + {label} + </Link> + ); + return ( + <nav aria-label="cleanup tabs" className="flex flex-wrap gap-1"> + {tab("/cleanup/space", "space", "Free up space")} + {tab("/cleanup", "audio", "Audio & holds")} + </nav> + ); +} diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx @@ -17,6 +17,9 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates"; import { LaneActionButton } from "../components/lanes/LaneActionButton"; import { workThroughSpeakersAction } from "../jobs/actions"; +import { CleanupTabs } from "./components/CleanupTabs"; +import { loadSpace } from "./space/lib/loadSpace"; +import { spaceSummaryLine } from "yt-dlp-transcript-common/lib/spaceSuggestions"; export const dynamic = "force-dynamic"; @@ -35,6 +38,10 @@ export default async function CleanupPage() { const settings = getSettings(); const speakersWorking = settings.autoQueue.backfill.enabled && !isGateHeld(settings, "backfill"); + // Free up space's one line: the last space scan's file and each disk's free + // space now — no walk. + const space = await loadSpace(); + const spaceLine = spaceSummaryLine(space.result, space.live); const { rows, includedReclaimBytes, @@ -60,6 +67,13 @@ export default async function CleanupPage() { <div className="flex items-center justify-between flex-wrap gap-2"> <h1 className="text-2xl font-semibold">Cleanup</h1> </div> + <CleanupTabs active="audio" /> + <p className="text-sm" aria-label="space summary"> + {spaceLine ?? "No space scan yet."}{" "} + <Link href="/cleanup/space" className="underline hover:text-foreground"> + Free up space + </Link> + </p> {/* Hero readout — the reclamation console. */} <section diff --git a/editor/app/cleanup/space/actions.ts b/editor/app/cleanup/space/actions.ts @@ -0,0 +1,27 @@ +"use server"; + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readSpaceSuggestions, readSpaceSuggestionsVersion } from "yt-dlp-transcript-common/controller/spaceScan"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { enqueueSpaceScanJob } from "./lib/spaceJob"; +import { runSpaceSuggestion, type SpaceRunOutcome } from "./lib/runSpaceAction"; + +// /cleanup/space's two buttons. Refresh is the `space-scan` job (`pnpm ops +// space-scan`); a suggestion's button names its KEY and runs the actions the +// scan wrote for it, through the existing writers (lib/runSpaceAction.ts). + +export async function startSpaceScanAction(): Promise<StreamActionResult> { + return enqueueSpaceScanJob(); +} + +export async function runSpaceSuggestionAction( + key: string, + opts: { dryRun?: boolean } = {}, +): Promise<SpaceRunOutcome> { + const result = await readSpaceSuggestions(getPaths()); + const fileVersion = result ? null : await readSpaceSuggestionsVersion(getPaths()); + const out = await runSpaceSuggestion({ result, fileVersion, key, dryRun: opts.dryRun === true }); + if (!out.dryRun && out.ok) safeRevalidate(["/cleanup", "/cleanup/space"]); + return out; +} diff --git a/editor/app/cleanup/space/components/SpaceRefresh.tsx b/editor/app/cleanup/space/components/SpaceRefresh.tsx @@ -0,0 +1,31 @@ +"use client"; + +import Link from "next/link"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { startSpaceScanAction } from "../actions"; + +// Refresh: the space scan as a job (`pnpm ops space-scan`). While one is +// queued or running the page names it instead of offering a second. +export function SpaceRefresh({ running }: { running: { jobId: string; status: string } | null }) { + if (running) { + return ( + <span className="text-sm text-muted-foreground" aria-label="space scan running"> + A scan is {running.status}:{" "} + <Link href={`/jobs/${running.jobId}`} className="underline hover:text-foreground"> + its job + </Link> + </span> + ); + } + return ( + <StreamActionLog + trigger={startSpaceScanAction} + cancelAction={cancelJobAction} + buttonLabel="Refresh" + runningLabel="Scanning…" + label="Space scan" + title="Measure every disk the archive writes to and what would free space on each (reads only)." + /> + ); +} diff --git a/editor/app/cleanup/space/components/SpaceRow.tsx b/editor/app/cleanup/space/components/SpaceRow.tsx @@ -0,0 +1,130 @@ +"use client"; + +import { useState, useTransition } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { Button } from "yt-dlp-transcript-common/components/ui/button"; +import { formatBytes } from "yt-dlp-transcript-common/lib/format"; +import type { SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import { runSpaceSuggestionAction } from "../actions"; + +// Ops that answer a dry run at once (lib/runSpaceAction.ts SPACE_DRY_RUNNABLE; +// repeated here because that module is server-only). +const DRY_RUNNABLE = new Set(["compress-text", "compact-saved-videos", "drop-saved-alternate"]); + +type Outcome = { ok: boolean; lines: string[]; jobIds: string[]; dryRun: boolean }; + +export function SpaceRow({ s, diskLabel }: { s: SpaceSuggestion; diskLabel: Record<string, string> }) { + const router = useRouter(); + const [open, setOpen] = useState(false); + const [preview, setPreview] = useState<Outcome | null>(null); + const [done, setDone] = useState<Outcome | null>(null); + const [pending, start] = useTransition(); + const canDry = !!s.actions?.length && s.actions.every((a) => DRY_RUNNABLE.has(a.op)); + const label = (id: string) => diskLabel[id] ?? id; + + const run = (dryRun: boolean) => + start(async () => { + const out = await runSpaceSuggestionAction(s.key, { dryRun }); + if (dryRun) setPreview(out); + else { + setDone(out); + router.refresh(); + } + }); + + return ( + <li className="flex flex-col gap-1.5 border-t border-border py-2.5 first:border-t-0" aria-label={s.title}> + <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1"> + <span className="text-sm">{s.title}</span> + <span className="font-mono text-sm tabular-nums"> + {s.frees ? ( + <> + {s.basis === "estimate" ? "~" : ""} + {formatBytes(s.frees.bytes)} on {label(s.frees.disk)} + </> + ) : s.later ? ( + <> + later ~{formatBytes(s.later.low)}–{formatBytes(s.later.high)} on {label(s.later.disk)} + </> + ) : null} + </span> + </div> + <div className="flex flex-col gap-0.5 text-xs text-muted-foreground"> + {s.fills && ( + <span> + Fills {label(s.fills.disk)} by {formatBytes(s.fills.bytes)} + {s.fills.freeAfter !== null ? ` (${formatBytes(Math.max(0, s.fills.freeAfter))} free after)` : ""} ·{" "} + {s.fills.fits ? "fits" : "does not fit"} + </span> + )} + {s.later && <span>Frees nothing now: {s.later.when}.</span>} + <span>{s.basisText}</span> + <span>Loses: {s.loss}</span> + {s.shared && ( + <span> + Shared: {s.shared.files} file(s), {formatBytes(s.shared.bytes)} with another hard link, not counted + </span> + )} + {s.disabled && <span className="text-amber-600 dark:text-amber-400">{s.disabled}</span>} + </div> + <div className="flex flex-wrap items-center gap-2"> + {s.actions?.length && !s.disabled && !done?.ok ? ( + open ? null : ( + <Button size="xs" variant="outline" onClick={() => setOpen(true)}> + {s.kind === "compact" ? "Compact…" : s.kind.startsWith("move") ? "Move…" : s.kind.startsWith("compress") ? "Compress…" : s.kind === "reverify-landing" ? "Verify again…" : "Free it…"} + </Button> + ) + ) : null} + {s.link && ( + <Link href={s.link.href} className="text-xs underline hover:text-foreground"> + {s.link.label} + </Link> + )} + </div> + {open && !done?.ok && ( + <div className="flex flex-col gap-2 rounded-md border border-border bg-muted/40 p-3 text-xs" role="group" aria-label={`confirm ${s.title}`}> + <span> + Runs{" "} + {s.actions!.map((a, i) => ( + <code key={i} className="mr-1 font-mono"> + pnpm ops {a.op} --json &apos;{JSON.stringify(a.body)}&apos; + </code> + ))} + </span> + {canDry && ( + <div className="flex flex-col gap-1"> + <Button size="xs" variant="ghost" className="self-start" disabled={pending} onClick={() => run(true)}> + Dry run + </Button> + {preview && ( + <pre className="max-h-48 overflow-auto whitespace-pre-wrap font-mono" aria-label="dry run"> + {preview.lines.join("\n")} + </pre> + )} + </div> + )} + <div className="flex gap-2"> + <Button size="xs" disabled={pending} onClick={() => run(false)}> + Confirm + </Button> + <Button size="xs" variant="ghost" disabled={pending} onClick={() => setOpen(false)}> + Cancel + </Button> + </div> + </div> + )} + {done && ( + <div className={`text-xs ${done.ok ? "text-muted-foreground" : "text-destructive"}`} role="status"> + {done.lines.join(" · ")} + {done.jobIds.map((id) => ( + <Link key={id} href={`/jobs/${id}`} className="ml-2 underline"> + job + </Link> + ))} + {done.ok && <span> · rescan to update</span>} + </div> + )} + </li> + ); +} diff --git a/editor/app/cleanup/space/lib/loadSpace.ts b/editor/app/cleanup/space/lib/loadSpace.ts @@ -0,0 +1,78 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readSpaceSuggestions } from "yt-dlp-transcript-common/controller/spaceScan"; +import { INTERNAL_LOCATION_ID, volumeFreeBytes } from "yt-dlp-transcript-common/controller/storageLocations"; +import { + SPACE_SCAN_JOB_KIND, + diskNeedOrder, + fullestDiskId, + groupSuggestions, + leadKindsFor, + suggestionsForDisk, + type SpaceScanResult, +} from "yt-dlp-transcript-common/lib/spaceSuggestions"; + +// WHAT /cleanup/space, its summary line and `get space-suggestions` read: the +// scan's file (never a walk, a stat of the corpus or an ffprobe), the live +// free space of each disk (two syscalls a location — tables never probe), and +// whether a scan is queued or running. + +export type SpaceScanJob = { jobId: string; status: string } | null; + +export function spaceScanJob(): SpaceScanJob { + const j = getRegistry() + .list() + .filter((r) => r.kind === SPACE_SCAN_JOB_KIND && (r.status === "queued" || r.status === "running")) + .sort((a, b) => (b.queuedAt ?? 0) - (a.queuedAt ?? 0))[0]; + return j ? { jobId: j.id, status: j.status } : null; +} + +// Free bytes now, by the scan's disk ids: `corpus` is the corpus volume, a +// location's disk takes its first location id. +export async function liveFreeByDisk(result: SpaceScanResult | null): Promise<Record<string, number | undefined>> { + if (!result) return {}; + const paths = getPaths(); + const free = await volumeFreeBytes({ paths, locations: getSettings().storage.locations }).catch( + () => ({}) as Record<string, number | undefined>, + ); + const out: Record<string, number | undefined> = {}; + for (const d of result.disks) { + if (d.status !== "ok") continue; + const v = d.id === "corpus" ? free[INTERNAL_LOCATION_ID] : d.locationIds.map((id) => free[id]).find((x) => x !== undefined); + if (v !== undefined) out[d.id] = v; + } + return out; +} + +export async function loadSpace(): Promise<{ + result: SpaceScanResult | null; + live: Record<string, number | undefined>; + job: SpaceScanJob; +}> { + const result = await readSpaceSuggestions(getPaths()); + return { result, live: await liveFreeByDisk(result), job: spaceScanJob() }; +} + +// The read the ops route answers: the file less its probe memo, the disks in +// order of need, the suggestions for one disk (default: the fullest). +export function spaceView(result: SpaceScanResult, disk: string | null) { + const { probes: _probes, ...rest } = result; + void _probes; + const id = disk ?? fullestDiskId(result.disks, result.floorBytes); + const suggestions = id ? suggestionsForDisk(result, id) : []; + return { + ...rest, + disks: diskNeedOrder(result.disks, result.floorBytes), + disk: id, + // The page's groups, in its order (a lead kind first, then by subtotal). + groups: groupSuggestions(suggestions, { lead: id ? leadKindsFor(id) : [] }).map((g) => ({ + kind: g.kind, + label: g.label, + bytes: g.bytes, + count: g.rows.length, + ...(g.laterHigh ? { later: [g.laterLow, g.laterHigh] } : {}), + })), + suggestions, + }; +} diff --git a/editor/app/cleanup/space/lib/runSpaceAction.test.ts b/editor/app/cleanup/space/lib/runSpaceAction.test.ts @@ -0,0 +1,105 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import type { SpaceScanResult, SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import { runSpaceSuggestion, type SpaceRunner } from "./runSpaceAction"; + +// Run with: +// pnpm -C editor exec tsx --test "app/cleanup/space/lib/runSpaceAction.test.ts" +// +// The page's button names a suggestion by its key; what runs is the body the +// SCAN wrote for it, through the existing writer — never a body the browser +// sends. + +function row(extra: Partial<SpaceSuggestion>): SpaceSuggestion { + return { key: "k", kind: "evict-clips", title: "", frees: { disk: "corpus", bytes: 1 }, basis: "measured", basisText: "", loss: "", ...extra }; +} + +function result(rows: SpaceSuggestion[]): SpaceScanResult { + return { suggestions: rows } as unknown as SpaceScanResult; +} + +function recorder() { + const calls: { op: string; body: Record<string, unknown>; dryRun: boolean }[] = []; + const make = (op: string): SpaceRunner => async (body, o) => { + calls.push({ op, body, dryRun: o.dryRun }); + return { ok: true, lines: [`${op} ran`], jobIds: o.dryRun ? [] : [`job-${op}`], dryRun: o.dryRun }; + }; + const runners: Record<string, SpaceRunner> = Object.fromEntries( + ["compress-text", "evict-clips", "drop-saved-alternate", "relocate", "delete-file"].map((op) => [op, make(op)]), + ); + return { calls, runners }; +} + +test("the scan's own body runs, each action in turn; a dry run only where the writer has one", async () => { + const { calls, runners } = recorder(); + const r = result([ + row({ key: "a", actions: [{ op: "evict-clips", body: { slug: "s", id: "v1", olderThanDays: 30 } }, { op: "evict-clips", body: { slug: "s", id: "v2", olderThanDays: 30 } }] }), + row({ key: "b", kind: "compress-captions", actions: [{ op: "compress-text", body: { slugs: ["s"], kinds: ["captions"] } }] }), + ]); + const out = await runSpaceSuggestion({ result: r, key: "a", dryRun: false, runners, recheck: async () => null }); + assert.equal(out.ok, true); + assert.deepEqual(out.jobIds, ["job-evict-clips", "job-evict-clips"]); + assert.deepEqual(calls.map((c) => c.body.id), ["v1", "v2"]); + // evict-clips' dry run is a job of its own: not offered as a preview. + const pre = await runSpaceSuggestion({ result: r, key: "a", dryRun: true, runners, recheck: async () => null }); + assert.equal(pre.ok, false); + assert.match(pre.lines[0], /no dry run/); + const dry = await runSpaceSuggestion({ result: r, key: "b", dryRun: true, runners, recheck: async () => null }); + assert.equal(dry.ok, true); + assert.equal(calls.at(-1)!.dryRun, true); + assert.deepEqual(calls.at(-1)!.body, { slugs: ["s"], kinds: ["captions"] }); +}); + +test("refusals: an unknown key, a row with only a link, a disabled row, an op with no runner, a body of the wrong shape", async () => { + const { calls, runners } = recorder(); + const r = result([ + row({ key: "link", link: { href: "/x", label: "x" } }), + row({ key: "off", actions: [{ op: "relocate", body: { slugs: ["s"], locationId: "p" } }], disabled: "does not fit" }), + row({ key: "odd", actions: [{ op: "rm-rf", body: {} }] }), + row({ key: "bad", actions: [{ op: "delete-file", body: { slug: "../etc", id: "v", file: "a.part" } }] }), + row({ key: "badfile", actions: [{ op: "delete-file", body: { slug: "s", id: "v", file: "x/../../y" } }] }), + ]); + for (const [key, re] of [ + ["nope", /no suggestion "nope"/], + ["link", /nothing to run here/], + ["off", /does not fit/], + ["odd", /not a writer this page runs: rm-rf/], + ["bad", /not a channel slug/], + ["badfile", /not a file name/], + ] as const) { + const out = await runSpaceSuggestion({ result: r, key, dryRun: false, runners, recheck: async () => null }); + assert.equal(out.ok, false, key); + assert.match(out.lines.join(" "), re, key); + } + assert.equal(calls.length, 0); +}); + +test("the click re-checks the row first: a refusal runs nothing and says why; the former-original flag is never sent", async () => { + const { calls, runners } = recorder(); + const r = result([row({ key: "p", actions: [{ op: "delete-file", body: { slug: "s", id: "v", file: "a.part" } }] })]); + const out = await runSpaceSuggestion({ result: r, key: "p", dryRun: false, runners, recheck: async () => "the last scan is 30 h old: rescan first" }); + assert.equal(out.ok, false); + assert.match(out.lines[0], /rescan first/); + assert.equal(calls.length, 0); + const src = await import("node:fs/promises").then((fs) => fs.readFile(new URL("./runSpaceAction.ts", import.meta.url), "utf8")); + assert.ok(!src.includes("confirm" + "FormerOriginal")); +}); + +test("a failing action stops the rest and says so", async () => { + const { runners } = recorder(); + runners["delete-file"] = async () => ({ ok: false, lines: ["refused: drive not answering"], jobIds: [], dryRun: false }); + const r = result([ + row({ key: "p", actions: [{ op: "delete-file", body: { slug: "s", id: "v", file: "a.part" } }, { op: "delete-file", body: { slug: "s", id: "v", file: "a.ytdl" } }] }), + ]); + const out = await runSpaceSuggestion({ result: r, key: "p", dryRun: false, runners, recheck: async () => null }); + assert.equal(out.ok, false); + assert.deepEqual(out.lines, ["refused: drive not answering", "1 more not run"]); +}); + +test("review 2: a scan file of another version is refused with rescan first, not run", async () => { + const { calls, runners } = recorder(); + const out = await runSpaceSuggestion({ result: null, fileVersion: 1, key: "p", dryRun: false, runners, recheck: async () => null }); + assert.equal(out.ok, false); + assert.match(out.lines[0], /older format \(version 1,.*rescan first/); + assert.equal(calls.length, 0); +}); diff --git a/editor/app/cleanup/space/lib/runSpaceAction.ts b/editor/app/cleanup/space/lib/runSpaceAction.ts @@ -0,0 +1,193 @@ +import { SPACE_SCAN_VERSION, type SpaceScanResult, type SpaceSuggestion } from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { formatBytes } from "yt-dlp-transcript-common/lib/format"; +import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; + +// THE PAGE'S BUTTON, ON THE SERVER. It names a suggestion by its key; what runs +// is the `actions` the SCAN wrote for it (`pnpm ops <op> --json <body>`), each +// through the same action its ops route calls — compress-text, the cleanup +// sweeps, relocate, evict-clips, delete-file, compact-saved-videos, +// drop-saved-alternate, kept-failed-encodes, live-recording-verify. Nothing +// else: an op not in the table is refused, no body comes from the browser, +// and a body of the wrong shape (a slug, an id or a file name that is not one +// path segment) is refused. +// +// THE WRITERS DO NOT ALL GUARD WHAT THIS PAGE PROMISES (review 1, B4): the +// Files list's delete, for one, asks no do-not-clean, recording, job or +// marker. So before anything runs the row is RE-CHECKED against the disk as +// it is now (controller/spaceHold.ts recheckSpaceRow): a scan older than a day +// is refused, then the held predicate (do-not-clean, a must-keep or +// unfinished live recording, a job for the video, a relocation marker of the +// channel or of the store), then each target file's size, mtime and single +// link, and a channel-wide eviction's whole set of old windows. A mismatch +// refuses the row and says why. +// +// NOT "use server" (every export there is an endpoint): actions.ts wraps it. + +export type SpaceRunOutcome = { ok: boolean; lines: string[]; jobIds: string[]; dryRun: boolean }; +export type SpaceRunner = (body: Record<string, unknown>, o: { dryRun: boolean }) => Promise<SpaceRunOutcome>; + +// The writers whose dry run answers at once (a job's would be a job). +export const SPACE_DRY_RUNNABLE: ReadonlySet<string> = new Set(["compress-text", "compact-saved-videos", "drop-saved-alternate"]); + +const str = (v: unknown): string => (typeof v === "string" ? v : ""); +const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); + +function fromStream(r: StreamActionResult): SpaceRunOutcome { + if (!r.ok) return { ok: false, lines: [r.error], jobIds: [], dryRun: false }; + void r.stream.cancel(); + return { ok: true, lines: ["queued"], jobIds: [r.jobId], dryRun: false }; +} + +const fail = (error: string): SpaceRunOutcome => ({ ok: false, lines: [error], jobIds: [], dryRun: false }); + +// The real table: the same calls the ops routes make. Imported lazily, so the +// dispatcher's test (and a page that only renders) loads none of them. +export const SPACE_RUNNERS: Record<string, SpaceRunner> = { + "compress-text": async (body, o) => { + const { compressTextAction } = await import("../../../storage/compressTextActions"); + const kinds = strs(body.kinds) as ("live-chat" | "captions")[]; + const r = await compressTextAction({ slugs: strs(body.slugs), ...(kinds.length ? { kinds } : {}), dryRun: o.dryRun }); + if (!r.ok) return fail(r.error); + if (r.dryRun) return { ok: true, lines: r.result.lines, jobIds: [], dryRun: true }; + return { ok: true, lines: [`${r.jobIds.length} job(s) queued`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false }; + }, + cleanup: async (body) => { + const w = await import("../../../channels/[slug]/whisperActions"); + const slug = str(body.slug); + if (body.sweep === "transcribed") return fromStream(await w.cleanAudioAction(slug)); + if (body.sweep === "extra-formats") return fromStream(await w.cleanExtraAudioFormatsAction(slug)); + return fail(`sweep "${str(body.sweep)}" is not one this page runs`); + }, + relocate: async (body) => { + const { bulkRelocateChannelMediaAction } = await import("../../../channels/bulkStorageActions"); + const r = await bulkRelocateChannelMediaAction(strs(body.slugs), { kind: "location", locationId: str(body.locationId) }); + return { + ok: r.queued.length > 0, + lines: [...r.queued.map((s) => `${s}: queued`), ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], + jobIds: r.jobIds, + dryRun: false, + }; + }, + "evict-clips": async (body) => { + const { evictClipWindowsAction } = await import("../../../storage/actions"); + return fromStream( + await evictClipWindowsAction({ + ...(body.slug ? { slug: str(body.slug) } : {}), + ...(body.id ? { id: str(body.id) } : {}), + ...(typeof body.olderThanDays === "number" ? { olderThanDays: body.olderThanDays } : {}), + }), + ); + }, + "delete-file": async (body) => { + const { deleteVideoFileAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); + const r = await deleteVideoFileAction(str(body.slug), str(body.id), str(body.file)); + return r.ok ? { ok: true, lines: [`${str(body.file)} removed${r.note ? ` (${r.note})` : ""}`], jobIds: [], dryRun: false } : fail(r.error); + }, + "compact-saved-videos": async (body, o) => { + const { compactSavedVideosAction } = await import("../../../saved-videos/compactActions"); + const items = (Array.isArray(body.items) ? body.items : []).map((i) => ({ slug: str((i as Record<string, unknown>).slug), id: str((i as Record<string, unknown>).id) })); + const r = await compactSavedVideosAction({ items, dryRun: o.dryRun }); + if (!r.ok) return fail(r.error); + if (r.dryRun) return { ok: true, lines: r.plan.lines, jobIds: [], dryRun: true }; + return { ok: true, lines: [`${r.jobIds.length} job(s) queued on the compact queue`, ...r.skipped.map((s) => `${s.slug}: ${s.reason}`)], jobIds: r.jobIds, dryRun: false }; + }, + "drop-saved-alternate": async (body, o) => { + const { dropSavedAlternateAction } = await import("../../../channels/[slug]/videos/[id]/videoActions"); + const r = await dropSavedAlternateAction(str(body.slug), str(body.id), str(body.file), { + dryRun: o.dryRun, + confirmOriginal: body.confirmOriginal === true, + }); + if (!r.ok) return fail(r.error); + const verb = r.result.dryRun ? "would free" : "freed"; + return { ok: true, lines: [`${r.result.alternate.file}: ${verb} ${formatBytes(r.result.bytes)}${r.result.existed ? "" : " (already gone: only its entry)"}`], jobIds: [], dryRun: r.result.dryRun }; + }, + "kept-failed-encodes": async (body) => { + const { keptFailedEncodesAction } = await import("../../../saved-videos/compactActions"); + const c = (body.clear ?? {}) as Record<string, unknown>; + const r = await keptFailedEncodesAction({ clear: { slug: str(c.slug), id: str(c.id) } }); + const cleared = r.cleared; + return cleared?.cleared ? { ok: true, lines: [cleared.why], jobIds: [], dryRun: false } : fail(cleared?.why ?? "not cleared"); + }, + "live-recording-verify": async (body) => { + const { reverifyLiveRecordingAction } = await import("../../../channels/[slug]/liveMediaActions"); + const r = await reverifyLiveRecordingAction({ slug: str(body.slug), id: str(body.id), ...(body.startedAt ? { startedAt: str(body.startedAt) } : {}) }); + if (!r.ok) return fail(r.error); + return { + ok: true, + lines: [r.verified ? `verified: ${r.removed.length} stream file(s) removed` : `not verified: ${r.why ?? "nothing removed"}`], + jobIds: [], + dryRun: false, + }; + }, +}; + +// THE BODY'S SHAPE: every slug a channel slug, every id and file one path +// segment. The scan writes these; a file edited by hand is refused here. +const SEGMENT = /^(?!\.\.?$)[\w.-]+$/; +export function bodyShapeProblem(body: Record<string, unknown>): string | null { + const slugs = [body.slug, ...(Array.isArray(body.slugs) ? body.slugs : [])]; + const items = Array.isArray(body.items) ? (body.items as Record<string, unknown>[]) : []; + const clear = body.clear && typeof body.clear === "object" ? (body.clear as Record<string, unknown>) : null; + for (const it of [...items, ...(clear ? [clear] : [])]) slugs.push(it.slug); + for (const v of slugs) if (v !== undefined && (typeof v !== "string" || !isValidChannelSlug(v))) return `"${String(v)}" is not a channel slug`; + const ids = [body.id, ...items.map((i) => i.id), ...(clear ? [clear.id] : [])]; + for (const v of ids) if (v !== undefined && (typeof v !== "string" || !SEGMENT.test(v))) return `"${String(v)}" is not a video id`; + if (body.file !== undefined && (typeof body.file !== "string" || !SEGMENT.test(body.file))) return `"${String(body.file)}" is not a file name in one path segment`; + return null; +} + +// The click-time re-check (controller/spaceHold.ts), loaded lazily so a test +// that names its own never reaches the registry or the disk. +async function defaultRecheck(result: Pick<SpaceScanResult, "computedAt" | "version">, row: SpaceSuggestion): Promise<string | null> { + const { recheckSpaceRow, SpaceHolds } = await import("yt-dlp-transcript-common/controller/spaceHold"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + const paths = getPaths(); + return recheckSpaceRow({ paths, result, row, holds: new SpaceHolds(paths) }); +} + +export async function runSpaceSuggestion(opts: { + result: Pick<SpaceScanResult, "suggestions" | "computedAt" | "version"> | null; + // The version the file on disk says, when it did not parse as this + // editor's (`result` null): an older format is "rescan first" (F2). + fileVersion?: number | null; + key: string; + dryRun: boolean; + runners?: Record<string, SpaceRunner>; + recheck?: (row: SpaceSuggestion) => Promise<string | null>; +}): Promise<SpaceRunOutcome> { + const runners = opts.runners ?? SPACE_RUNNERS; + if (!opts.result && typeof opts.fileVersion === "number" && opts.fileVersion !== SPACE_SCAN_VERSION) { + return fail(`the last scan is of an older format (version ${opts.fileVersion}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`); + } + const s = opts.result?.suggestions.find((x) => x.key === opts.key); + if (!s || !opts.result) return fail(`no suggestion "${opts.key}" in the last scan: refresh the page`); + if (!s.actions?.length) return fail(`nothing to run here: ${s.link ? `see ${s.link.label}` : "this row is for information"}`); + if (s.disabled) return fail(s.disabled); + const unknown = s.actions.find((a) => !runners[a.op]); + if (unknown) return fail(`not a writer this page runs: ${unknown.op}`); + for (const a of s.actions) { + const bad = bodyShapeProblem(a.body); + if (bad) return fail(`refused: ${bad}`); + } + const result = opts.result; + const problem = await (opts.recheck ?? ((row: SpaceSuggestion) => defaultRecheck(result, row)))(s); + if (problem) return fail(`refused: ${problem}`); + if (opts.dryRun && s.actions.some((a) => !SPACE_DRY_RUNNABLE.has(a.op))) { + return fail(`${s.actions[0].op} has no dry run that answers here: the numbers above are the scan's`); + } + const out: SpaceRunOutcome = { ok: true, lines: [], jobIds: [], dryRun: opts.dryRun }; + for (let i = 0; i < s.actions.length; i++) { + const a = s.actions[i]; + const r = await runners[a.op](a.body, { dryRun: opts.dryRun }).catch((e: Error) => fail(e.message)); + out.lines.push(...r.lines); + out.jobIds.push(...r.jobIds); + if (!r.ok) { + out.ok = false; + const rest = s.actions.length - i - 1; + if (rest > 0) out.lines.push(`${rest} more not run`); + break; + } + } + return out; +} diff --git a/editor/app/cleanup/space/lib/spaceJob.ts b/editor/app/cleanup/space/lib/spaceJob.ts @@ -0,0 +1,26 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { enqueueSpaceScan } from "yt-dlp-transcript-common/controller/spaceScan"; +import { safeRevalidate } from "../../../lib/safeRevalidate"; +import { spaceScanJob } from "./loadSpace"; + +// ONE ENQUEUE OF THE SPACE SCAN, for /cleanup/space's Refresh and the +// `/api/ops/space-scan` adapter. Not in `actions.ts` ("use server": every +// export there is an endpoint), like storage/lib/evictClipsJob.ts. +// +// ONE AT A TIME, AND NEVER TWICE (review 1, 15): while a scan is queued or +// running, a second Refresh queues nothing and answers with the one there is. +export async function enqueueSpaceScanJob(opts: { compaction?: boolean } = {}): Promise<StreamActionResult> { + const there = spaceScanJob(); + if (there) { + return { ok: false, info: true, error: `A space scan is already ${there.status} (job ${there.jobId}): its result replaces this page's when it ends.` }; + } + return enqueueSpaceScan({ + paths: getPaths(), + // The settings as they are when the job STARTS (it may have queued). + settings: () => getSettings(), + ...(opts.compaction === false ? { compaction: false } : {}), + onDone: () => safeRevalidate(["/cleanup", "/cleanup/space"]), + }); +} diff --git a/editor/app/cleanup/space/page.tsx b/editor/app/cleanup/space/page.tsx @@ -0,0 +1,283 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { formatBytes } from "yt-dlp-transcript-common/lib/format"; +import { + ageText, + diskNeedOrder, + diskSuggestedBytes, + fullestDiskId, + groupSuggestions, + leadKindsFor, + suggestionsForDisk, + usedPercent, + type SpaceArchiveShare, + type SpaceDisk, +} from "yt-dlp-transcript-common/lib/spaceSuggestions"; +import { CleanupTabs } from "../components/CleanupTabs"; +import { SpaceRefresh } from "./components/SpaceRefresh"; +import { SpaceRow } from "./components/SpaceRow"; +import { loadSpace } from "./lib/loadSpace"; + +// FREE UP SPACE (lane space-suggestions): every disk the archive writes to, +// fullest first, and what would free space on the one picked — each through +// the writer that already exists. Everything here is the last space scan's +// file (controller/spaceScan.ts) plus each disk's free space now; the page +// never walks, stats the corpus or probes a container. +export const dynamic = "force-dynamic"; + +export const metadata: Metadata = { title: "Free up space" }; + +const SHARE: { key: keyof SpaceArchiveShare; label: string; color: string }[] = [ + { key: "media", label: "Media", color: "var(--chart-1)" }, + { key: "text", label: "Text", color: "var(--chart-2)" }, + { key: "clips", label: "Clip windows", color: "var(--chart-3)" }, + { key: "store", label: "Saved videos", color: "var(--chart-4)" }, + { key: "playable", label: "Playable copies", color: "var(--chart-5)" }, + { key: "builds", label: "Site builds", color: "var(--chart-2)" }, + { key: "reports", label: "umtool reports", color: "var(--chart-3)" }, + { key: "other", label: "Index and other", color: "var(--chart-4)" }, +]; + +export default async function SpacePage({ searchParams }: { searchParams: Promise<{ disk?: string }> }) { + const { disk: diskParam } = await searchParams; + const { result, live, job } = await loadSpace(); + const disks = result ? diskNeedOrder(result.disks, result.floorBytes) : []; + const fullest = result ? fullestDiskId(result.disks, result.floorBytes) : null; + const selected = disks.find((d) => d.id === diskParam && d.status === "ok")?.id ?? fullest; + const diskLabel = Object.fromEntries(disks.map((d) => [d.id, d.label])); + const list = result && selected ? suggestionsForDisk(result, selected) : []; + const groups = groupSuggestions(list, { lead: selected ? leadKindsFor(selected) : [] }); + const overflow = result?.overflow.filter((o) => o.disk === selected) ?? []; + + return ( + <div className="flex flex-col gap-6"> + <div className="flex flex-wrap items-center justify-between gap-2"> + <h1 className="text-2xl font-semibold">Cleanup</h1> + </div> + <CleanupTabs active="space" /> + + <section aria-label="space scan" className="flex flex-wrap items-center justify-between gap-3"> + <p className="text-sm text-muted-foreground"> + {result ? ( + <> + Scanned {ageText(result.computedAt)} ({Math.round(result.tookMs / 1000)} s) + {result.compactionAt && result.compactionAt !== result.computedAt + ? ` · compaction rows from ${ageText(result.compactionAt)}` + : ""} + </> + ) : ( + "No scan yet." + )} + </p> + <SpaceRefresh running={job} /> + </section> + + {result && ( + <> + <section aria-label="disks" className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3"> + {disks.map((d) => ( + <DiskCard key={d.id} d={d} free={live[d.id] ?? d.freeBytes} fullest={d.id === fullest} selected={d.id === selected} floor={result.floorBytes} /> + ))} + </section> + + <section aria-label="suggestions" className="flex flex-col gap-4"> + <h2 className="text-lg font-semibold"> + {selected ? `What frees space on ${diskLabel[selected] ?? selected}` : "No disk to free"} + {selected && list.length > 0 && ( + <span className="ml-2 font-mono text-sm font-normal text-muted-foreground">~{formatBytes(diskSuggestedBytes(list))}, each file once</span> + )} + </h2> + {groups.length === 0 && <p className="text-sm text-muted-foreground">Nothing the scan found frees space here.</p>} + {groups.map((g) => ( + <div key={g.kind} className="rounded-xl border border-border bg-card px-4 py-3" aria-label={`group ${g.kind}`}> + <div className="flex flex-wrap items-baseline justify-between gap-2"> + <h3 className="font-medium">{g.label}</h3> + <span className="font-mono text-sm tabular-nums"> + {g.bytes > 0 ? formatBytes(g.bytes) : g.laterLow > 0 ? `later ~${formatBytes(g.laterLow)}–${formatBytes(g.laterHigh)}` : "—"} + </span> + </div> + <ul className="mt-1"> + {g.rows.map((s) => ( + <SpaceRow key={s.key} s={s} diskLabel={diskLabel} /> + ))} + </ul> + {overflow + .filter((o) => o.kind === g.kind) + .map((o) => ( + <p key={o.kind} className="mt-1 text-xs text-muted-foreground"> + And {o.count.toLocaleString("en-US")} more ({formatBytes(o.bytes)}) + {o.link ? ( + <> + {" "} + — <Link href={o.link.href} className="underline">{o.link.label}</Link> + </> + ) : null} + </p> + ))} + </div> + ))} + </section> + + {result.held.length > 0 && ( + <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="held"> + <summary className="cursor-pointer font-medium">Held: not offered ({result.held.length})</summary> + <ul className="mt-2 flex flex-col gap-1 text-sm"> + {result.held.map((h) => ( + <li key={h.key} className="flex flex-wrap justify-between gap-2"> + <span> + {h.what}: {h.why} + {h.link ? ( + <> + {" "} + — <Link href={h.link.href} className="underline">{h.link.label}</Link> + </> + ) : null} + </span> + <span className="font-mono tabular-nums text-muted-foreground"> + {h.bytes !== null ? formatBytes(h.bytes) : "—"} + {h.disk ? ` · ${diskLabel[h.disk] ?? h.disk}` : ""} + </span> + </li> + ))} + </ul> + </details> + )} + + {result.refused.length > 0 && ( + <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="refused by the compaction selector"> + <summary className="cursor-pointer font-medium"> + Saved videos the compaction selector does not pick ({formatBytes(result.refused.reduce((n, g) => n + g.bytes, 0))}) + </summary> + <ul className="mt-2 flex flex-col gap-1 text-sm"> + {result.refused.map((g) => ( + <li key={g.group} className="flex flex-col gap-0.5"> + <span className="flex flex-wrap justify-between gap-2"> + <span> + {g.group}: {g.count.toLocaleString("en-US")} container(s) + </span> + <span className="font-mono tabular-nums text-muted-foreground">{formatBytes(g.bytes)}</span> + </span> + <span className="text-xs text-muted-foreground"> + Biggest:{" "} + {g.examples.map((e, i) => ( + <span key={`${e.slug}/${e.id}`}> + {i ? ", " : ""} + <Link href={`/channels/${e.slug}/videos/${e.id}`} className="underline"> + {e.slug}/{e.id} + </Link>{" "} + {formatBytes(e.bytes)} + </span> + ))} + </span> + </li> + ))} + </ul> + </details> + )} + + {result.unmanaged.length > 0 && ( + <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="no writer here"> + <summary className="cursor-pointer font-medium">The archive&apos;s, with no writer here ({formatBytes(result.unmanaged.reduce((n, u) => n + u.bytes, 0))})</summary> + <ul className="mt-2 flex flex-col gap-1 text-sm"> + {result.unmanaged.map((u) => ( + <li key={u.key} className="flex flex-wrap justify-between gap-2"> + <span> + {u.what}: {u.owner} + {u.command ? ( + <> + {" "} + — <code className="font-mono text-xs">{u.command}</code> + </> + ) : null} + {u.link ? ( + <> + {" "} + — <Link href={u.link.href} className="underline">{u.link.label}</Link> + </> + ) : null} + </span> + <span className="font-mono tabular-nums text-muted-foreground"> + {formatBytes(u.bytes)} + {u.disk ? ` · ${diskLabel[u.disk] ?? u.disk}` : ""} + </span> + </li> + ))} + </ul> + </details> + )} + + {result.notScanned.length > 0 && ( + <details className="rounded-xl border border-border bg-card px-4 py-3" aria-label="not scanned"> + <summary className="cursor-pointer font-medium">Channels not scanned ({result.notScanned.length})</summary> + <ul className="mt-2 flex flex-col gap-1 text-sm"> + {result.notScanned.map((n) => ( + <li key={n.slug}> + <Link href={`/channels/${n.slug}`} className="underline">{n.slug}</Link>: {n.why} + </li> + ))} + </ul> + </details> + )} + + <p className="text-xs text-muted-foreground"> + Each button runs the existing writer for its kind, which refuses what it refuses when it runs.{" "} + <code className="font-mono">pnpm ops get space-suggestions</code> answers the same list. + </p> + </> + )} + </div> + ); +} + +function DiskCard({ d, free, fullest, selected, floor }: { d: SpaceDisk; free: number | null; fullest: boolean; selected: boolean; floor: number }) { + if (d.status !== "ok") { + return ( + <div className="flex flex-col gap-1 rounded-xl border border-dashed border-border bg-card p-4 text-sm text-muted-foreground" aria-label={`disk ${d.id}`}> + <span className="font-medium text-foreground">{d.label}</span> + <span>{d.status === "not-mounted" ? "Not mounted" : "Not answering"}</span> + {d.detail && <span className="text-xs">{d.detail}</span>} + </div> + ); + } + const size = d.sizeBytes ?? 0; + const pct = usedPercent(d, free); + const share = d.archive; + const seg = (n: number) => (size > 0 ? `${(n / size) * 100}%` : "0%"); + const used = size > 0 && free !== null ? size - free : 0; + const notArchive = Math.max(0, used - (d.archiveBytes ?? 0)); + return ( + <Link + href={`/cleanup/space?disk=${encodeURIComponent(d.id)}`} + aria-label={`disk ${d.id}`} + aria-current={selected ? "true" : undefined} + className={`flex flex-col gap-2 rounded-xl border bg-card p-4 text-sm ${selected ? "border-foreground" : "border-border hover:border-muted-foreground"}`} + > + <div className="flex flex-wrap items-baseline justify-between gap-2"> + <span className="font-medium">{d.label}</span> + {fullest && <span className="rounded bg-destructive/15 px-1.5 py-0.5 font-mono text-[11px] uppercase text-destructive">fullest</span>} + </div> + <span className="text-xs text-muted-foreground"> + {d.mountpoint ?? "?"} · {d.roles.join(", ")} + </span> + <div className="flex h-2 w-full overflow-hidden rounded-full bg-muted" role="img" aria-label={`${d.label} usage`}> + {share && SHARE.map((c) => <span key={c.key} className="h-full" style={{ width: seg(share[c.key]), background: c.color }} />)} + <span className="h-full bg-muted-foreground/40" style={{ width: seg(notArchive) }} /> + </div> + <span className="font-mono text-xs tabular-nums"> + {free !== null ? `${formatBytes(free)} free` : "free ?"} of {size ? formatBytes(size) : "?"} + {pct !== null ? ` · ${pct} % used` : ""} + {floor > 0 && free !== null && free < floor ? " · under the floor" : ""} + </span> + <span className="text-xs text-muted-foreground"> + The archive&apos;s: {formatBytes(d.archiveBytes ?? 0)} + {share + ? ` (${SHARE.filter((c) => share[c.key] > 0) + .map((c) => `${c.label.toLowerCase()} ${formatBytes(share[c.key])}`) + .join(", ")})` + : ""} + {" · "}not the archive&apos;s: {formatBytes(notArchive)} + </span> + {d.detail && <span className="text-xs text-amber-600 dark:text-amber-400">{d.detail}</span>} + </Link> + ); +} diff --git a/editor/app/lib/nav.ts b/editor/app/lib/nav.ts @@ -119,7 +119,7 @@ export const NAV_GROUPS: NavGroup[] = [ links: [ { href: "/jobs", label: "Jobs", icon: ListChecks, badgeKey: "jobs", keywords: "queue tasks active running live monitor stuck" }, { href: "/workers", label: "Workers", icon: Cpu, keywords: "transcription whisper gpu" }, - { href: "/cleanup", label: "Cleanup", icon: Trash2, badgeKey: "cleanable", keywords: "clean reclaim disk space prune audio" }, + { href: "/cleanup", label: "Cleanup", icon: Trash2, badgeKey: "cleanable", keywords: "clean reclaim disk space prune audio free up compaction compact move platter" }, { href: "/storage", label: "Storage", icon: HardDrive, keywords: "drive disk platter mount volume media location relocate cold" }, { href: "/saved-videos", label: "Saved videos", icon: Bookmark, keywords: "backup" }, { href: "/cookies", label: "Cookies", icon: Cookie, keywords: "cookie refresh rumble x twitter youtube odysee archive.today forum kiwi farms cf_clearance session login jar stale recheck connect" }, diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -272,6 +272,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // Render mode's state (common/lib/renderPriority.mjs): the slot's own, so // its heartbeat never ends — and its /jobs never shows — the machine's. editorEnv.RENDER_PRIORITY_FILE = join(paths.transcriptsDir, ".render-priority.json"); + // umtool's reports as the space scan sizes them (controller/spaceScan.ts): + // the slot's own, so a scan never walks the operator's ~/reports. + editorEnv.SPACE_SCAN_REPORTS_DIR = join(paths.transcriptsDir, ".space-scan-reports"); // A start-mode server runs the stamped build (shared, read-only); a second // `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`). if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR; diff --git a/editor/e2e/space-suggestions.spec.ts b/editor/e2e/space-suggestions.spec.ts @@ -0,0 +1,91 @@ +import { mkdir, stat, utimes, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { test, expect } from "@playwright/test"; +import { resetData, resolvePath, testPaths } from "./helpers"; +import { baseUrl } from "./baseUrl"; + +// /cleanup/space (lane space-suggestions): Refresh runs the space scan as a +// job; the disks render, fullest marked; caption compression leads the corpus +// disk; a suggestion's button runs the existing writer (here evict-clips, by +// age) and a rescan no longer lists what it freed. A dry run answers in place +// (compress-text's). Nothing here reaches a platform. + +const SLUG = "test-transcribe"; +const DATA = `${testPaths().transcriptsDir}/channels/${SLUG}/data`; +const RESULT = `${testPaths().transcriptsDir}/.space-suggestions.json`; +const DAY = 86_400_000; + +async function seed(): Promise<string> { + await writeFile(resolvePath(`${DATA}/vidA/transcript.en.vtt`), "WEBVTT\n\n" + "00:00.000 --> 00:01.000\nhello\n\n".repeat(4000)); + const clip = resolvePath(`${DATA}/vidB/clips/10.00-20.00.mp4`); + await mkdir(path.dirname(clip), { recursive: true }); + await writeFile(clip, Buffer.alloc(200_000, 1)); + const old = new Date(Date.now() - 60 * DAY); + await utimes(clip, old, old); + return clip; +} + +async function scan(page: import("@playwright/test").Page): Promise<void> { + const before = await stat(resolvePath(RESULT)).then((s) => s.mtimeMs, () => 0); + await page.getByRole("region", { name: "space scan" }).getByRole("button", { name: "Refresh" }).click(); + await expect + .poll(async () => stat(resolvePath(RESULT)).then((s) => s.mtimeMs, () => 0), { timeout: 60_000 }) + .toBeGreaterThan(before); + // The file lands before the job's record says done: reload until the page + // offers Refresh again rather than naming a running scan. + await expect + .poll(async () => { + await page.reload(); + return page.getByLabel("space scan running").count(); + }, { timeout: 30_000 }) + .toBe(0); +} + +test("free up space: a scan, the disks, caption compression first, an eviction through its writer", async ({ page }) => { + await resetData("one-transcribe-channel-with-audio"); + const clip = await seed(); + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); + + await page.goto("/cleanup"); + await expect(page.getByLabel("space summary")).toContainText("No space scan yet."); + await page.getByRole("link", { name: "Free up space" }).first().click(); + await expect(page).toHaveURL(/\/cleanup\/space$/); + await expect(page.getByText("No scan yet.")).toBeVisible(); + + await scan(page); + const corpus = page.getByLabel("disk corpus"); + await expect(corpus).toBeVisible(); + await expect(corpus).toContainText("fullest"); + await expect(corpus).toContainText("The archive's:"); + + // Caption compression leads the corpus disk's list. + const groups = page.getByRole("region", { name: "suggestions" }).locator("[aria-label^='group ']"); + await expect(groups.first()).toHaveAttribute("aria-label", "group compress-captions"); + const evict = page.getByLabel("group evict-clips"); + await expect(evict).toContainText("clip window(s) untouched 30+ days"); + + // A dry run answers in place, and runs nothing. + const captions = page.getByLabel("group compress-captions"); + await captions.getByRole("button", { name: "Compress…" }).first().click(); + await captions.getByRole("button", { name: "Dry run" }).click(); + await expect(captions.getByLabel("dry run")).toContainText(SLUG); + await captions.getByRole("button", { name: "Cancel" }).click(); + + // The eviction: the confirm names the ops call; Confirm runs evict-clips. + await evict.getByRole("button", { name: "Free it…" }).first().click(); + await expect(evict.getByRole("group")).toContainText("pnpm ops evict-clips"); + await evict.getByRole("button", { name: "Confirm" }).click(); + await expect(evict.getByRole("status")).toContainText("rescan to update"); + await expect.poll(() => existsAbs(clip), { timeout: 30_000 }).toBe(false); + + // A rescan no longer lists it; the summary line on /cleanup names the disk. + await page.goto("/cleanup/space"); + await scan(page); + await expect(page.getByLabel("group evict-clips")).toHaveCount(0); + await page.goto("/cleanup"); + await expect(page.getByLabel("space summary")).toContainText("Corpus disk:"); +}); + +async function existsAbs(p: string): Promise<boolean> { + return stat(p).then(() => true, () => false); +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -86,6 +86,8 @@ // pnpm ops get remote-listing demo-odysee // pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait // pnpm ops get transcript <videoId> --slug demo-yt +// pnpm ops space-scan --json '{"compaction":false}' --wait +// pnpm ops get space-suggestions corpus // pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}' // pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}' // pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}' @@ -339,6 +341,11 @@ const GETTERS = { // drop, nothing): the compaction review list. "compaction-review": (slug) => slug ? `/api/ops/compaction-review?slug=${encodeURIComponent(slug)}` : "/api/ops/compaction-review", + // The last space scan (lane space-suggestions): every disk the archive + // writes to, the archive's share of it, and what would free space on each + // (one disk's list when named, default the fullest). Reads the file only. + "space-suggestions": (disk) => + disk ? `/api/ops/space-suggestions?disk=${encodeURIComponent(disk)}` : "/api/ops/space-suggestions", // Every pointer that keeps an original or a former original (what an editor // rolled back past compaction would mistreat), and drops in flight. "kept-originals": (slug) => @@ -464,6 +471,7 @@ const GET_ARG_OPTIONAL = new Set([ "storage", "saved-alternates", "compaction-review", + "space-suggestions", "kept-originals", "sites", "archives", @@ -611,6 +619,10 @@ const ACTIONS = [ "compaction-markers", // The failed encodes kept for a re-verify, and clearing one ({} | {clear: {slug, id}}). "kept-failed-encodes", + // THE SPACE SCAN (lane space-suggestions): every disk the archive writes to + // measured, and what would free space on each, into + // transcripts/.space-suggestions.json ({compaction?}), as a space-scan job. + "space-scan", // The raw live chats stored zstd-compressed, one file at a time, verified // before each original goes ({slugs?, kinds?, dryRun?, limit? (one slug), verify?, restore?}). "compress-text", @@ -1438,6 +1450,7 @@ export function usage() { " pnpm ops get network [--probe]", " pnpm ops get saved-alternates [<slug>]", " pnpm ops get compaction-review [<slug>]", + " pnpm ops get space-suggestions [<disk>]", " pnpm ops get kept-originals [<slug>]", " pnpm ops get marks <slug>", " pnpm ops get services", @@ -1513,6 +1526,15 @@ export function usage() { " availability and why, the original's entry, sizes, checks, the re-check,", ' "watch" (both files and an smplayer command that plays them) and any', ' "leftover" of an interrupted drop.', + "get space-suggestions [<disk>] answers the last space scan (space-scan):", + " every disk the archive writes to, most in need first, each with its size,", + " free space and how much of it is the archive's; and one disk's", + " suggestions (default the fullest), biggest saving first. Each says what", + " it frees and where (measured, or an estimate and from what), what a move", + " fills, what is lost, and its \"actions\": the existing ops call that does", + " it. Then what is held and why, the compaction selector's refusals by", + " rule, and the archive's bytes no writer here removes, with their owner.", + " It reads the file only: computedAt null means no scan yet.", "get marks <slug> lists the channel's do-not-clean marks and who set each", ' one and when, as the video page says it ("setBy": "availability check,', ' 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live', @@ -3482,6 +3504,24 @@ export function usage() { " with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos,", " matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}.", "", + 'space-scan measures every disk the archive writes to: {"compaction"?} ->', + " {jobId}. The corpus disk, each storage location, the saved-video store's,", + " the site builds' and umtool's reports' disks, by device: allocated bytes,", + " each inode once, a file with other hard links never counted as freed, a", + " tier link on its target's disk, a drive not mounted or not answering", + " unknown (never empty). Then what would free space on each through the", + " writers that exist — compress-text (captions, live chats), the cleanup", + " sweeps, relocate, evict-clips, delete-file (abandoned partials),", + " compact-saved-videos, drop-saved-alternate (compacted originals,", + " alternates), kept-failed-encodes, live-recording-verify — with what is", + " held (do-not-clean, a pin's copies, a live recording, a move in flight)", + " and why. It only reads: nothing is removed, moved or fetched. Written to", + " transcripts/.space-suggestions.json; get space-suggestions reads it.", + ' "compaction": false skips the selector\'s pass (one ffprobe per saved', + " container not seen unchanged before) and keeps the last scan's rows.", + " While a scan is queued or running, nothing more is queued: the answer is", + " that job ({jobId, alreadyQueued: true}).", + "", 'copies-scan pairs a source group\'s channels video by video: {"group",', ' "dryRun"?} -> {jobId}. The group is settings.sourceGroups\' (an ordered', " list of channels holding the same recordings, the preferred source first;", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -1362,3 +1362,14 @@ test("copies-scan, copies-release, copies-confirm and copies-reject are POSTs; g assert.equal(parseArgs(["get", "copies", "stream-copies"]).path, "/api/ops/copies?group=stream-copies&pairs=1"); assert.match(usage(), /get copies \[<group>\]/); }); + +// Lane space-suggestions: the space scan is a job; its list is a read. +test("space-scan is a POST; get space-suggestions reads the last scan, one disk's list when named", () => { + const scan = parseArgs(["space-scan", "--json", '{"compaction":false}', "--wait"]); + assert.equal(scan.path, "/api/ops/space-scan"); + assert.deepEqual(scan.body, { compaction: false }); + assert.equal(parseArgs(["get", "space-suggestions"]).path, "/api/ops/space-suggestions"); + assert.equal(parseArgs(["get", "space-suggestions", "platter"]).path, "/api/ops/space-suggestions?disk=platter"); + assert.match(usage(), /get space-suggestions \[<disk>\]/); + assert.match(usage(), /space-scan measures every disk the archive writes to/); +});