commit 53bae5a6ed747588bf1494941c63473c164acce2
parent 31d3e5499638781f95f996e71aac813b51f8acfb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 28 Oct 2026 22:42:48 -0400
Merge lane/take-prune: takes' build work is pruned by policy (umtool prune, the Takes page, after a take, a disk guard before a render)
- lib/report/takePrune.mjs: each take's WORK files (segments' encodes, chrome
frames, crossfade batches, chunks, raw clip copies, work-from-*), counted by
inode so hard-linked files count once; kept or prunable by policy (a build
in or from it, the picked take, pins, newest N, recent, --from bases).
- umtool prune <project> | --all: a dry run unless --yes; --json.
- Takes page: each take's work and why it is kept, Free work files.
- makeTake holds takes/<id>/.building.json and prunes after; build-video
runs a disk guard inside the heavy slot (prune under 30 GB, refuse under 10).
- Segment records and a batch's .from.json are kept; only encodes go.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 2185 insertions(+), 19 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Report-video takes no longer keep their build work forever.** On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB), and 131 GB of it was takes' build work: each full take's chrome frames (about 12 GB for the 34-minute Huck cut, kept with `--keep-frames` so a `--from` twin can reuse them), its crossfade batches and its clip segments, swept by hand. `umtool prune <project>` (or `--all`) now lists each take's work files — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — and what freeing them gives back, or why the take keeps them: a build running in it or from it (never freed), the picked take, the take the project's manifest is, a pin in `takes/prune.json`, the newest 2 of its group, anything modified in the last 3 days, and the `--from` bases of those. It is a dry run unless `--yes`. Files hard-linked between takes are counted once, and freed only when every take holding them lets them go, so the numbers are what the disk gets back, not a sum of `du`s. The renders, previews, take.json and manifests are never touched, and nothing is followed out of a take through a link. The Takes page says each take's work and why it is kept, with **Free work files** per take and for the project (the plan first, then **Free them**). A take that finishes building now prunes its project by the same rules and says what it freed in its log, and a render that starts with under 30 GB free does the same across every project, and refuses to start under 10 GB with a sentence saying so. `--keep`, `--older-than`, `takes/prune.json` and `UMTOOL_PRUNE_*` / `UMTOOL_DISK_GUARD*` change the rules or turn them off. A dry run over ~/reports on 2026-10-27, after the hand sweep: 27 GiB of work in 32 projects' takes, 4.0 GiB of it free to go (2.4 GiB in the Huck project, whose last three days of takes are all kept). Needs a restart of umtool for the Takes page and for takes made from it; the CLI has it at once.
- **An X post's screenshot is of the post, not of a page in the middle of laying itself out.** On 2026-10-27 a forced capture of TheQuartering's post 2114859155022389342 came out shifted about 100 px: its left edge cut off, X's menu laid over its words and the gap beside the column showing; another post once came out as a strip of the post above it. The shot was a full-page capture, which resizes the page for the moment of the capture — in the X session profile the page saw its window go to 1×1 — and X laid itself out again for that size while it was being captured, so the shot was cut from a different layout than the one measured. A post is now shot from the window as it stands: scrolled into it, the window made taller first when the post is taller than it, so nothing is resized under the shot; and the post is measured again after the shot and shot again if it moved. An X Article's shot is taken the same way. Posts taller than the tallest window (16,384 px) are still shot from a full-page capture. Needs a restart of the editor.
- **Use with AI is the homepage's.** A published site's header and slide-out menu no longer carry it (nor the hub's header); a site still reaches the homepage's AI and MCP doc from its footer and from Ask AI, and its corpus.json and llms.txt still name it. Rebuild a site to see it.
- **The site-swap intro no longer shifts vertically on the chime.** With the URLs under MEDIA the drawing used to rise to stay centred; the lockup is now centred as the plain intro centres it and the URLs hang below it, so on the chime it only moves sideways. Intros without a site swap are unchanged.
diff --git a/umtool/app/api/report/takes/prune/route.ts b/umtool/app/api/report/takes/prune/route.ts
@@ -0,0 +1,50 @@
+import { answerDelete, type DeletePlanView } from "@/lib/delete-plan";
+import { projectRef } from "@/lib/projects";
+import { deleteViewOf, planPrune, planView, pruneProject } from "@/lib/report/takePrune.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE TAKES' WORK FILES (2026-10-27): lib/report/takePrune.mjs, the writer
+// `umtool prune` runs.
+//
+// GET ?project=<id> the plan, every take measured: its work
+// bytes, what freeing it gives back, kept
+// because … or prunable (the Takes page)
+// POST { project, take?, dryRun?, force? } "Free work files", answered as a delete
+// (lib/delete-plan.ts): the project's
+// prunable takes, or one take; `force`
+// frees a take the policy keeps, never
+// one being built or built from
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(url.searchParams.get("project") ?? "");
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ try {
+ const plan = await planPrune({ id: project.id, dir: project.dir }, { measure: "all" });
+ return Response.json({ plan: planView(plan) }, { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 });
+ }
+}
+
+export async function POST(request: Request) {
+ const body = (await request.json().catch(() => ({}))) as { project?: unknown; take?: unknown; dryRun?: unknown; force?: unknown };
+ if (body.take !== undefined && body.take !== null && !isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 });
+ const take = typeof body.take === "string" ? body.take : null;
+ const found = await projectRef(String(body.project ?? ""));
+ if (!found) return Response.json({ error: "no such project" }, { status: 404 });
+ const project = { id: found.id, dir: found.dir };
+ const force = body.force === true;
+ const opts = { takes: take ? [take] : null, anyway: force && !!take };
+ try {
+ const plan = await planPrune(project, { ...opts, measure: "prunable" });
+ return await answerDelete(deleteViewOf(plan, { take }) as DeletePlanView, { dryRun: body.dryRun === true, force }, async () => {
+ const r = await pruneProject(project, { ...opts, by: "ui" });
+ return { plan: deleteViewOf(r.plan, { take }) as DeletePlanView, removed: r.removed, failed: r.failed };
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return Response.json({ error: message }, { status: /has no take/.test(message) ? 404 : 500 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -65,6 +65,8 @@
// the editor as one fetch-windows batch (release 35)
// umtool prep <project> [--clips a,b] [--wait | --status] [--json] the bench's excerpts and waveforms,
// made before the walk (one clip at a time, in the heavy slot)
+// umtool prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--yes] [--json]
+// takes' work files (segments, chrome frames, batches) measured by inode, freed by policy
// umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] stand-ins for refused windows
// umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex]
// [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass)
@@ -787,6 +789,10 @@ function usage() {
" what the clip bench makes on a clip's first open (a long recording's excerpt, the waveform),",
" made before the walk: queued and run in the background, one clip at a time, in the heavy slot",
" (a small declared estimate), under nice/ionice; --wait runs it here; a write or a fetch queues it too",
+ " umtool prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--yes] [--json]",
+ " takes' work files (segments, chrome frames, crossfade batches, encode chunks): what each holds",
+ " (hard links counted by inode), which takes keep theirs and why, what freeing the rest gives back;",
+ " a dry run unless --yes. A take build prunes its project after; a render prunes when disk is low",
" umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] [--json]",
" stand-ins for refused montage windows: the instance's public alternate (YouTube first), on the clip",
" umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]",
@@ -869,6 +875,8 @@ const COMMANDS = {
fetch: async () => process.exit(await settled(await (await import("../lib/report/fetchCli.mjs")).fetchCommand(argv.slice(argv.indexOf("fetch") + 1)))),
// The clip bench's first-open work, ahead of the walk: lib/report/prepCli.mjs.
prep: async () => process.exit(await (await import("../lib/report/prepCli.mjs")).prepCommand(argv.slice(argv.indexOf("prep") + 1))),
+ // Takes' work files, by policy (2026-10-27): lib/report/pruneCli.mjs.
+ prune: async () => process.exit(await (await import("../lib/report/pruneCli.mjs")).pruneCommand(argv.slice(argv.indexOf("prune") + 1))),
fallback: async () => process.exit(await (await import("../lib/report/standInsCli.mjs")).fallbackCommand(argv.slice(argv.indexOf("fallback") + 1))),
// The phrase finder (release 34): lib/phrase-finder/cli.mjs.
phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))),
diff --git a/umtool/components/DeletePlan.tsx b/umtool/components/DeletePlan.tsx
@@ -42,6 +42,8 @@ export default function DeletePlan({
endpoint,
body,
forceLabel = "delete anyway",
+ verb = "Delete",
+ confirmLabel = "Confirm delete",
onDone,
size = "sm",
}: {
@@ -50,6 +52,9 @@ export default function DeletePlan({
endpoint: string;
body: Record<string, unknown>;
forceLabel?: string;
+ /** The plan's first word ("Free" for the takes' work files); the region keeps its "delete <subject>" name. */
+ verb?: string;
+ confirmLabel?: string;
onDone: (answer: Extract<DeleteAnswer, { applied: true }>) => void;
size?: "sm" | "md";
}) {
@@ -113,7 +118,7 @@ export default function DeletePlan({
className="mt-2 basis-full rounded border border-[var(--color-bad)] bg-[var(--color-ink)] p-2 text-[12px]"
>
<p className="font-medium">
- Delete {subject}: {plan.remove.length} path{plan.remove.length === 1 ? "" : "s"},{" "}
+ {verb} {subject}: {plan.remove.length} path{plan.remove.length === 1 ? "" : "s"},{" "}
<span className="num" data-delete-bytes={plan.bytes}>
{fmt(plan.bytes)}
</span>{" "}
@@ -189,7 +194,7 @@ export default function DeletePlan({
</label>
)}
<Button size="sm" variant="outline" disabled={blocked.length > 0 || phase.at === "deleting"} onClick={() => void confirm(plan)}>
- {phase.at === "deleting" ? "Deleting…" : "Confirm delete"}
+ {phase.at === "deleting" ? `${verb === "Delete" ? "Deleting" : `${verb}ing`}…` : confirmLabel}
</Button>
<Button
size="sm"
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -9,7 +9,7 @@ import { NotesProvider, useSharedNotes } from "@/components/notes/NotesProvider"
import TimedNotes from "@/components/notes/TimedNotes";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
-import { fmtAgo } from "@/lib/format";
+import { fmtAgo, fmtBytes } from "@/lib/format";
import { playHref } from "@/lib/hrefs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
@@ -49,6 +49,27 @@ export type Take = {
stale?: boolean | null;
};
+/** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */
+export type TakeWork = {
+ id: string;
+ status: "prunable" | "kept" | "no-work";
+ keep: { code: string; why: string; hard: boolean }[];
+ workBytes: number | null;
+ freedBytes: number | null;
+ files: number | null;
+ pruned: { at: string; freedBytes: number } | null;
+};
+type WorkPlan = {
+ takes: TakeWork[];
+ policy: { keep: number; olderThanDays: number; pin: string[] };
+ totals: {
+ takes: number;
+ workBytes: number | null;
+ prunable: { takes: number; workBytes: number; freedBytes: number; files: number };
+ kept: { takes: number; workBytes: number | null };
+ };
+};
+
export type Verdict = "like" | "maybe" | "no";
export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true };
@@ -119,6 +140,28 @@ export default function TakesBench({
const starting = useRef(false);
useEffect(() => setReady(true), []);
+
+ // The takes' work files (lib/report/takePrune.mjs), measured after the page
+ // is up: a project's takes can hold hundreds of thousands of frames, so the
+ // page never waits on them.
+ const [work, setWork] = useState<WorkPlan | null>(null);
+ const [workError, setWorkError] = useState<string | null>(null);
+ const loadWork = useCallback(async () => {
+ try {
+ const r = await fetch(`/api/report/takes/prune?${new URLSearchParams({ project })}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as { plan?: WorkPlan; error?: string };
+ if (!r.ok || !j.plan) throw new Error(j.error ?? `HTTP ${r.status}`);
+ setWork(j.plan);
+ setWorkError(null);
+ } catch (e) {
+ setWorkError(e instanceof Error ? e.message : String(e));
+ }
+ }, [project]);
+ useEffect(() => {
+ void loadWork();
+ }, [loadWork]);
+ const workOf = new Map((work?.takes ?? []).map((w) => [w.id, w]));
+
useEffect(() => {
listenRef.current = listen;
for (const [id, v] of videos.current) v.muted = id !== listen;
@@ -229,6 +272,7 @@ export default function TakesBench({
<BenchBody verdict={verdictBar}>
<div className="space-y-6">
{head}
+ <WorkSummary project={project} work={work} error={workError} ready={ready} onFreed={() => void loadWork()} />
{groups.map((g) => {
const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const)
.filter(([, n]) => n > 0)
@@ -289,6 +333,8 @@ export default function TakesBench({
}}
save={(patch) => save(t.id, patch)}
onPicked={(v) => setVerdicts(v)}
+ work={work ? (workOf.get(t.id) ?? null) : undefined}
+ onFreed={() => void loadWork()}
/>
))}
</div>
@@ -302,6 +348,114 @@ export default function TakesBench({
);
}
+const days = (d: number) => (d >= 1 ? `${+d.toFixed(2)} d` : `${+(d * 24).toFixed(1)} h`);
+
+/**
+ * The takes' work files at the head of the bench: how much, how much the
+ * policy would free, and the project's "Free work files" (the plan, then the
+ * confirm: components/DeletePlan.tsx over POST /api/report/takes/prune).
+ */
+function WorkSummary({
+ project,
+ work,
+ error,
+ ready,
+ onFreed,
+}: {
+ project: string;
+ work: WorkPlan | null;
+ error: string | null;
+ ready: boolean;
+ onFreed: () => void;
+}) {
+ if (error) {
+ return (
+ <p data-takes-work="" className="text-[11.5px] text-[var(--color-bad)]">
+ Work files could not be measured: {error}
+ </p>
+ );
+ }
+ if (!work) {
+ return (
+ <p data-takes-work="" data-state="measuring" className="text-[11.5px] text-[var(--color-dim)]">
+ measuring the takes' work files…
+ </p>
+ );
+ }
+ const p = work.totals.prunable;
+ return (
+ <section data-takes-work="" data-state="measured" className="flex flex-wrap items-center gap-2 text-[11.5px] text-[var(--color-dim)]">
+ <h2 className="micro">work files</h2>
+ <span className="num" data-work-bytes={work.totals.workBytes ?? 0}>
+ {fmtBytes(work.totals.workBytes ?? 0)} in {work.takes.filter((t) => t.status !== "no-work").length} takes
+ </span>
+ <span>·</span>
+ <span data-work-prunable={p.takes}>
+ {p.takes ? (
+ <>
+ {p.takes} prunable, frees <span className="num">{fmtBytes(p.freedBytes)}</span>
+ </>
+ ) : (
+ "none prunable"
+ )}
+ </span>
+ <span title="lib/report/takePrune.mjs: running builds and their bases, the picked or current take, pins in takes/prune.json and the --from bases of kept takes are kept too">
+ · keeps the newest {work.policy.keep} per group and anything modified within {days(work.policy.olderThanDays)}
+ </span>
+ {ready && p.takes > 0 && (
+ <DeletePlan
+ label="Free work files"
+ subject={`the work files of ${project}'s prunable takes`}
+ endpoint="/api/report/takes/prune"
+ body={{ project }}
+ verb="Free"
+ confirmLabel="Free them"
+ onDone={onFreed}
+ />
+ )}
+ </section>
+ );
+}
+
+/** One take's work files on its card: size, kept because … or prunable, and its own "Free work files". */
+function TakeWorkLine({ project, work: w, ready, onFreed }: { project: string; work: TakeWork | null | undefined; ready: boolean; onFreed: () => void }) {
+ if (w === undefined) return null;
+ if (w === null || w.status === "no-work") {
+ return (
+ <p data-take-work="none" className="text-[11px] text-[var(--color-dim)]">
+ no work files
+ {w?.pruned && ` · pruned ${w.pruned.at.slice(0, 10)}, ${fmtBytes(w.pruned.freedBytes)} freed`}
+ </p>
+ );
+ }
+ const shared = w.workBytes !== null && w.freedBytes !== null && w.workBytes > w.freedBytes ? w.workBytes - w.freedBytes : 0;
+ return (
+ <div data-take-work={w.status} className="flex flex-wrap items-center gap-1.5 text-[11px] text-[var(--color-dim)]">
+ <span className="num">work {fmtBytes(w.workBytes ?? 0)}</span>
+ {w.status === "prunable" ? (
+ <span data-take-prunable="">
+ · prunable, frees <span className="num">{fmtBytes(w.freedBytes ?? 0)}</span>
+ {shared > 0 && ` (${fmtBytes(shared)} also linked elsewhere stays)`}
+ </span>
+ ) : (
+ <span data-take-kept="">· kept because {w.keep.map((r) => r.why).join("; ")}</span>
+ )}
+ {ready && (
+ <DeletePlan
+ label="Free work files"
+ subject={`the work files of take ${w.id}`}
+ endpoint="/api/report/takes/prune"
+ body={{ project, take: w.id }}
+ forceLabel="free anyway"
+ verb="Free"
+ confirmLabel="Free them"
+ onDone={onFreed}
+ />
+ )}
+ </div>
+ );
+}
+
function TakeCard({
project,
take: t,
@@ -315,6 +469,8 @@ function TakeCard({
onUnmute,
save,
onPicked,
+ work,
+ onFreed,
}: {
project: string;
take: Take;
@@ -328,6 +484,9 @@ function TakeCard({
onUnmute: () => void;
save: (patch: { verdict?: Verdict | null; note?: string }) => Promise<void>;
onPicked: (verdicts: Record<string, TakeVerdict>) => void;
+ /** undefined while the work files are measured; null when the plan does not list the take. */
+ work?: TakeWork | null;
+ onFreed: () => void;
}) {
const notes = useSharedNotes({ project });
const router = useRouter();
@@ -547,6 +706,7 @@ function TakeCard({
)}
</p>
)}
+ <TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} />
<div className="flex flex-wrap">
<DeletePlan
label={`Delete take ${t.id}`}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -51,6 +51,7 @@ Inbox cannot disagree about what is wrong with one.
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). **Exit 1** when a clip failed (`--wait`) |
+| `prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]` · `prune --all [--keep N] [--older-than 3d] [--yes] [--json]` | **the takes' work files** (the Takes page's **Free work files**): per take its work — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — counted by inode (a file hard-linked into two takes is counted once and freed only when both let it go), what freeing it gives back, or why it is kept: a running build or the take one builds from (never freed), the picked or current take, a pin in `takes/prune.json`, the newest `--keep` (2) of its group, anything modified within `--older-than` (3d), the `--from` bases of those. A dry run unless `--yes`; `--take X --anyway` frees a take the policy keeps. Renders, previews, take.json and manifests are never touched. **Exit 1** when a path could not be removed ([report-video.md](report-video.md#a-takes-work-files-and-pruning-them)) |
| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
| `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
@@ -88,6 +89,9 @@ whatever directory it is run from — `umtool notes --all` from a report workspa
from its cwd to `pnpm-workspace.yaml`.
| `VIDEO_ROOT` (`song/spec.mjs`, `song/video-dir.mjs`) | `~/reports/quartering-uh-song/videos` |
| `UMTOOL_BENCH_PREP` | unset = a fetch that lands and a write that moves or adds a clip queue the bench's prep (`prep`); `0` queues nothing (the triggers, `umtool prep` and the Cut tab's button; `prep --wait` still runs) |
+| `UMTOOL_PRUNE_KEEP`, `UMTOOL_PRUNE_DAYS` | the prune policy's newest-per-group (2) and age (`3d`) when neither `takes/prune.json` nor the command line says (`prune`) |
+| `UMTOOL_PRUNE_AFTER_BUILD` | unset = a take that is made prunes its project's takes by the policy after; `0` does not |
+| `UMTOOL_DISK_GUARD`, `UMTOOL_DISK_GUARD_GB`, `UMTOOL_DISK_FLOOR_GB` | before a render: under 30 GiB free it prunes every project's takes by policy, under 10 GiB it refuses the render; `UMTOOL_DISK_GUARD=0` turns it off |
## `check` is the one to run before every build
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -934,6 +934,88 @@ the one the take was made from (its `baseHash`), the card says **The project cha
take was made** and the pick waits for **Use anyway**. A take that does not record its base asks
the same.
+### A take's work files, and pruning them
+
+A take's build leaves behind what makes the NEXT build fast: its clip segments, the chrome
+layers' frames (kept with `--keep-frames` so a `--from` twin reuses them; ~12 GB for a 34-minute
+cut), the crossfade batches, the final encode's chunks. Kept forever they filled /home on
+2026-10-27 (131 GB of it was takes' work). `lib/report/takePrune.mjs` names them, measures them
+and removes them where no take is likely to need them; `umtool prune`, the Takes page, a take's
+build and a render's disk guard all call it.
+
+**WORK** is exactly these, under `takes/<id>/out/` — everything else in a take is **FINAL** and
+never touched (the renders `out/<slug>.mp4` with its ladder rungs and trailer, `preview.mp4`,
+`take.json`, the manifests, `schedule.json`, `sync.json`, the chapters, the cards and QRs, the
+chrome compositions, every small record, and any name not on the list):
+
+| Path | What |
+|---|---|
+| `<variant>/segments/*.mp4` | each clip's encoded segment — its records (`<id>.cut.json`, `.teaser.json`, …) stay: `umtool trailer` maps beats through them and verify-build reads a teaser's |
+| `<variant>/chrome/<layer>-frames/`, `<variant>/chrome/work-*/` | each layer's PNG sequence; a render's leftovers and `--from`'s `work-from-*` |
+| `<variant>/xfade-batches/batch-*.mov` | the crossfade batches (`.from.json` stays) |
+| `<variant>/chunks/`, `<variant>/.content-hashes.json` | the chunked final encode and its content-hash memo |
+| `<variant>/<slug>.prerail*.mp4` (and `.segments`) | the rail's cached base (`--rail-only`) |
+| `.keep-frames/` | layers kept aside for a `--from` |
+| `clips-raw/` (a real directory) | raw clip copies — the usual `clips-raw` is a link to the project's, which is not work |
+
+**Hard links are counted by inode.** `--from` links the other take's segments and frames in, so a
+`du` of each take counts them twice. A take's **work** is its unique inodes' allocated bytes; what
+it **frees** is the bytes whose every link is among the paths removed (st_nlink against the links
+in the set); a plan over several takes counts the union, so two prunable twins free their shared
+segments together. Freeing a take whose files another take also holds frees only what is its own,
+and the other take's files are whole.
+
+**What is kept** — a take keeps its work while it is:
+
+- **being built**: a live build lock — `takes/<id>/.building.json` (the take maker writes it for
+ the whole make, naming the `--from` take) or `<out>/.building.json` (build-video writes it in
+ its `--out` for a render) — or a pipeline process naming a path in it (`lib/report/busy.mjs`).
+ A lock whose process is gone is ignored and said;
+- **the base of a take being built** (a live lock's `from`);
+- **picked** in its group (verdicts.json), or **current** (the project's `video.manifest.json` is
+ this take's);
+- **pinned** in the project's `takes/prune.json`;
+- one of the **newest K** of its group, by `builtAt` (default 2);
+- **modified within D days** — take.json, the preview or `builtAt` (default 3);
+- the **`--from` base of a kept take** (take.json's `from`, which the take maker now records, or
+ `xfade-batches/.from.json`), transitively.
+
+Everything else's work is prunable. The first two are never overridden; the rest are policy, and
+naming one take with `--anyway` (the page's **free anyway**) frees it all the same.
+
+**The settings**, later winning: the defaults; `UMTOOL_PRUNE_KEEP`, `UMTOOL_PRUNE_DAYS` (`3d`,
+`12h`, a number of days); the project's `takes/prune.json`; `--keep` / `--older-than` on the
+command line. `takes/prune.json` is `{ "keep": 2, "olderThanDays": 3, "pin": ["<take>"],
+"afterBuild": true }`, every key optional; one that does not parse, or is not that shape, refuses
+the prune rather than guess.
+
+**Where it runs.**
+
+- `umtool prune <project>` / `umtool prune --all`: the plan, per take — work and what it frees,
+ or `kept because …` — and the totals. A dry run unless `--yes` ([cli.md](cli.md)).
+- **The Takes page**: the head says the takes' work in all and what the policy would free, with
+ **Free work files** for the project; each card says its work and why it is kept or that it is
+ prunable, with its own **Free work files**. Both show the plan (each take, its work paths and
+ sizes, what is kept and why) and free only on **Free them** (`POST /api/report/takes/prune`, a
+ dry run first, as every delete on the page).
+- **After a take is made** (`umtool take`, the page's New take and Rebuild, `takes make`): the
+ project's takes by its policy, the new take kept, one `prune: freed … / nothing to free` line in
+ the take's log. Off with `UMTOOL_PRUNE_AFTER_BUILD=0` or `"afterBuild": false`.
+- **Before a render** (build-video, once it has the heavy slot): when the least free of the render's
+ `--out` filesystem and the reports root is under `UMTOOL_DISK_GUARD_GB` (default 30, in GiB) it
+ prunes every project's takes by their policies and says what that freed; still under
+ `UMTOOL_DISK_FLOOR_GB` (default 10) the render is refused with a sentence and nothing is
+ rendered. `UMTOOL_DISK_GUARD=0` turns it off (the e2e suite does).
+
+**Deleting never leaves the take.** Each work path is lstat'ed (a link is not work: never followed,
+never removed) and its real path must be inside the take's real directory — or, when the take's
+`out` is the media root's link (`UMTOOL_MEDIA_DIR`), inside that link's mirror. Under it, files
+and links are unlinked and only real directories are descended into: a clip copy that links into
+the corpus loses the link, never the corpus file. Each pruned chrome layer's frame count and key
+go into its `chrome/pruned.json` first, so `verify-build` still checks the cut; what went is
+appended to `takes/<id>/pruned-work.json`. The project's own `out/` is not a take and is not
+touched. A pruned take rebuilt, or used as a `--from` base, renders its work again.
+
### Trailer from the master
`umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) [--intro] [--finale S]
diff --git a/umtool/lib/report/busy.mjs b/umtool/lib/report/busy.mjs
@@ -55,25 +55,19 @@ export function namesProject(args, cwd, project) {
}
/**
- * The pids of pipeline processes working in `project` (see the top of the file).
- * @param {{ dir: string, id?: string, name?: string }} project
+ * Every pipeline process running now (the scripts above, by argv), with its
+ * argv and working directory -- read from /proc once, for a caller that asks
+ * about many directories (takePrune.mjs asks about every take of a project).
* @param {{ procRoot?: string, selfPid?: number }} [opts]
- * @returns {number[]}
+ * @returns {{ pid: number, args: string[], cwd: string | null }[]}
*/
-export function pipelineProcessesFor(project, { procRoot = "/proc", selfPid = process.pid } = {}) {
- let realDir = project.dir;
- try {
- realDir = realpathSync(project.dir);
- } catch {
- /* gone: nothing can be running in it */
- }
- const ref = { ...project, realDir };
- const pids = [];
+export function pipelineProcesses({ procRoot = "/proc", selfPid = process.pid } = {}) {
+ const out = [];
let entries = [];
try {
entries = readdirSync(procRoot).filter((n) => /^\d+$/.test(n));
} catch {
- return pids;
+ return out;
}
for (const pid of entries) {
if (Number(pid) === selfPid) continue;
@@ -90,7 +84,29 @@ export function pipelineProcessesFor(project, { procRoot = "/proc", selfPid = pr
} catch {
/* another user's process, or gone */
}
- if (namesProject(args, cwd, ref)) pids.push(Number(pid));
+ out.push({ pid: Number(pid), args, cwd });
}
- return pids;
+ return out;
+}
+
+/** `project` with its real directory beside it, for namesProject. */
+export function projectRefOf(project) {
+ let realDir = project.dir;
+ try {
+ realDir = realpathSync(project.dir);
+ } catch {
+ /* gone: nothing can be running in it */
+ }
+ return { ...project, realDir };
+}
+
+/**
+ * The pids of pipeline processes working in `project` (see the top of the file).
+ * @param {{ dir: string, id?: string, name?: string }} project
+ * @param {{ procRoot?: string, selfPid?: number }} [opts]
+ * @returns {number[]}
+ */
+export function pipelineProcessesFor(project, opts = {}) {
+ const ref = projectRefOf(project);
+ return pipelineProcesses(opts).filter((p) => namesProject(p.args, p.cwd, ref)).map((p) => p.pid);
}
diff --git a/umtool/lib/report/pruneCli.mjs b/umtool/lib/report/pruneCli.mjs
@@ -0,0 +1,185 @@
+// `umtool prune` (2026-10-27): the takes' work files -- what a build keeps to
+// make the next build faster -- measured, and removed where the policy says
+// no take will need them (lib/report/takePrune.mjs says what is work, what is
+// kept and why). A dry run unless --yes. The Takes page's "Free work files"
+// calls the same writer (pruneProject).
+//
+// umtool prune <project> [--take X …] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]
+// umtool prune --all [--keep N] [--older-than 3d] [--yes] [--json]
+//
+// Plain ESM: the CLI runs it with bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import {
+ fmtBytes,
+ freeBytesAt,
+ planPrune,
+ planView,
+ policyLine,
+ pruneAllProjects,
+ pruneProject,
+} from "./takePrune.mjs";
+
+export const PRUNE_USAGE = [
+ "usage: umtool prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]",
+ " umtool prune --all [--keep N] [--older-than 3d] [--yes] [--json]",
+ "",
+ "Each take's WORK files -- clip segments, chrome frames, crossfade batches, encode chunks, raw clip",
+ "copies, work-from-* -- measured by inode (a file hard-linked into two takes is counted once, and",
+ "freed only when both let it go), and which takes keep theirs and why. Kept: a running build and the",
+ "take it builds from, the picked take, the take the project's manifest is, pins in takes/prune.json,",
+ "the newest N of each group (--keep, default 2), anything modified within --older-than (default 3d),",
+ "and the --from bases of those. The renders, preview.mp4, take.json and the manifests are never",
+ "touched. A dry run unless --yes. --take X: only that take; --anyway also frees it when the policy",
+ "keeps it (never a take being built, or built from).",
+].join("\n");
+
+class CliError extends Error {}
+
+function parse(args) {
+ const valued = new Set(["--take", "--keep", "--older-than"]);
+ /** @type {Record<string, string[]>} */
+ const flags = {};
+ const positional = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a.startsWith("--")) {
+ const [name, inline] = a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, null];
+ if (valued.has(name)) {
+ const v = inline ?? args[++i];
+ if (v === undefined) throw new CliError(`${name} needs a value`);
+ (flags[name] ??= []).push(v);
+ } else (flags[name] ??= []).push("");
+ } else positional.push(a);
+ }
+ return { flags, positional, has: (n) => n in flags, one: (n) => flags[n]?.[flags[n].length - 1] };
+}
+
+const pad = (s, n) => (s.length >= n ? s + " " : s + " ".repeat(n - s.length));
+
+/** One project's plan as lines; `compact` lists only the takes that hold work. */
+export function planLines(plan, { compact = false } = {}) {
+ const lines = [`${plan.project.id} — ${policyLine(plan.policy)}`];
+ const width = Math.min(40, Math.max(12, ...plan.takes.map((t) => t.id.length + 2)));
+ for (const t of plan.takes) {
+ if (compact && t.status === "no-work") continue;
+ const work = t.workBytes === null ? "" : fmtBytes(t.workBytes);
+ if (t.status === "no-work") {
+ lines.push(` ${pad(t.id, width)}no work files${t.pruned ? ` (pruned ${t.pruned.at.slice(0, 10)}, ${fmtBytes(t.pruned.freedBytes)} freed)` : ""}`);
+ continue;
+ }
+ const shared = t.workBytes !== null && t.freedBytes !== null && t.workBytes > t.freedBytes ? `, ${fmtBytes(t.workBytes - t.freedBytes)} of it also linked elsewhere (another take, the project's out/)` : "";
+ if (t.status === "prunable") {
+ const over = t.overridden.length ? ` — kept by policy (${t.overridden.map((r) => r.why).join("; ")}), freed anyway` : "";
+ lines.push(` ${pad(t.id, width)}prunable work ${work}, frees ${fmtBytes(t.freedBytes ?? 0)}${shared}${over}`);
+ } else {
+ lines.push(` ${pad(t.id, width)}kept work ${work || "(not measured)"}${t.freedBytes !== null ? `, would free ${fmtBytes(t.freedBytes)}` : ""} — ${t.keep.map((r) => r.why).join("; ")}`);
+ }
+ for (const n of t.notes) lines.push(` ${pad("", width)} note: ${n}`);
+ }
+ const p = plan.totals.prunable;
+ const k = plan.totals.kept;
+ const none = plan.takes.filter((t) => t.status === "no-work").length;
+ lines.push(
+ ` ${p.takes} prunable${p.takes ? `: frees ${fmtBytes(p.freedBytes)}${p.workBytes > p.freedBytes ? ` of ${fmtBytes(p.workBytes)} (the rest is also linked from a kept take or the project's out/)` : ""}` : ""}` +
+ ` · ${k.takes} kept${k.workBytes !== null ? ` with ${fmtBytes(k.workBytes)} of work` : ""}` +
+ `${none ? ` · ${none} with no work files` : ""}` +
+ `${plan.totals.workBytes !== null ? ` · ${fmtBytes(plan.totals.workBytes)} of work in all` : ""}`,
+ );
+ for (const n of plan.notes) lines.push(` note: ${n}`);
+ return lines;
+}
+
+async function pickProject(arg, root) {
+ const r = await resolveProject(arg, root);
+ if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${arg}"`);
+ return { id: r.project.id, dir: r.project.dir };
+}
+
+/**
+ * `umtool prune …`
+ * @param {string[]} args everything after `prune`
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, any> }} [opts]
+ * `deps`: passed to the planner/pruner (a test's `processes`, `alive`, `now`).
+ * @returns {Promise<number>}
+ */
+export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps = {} } = {}) {
+ try {
+ const p = parse(args);
+ if (p.has("--help")) {
+ log(PRUNE_USAGE);
+ return 0;
+ }
+ const all = p.has("--all");
+ if (!all && !p.positional.length) {
+ err(PRUNE_USAGE);
+ return 2;
+ }
+ if (all && p.positional.length) throw new CliError("a project or --all, not both");
+ if (p.has("--yes") && p.has("--dry-run")) throw new CliError("--yes or --dry-run, not both");
+ const takes = (p.flags["--take"] ?? []).flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean);
+ if (takes.length && all) throw new CliError("--take names a take of one project: pass the project, not --all");
+ if (p.has("--anyway") && !takes.length) throw new CliError("--anyway frees a take the policy keeps: name it with --take");
+ const flags = { ...(p.has("--keep") ? { keep: p.one("--keep") } : {}), ...(p.has("--older-than") ? { olderThan: p.one("--older-than") } : {}) };
+ const apply = p.has("--yes");
+ const json = p.has("--json");
+ const common = { reportsRoot, flags, ...deps };
+
+ /** @type {{ project: { id: string, dir: string }, plan?: any, pruned?: any[], removed?: string[], failed?: any[], freedBytes?: number, error?: string }[]} */
+ let results;
+ if (all) {
+ results = (await pruneAllProjects({ ...common, dryRun: !apply, by: "cli", measure: apply ? "prunable" : "all" })).results;
+ } else {
+ const project = await pickProject(p.positional[0], reportsRoot);
+ const opts = { ...common, takes: takes.length ? takes : null, anyway: p.has("--anyway"), by: "cli" };
+ results = [apply ? { project, ...(await pruneProject(project, opts)) } : { project, plan: await planPrune(project, { ...opts, measure: "all" }) }];
+ }
+
+ const freed = results.reduce((s, r) => s + (apply ? r.freedBytes ?? 0 : r.plan?.totals.prunable.freedBytes ?? 0), 0);
+ const failed = results.flatMap((r) => (r.failed ?? []).map((f) => ({ project: r.project.id, ...f })));
+ const errors = results.filter((r) => r.error);
+ const free = await freeBytesAt(reportsRoot);
+ if (json) {
+ log(
+ JSON.stringify(
+ {
+ dryRun: !apply,
+ projects: results.map((r) =>
+ r.error
+ ? { project: r.project, error: r.error }
+ : { ...planView(r.plan), ...(apply ? { pruned: r.pruned, removed: r.removed, failed: r.failed, freedBytes: r.freedBytes } : {}) },
+ ),
+ freedBytes: freed,
+ freeBytes: free,
+ },
+ null,
+ 2,
+ ),
+ );
+ } else {
+ for (const r of results) {
+ if (r.error) {
+ err(`${r.project.id}: ${r.error}`);
+ continue;
+ }
+ if (all && !r.plan.takes.some((t) => t.status !== "no-work")) continue;
+ for (const line of planLines(r.plan, { compact: all })) log(line);
+ if (apply) for (const pr of r.pruned ?? []) log(` freed ${pr.id}: ${pr.paths.join(", ")}`);
+ log("");
+ }
+ for (const f of failed) err(`not removed: ${f.project}/${f.path} — ${f.error}`);
+ const freeNote = free !== null ? ` (${fmtBytes(free)} free under ${reportsRoot})` : "";
+ if (apply) log(`freed ${fmtBytes(freed)}${freeNote}`);
+ else if (freed > 0) log(`dry run — nothing deleted. --yes frees ${fmtBytes(freed)}${freeNote}`);
+ else log(`dry run — nothing to free${freeNote}`);
+ }
+ return failed.length || errors.length ? 1 : 0;
+ } catch (e) {
+ if (e instanceof CliError) {
+ err(e.message);
+ return 2;
+ }
+ err(e instanceof Error ? e.message : String(e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -481,8 +481,35 @@ export async function linkSharedOut(projectDir, takeOut) {
* batches are hard-linked in before the render (takeFrom.mjs), so the build
* reuses whatever still matches. `keepFrames`: the build keeps its chrome
* frames after the mux (build-video --keep-frames), for a later `from`.
+ * `pruneAfter: false`: no prune after the take is made (see below).
+ *
+ * While it builds, the take holds a build lock (`takes/<id>/.building.json`,
+ * naming `from`), so nothing prunes its work or its base's. Once it is made,
+ * the project's takes are pruned by its policy, this one kept, and what that
+ * freed is said in the log (takePrune.mjs; UMTOOL_PRUNE_AFTER_BUILD=0 or
+ * `"afterBuild": false` in takes/prune.json turns it off).
*/
export async function makeTake(projectDir, rawSpec, opts = {}) {
+ const prune = await import("./takePrune.mjs");
+ let lockFile = null;
+ const onTakeDir = async (takeDir, id) => {
+ lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null }).catch(() => null);
+ };
+ let r;
+ try {
+ r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir });
+ } finally {
+ if (lockFile) await prune.removeBuildLock(lockFile);
+ }
+ if (!r.skipped && opts.pruneAfter !== false) {
+ const log = opts.log ?? (() => {});
+ await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => log(`${r.id}: ${line}`) });
+ }
+ return r;
+}
+
+/** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */
+async function makeTakeLocked(projectDir, rawSpec, opts) {
const spec = checkSpec(rawSpec);
const emit = opts.emit ?? (() => {});
const log = opts.log ?? (() => {});
@@ -543,6 +570,7 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER));
await mkdir(takeDir, { recursive: true });
+ await opts.onTakeDir?.(takeDir, spec.id);
const takeOut = path.join(takeDir, "out");
await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut);
const linked = await linkSharedOut(projectDir, takeOut);
@@ -626,6 +654,8 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
...(spec.quick ? { quick: true } : {}),
...(covered ? { entries: { ids: covered.ids, basis: covered.basis } } : {}),
baseHash: hashText(baseText),
+ // The take it was built from: the pruner keeps a kept take's base (takePrune.mjs).
+ ...(opts.from ? { from: opts.from } : {}),
};
const tmp = `${takeFile}.tmp-${process.pid}`;
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs
@@ -0,0 +1,1090 @@
+// PRUNING TAKES' WORK FILES (2026-10-27): what a take's build leaves behind to
+// make the next build faster, removed when no take is likely to need it.
+//
+// On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB): 131 GB of it was
+// report-video takes' build work, kept forever -- each full take's chrome
+// frames (~12 GB for a 34-minute cut, kept on purpose by `--keep-frames` so a
+// `--from` twin reuses them), its crossfade batches and its clip segments.
+//
+// FINAL AND WORK. Everything under `takes/<id>/` is FINAL -- never touched --
+// except the WORK this file names, all of it under the take's `out/`:
+//
+// out/.keep-frames/ layers kept aside for a --from (takeFrom.mjs)
+// out/clips-raw/ a real directory of raw clip copies (the
+// usual one is a LINK to the project's: not work)
+// out/<variant>/segments/*.mp4 each clip's encoded segment -- its records
+// (<id>.cut.json, .teaser.json, …) stay: a
+// trailer (`umtool trailer`) maps beats through
+// them, verify-build reads a teaser's
+// out/<variant>/xfade-batches/*.mov the crossfade batches (.from.json stays)
+// out/<variant>/chunks/ the final encode's chunks (chunked-encode.mjs)
+// out/<variant>/.content-hashes.json that encode's content-hash memo
+// out/<variant>/chrome/*-frames/ each chrome layer's PNG sequence
+// out/<variant>/chrome/work-*/ a render's leftovers, --from's work-from-*
+// out/<variant>/<slug>.prerail*.mp4 the rail's cached base (--rail-only), and
+// its .segments record
+//
+// So the renders (out/<slug>.mp4, its ladder rungs, the trailer), preview.mp4,
+// take.json, the manifests, schedule.json, sync.json, the chapters, the cards,
+// the QRs, the chrome compositions and every small record stay. A name not on
+// that list is FINAL by default: an unknown file is never removed.
+//
+// HARD LINKS ARE COUNTED, NOT SUMMED. `umtool take --from` links the other
+// take's segments and frames in, so two takes may hold the same inodes and a
+// `du` of each counts them twice. A file's bytes are freed only when EVERY link
+// to it goes: a file with st_nlink 1 is freed by removing it; one with more is
+// freed only when all its links are among the paths removed (counted by inode,
+// over the whole set being removed). A take's "work" is its unique inodes'
+// bytes; "frees" is what removing that take's work alone gives back; a plan
+// over several takes counts the union. Bytes are allocated blocks (st_blocks ×
+// 512, what df sees), directories included.
+//
+// WHAT IS KEPT (the policy). A take keeps its work when it is:
+// - being built: a live build lock (`takes/<id>/.building.json`, written by
+// the take maker; `<out>/.building.json`, by build-video for its --out), or
+// a pipeline process naming a path in it (busy.mjs) -- never pruned, not
+// even by name;
+// - the base of a take being built (its lock's `from`) -- never pruned either;
+// - picked in its group (verdicts.json), or the project's manifest is its
+// manifest (the deliverable is built from it);
+// - pinned in the project's `takes/prune.json` (`"pin": ["<take>"]`);
+// - one of the newest K of its group (by builtAt; default 2);
+// - modified within D days (take.json, preview.mp4, builtAt; default 3);
+// - the `--from` base of a take kept for any reason above (take.json's
+// `from`, a lock's, xfade-batches/.from.json's), transitively.
+// Everything else's work is prunable. Naming a take (`--take X`) with
+// `--anyway` (the UI's "free anyway") overrides the reasons that are policy,
+// never the two that are a running build.
+//
+// THE SETTINGS, lowest first: the defaults; UMTOOL_PRUNE_KEEP,
+// UMTOOL_PRUNE_DAYS, UMTOOL_PRUNE_AFTER_BUILD=0; the project's
+// `takes/prune.json` ({ keep, olderThanDays, pin, afterBuild }); the CLI's
+// --keep / --older-than. The disk guard: UMTOOL_DISK_GUARD=0,
+// UMTOOL_DISK_GUARD_GB (30), UMTOOL_DISK_FLOOR_GB (10). docs/report-video.md.
+//
+// DELETION never leaves the take. Each WORK path is lstat'ed (a symlink is not
+// work: never followed, never removed) and its REAL path must be inside the
+// take's real directory -- or, when the take's out/ is the media root's link
+// (storage.mjs), inside that link's own mirror target. The walk under it
+// unlinks files and symlinks (a link, not what it points at) and descends only
+// into real directories. A clip copy that links into the corpus loses the
+// link, never the corpus file.
+//
+// Plain ESM: the CLI runs it with bare node, the app imports it. Every path is
+// a parameter or from paths.mjs.
+
+import { lstat, readdir, readFile, realpath, rename, rmdir, stat, statfs, unlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { MEDIA_ROOT, REPORTS_ROOT, inside, mediaMirror } from "../paths.mjs";
+import { namesProject, pipelineProcesses } from "./busy.mjs";
+import { TAKES_DIR, isTakeId, parseTake, readVerdicts, takesDirOf } from "./takes.mjs";
+
+/** The project's prune settings: `takes/prune.json`. */
+export const POLICY_FILE = "prune.json";
+/** A build's lock: `takes/<id>/.building.json` (the take maker), `<out>/.building.json` (build-video). */
+export const BUILD_LOCK = ".building.json";
+/** What was pruned from a take, newest last: `takes/<id>/pruned-work.json`. */
+export const PRUNE_RECORD = "pruned-work.json";
+const PRUNE_RECORD_KEEP = 20;
+
+export const DEFAULT_POLICY = Object.freeze({ keep: 2, olderThanDays: 3, afterBuild: true });
+export const DISK_GUARD_DEFAULTS = Object.freeze({ thresholdGB: 30, floorGB: 10 });
+
+// The writers' names (checked against their constants in takePrune.test.mjs;
+// not imported, so the CLI need not load build-video.mjs to prune).
+export const KEEP_FRAMES_DIR = ".keep-frames"; // takeFrom.mjs
+export const XFADE_FROM_FILE = ".from.json"; // build-video.mjs
+const NOT_VARIANTS = new Set(["clips-raw", "narration", "bench-excerpts", "posts-media", KEEP_FRAMES_DIR]);
+// kind "files": the files in that directory whose names match, never the
+// directory or anything else in it.
+const IN_VARIANT = [
+ { name: "segments", kind: "files", match: /^[^.].*\.mp4$/, glob: "*.mp4", what: "clip segments (the encodes; their records stay)" },
+ { name: "xfade-batches", kind: "files", match: /^batch-.*\.mov$/, glob: "batch-*.mov", what: "crossfade batches" },
+ { name: "chunks", kind: "dir", what: "the final encode's chunks" },
+ { name: ".content-hashes.json", kind: "file", what: "the encode's content-hash memo" },
+];
+const PRERAIL = /\.prerail(-hardcut)?\.mp4(\.segments)?$/;
+
+/** The reasons a take is kept that no `--anyway` overrides. */
+export const HARD_REASONS = new Set(["building", "base-of-building", "just-built", "link"]);
+
+const GiB = 1024 ** 3;
+
+/** Bytes for a person: `12.3 GiB`, `840 MiB`, `0 B`. */
+export function fmtBytes(n) {
+ const v = Number(n) || 0;
+ if (v < 1024) return `${v} B`;
+ const units = ["KiB", "MiB", "GiB", "TiB"];
+ let x = v / 1024;
+ let i = 0;
+ while (x >= 1024 && i < units.length - 1) {
+ x /= 1024;
+ i += 1;
+ }
+ return `${x.toFixed(x >= 100 || i < 2 ? 0 : 1)} ${units[i]}`;
+}
+
+/**
+ * An age in days: `3d`, `12h`, `90m`, `2.5` (days), `0`.
+ * @returns {number}
+ */
+export function parseAge(v) {
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0) return v;
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(d|h|m)?\s*$/i.exec(String(v ?? ""));
+ if (!m) throw new Error(`"${v}" is not an age: a number of days, or 3d, 12h, 90m`);
+ const n = Number(m[1]);
+ const unit = (m[2] ?? "d").toLowerCase();
+ return unit === "d" ? n : unit === "h" ? n / 24 : n / (24 * 60);
+}
+
+const keepCount = (v, where) => {
+ const n = Number(v);
+ if (!Number.isInteger(n) || n < 0) throw new Error(`${where}: keep is a whole number ≥ 0, not ${JSON.stringify(v)}`);
+ return n;
+};
+
+/**
+ * The project's `takes/prune.json`, checked: `{}` when there is none. One that
+ * does not parse, or says something that is not the shape, is an ERROR --
+ * pruning on a policy nobody wrote would delete what it meant to keep.
+ */
+export async function readPolicyFile(projectDir) {
+ const file = path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), POLICY_FILE);
+ let text;
+ try {
+ text = await readFile(/* turbopackIgnore: true */ file, "utf8");
+ } catch {
+ return {};
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ throw new Error(`${TAKES_DIR}/${POLICY_FILE} does not parse (${err instanceof Error ? err.message : err}): not pruning on a guess`);
+ }
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${TAKES_DIR}/${POLICY_FILE} is not an object`);
+ const out = {};
+ const where = `${TAKES_DIR}/${POLICY_FILE}`;
+ if (raw.keep !== undefined) out.keep = keepCount(raw.keep, where);
+ if (raw.olderThanDays !== undefined) {
+ try {
+ out.olderThanDays = parseAge(raw.olderThanDays);
+ } catch (err) {
+ throw new Error(`${where}: olderThanDays — ${err instanceof Error ? err.message : err}`);
+ }
+ }
+ if (raw.pin !== undefined) {
+ if (!Array.isArray(raw.pin) || !raw.pin.every((t) => isTakeId(t))) throw new Error(`${where}: pin is a list of take ids`);
+ out.pin = [...raw.pin];
+ }
+ if (raw.afterBuild !== undefined) {
+ if (typeof raw.afterBuild !== "boolean") throw new Error(`${where}: afterBuild is true or false`);
+ out.afterBuild = raw.afterBuild;
+ }
+ return out;
+}
+
+/**
+ * The policy in force: the defaults, then the environment, then the project's
+ * file, then the command line. `from` says where each value came from.
+ *
+ * @param {{ file?: Record<string, any>, env?: NodeJS.ProcessEnv, flags?: { keep?: unknown, olderThan?: unknown } }} [src]
+ */
+export function resolvePolicy({ file = {}, env = process.env, flags = {} } = {}) {
+ const p = { keep: DEFAULT_POLICY.keep, olderThanDays: DEFAULT_POLICY.olderThanDays, afterBuild: DEFAULT_POLICY.afterBuild, pin: /** @type {string[]} */ ([]) };
+ const from = { keep: "default", olderThanDays: "default", afterBuild: "default" };
+ if (env.UMTOOL_PRUNE_KEEP !== undefined && env.UMTOOL_PRUNE_KEEP !== "") {
+ p.keep = keepCount(env.UMTOOL_PRUNE_KEEP, "UMTOOL_PRUNE_KEEP");
+ from.keep = "UMTOOL_PRUNE_KEEP";
+ }
+ if (env.UMTOOL_PRUNE_DAYS !== undefined && env.UMTOOL_PRUNE_DAYS !== "") {
+ p.olderThanDays = parseAge(env.UMTOOL_PRUNE_DAYS);
+ from.olderThanDays = "UMTOOL_PRUNE_DAYS";
+ }
+ if (env.UMTOOL_PRUNE_AFTER_BUILD === "0") {
+ p.afterBuild = false;
+ from.afterBuild = "UMTOOL_PRUNE_AFTER_BUILD";
+ }
+ if (file.keep !== undefined) [p.keep, from.keep] = [file.keep, POLICY_FILE];
+ if (file.olderThanDays !== undefined) [p.olderThanDays, from.olderThanDays] = [file.olderThanDays, POLICY_FILE];
+ if (file.afterBuild !== undefined) [p.afterBuild, from.afterBuild] = [file.afterBuild, POLICY_FILE];
+ if (file.pin) p.pin = [...file.pin];
+ if (flags.keep !== undefined) [p.keep, from.keep] = [keepCount(flags.keep, "--keep"), "--keep"];
+ if (flags.olderThan !== undefined) [p.olderThanDays, from.olderThanDays] = [parseAge(flags.olderThan), "--older-than"];
+ return { ...p, from };
+}
+
+/** The policy as one line. */
+export function policyLine(p) {
+ const days = p.olderThanDays >= 1 ? `${+p.olderThanDays.toFixed(2)} d` : `${+(p.olderThanDays * 24).toFixed(1)} h`;
+ return (
+ `keeps: running builds and their bases, the picked or current take, ` +
+ `the newest ${p.keep} per group, anything modified within ${days}` +
+ `${p.pin?.length ? `, pinned (${p.pin.join(", ")})` : ""}, and the --from bases of those`
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Build locks
+// ---------------------------------------------------------------------------
+
+/** Is a process with this pid alive here? EPERM (another user's) is alive. */
+export function pidAlive(pid) {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return /** @type {NodeJS.ErrnoException} */ (err)?.code === "EPERM";
+ }
+}
+
+/** A build lock, read: null when there is none or it does not parse. */
+export async function readBuildLock(file) {
+ try {
+ const j = JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8"));
+ return j && typeof j === "object" && !Array.isArray(j) ? j : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Is this lock a build running now? A lock from another host is taken as
+ * running (this machine cannot tell); one from here whose pid is gone is stale.
+ */
+export function lockIsLive(lock, { host = os.hostname(), alive = pidAlive } = {}) {
+ if (!lock) return false;
+ if (lock.host && lock.host !== host) return true;
+ return alive(Number(lock.pid));
+}
+
+/**
+ * Write a build lock in `dir` (which must exist): `{ pid, host, startedAt, ...info }`.
+ * @returns {Promise<string>} the lock's path
+ */
+export async function writeBuildLock(dir, info = {}, { now = () => new Date() } = {}) {
+ const file = path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK);
+ const doc = { pid: process.pid, host: os.hostname(), startedAt: now().toISOString(), ...info };
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc) + "\n", "utf8");
+ await rename(tmp, file);
+ return file;
+}
+
+/** Remove a lock this process wrote (another process's is left). */
+export async function removeBuildLock(file) {
+ const lock = await readBuildLock(file);
+ if (lock && Number(lock.pid) === process.pid && (!lock.host || lock.host === os.hostname())) await unlink(file).catch(() => {});
+}
+
+/**
+ * Run `fn` holding a build lock in `dir`. With no `dir` (or one that is not
+ * there), just runs it: the lock is a marker for the pruner, not a mutex.
+ * @template T
+ * @param {string | null | undefined} dir
+ * @param {Record<string, unknown>} info
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+export async function withBuildLock(dir, info, fn) {
+ let file = null;
+ if (dir && (await stat(/* turbopackIgnore: true */ dir).then((s) => s.isDirectory(), () => false))) {
+ file = await writeBuildLock(dir, info).catch(() => null);
+ }
+ try {
+ return await fn();
+ } finally {
+ if (file) await removeBuildLock(file);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// One take's WORK, found and measured
+// ---------------------------------------------------------------------------
+
+/**
+ * The directories a WORK path's real path may be in: the take's own, and --
+ * when its out/ is the media root's link -- that link's mirror target.
+ */
+async function allowedRootsOf(takeDir, { reportsRoot, mediaRoot }) {
+ const notes = [];
+ const realTake = await realpath(/* turbopackIgnore: true */ takeDir).catch(() => null);
+ if (!realTake) return { allowed: [], out: null, notes: ["the take's directory is not readable"] };
+ const out = path.join(/* turbopackIgnore: true */ takeDir, "out");
+ const st = await lstat(/* turbopackIgnore: true */ out).catch(() => null);
+ if (!st) return { allowed: [realTake], out: null, notes };
+ if (st.isDirectory()) return { allowed: [realTake], out, notes };
+ if (!st.isSymbolicLink()) return { allowed: [realTake], out: null, notes };
+ const target = await realpath(/* turbopackIgnore: true */ out).catch(() => null);
+ // Untiered (the media root IS the reports root), out/'s "mirror" is out/ itself: no link is the media root's.
+ const mirror = mediaMirror(out, { reportsRoot, mediaRoot });
+ const tiered = !!mirror && path.resolve(/* turbopackIgnore: true */ mirror) !== path.resolve(/* turbopackIgnore: true */ out);
+ const realMirror = tiered ? await realpath(/* turbopackIgnore: true */ /** @type {string} */ (mirror)).catch(() => null) : null;
+ if (target && realMirror && target === realMirror) return { allowed: [realTake, target], out, notes };
+ notes.push(`out/ is a link${target ? ` to ${target}` : " that does not resolve"}, not this take's media-root mirror: not followed`);
+ return { allowed: [realTake], out: null, notes };
+}
+
+/**
+ * The WORK paths of one take (see the top of the file), each checked: a real
+ * directory or file (never a link), whose real path is inside an allowed root.
+ *
+ * @param {string} takeDir
+ * @param {{ reportsRoot?: string, mediaRoot?: string }} [opts]
+ * @returns {Promise<{ roots: { abs: string, rel: string, kind: "dir" | "file" | "files", what: string, match?: RegExp }[], allowed: string[], notes: string[] }>}
+ */
+export async function workPathsOf(takeDir, { reportsRoot = REPORTS_ROOT, mediaRoot = MEDIA_ROOT } = {}) {
+ const { allowed, out, notes } = await allowedRootsOf(takeDir, { reportsRoot, mediaRoot });
+ const roots = [];
+ const names = async (dir) => readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []);
+ if (!out) return { roots, allowed, notes };
+ const add = async (abs, kind, what, w = null) => {
+ const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null);
+ if (!st || st.isSymbolicLink()) return;
+ if (kind === "file" ? !st.isFile() : !st.isDirectory()) return;
+ const real = await realpath(/* turbopackIgnore: true */ abs).catch(() => null);
+ if (!real || !allowed.some((a) => real !== a && inside(a, real))) {
+ notes.push(`${path.relative(takeDir, abs)} resolves outside the take: not touched`);
+ return;
+ }
+ if (kind === "files") {
+ // Only when one is there: a directory of records alone holds no work.
+ const files = (await names(abs)).filter((e) => e.isFile() && w.match.test(e.name));
+ if (!files.length) return;
+ roots.push({ abs, rel: `${path.relative(takeDir, abs)}/${w.glob}`, kind, what, match: w.match });
+ return;
+ }
+ roots.push({ abs, rel: path.relative(takeDir, abs), kind, what });
+ };
+ await add(path.join(/* turbopackIgnore: true */ out, KEEP_FRAMES_DIR), "dir", "chrome frames kept aside for --from");
+ await add(path.join(/* turbopackIgnore: true */ out, "clips-raw"), "dir", "raw clip copies");
+ for (const v of await names(out)) {
+ if (!v.isDirectory() || v.name.startsWith(".") || NOT_VARIANTS.has(v.name)) continue;
+ const vdir = path.join(/* turbopackIgnore: true */ out, v.name);
+ const inV = await names(vdir);
+ for (const w of IN_VARIANT) if (inV.some((e) => e.name === w.name)) await add(path.join(/* turbopackIgnore: true */ vdir, w.name), w.kind, w.what, w);
+ for (const e of inV) if (e.isFile() && PRERAIL.test(e.name)) await add(path.join(/* turbopackIgnore: true */ vdir, e.name), "file", "the rail's cached base");
+ for (const c of await names(path.join(/* turbopackIgnore: true */ vdir, "chrome"))) {
+ if (!c.isDirectory()) continue;
+ if (c.name.endsWith("-frames")) await add(path.join(/* turbopackIgnore: true */ vdir, "chrome", c.name), "dir", `chrome frames (${c.name.replace(/-frames$/, "")})`);
+ else if (c.name.startsWith("work-")) await add(path.join(/* turbopackIgnore: true */ vdir, "chrome", c.name), "dir", "a chrome render's work");
+ }
+ }
+ roots.sort((a, b) => a.rel.localeCompare(b.rel));
+ return { roots, allowed, notes };
+}
+
+const blocksOf = (st) => (typeof st.blocks === "number" ? st.blocks * 512 : st.size);
+
+/**
+ * Measure WORK paths: every entry lstat'ed, nothing followed. Inodes with one
+ * link are summed at once; those with more are returned by `dev:ino` with
+ * their link count and how many of their paths are in these roots.
+ *
+ * @param {{ abs: string, kind: "dir" | "file" | "files", match?: RegExp }[]} roots
+ * @returns {Promise<{ single: number, files: number, multi: Map<string, { nlink: number, bytes: number, n: number }>, perRoot: { bytes: number, files: number }[] }>}
+ */
+export async function measurePaths(roots) {
+ let single = 0;
+ let files = 0;
+ const multi = new Map();
+ const perRoot = [];
+ const seen = new Set();
+ for (const root of roots) {
+ let rb = 0;
+ let rf = 0;
+ const take = (st) => {
+ if (st.isDirectory()) {
+ single += blocksOf(st);
+ rb += blocksOf(st);
+ return;
+ }
+ files += 1;
+ rf += 1;
+ const b = blocksOf(st);
+ if (st.nlink <= 1) {
+ single += b;
+ rb += b;
+ return;
+ }
+ const key = `${st.dev}:${st.ino}`;
+ const m = multi.get(key);
+ if (m) m.n += 1;
+ else multi.set(key, { nlink: st.nlink, bytes: b, n: 1 });
+ if (!seen.has(key)) {
+ seen.add(key);
+ rb += b;
+ }
+ };
+ const top = await lstat(/* turbopackIgnore: true */ root.abs).catch(() => null);
+ if (!top || top.isSymbolicLink()) {
+ perRoot.push({ bytes: 0, files: 0 });
+ continue;
+ }
+ if (root.kind === "files") {
+ // The matching files only: the directory and its records stay.
+ const entries = (await readdir(/* turbopackIgnore: true */ root.abs, { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && root.match?.test(e.name));
+ const sts = await Promise.all(entries.map((e) => lstat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ root.abs, e.name)).catch(() => null)));
+ for (const st of sts) if (st?.isFile()) take(st);
+ perRoot.push({ bytes: rb, files: rf });
+ continue;
+ }
+ take(top);
+ const stack = top.isDirectory() ? [root.abs] : [];
+ while (stack.length) {
+ const dir = /** @type {string} */ (stack.pop());
+ const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []);
+ for (let i = 0; i < entries.length; i += 256) {
+ const batch = entries.slice(i, i + 256);
+ const sts = await Promise.all(batch.map((e) => lstat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, e.name)).catch(() => null)));
+ batch.forEach((e, k) => {
+ const st = sts[k];
+ if (!st) return;
+ take(st);
+ if (st.isDirectory() && !st.isSymbolicLink()) stack.push(path.join(/* turbopackIgnore: true */ dir, e.name));
+ });
+ }
+ }
+ perRoot.push({ bytes: rb, files: rf });
+ }
+ return { single, files, multi, perRoot };
+}
+
+/** Work bytes (unique inodes) and what removing these paths alone frees. */
+function sizesOf(m) {
+ let work = m.single;
+ let freed = m.single;
+ for (const v of m.multi.values()) {
+ work += v.bytes;
+ if (v.n >= v.nlink) freed += v.bytes;
+ }
+ return { workBytes: work, freedBytes: freed };
+}
+
+/** What removing every set in `measures` together frees: inodes counted over the union. */
+export function unionFreed(measures) {
+ let freed = 0;
+ const multi = new Map();
+ for (const m of measures) {
+ freed += m.single;
+ for (const [k, v] of m.multi) {
+ const u = multi.get(k);
+ if (u) u.n += v.n;
+ else multi.set(k, { ...v });
+ }
+ }
+ for (const v of multi.values()) if (v.n >= v.nlink) freed += v.bytes;
+ return freed;
+}
+
+/** The bytes the sets in `measures` hold between them: each inode once (a `du` of them all). */
+export function unionWork(measures) {
+ let work = 0;
+ const seen = new Set();
+ for (const m of measures) {
+ work += m.single;
+ for (const [k, v] of m.multi) {
+ if (seen.has(k)) continue;
+ seen.add(k);
+ work += v.bytes;
+ }
+ }
+ return work;
+}
+
+// ---------------------------------------------------------------------------
+// The plan
+// ---------------------------------------------------------------------------
+
+const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null);
+const mtimeOf = (file) => lstat(/* turbopackIgnore: true */ file).then((s) => s.mtimeMs, () => 0);
+
+/** The takes a take was started from: take.json's `from`, and xfade-batches/.from.json's. */
+async function basesOf(takeDir, raw) {
+ const out = new Set();
+ if (isTakeId(raw?.from)) out.add(raw.from);
+ const outDir = path.join(/* turbopackIgnore: true */ takeDir, "out");
+ for (const v of await readdir(/* turbopackIgnore: true */ outDir, { withFileTypes: true }).catch(() => [])) {
+ if (!v.isDirectory()) continue;
+ const j = await readJson(path.join(/* turbopackIgnore: true */ outDir, v.name, "xfade-batches", XFADE_FROM_FILE));
+ if (isTakeId(j?.take)) out.add(j.take);
+ }
+ return [...out];
+}
+
+/**
+ * Every directory under `takes/`, read: take.json (parsed, or why not), its
+ * group and times, its bases, its build locks.
+ */
+async function readTakeDirs(projectDir, { host, alive }) {
+ const root = takesDirOf(projectDir);
+ const entries = await readdir(/* turbopackIgnore: true */ root, { withFileTypes: true }).catch(() => []);
+ const out = [];
+ for (const e of entries) {
+ if (e.name.startsWith(".")) continue;
+ if (!e.isDirectory() && !e.isSymbolicLink()) continue;
+ const dir = path.join(/* turbopackIgnore: true */ root, e.name);
+ if (e.isSymbolicLink()) {
+ const isDir = await stat(/* turbopackIgnore: true */ dir).then((s) => s.isDirectory(), () => false);
+ if (isDir) out.push({ id: e.name, dir, link: true, take: null, raw: null, why: "the take's directory is a link", modifiedMs: 0, builtMs: 0, bases: [], locks: [] });
+ continue;
+ }
+ const raw = await readJson(path.join(/* turbopackIgnore: true */ dir, "take.json"));
+ const parsed = raw ? parseTake(e.name, raw) : null;
+ const take = parsed && "take" in parsed ? parsed.take : null;
+ const builtMs = take?.builtAt ? Date.parse(take.builtAt) || 0 : 0;
+ const modifiedMs = Math.max(
+ builtMs,
+ await mtimeOf(path.join(/* turbopackIgnore: true */ dir, "take.json")),
+ await mtimeOf(path.join(/* turbopackIgnore: true */ dir, take?.preview ?? "preview.mp4")),
+ // A take with no take.json yet (a build that never finished): its out/.
+ take ? 0 : await mtimeOf(path.join(/* turbopackIgnore: true */ dir, "out")),
+ );
+ const locks = [];
+ for (const f of [path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK), path.join(/* turbopackIgnore: true */ dir, "out", BUILD_LOCK)]) {
+ const lock = await readBuildLock(f);
+ if (lock) locks.push({ file: path.relative(projectDir, f), lock, live: lockIsLive(lock, { host, alive }) });
+ }
+ out.push({
+ id: e.name,
+ dir,
+ link: false,
+ take,
+ raw,
+ why: raw ? (take ? null : /** @type {any} */ (parsed).error) : "no take.json",
+ modifiedMs,
+ builtMs,
+ bases: await basesOf(dir, raw),
+ locks,
+ });
+ }
+ return out.sort((a, b) => a.id.localeCompare(b.id));
+}
+
+/**
+ * @typedef {{ code: string, why: string, hard: boolean }} KeepReason
+ * @typedef {{
+ * id: string, group: string | null, label: string | null, listed: boolean,
+ * builtAt: string | null, modifiedAt: string | null, bases: string[],
+ * status: "prunable" | "kept" | "no-work",
+ * keep: KeepReason[], overridden: KeepReason[],
+ * roots: { rel: string, kind: "dir" | "file" | "files", what: string, bytes: number | null, files: number | null }[],
+ * workBytes: number | null, freedBytes: number | null, files: number | null,
+ * notes: string[], pruned: { at: string, freedBytes: number } | null,
+ * }} TakePlan
+ */
+
+/**
+ * WHAT PRUNING A PROJECT'S TAKES WOULD DO. Reads only.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{
+ * policy?: ReturnType<typeof resolvePolicy>, flags?: { keep?: unknown, olderThan?: unknown }, env?: NodeJS.ProcessEnv,
+ * takes?: string[] | null, anyway?: boolean, protect?: string[], measure?: "all" | "prunable" | "none",
+ * now?: () => Date, reportsRoot?: string, mediaRoot?: string,
+ * procRoot?: string, processes?: { pid: number, args: string[], cwd: string | null }[],
+ * host?: string, alive?: (pid: number) => boolean,
+ * }} [opts]
+ * `takes`: only these (the CLI's --take, the UI's per-take button); `anyway`:
+ * their policy reasons are overridden; `protect`: kept as just built.
+ */
+export async function planPrune(project, opts = {}) {
+ const now = (opts.now ?? (() => new Date()))().getTime();
+ const policy = opts.policy ?? resolvePolicy({ file: await readPolicyFile(project.dir), env: opts.env ?? process.env, flags: opts.flags ?? {} });
+ const host = opts.host ?? os.hostname();
+ const alive = opts.alive ?? pidAlive;
+ const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT };
+ const dirs = await readTakeDirs(project.dir, { host, alive });
+ const notes = [];
+ for (const id of opts.takes ?? []) if (!dirs.some((d) => d.id === id)) throw new Error(`${project.id} has no take ${id}`);
+
+ const [verdicts, projectManifest] = await Promise.all([
+ readVerdicts(project.dir),
+ readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null),
+ ]);
+ const procs = opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" });
+
+ /** @type {Map<string, KeepReason[]>} */
+ const reasons = new Map(dirs.map((d) => [d.id, []]));
+ const why = (id, code, text) => {
+ const list = reasons.get(id);
+ if (list && !list.some((r) => r.code === code)) list.push({ code, why: text, hard: HARD_REASONS.has(code) });
+ };
+
+ // Running builds, and the takes they build from.
+ for (const d of dirs) {
+ if (d.link) {
+ why(d.id, "link", "its directory is a link: its files are not this project's to prune");
+ continue;
+ }
+ for (const l of d.locks) {
+ if (l.live) {
+ why(d.id, "building", `a build is running (${l.file}, pid ${l.lock.pid}${l.lock.host && l.lock.host !== host ? ` on ${l.lock.host}` : ""})`);
+ if (isTakeId(l.lock.from)) why(l.lock.from, "base-of-building", `take ${d.id} is being built from it`);
+ } else notes.push(`${l.file}: a build lock whose process (pid ${l.lock.pid}) is gone — ignored`);
+ }
+ const ref = { dir: d.dir, realDir: await realpath(/* turbopackIgnore: true */ d.dir).catch(() => d.dir) };
+ const pids = procs.filter((p) => namesProject(p.args, p.cwd, ref)).map((p) => p.pid);
+ if (pids.length) why(d.id, "building", `a build process is working in it (pid ${pids.join(", ")})`);
+ }
+ for (const id of opts.protect ?? []) why(id, "just-built", "just built");
+
+ // The picked take, and the take whose manifest the project's is.
+ for (const d of dirs) {
+ if (d.link) continue;
+ if (verdicts[d.id]?.picked) why(d.id, "picked", `picked in group "${d.take?.group ?? "?"}"`);
+ if (projectManifest !== null) {
+ const mine = await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ d.dir, "video.manifest.json"), "utf8").catch(() => null);
+ if (mine !== null && mine === projectManifest) why(d.id, "current", "the project's manifest is this take's");
+ }
+ if (policy.pin.includes(d.id)) why(d.id, "pinned", `pinned in ${TAKES_DIR}/${POLICY_FILE}`);
+ }
+ for (const id of policy.pin) if (!dirs.some((d) => d.id === id)) notes.push(`${TAKES_DIR}/${POLICY_FILE} pins ${id}, which is not a take`);
+
+ // The newest K of each group.
+ const groups = new Map();
+ for (const d of dirs) {
+ if (!d.take) continue;
+ if (!groups.has(d.take.group)) groups.set(d.take.group, []);
+ groups.get(d.take.group).push(d);
+ }
+ for (const [group, list] of groups) {
+ list.sort((a, b) => (b.builtMs || b.modifiedMs) - (a.builtMs || a.modifiedMs) || a.id.localeCompare(b.id));
+ list.slice(0, policy.keep).forEach((d, i) => why(d.id, "newest", `the ${i === 0 ? "newest" : `${ordinal(i + 1)} newest`} of group "${group}" (keeps ${policy.keep})`));
+ }
+
+ // Modified within D days.
+ const horizon = now - policy.olderThanDays * 24 * 3600 * 1000;
+ for (const d of dirs) {
+ if (d.link || !d.modifiedMs || d.modifiedMs < horizon) continue;
+ const ago = (now - d.modifiedMs) / 3600000;
+ why(d.id, "recent", `modified ${ago < 48 ? `${Math.max(0, Math.round(ago))} h` : `${(ago / 24).toFixed(1)} d`} ago (keeps ${policyAge(policy.olderThanDays)})`);
+ }
+
+ // The --from bases of a kept take, transitively.
+ const byId = new Map(dirs.map((d) => [d.id, d]));
+ for (let changed = true; changed; ) {
+ changed = false;
+ for (const d of dirs) {
+ if (!(reasons.get(d.id) ?? []).length) continue;
+ for (const b of d.bases) {
+ if (!byId.has(b) || (reasons.get(b) ?? []).some((r) => r.code === "base")) continue;
+ why(b, "base", `the --from base of ${d.id}, which is kept`);
+ changed = true;
+ }
+ }
+ }
+
+ const named = opts.takes ? new Set(opts.takes) : null;
+ const measure = opts.measure ?? "all";
+ /** @type {TakePlan[]} */
+ const takes = [];
+ /** @type {Map<string, Awaited<ReturnType<typeof measurePaths>>>} */
+ const measured = new Map();
+ for (const d of dirs) {
+ if (named && !named.has(d.id)) continue;
+ let keep = reasons.get(d.id) ?? [];
+ let overridden = [];
+ if (named && opts.anyway) {
+ overridden = keep.filter((r) => !r.hard);
+ keep = keep.filter((r) => r.hard);
+ }
+ const work = d.link ? { roots: [], notes: [] } : await workPathsOf(d.dir, roots);
+ const status = work.roots.length === 0 ? "no-work" : keep.length ? "kept" : "prunable";
+ let m = null;
+ if (work.roots.length && (measure === "all" || (measure === "prunable" && status === "prunable"))) {
+ m = await measurePaths(work.roots);
+ measured.set(d.id, m);
+ }
+ const sizes = m ? sizesOf(m) : null;
+ const record = await readJson(path.join(/* turbopackIgnore: true */ d.dir, PRUNE_RECORD));
+ const last = Array.isArray(record?.prunes) ? record.prunes[record.prunes.length - 1] : null;
+ takes.push({
+ id: d.id,
+ group: d.take?.group ?? null,
+ label: d.take?.label ?? null,
+ listed: !!d.take,
+ builtAt: d.take?.builtAt ?? null,
+ modifiedAt: d.modifiedMs ? new Date(d.modifiedMs).toISOString() : null,
+ bases: d.bases,
+ status,
+ keep,
+ overridden,
+ roots: work.roots.map((r, i) => ({ rel: r.rel, kind: r.kind, what: r.what, bytes: m ? m.perRoot[i].bytes : null, files: m ? m.perRoot[i].files : null })),
+ workBytes: sizes?.workBytes ?? null,
+ freedBytes: sizes?.freedBytes ?? null,
+ files: m ? m.files : null,
+ notes: [
+ ...(d.take || d.link ? [] : [d.why === "no take.json" ? "no take.json (a build that never finished?)" : `not listed on the Takes page: ${d.why}`]),
+ ...work.notes,
+ ],
+ pruned: last && typeof last.at === "string" ? { at: last.at, freedBytes: Number(last.freedBytes) || 0 } : null,
+ });
+ }
+ const prunable = takes.filter((t) => t.status === "prunable");
+ const kept = takes.filter((t) => t.status === "kept");
+ const sum = (list, k) => list.reduce((s, t) => s + (t[k] ?? 0), 0);
+ const of = (list) => list.map((t) => measured.get(t.id)).filter((m) => !!m);
+ const keptMeasured = kept.some((t) => measured.has(t.id));
+ return {
+ project: { id: project.id, dir: project.dir },
+ policy,
+ at: new Date(now).toISOString(),
+ takes,
+ // Bytes over several takes count each inode once (`du` of them together).
+ totals: {
+ takes: takes.length,
+ workBytes: measure === "all" ? unionWork([...measured.values()]) : null,
+ prunable: { takes: prunable.length, workBytes: unionWork(of(prunable)), freedBytes: unionFreed(of(prunable)), files: sum(prunable, "files") },
+ kept: { takes: kept.length, workBytes: keptMeasured ? unionWork(of(kept)) : null },
+ },
+ notes,
+ /** Not serialised: the measurements, for pruneProject. */
+ measured,
+ };
+}
+
+const ordinal = (n) => `${n}${n % 10 === 1 && n % 100 !== 11 ? "st" : n % 10 === 2 && n % 100 !== 12 ? "nd" : n % 10 === 3 && n % 100 !== 13 ? "rd" : "th"}`;
+const policyAge = (d) => (d >= 1 ? `${+d.toFixed(2)} d` : `${+(d * 24).toFixed(1)} h`);
+
+/** The plan without its measurements: what --json and the route answer. */
+export function planView(plan) {
+ const { measured: _m, ...rest } = plan;
+ return rest;
+}
+
+/**
+ * The plan as the delete routes answer one (lib/delete-plan.ts), so the Takes
+ * page's "Free work files" is components/DeletePlan.tsx: what goes (each
+ * prunable take, its work paths as parts), what is kept and why, and -- for
+ * a take named alone -- the policy's reasons as refusals "free anyway"
+ * answers, a running build as one nothing does.
+ *
+ * @param {Awaited<ReturnType<typeof planPrune>>} plan
+ * @param {{ take?: string | null }} [o]
+ */
+export function deleteViewOf(plan, { take = null } = {}) {
+ const refusals = [];
+ if (take) {
+ const t = plan.takes.find((x) => x.id === take);
+ if (t?.status === "no-work") refusals.push({ reason: `take ${take} has no work files${t.pruned ? ` (pruned ${t.pruned.at.slice(0, 10)})` : ""}`, forceable: false });
+ for (const r of t?.keep ?? []) {
+ refusals.push(r.hard ? { reason: `kept: ${r.why}`, forceable: false } : { reason: `kept by the policy: ${r.why}`, forceable: true });
+ }
+ }
+ const prunable = plan.takes.filter((t) => t.status === "prunable");
+ if (!take && !prunable.length) refusals.push({ reason: "nothing to free: every take's work files are kept, or there are none", forceable: false });
+ const remove = prunable.map((t) => ({
+ path: `${TAKES_DIR}/${t.id}/`,
+ label: `${t.id}/`,
+ what: `work files${t.overridden.length ? " (freed anyway)" : ""}${t.workBytes !== null && t.freedBytes !== null && t.workBytes > t.freedBytes ? ` — ${fmtBytes(t.workBytes - t.freedBytes)} of it is also linked elsewhere (another take, the project's out/) and stays` : ""}`,
+ kind: /** @type {const} */ ("dir"),
+ bytes: t.freedBytes ?? 0,
+ files: t.files ?? 0,
+ parts: t.roots.map((r) => ({ name: r.rel, bytes: r.bytes ?? 0 })),
+ }));
+ const kept = [
+ ...plan.takes
+ .filter((t) => t.status === "kept" && (!take || t.id === take))
+ .map((t) => ({ what: `take ${t.id}${t.workBytes !== null ? ` (${fmtBytes(t.workBytes)} of work)` : ""}`, path: `${TAKES_DIR}/${t.id}/`, why: t.keep.map((r) => r.why).join("; ") })),
+ { what: "every take's renders, preview.mp4, take.json, manifests, schedule, sync and chapters", why: "final: never pruned" },
+ ];
+ return {
+ refusals,
+ steps: prunable.some((t) => t.roots.some((r) => /chrome\/[^/]+-frames$/.test(r.rel))) ? ["each pruned chrome layer's frame count and key go into its chrome/pruned.json first, so the cut stays verifiable"] : [],
+ remove,
+ kept,
+ bytes: plan.totals.prunable.freedBytes,
+ files: plan.totals.prunable.files,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Removing
+// ---------------------------------------------------------------------------
+
+/**
+ * Remove one WORK path: refused (a reason returned, nothing removed) when it
+ * is a link or its real path is not inside `allowed`. Files and links are
+ * unlinked; only real directories are descended into.
+ * @returns {Promise<string | null>} why not, or null when removed
+ */
+export async function removeWorkPath(abs, allowed) {
+ const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null);
+ if (!st) return null;
+ if (st.isSymbolicLink()) return "a link: not followed, not removed";
+ const real = await realpath(/* turbopackIgnore: true */ abs).catch(() => null);
+ if (!real || !allowed.some((a) => real !== a && inside(a, real))) return "resolves outside the take: not removed";
+ if (!st.isDirectory()) {
+ await unlink(/* turbopackIgnore: true */ abs);
+ return null;
+ }
+ await removeTree(abs);
+ return null;
+}
+
+/**
+ * Remove the files in `dir` whose names match (a "files" work path): files
+ * only, never a link or a directory, never `dir` itself; `dir` must resolve
+ * inside `allowed`.
+ * @returns {Promise<string | null>} why not, or null when done
+ */
+export async function removeWorkFiles(dir, match, allowed) {
+ const st = await lstat(/* turbopackIgnore: true */ dir).catch(() => null);
+ if (!st) return null;
+ if (st.isSymbolicLink()) return "a link: not followed, not removed";
+ const real = await realpath(/* turbopackIgnore: true */ dir).catch(() => null);
+ if (!real || !allowed.some((a) => real !== a && inside(a, real))) return "resolves outside the take: not removed";
+ for (const e of await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true })) {
+ if (e.isFile() && match.test(e.name)) await unlink(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, e.name));
+ }
+ return null;
+}
+
+async function removeTree(dir) {
+ const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true });
+ for (let i = 0; i < entries.length; i += 256) {
+ const batch = entries.slice(i, i + 256);
+ await Promise.all(
+ batch.map(async (e) => {
+ const p = path.join(/* turbopackIgnore: true */ dir, e.name);
+ // withFileTypes is lstat's view: a link to a directory is not a directory.
+ if (e.isDirectory()) await removeTree(p);
+ else await unlink(/* turbopackIgnore: true */ p);
+ }),
+ );
+ }
+ await rmdir(/* turbopackIgnore: true */ dir);
+}
+
+async function appendPruneRecord(takeDir, entry) {
+ const file = path.join(/* turbopackIgnore: true */ takeDir, PRUNE_RECORD);
+ const prev = await readJson(file);
+ const prunes = Array.isArray(prev?.prunes) ? prev.prunes : [];
+ const doc = { format: "umtool-pruned-work", version: 1, prunes: [...prunes, entry].slice(-PRUNE_RECORD_KEEP) };
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * PRUNE A PROJECT'S TAKES: the plan made (or made again), then each prunable
+ * take's work removed -- after its build state is read once more, so a build
+ * that started since the plan keeps its take and the take it builds from.
+ * Each pruned take's chrome frames are recorded first (chrome/pruned.json,
+ * so verify-build can still check its cut), and what went is appended to
+ * `takes/<id>/pruned-work.json`.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Parameters<typeof planPrune>[1] & { by?: string, log?: (line: string) => void }} [opts]
+ */
+export async function pruneProject(project, opts = {}) {
+ const plan = await planPrune(project, { ...opts, measure: "prunable" });
+ const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT };
+ const { recordPrunedSequences } = await import("umtool-report-to-video/prune-frames");
+ const removed = [];
+ const failed = [];
+ const pruned = [];
+ let freedBytes = 0;
+ const host = opts.host ?? os.hostname();
+ const alive = opts.alive ?? pidAlive;
+ for (const t of plan.takes) {
+ if (t.status !== "prunable") continue;
+ const takeDir = path.join(/* turbopackIgnore: true */ takesDirOf(project.dir), t.id);
+ // Once more, now: a build started since the plan, here or from here.
+ const fresh = await readTakeDirs(project.dir, { host, alive });
+ const realTake = await realpath(/* turbopackIgnore: true */ takeDir).catch(() => takeDir);
+ const busy =
+ fresh.find((d) => d.id === t.id)?.locks.some((l) => l.live) ||
+ fresh.some((d) => d.locks.some((l) => l.live && l.lock.from === t.id)) ||
+ (opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" })).some((p) =>
+ namesProject(p.args, p.cwd, { dir: takeDir, realDir: realTake }),
+ );
+ if (busy) {
+ failed.push({ path: `${TAKES_DIR}/${t.id}/`, error: "a build started in it (or from it) since the plan: kept" });
+ continue;
+ }
+ const work = await workPathsOf(takeDir, roots);
+ // Frames first in the record, so a verified cut stays verifiable.
+ const byChrome = new Map();
+ for (const r of work.roots) {
+ if (r.kind !== "dir" || !/\/chrome\/[^/]+-frames$/.test(r.abs)) continue;
+ const c = path.dirname(r.abs);
+ byChrome.set(c, [...(byChrome.get(c) ?? []), path.basename(r.abs)]);
+ }
+ for (const [chromeDir, names] of byChrome) await recordPrunedSequences(chromeDir, names).catch(() => {});
+ const gone = [];
+ for (const r of work.roots) {
+ try {
+ const no = r.kind === "files" ? await removeWorkFiles(r.abs, /** @type {RegExp} */ (r.match), work.allowed) : await removeWorkPath(r.abs, work.allowed);
+ if (no) failed.push({ path: `${TAKES_DIR}/${t.id}/${r.rel}`, error: no });
+ else gone.push(r.rel);
+ } catch (err) {
+ failed.push({ path: `${TAKES_DIR}/${t.id}/${r.rel}`, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+ const takeFreed = t.freedBytes ?? 0;
+ if (gone.length) {
+ removed.push(...gone.map((g) => `${TAKES_DIR}/${t.id}/${g}`));
+ await appendPruneRecord(takeDir, { at: new Date().toISOString(), by: opts.by ?? "cli", workBytes: t.workBytes ?? 0, freedBytes: takeFreed, paths: gone }).catch(() => {});
+ pruned.push({ id: t.id, freedBytes: takeFreed, paths: gone });
+ }
+ }
+ // The union: two prunable takes sharing inodes free them together.
+ freedBytes = unionFreed(pruned.map((p) => plan.measured.get(p.id)).filter(Boolean));
+ return { plan, pruned, removed, failed, freedBytes };
+}
+
+/** One line for a log: what a prune freed and what it kept. */
+export function pruneSummary(r, projectId) {
+ const kept = r.plan.takes.filter((t) => t.status === "kept").length;
+ const head = r.pruned.length
+ ? `freed ${fmtBytes(r.freedBytes)} of work files from ${r.pruned.length} take(s): ${r.pruned.map((p) => p.id).join(", ")}`
+ : "nothing to free";
+ const tail = kept ? `; ${kept} take(s) keep theirs (\`umtool prune ${projectId}\` says why)` : "";
+ const fails = r.failed.length ? `; ${r.failed.length} path(s) not removed: ${r.failed.map((f) => `${f.path} (${f.error})`).join("; ")}` : "";
+ return `prune: ${head}${tail}${fails}`;
+}
+
+// ---------------------------------------------------------------------------
+// After a take's build, and before a render
+// ---------------------------------------------------------------------------
+
+/** A project's id from its directory: its path under the reports root, else its name. */
+export function projectIdOfDir(dir, reportsRoot = REPORTS_ROOT) {
+ const rel = path.relative(reportsRoot, dir);
+ return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel.split(path.sep).join("/") : path.basename(dir);
+}
+
+/**
+ * The take maker's hook (takeMaker.mjs makeTake): after a take is built, the
+ * policy over its project, the take just built kept. Off with
+ * UMTOOL_PRUNE_AFTER_BUILD=0 or `"afterBuild": false` in takes/prune.json.
+ * Never throws: a prune that fails says so and the build stands.
+ *
+ * @returns {Promise<string | null>} the line it logged, or null when off
+ */
+export async function pruneAfterBuild(projectDir, { built, log = () => {}, env = process.env, ...rest } = {}) {
+ try {
+ if (env.UMTOOL_PRUNE_AFTER_BUILD === "0") return null;
+ const file = await readPolicyFile(projectDir);
+ const policy = resolvePolicy({ file, env });
+ if (!policy.afterBuild) return null;
+ const project = { id: projectIdOfDir(projectDir, rest.reportsRoot), dir: projectDir };
+ const r = await pruneProject(project, { ...rest, policy, protect: built ? [built] : [], by: "after-build" });
+ const line = pruneSummary(r, project.id);
+ log(line);
+ return line;
+ } catch (err) {
+ const line = `prune: not run — ${err instanceof Error ? err.message : err}`;
+ log(line);
+ return line;
+ }
+}
+
+/**
+ * Every project under `reportsRoot` that has a takes/ directory, pruned by its
+ * own policy. Returns the total and each project's result.
+ */
+export async function pruneAllProjects({ reportsRoot = REPORTS_ROOT, dryRun = false, by = "cli", ...rest } = {}) {
+ const { walkProjects } = await import("../projects/walk.mjs");
+ const refs = await walkProjects(reportsRoot);
+ const results = [];
+ for (const p of refs) {
+ const has = await stat(/* turbopackIgnore: true */ takesDirOf(p.dir)).then((s) => s.isDirectory(), () => false);
+ if (!has) continue;
+ const project = { id: p.id, dir: p.dir };
+ try {
+ if (dryRun) results.push({ project, plan: await planPrune(project, { reportsRoot, ...rest }) });
+ else results.push({ project, ...(await pruneProject(project, { reportsRoot, by, ...rest })) });
+ } catch (err) {
+ results.push({ project, error: err instanceof Error ? err.message : String(err) });
+ }
+ }
+ const freedBytes = results.reduce((s, r) => s + (dryRun ? r.plan?.totals.prunable.freedBytes ?? 0 : r.freedBytes ?? 0), 0);
+ return { results, freedBytes };
+}
+
+/** Free bytes for an unprivileged writer on the filesystem holding `dir` (null when unreadable). */
+export async function freeBytesAt(dir) {
+ const s = await statfs(/* turbopackIgnore: true */ dir).catch(() => null);
+ return s ? Number(s.bavail) * Number(s.bsize) : null;
+}
+
+/** The disk guard's settings, from the environment. */
+export function guardSettings(env = process.env) {
+ const gb = (name, dflt) => {
+ const v = env[name];
+ if (v === undefined || v === "") return dflt;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) throw new Error(`${name}=${v} is not a number of GB`);
+ return n;
+ };
+ return {
+ enabled: env.UMTOOL_DISK_GUARD !== "0",
+ thresholdBytes: gb("UMTOOL_DISK_GUARD_GB", DISK_GUARD_DEFAULTS.thresholdGB) * GiB,
+ floorBytes: gb("UMTOOL_DISK_FLOOR_GB", DISK_GUARD_DEFAULTS.floorGB) * GiB,
+ };
+}
+
+export class DiskGuardRefused extends Error {}
+
+/**
+ * THE DISK GUARD, before a render starts: under the threshold, the prune
+ * policy across every project (what it freed said); still under the floor,
+ * refused with a sentence (DiskGuardRefused). `dirs` are where the render
+ * writes and the projects root; the least free of them decides.
+ *
+ * @param {{ dirs: string[], env?: NodeJS.ProcessEnv, say?: (line: string) => void,
+ * free?: (dir: string) => Promise<number | null>, pruneAll?: () => Promise<{ freedBytes: number, results: any[] }> }} o
+ * @returns {Promise<{ checked: boolean, freeBefore: number | null, freeAfter: number | null, freedBytes: number }>}
+ */
+export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }) }) {
+ const s = guardSettings(env);
+ if (!s.enabled) return { checked: false, freeBefore: null, freeAfter: null, freedBytes: 0 };
+ const least = async () => {
+ let min = null;
+ let at = null;
+ for (const d of [...new Set(dirs.filter(Boolean))]) {
+ const f = await free(d);
+ if (f !== null && (min === null || f < min)) [min, at] = [f, d];
+ }
+ return { min, at };
+ };
+ const before = await least();
+ if (before.min === null || before.min >= s.thresholdBytes) return { checked: true, freeBefore: before.min, freeAfter: before.min, freedBytes: 0 };
+ say(`disk guard: ${fmtBytes(before.min)} free under ${before.at} (under ${fmtBytes(s.thresholdBytes)}): freeing takes' work files by each project's prune policy`);
+ let freedBytes = 0;
+ try {
+ const r = await pruneAll();
+ freedBytes = r.freedBytes;
+ const n = r.results.reduce((k, x) => k + (x.pruned?.length ?? 0), 0);
+ say(`disk guard: freed ${fmtBytes(freedBytes)} from ${n} take(s) in ${r.results.filter((x) => x.pruned?.length).length} project(s)`);
+ } catch (err) {
+ say(`disk guard: the prune failed — ${err instanceof Error ? err.message : err}`);
+ }
+ const after = await least();
+ if (after.min !== null && after.min < s.floorBytes) {
+ throw new DiskGuardRefused(
+ `disk guard: only ${fmtBytes(after.min)} free under ${after.at}, under the ${fmtBytes(s.floorBytes)} a render needs — nothing was rendered. ` +
+ "`umtool prune --all` says what is kept and why; free space, or set UMTOOL_DISK_FLOOR_GB (UMTOOL_DISK_GUARD=0 turns the guard off).",
+ );
+ }
+ if (after.min !== null) say(`disk guard: ${fmtBytes(after.min)} free now`);
+ return { checked: true, freeBefore: before.min, freeAfter: after.min, freedBytes };
+}
+
+/** For build-video's CLI: the guard over its --out (or its manifest's directory) and the projects root. */
+export async function guardBeforeRender({ out, manifestPath, env = process.env, say }) {
+ const where = out ? path.resolve(/* turbopackIgnore: true */ out) : path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ manifestPath));
+ // The out dir may not exist yet: its nearest existing parent's filesystem.
+ let dir = where;
+ while (!(await stat(/* turbopackIgnore: true */ dir).then(() => true, () => false))) {
+ const up = path.dirname(/* turbopackIgnore: true */ dir);
+ if (up === dir) break;
+ dir = up;
+ }
+ return diskGuard({ dirs: [dir, REPORTS_ROOT], env, say });
+}
diff --git a/umtool/lib/report/takePrune.test.mjs b/umtool/lib/report/takePrune.test.mjs
@@ -0,0 +1,482 @@
+// The takes' work-file pruner (takePrune.mjs): what is work and what is final,
+// hard links counted by inode, the retention rules, the build lock, the disk
+// guard, the symlink-escape guard, the CLI and the take maker's prune after a
+// take is made. Every project is a temp directory.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { link, lstat, mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test, { after } from "node:test";
+
+import {
+ BUILD_LOCK,
+ DiskGuardRefused,
+ KEEP_FRAMES_DIR,
+ PRUNE_RECORD,
+ XFADE_FROM_FILE,
+ deleteViewOf,
+ diskGuard,
+ measurePaths,
+ parseAge,
+ planPrune,
+ pruneAfterBuild,
+ pruneProject,
+ readBuildLock,
+ removeWorkPath,
+ resolvePolicy,
+ unionFreed,
+ workPathsOf,
+ writeBuildLock,
+} from "./takePrune.mjs";
+import { pruneCommand } from "./pruneCli.mjs";
+import { makeTake } from "./takeMaker.mjs";
+import { framesOf, frameKeyOf } from "umtool-report-to-video/prune-frames";
+
+const DAY = 24 * 3600 * 1000;
+const KiB = 1024;
+// A clock ten days on: nothing on disk is "recent" to it.
+const later = () => new Date(Date.now() + 10 * DAY);
+// No pipeline processes, and only this process's pid alive.
+const quiet = { processes: [], alive: (pid) => pid === process.pid };
+
+// Every temp project, removed at the end (/tmp may be memory).
+const made = [];
+after(() => Promise.all(made.map((d) => rm(d, { recursive: true, force: true }))));
+
+async function root() {
+ const r = await mkdtemp(path.join(tmpdir(), "takeprune-"));
+ made.push(r);
+ const reports = path.join(r, "reports");
+ const dir = path.join(reports, "proj");
+ await mkdir(path.join(dir, "takes"), { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "fx", timeline: [] }) + "\n");
+ return { r, reports, dir, project: { id: "proj", dir }, opts: { reportsRoot: reports, mediaRoot: reports, ...quiet } };
+}
+
+const bytes = (n, ch = "x") => Buffer.alloc(n, ch);
+
+/**
+ * A take with final files and work: segments, two chrome layers' frames, a
+ * crossfade batch, encode chunks, the hash memo -- each `kib` KiB a file.
+ */
+async function mkTake(dir, id, { group = "takes", builtAt = "2026-10-01T00:00:00Z", from, manifest, kib = 16, frames = 3, work = true } = {}) {
+ const t = path.join(dir, "takes", id);
+ const v = path.join(t, "out", "sourced");
+ await mkdir(v, { recursive: true });
+ await writeFile(path.join(t, "take.json"), JSON.stringify({ id, group, order: 1, label: id, kind: "different", preview: "preview.mp4", builtAt, ...(from ? { from } : {}) }) + "\n");
+ await writeFile(path.join(t, "preview.mp4"), bytes(kib * KiB, "p"));
+ await link(path.join(t, "preview.mp4"), path.join(t, "out", "fx.mp4"));
+ await writeFile(path.join(t, "out", "fx.720p.mp4"), bytes(8 * KiB, "r"));
+ await writeFile(path.join(t, "video.manifest.json"), manifest ?? JSON.stringify({ slug: "fx", take: id }) + "\n");
+ for (const f of ["schedule.json", "sync.json", "chapters.ffmeta"]) await writeFile(path.join(v, f), "{}\n");
+ await mkdir(path.join(v, "cards"), { recursive: true });
+ await writeFile(path.join(v, "cards", "c1.png"), bytes(4 * KiB));
+ await mkdir(path.join(v, "chrome", "deck"), { recursive: true });
+ await writeFile(path.join(v, "chrome", "deck", "index.html"), "<html></html>");
+ if (!work) return t;
+ await mkdir(path.join(v, "segments"), { recursive: true });
+ await writeFile(path.join(v, "segments", "s01.mp4"), bytes(kib * KiB, "1"));
+ await writeFile(path.join(v, "segments", "s01.cut.json"), "{}");
+ for (const layer of ["deck", "feed"]) {
+ const fd = path.join(v, "chrome", `${layer}-frames`);
+ await mkdir(fd, { recursive: true });
+ await writeFile(path.join(fd, ".key"), `key-${layer}-${id}\n`);
+ for (let i = 1; i <= frames; i++) await writeFile(path.join(fd, `frame_${String(i).padStart(6, "0")}.png`), bytes(kib * KiB, "f"));
+ }
+ await mkdir(path.join(v, "xfade-batches"), { recursive: true });
+ await writeFile(path.join(v, "xfade-batches", "batch-abc.mov"), bytes(kib * KiB, "b"));
+ if (from) await writeFile(path.join(v, "xfade-batches", XFADE_FROM_FILE), JSON.stringify({ take: from }) + "\n");
+ await mkdir(path.join(v, "chunks"), { recursive: true });
+ await writeFile(path.join(v, "chunks", "chunk-0a.mp4"), bytes(kib * KiB, "c"));
+ await writeFile(path.join(v, ".content-hashes.json"), "{}");
+ return t;
+}
+
+const exists = (p) => lstat(p).then(() => true, () => false);
+const byId = (plan, id) => plan.takes.find((t) => t.id === id);
+const codes = (plan, id) => byId(plan, id).keep.map((r) => r.code).sort();
+
+test("work and final: the work is the named build files under out/; the renders, preview, records and cards are not", async () => {
+ const { dir, opts } = await root();
+ const t = await mkTake(dir, "a");
+ // A shared link to the project's clips-raw is not work; a real one is.
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await symlink(path.join(dir, "out", "clips-raw"), path.join(t, "out", "clips-raw"));
+ await writeFile(path.join(t, "out", "sourced", "fx.prerail-hardcut.mp4"), bytes(KiB));
+ const { roots } = await workPathsOf(t, opts);
+ assert.deepEqual(roots.map((r) => r.rel), [
+ "out/sourced/.content-hashes.json",
+ "out/sourced/chrome/deck-frames",
+ "out/sourced/chrome/feed-frames",
+ "out/sourced/chunks",
+ "out/sourced/fx.prerail-hardcut.mp4",
+ "out/sourced/segments/*.mp4",
+ "out/sourced/xfade-batches/batch-*.mov",
+ ]);
+
+ const r = await pruneProject({ id: "proj", dir }, { ...opts, flags: { keep: 0 }, now: later });
+ assert.deepEqual(r.pruned.map((p) => p.id), ["a"]);
+ for (const f of ["take.json", "preview.mp4", "out/fx.mp4", "out/fx.720p.mp4", "video.manifest.json", "out/sourced/schedule.json", "out/sourced/sync.json", "out/sourced/chapters.ffmeta", "out/sourced/cards/c1.png", "out/sourced/chrome/deck/index.html"]) {
+ assert.ok(await exists(path.join(t, f)), `${f} is final and stays`);
+ }
+ for (const f of ["out/sourced/segments/s01.mp4", "out/sourced/chrome/deck-frames", "out/sourced/xfade-batches/batch-abc.mov", "out/sourced/chunks", "out/sourced/.content-hashes.json"]) {
+ assert.equal(await exists(path.join(t, f)), false, `${f} is work and goes`);
+ }
+ // A segment's records stay (a trailer maps its beats through them).
+ assert.ok(await exists(path.join(t, "out", "sourced", "segments", "s01.cut.json")));
+ assert.ok((await lstat(path.join(t, "out", "clips-raw"))).isSymbolicLink(), "the shared clips-raw link stays");
+ // A pruned chrome layer stays verifiable: its count and key were recorded.
+ const deck = path.join(t, "out", "sourced", "chrome", "deck-frames");
+ assert.equal(await framesOf(deck), 3);
+ assert.equal(await frameKeyOf(deck), "key-deck-a");
+ const rec = JSON.parse(await readFile(path.join(t, PRUNE_RECORD), "utf8"));
+ assert.equal(rec.prunes.length, 1);
+ assert.equal(rec.prunes[0].by, "cli");
+ assert.ok(rec.prunes[0].freedBytes > 0);
+ // Pruned once, a take has no work: the plan says so, and when.
+ const again = await planPrune({ id: "proj", dir }, { ...opts, flags: { keep: 0 }, now: later });
+ assert.equal(byId(again, "a").status, "no-work");
+ assert.ok(byId(again, "a").pruned);
+});
+
+test("hard links: a take built --from another shares its inodes; pruning one frees only what is its own, and the other keeps its bytes", async () => {
+ const { dir, project, opts } = await root();
+ const a = await mkTake(dir, "a", { builtAt: "2026-10-01T00:00:00Z" });
+ const b = await mkTake(dir, "b", { builtAt: "2026-10-02T00:00:00Z" });
+ // b's segment and deck frames ARE a's (takeFrom.mjs links them in).
+ const va = path.join(a, "out", "sourced");
+ const vb = path.join(b, "out", "sourced");
+ for (const f of ["s01.mp4", "s01.cut.json"]) {
+ await rm(path.join(vb, "segments", f));
+ await link(path.join(va, "segments", f), path.join(vb, "segments", f));
+ }
+ await rm(path.join(vb, "chrome", "deck-frames"), { recursive: true });
+ await mkdir(path.join(vb, "chrome", "deck-frames"));
+ for (const f of await readdir(path.join(va, "chrome", "deck-frames"))) await link(path.join(va, "chrome", "deck-frames", f), path.join(vb, "chrome", "deck-frames", f));
+
+ // Measured alone, each take's work counts the shared inodes; its "frees" does not.
+ const ma = await measurePaths((await workPathsOf(a, opts)).roots);
+ const mb = await measurePaths((await workPathsOf(b, opts)).roots);
+ const sharedKeys = [...ma.multi.keys()].filter((k) => mb.multi.has(k));
+ assert.ok(sharedKeys.length >= 5, "the segment, its record, three frames and the key are shared");
+ const plan = await planPrune(project, { ...opts, policy: resolvePolicy({ env: {}, flags: { keep: 0, olderThan: "0" } }), now: later });
+ const pa = byId(plan, "a");
+ assert.ok(pa.workBytes > pa.freedBytes, "a's work includes what b also holds");
+ const shared = [...ma.multi.values()].reduce((s, v) => s + v.bytes, 0);
+ assert.equal(pa.workBytes - pa.freedBytes, shared);
+ // Both prunable: the union frees the shared inodes too -- more than the two alone.
+ assert.equal(plan.totals.prunable.freedBytes, unionFreed([ma, mb]));
+ assert.equal(plan.totals.prunable.freedBytes, pa.freedBytes + byId(plan, "b").freedBytes + shared);
+ assert.equal(plan.totals.prunable.workBytes, plan.totals.prunable.freedBytes, "nothing outside the two holds a link");
+
+ // Prune a alone (b pinned): b's files are whole, and the freed count is a's own.
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ keep: 0, olderThanDays: 0, pin: ["b"] }));
+ const seg = await readFile(path.join(vb, "segments", "s01.mp4"));
+ const r = await pruneProject(project, { ...opts, now: later });
+ assert.deepEqual(r.pruned.map((p) => p.id), ["a"]);
+ assert.equal(r.freedBytes, pa.freedBytes);
+ assert.equal(await exists(path.join(va, "segments", "s01.mp4")), false);
+ assert.deepEqual(await readFile(path.join(vb, "segments", "s01.mp4")), seg);
+ assert.equal((await stat(path.join(vb, "segments", "s01.mp4"))).nlink, 1, "b holds the last link now");
+ assert.equal((await readdir(path.join(vb, "chrome", "deck-frames"))).length, 4);
+ // b, measured again, now frees all of its work.
+ const after = await planPrune(project, { ...opts, now: later });
+ const pb = byId(after, "b");
+ assert.equal(pb.status, "kept");
+ assert.equal(pb.workBytes, pb.freedBytes);
+});
+
+test("the policy: picked, current, pinned, newest K per group, modified within D days, and the --from bases of kept takes", async () => {
+ const { dir, project, opts } = await root();
+ const manifest = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+ await mkTake(dir, "old-1", { builtAt: "2026-09-01T00:00:00Z" });
+ await mkTake(dir, "old-2", { builtAt: "2026-09-02T00:00:00Z" });
+ await mkTake(dir, "picked", { builtAt: "2026-09-03T00:00:00Z" });
+ await mkTake(dir, "current", { builtAt: "2026-09-04T00:00:00Z", manifest });
+ await mkTake(dir, "base-of-base", { builtAt: "2026-09-05T00:00:00Z" });
+ await mkTake(dir, "base", { builtAt: "2026-09-06T00:00:00Z", from: "base-of-base" });
+ await mkTake(dir, "n2", { builtAt: "2026-09-07T00:00:00Z" });
+ await mkTake(dir, "n1", { builtAt: "2026-09-08T00:00:00Z", from: "base" });
+ await mkTake(dir, "other", { group: "intro", builtAt: "2026-09-01T00:00:00Z" });
+ await mkTake(dir, "pinned", { group: "intro", builtAt: "2026-08-01T00:00:00Z" });
+ await mkTake(dir, "nothing", { work: false, builtAt: "2026-08-01T00:00:00Z" });
+ await writeFile(path.join(dir, "takes", "verdicts.json"), JSON.stringify({ picked: { verdict: null, note: "", at: "", picked: true } }));
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: ["pinned"] }));
+
+ const plan = await planPrune(project, { ...opts, now: later });
+ assert.deepEqual(plan.policy.pin, ["pinned"]);
+ assert.equal(plan.policy.keep, 2);
+ assert.deepEqual(codes(plan, "n1"), ["newest"]);
+ assert.deepEqual(codes(plan, "n2"), ["newest"]);
+ assert.deepEqual(codes(plan, "base"), ["base"], "n1 is built from it");
+ assert.deepEqual(codes(plan, "base-of-base"), ["base"], "transitively");
+ assert.deepEqual(codes(plan, "picked"), ["picked"]);
+ assert.deepEqual(codes(plan, "current"), ["current"]);
+ assert.deepEqual(codes(plan, "other"), ["newest"], "the newest of its own group");
+ assert.deepEqual(codes(plan, "pinned"), ["newest", "pinned"]);
+ assert.equal(byId(plan, "old-1").status, "prunable");
+ assert.equal(byId(plan, "old-2").status, "prunable");
+ assert.equal(byId(plan, "nothing").status, "no-work");
+ assert.equal(byId(plan, "pinned").keep.find((r) => r.code === "newest").why, 'the 2nd newest of group "intro" (keeps 2)');
+
+ // Today's clock: everything was modified just now.
+ const today = await planPrune(project, opts);
+ assert.ok(codes(today, "old-1").includes("recent"));
+ assert.equal(today.totals.prunable.takes, 0);
+ // --keep and --older-than on the command line beat the file and the defaults.
+ const keep0 = await planPrune(project, { ...opts, flags: { keep: 0, olderThan: "12h" }, now: later });
+ assert.equal(byId(keep0, "n1").status, "prunable");
+ assert.equal(byId(keep0, "base").status, "prunable", "its child is not kept now, so neither is it");
+ assert.equal(byId(keep0, "pinned").status, "kept");
+ assert.equal(keep0.policy.from.keep, "--keep");
+ // A named take with --anyway: the policy's reasons are overridden.
+ const named = await planPrune(project, { ...opts, takes: ["picked"], anyway: true, now: later });
+ assert.deepEqual(named.takes.map((t) => t.id), ["picked"]);
+ assert.equal(byId(named, "picked").status, "prunable");
+ assert.deepEqual(byId(named, "picked").overridden.map((r) => r.code), ["picked"]);
+ // The route's view: without force, a forceable refusal; with it, the take goes.
+ const view = deleteViewOf(await planPrune(project, { ...opts, takes: ["picked"], now: later }), { take: "picked" });
+ assert.deepEqual(view.refusals.map((r) => r.forceable), [true]);
+ assert.equal(deleteViewOf(named, { take: "picked" }).refusals.length, 0);
+ await assert.rejects(planPrune(project, { ...opts, takes: ["nope"] }), /has no take nope/);
+});
+
+test("the settings: parseAge, the environment, and a prune.json that does not parse refuses", async () => {
+ assert.equal(parseAge("3d"), 3);
+ assert.equal(parseAge("12h"), 0.5);
+ assert.equal(parseAge("2"), 2);
+ assert.throws(() => parseAge("soon"), /not an age/);
+ const p = resolvePolicy({ env: { UMTOOL_PRUNE_KEEP: "4", UMTOOL_PRUNE_DAYS: "1d", UMTOOL_PRUNE_AFTER_BUILD: "0" }, file: { keep: 3 } });
+ assert.equal(p.keep, 3);
+ assert.equal(p.olderThanDays, 1);
+ assert.equal(p.afterBuild, false);
+ assert.deepEqual(p.from, { keep: "prune.json", olderThanDays: "UMTOOL_PRUNE_DAYS", afterBuild: "UMTOOL_PRUNE_AFTER_BUILD" });
+ assert.throws(() => resolvePolicy({ env: { UMTOOL_PRUNE_KEEP: "-1" } }), /whole number/);
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "a");
+ await writeFile(path.join(dir, "takes", "prune.json"), "{ nope");
+ await assert.rejects(planPrune(project, opts), /does not parse/);
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: "a" }));
+ await assert.rejects(planPrune(project, opts), /pin is a list/);
+});
+
+test("a running build: its take and the take it builds from are never pruned, not even by name; a dead lock is ignored", async () => {
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "base", { builtAt: "2026-09-01T00:00:00Z" });
+ const twin = await mkTake(dir, "twin", { builtAt: "2026-09-02T00:00:00Z" });
+ const other = await mkTake(dir, "other", { builtAt: "2026-09-03T00:00:00Z" });
+ await mkTake(dir, "loose", { builtAt: "2026-09-04T00:00:00Z" });
+ const flags = { keep: 0, olderThan: "0" };
+ await writeBuildLock(twin, { take: "twin", from: "base" });
+ // A lock of a process that is gone.
+ await writeFile(path.join(other, BUILD_LOCK), JSON.stringify({ pid: 999999999, host: (await import("node:os")).hostname(), startedAt: "x" }));
+ // build-video writing into loose's out/ by hand.
+ const processes = [{ pid: 4242, args: ["node", "/x/build-video.mjs", "m.json", "--out", path.join(dir, "takes", "loose", "out")], cwd: "/" }];
+
+ const plan = await planPrune(project, { ...opts, processes, flags, now: later });
+ assert.deepEqual(codes(plan, "twin"), ["building"]);
+ assert.deepEqual(codes(plan, "base"), ["base-of-building"]);
+ assert.deepEqual(codes(plan, "loose"), ["building"]);
+ assert.match(byId(plan, "loose").keep[0].why, /pid 4242/);
+ assert.equal(byId(plan, "other").status, "prunable");
+ assert.ok(plan.notes.some((n) => /pid 999999999\) is gone/.test(n)));
+ const anyway = await planPrune(project, { ...opts, processes, flags, takes: ["twin", "base"], anyway: true, now: later });
+ assert.equal(byId(anyway, "twin").status, "kept");
+ assert.equal(byId(anyway, "base").status, "kept");
+ const view = deleteViewOf(anyway, { take: "twin" });
+ assert.deepEqual(view.refusals.map((r) => r.forceable), [false]);
+
+ const r = await pruneProject(project, { ...opts, processes, flags, now: later });
+ assert.deepEqual(r.pruned.map((p) => p.id), ["other"]);
+ assert.ok(await exists(path.join(twin, "out", "sourced", "segments", "s01.mp4")));
+ assert.ok(await exists(path.join(dir, "takes", "base", "out", "sourced", "segments", "s01.mp4")));
+ assert.ok(await exists(path.join(dir, "takes", "loose", "out", "sourced", "segments", "s01.mp4")));
+ // The lock is this process's: removed, and the twin is prunable again.
+ const { removeBuildLock } = await import("./takePrune.mjs");
+ await removeBuildLock(path.join(twin, BUILD_LOCK));
+ assert.equal(await readBuildLock(path.join(twin, BUILD_LOCK)), null);
+});
+
+test("the symlink guard: a link is never work and never followed; a path resolving outside the take is not removed", async () => {
+ const { r, dir, project, opts } = await root();
+ const outside = path.join(r, "corpus");
+ await mkdir(outside, { recursive: true });
+ await writeFile(path.join(outside, "window.mp4"), bytes(2 * KiB, "w"));
+ await writeFile(path.join(outside, "frame.png"), bytes(KiB, "o"));
+ const t = await mkTake(dir, "a");
+ const v = path.join(t, "out", "sourced");
+ // segments/ is a link to the corpus: not work.
+ await rm(path.join(v, "segments"), { recursive: true });
+ await symlink(outside, path.join(v, "segments"));
+ // A real clips-raw holding a link into the corpus: the link goes, the corpus file stays.
+ await mkdir(path.join(t, "out", "clips-raw"));
+ await symlink(path.join(outside, "window.mp4"), path.join(t, "out", "clips-raw", "window.mp4"));
+ // A frame that is a link out of the take.
+ await symlink(path.join(outside, "frame.png"), path.join(v, "chrome", "deck-frames", "frame_000099.png"));
+ const { roots } = await workPathsOf(t, opts);
+ assert.equal(roots.some((x) => x.rel.endsWith("segments")), false);
+ assert.ok(roots.some((x) => x.rel === "out/clips-raw"));
+
+ const pr = await pruneProject(project, { ...opts, flags: { keep: 0 }, now: later });
+ assert.deepEqual(pr.pruned.map((p) => p.id), ["a"]);
+ assert.ok(await exists(path.join(outside, "window.mp4")), "the corpus file is whole");
+ assert.ok(await exists(path.join(outside, "frame.png")));
+ assert.ok((await lstat(path.join(v, "segments"))).isSymbolicLink(), "the link itself was not touched");
+ assert.ok(await exists(path.join(outside, "window.mp4")));
+ assert.equal(await exists(path.join(t, "out", "clips-raw")), false);
+ assert.equal(await exists(path.join(v, "chrome", "deck-frames")), false);
+
+ // removeWorkPath refuses a link and a path outside the allowed roots.
+ await symlink(outside, path.join(v, "work-link"));
+ assert.match(await removeWorkPath(path.join(v, "work-link"), [t]), /a link/);
+ assert.match(await removeWorkPath(path.join(outside, "window.mp4"), [t]), /outside the take/);
+ assert.ok(await exists(path.join(outside, "window.mp4")));
+
+ // A take whose out/ is a link anywhere but the media root's mirror: nothing in it is work.
+ const b = path.join(dir, "takes", "b");
+ await mkdir(b, { recursive: true });
+ await writeFile(path.join(b, "take.json"), JSON.stringify({ id: "b", group: "g", order: 1, label: "b", kind: "different", preview: "preview.mp4" }));
+ const elsewhere = path.join(r, "elsewhere");
+ await mkdir(path.join(elsewhere, "sourced", "segments"), { recursive: true });
+ await writeFile(path.join(elsewhere, "sourced", "segments", "s.mp4"), "s");
+ await symlink(elsewhere, path.join(b, "out"));
+ const wb = await workPathsOf(b, opts);
+ assert.equal(wb.roots.length, 0);
+ assert.match(wb.notes[0], /not this take's media-root mirror/);
+ // ... while out/ linked to its media-root mirror is followed.
+ const media = path.join(r, "media");
+ const c = path.join(dir, "takes", "c");
+ await mkdir(c, { recursive: true });
+ const mirror = path.join(media, "proj", "takes", "c", "out");
+ await mkdir(path.join(mirror, "sourced", "segments"), { recursive: true });
+ await writeFile(path.join(mirror, "sourced", "segments", "s.mp4"), "s");
+ await symlink(mirror, path.join(c, "out"));
+ const wc = await workPathsOf(c, { ...opts, mediaRoot: media });
+ assert.deepEqual(wc.roots.map((x) => x.rel), ["out/sourced/segments/*.mp4"]);
+});
+
+test("the disk guard: above the threshold nothing happens; under it the policy runs; still under the floor the render is refused", async () => {
+ const GB = 1024 ** 3;
+ let calls = 0;
+ const said = [];
+ const pruneAll = async () => {
+ calls += 1;
+ return { freedBytes: 5 * GB, results: [{ pruned: [{ id: "a" }, { id: "b" }] }] };
+ };
+ // Plenty of room.
+ let free = 100 * GB;
+ let r = await diskGuard({ dirs: ["/x"], env: {}, free: async () => free, pruneAll, say: (l) => said.push(l) });
+ assert.equal(calls, 0);
+ assert.equal(r.freedBytes, 0);
+ // Under 30 GB: pruned, said, and the render goes on above the floor.
+ const seq = [20 * GB, 25 * GB];
+ r = await diskGuard({ dirs: ["/x", "/y"], env: {}, free: async () => seq[Math.min(calls, 1)], pruneAll, say: (l) => said.push(l) });
+ assert.equal(calls, 1);
+ assert.equal(r.freedBytes, 5 * GB);
+ assert.ok(said.some((l) => /freed 5\.0 GiB from 2 take\(s\) in 1 project/.test(l)), said.join("\n"));
+ // Under the floor after the prune: refused, with a sentence.
+ free = 6 * GB;
+ await assert.rejects(
+ diskGuard({ dirs: ["/x"], env: {}, free: async () => free, pruneAll, say: () => {} }),
+ (err) => err instanceof DiskGuardRefused && /only 6\.0 GiB free under \/x, under the 10\.0 GiB a render needs — nothing was rendered/.test(err.message),
+ );
+ // The settings: thresholds from the environment, and off.
+ calls = 0;
+ r = await diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD_GB: "5", UMTOOL_DISK_FLOOR_GB: "1" }, free: async () => 6 * GB, pruneAll });
+ assert.equal(calls, 0);
+ r = await diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD: "0" }, free: async () => 1, pruneAll });
+ assert.equal(r.checked, false);
+ assert.equal(calls, 0);
+ await assert.rejects(diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD_GB: "lots" }, free: async () => 1, pruneAll }), /not a number/);
+});
+
+test("after a take is made: its project pruned by the policy, the new take kept, said in its log; the lock held during the render", async () => {
+ const { dir, reports } = await root();
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "fx", title: "Fx", render: { width: 64, height: 36, fps: 15 }, timeline: [{ type: "card", id: "k1", seconds: 2 }] }, null, 2) + "\n");
+ const old = await mkTake(dir, "old", { builtAt: "2026-09-01T00:00:00Z" });
+ const longAgo = new Date(Date.now() - 30 * DAY);
+ for (const f of ["take.json", "preview.mp4"]) await utimes(path.join(old, f), longAgo, longAgo);
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ keep: 0 }));
+ const logs = [];
+ let lockDuring = null;
+ const render = async (job) => {
+ lockDuring = await readBuildLock(path.join(dir, "takes", "new", BUILD_LOCK));
+ await mkdir(path.join(job.outDir, "sourced"), { recursive: true });
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, "render");
+ return { file };
+ };
+ const r = await makeTake(dir, { id: "new", label: "New", window: "full" }, { render, probe: async () => 2, log: (l) => logs.push(l), from: null });
+ assert.equal(r.skipped, false);
+ assert.equal(lockDuring?.pid, process.pid);
+ assert.equal(lockDuring?.take, "new");
+ assert.equal(await readBuildLock(path.join(dir, "takes", "new", BUILD_LOCK)), null, "released after");
+ assert.equal(await exists(path.join(old, "out", "sourced", "segments", "s01.mp4")), false, "the old take's work went");
+ assert.ok(await exists(path.join(old, "preview.mp4")));
+ assert.ok(logs.some((l) => /^new: prune: freed .* from 1 take\(s\): old/.test(l)), logs.join("\n"));
+ // Off in takes/prune.json: nothing pruned, nothing said.
+ const old2 = await mkTake(dir, "old2", { builtAt: "2026-09-01T00:00:00Z" });
+ for (const f of ["take.json", "preview.mp4"]) await utimes(path.join(old2, f), longAgo, longAgo);
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ keep: 0, afterBuild: false }));
+ logs.length = 0;
+ await makeTake(dir, { id: "new2", label: "New 2", window: "full" }, { render, probe: async () => 2, log: (l) => logs.push(l) });
+ assert.ok(await exists(path.join(old2, "out", "sourced", "segments", "s01.mp4")));
+ assert.equal(logs.some((l) => /prune:/.test(l)), false);
+ // pruneAfterBuild never throws: a bad policy file is said.
+ await writeFile(path.join(dir, "takes", "prune.json"), "{");
+ const line = await pruneAfterBuild(dir, { built: "new", reportsRoot: reports });
+ assert.match(line, /^prune: not run — .*does not parse/);
+ // A take made --from records it (what the pruner reads as its base).
+ await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ afterBuild: false }));
+ await makeTake(dir, { id: "twin", label: "Twin", window: "full" }, { render, probe: async () => 2, from: "new" });
+ assert.equal(JSON.parse(await readFile(path.join(dir, "takes", "twin", "take.json"), "utf8")).from, "new");
+});
+
+test("the CLI: a dry run by default, --yes frees, --json, and its refusals", async () => {
+ const { dir, reports } = await root();
+ await mkTake(dir, "a", { builtAt: "2026-09-01T00:00:00Z" });
+ await mkTake(dir, "b", { builtAt: "2026-09-02T00:00:00Z" });
+ const run = async (...args) => {
+ const out = [];
+ const err = [];
+ const code = await pruneCommand(args, { reportsRoot: reports, log: (l) => out.push(l), err: (l) => err.push(l), deps: { ...quiet, now: later } });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+ };
+ let r = await run("proj", "--keep", "1");
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /a\s+prunable\s+work .* frees/);
+ assert.match(r.out, /b\s+kept .* the newest of group "takes" \(keeps 1\)/);
+ assert.match(r.out, /dry run — nothing deleted\. --yes frees/);
+ assert.ok(await exists(path.join(dir, "takes", "a", "out", "sourced", "segments", "s01.mp4")), "a dry run deletes nothing");
+ r = await run("proj", "--keep", "1", "--json");
+ const j = JSON.parse(r.out);
+ assert.equal(j.dryRun, true);
+ assert.equal(j.projects[0].takes.find((t) => t.id === "a").status, "prunable");
+ assert.equal(j.projects[0].measured, undefined);
+ r = await run("--all", "--keep", "1", "--yes");
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /freed a: /);
+ assert.equal(await exists(path.join(dir, "takes", "a", "out", "sourced", "segments", "s01.mp4")), false);
+ assert.ok(await exists(path.join(dir, "takes", "b", "out", "sourced", "segments", "s01.mp4")));
+ r = await run("proj", "--take", "b", "--anyway", "--yes");
+ assert.equal(r.code, 0, r.err);
+ assert.equal(await exists(path.join(dir, "takes", "b", "out", "sourced", "segments", "s01.mp4")), false);
+ assert.equal((await run()).code, 2);
+ assert.match((await run("--all", "--take", "a")).err, /names a take of one project/);
+ assert.match((await run("proj", "--anyway")).err, /name it with --take/);
+ assert.match((await run("proj", "--yes", "--dry-run")).err, /not both/);
+ assert.match((await run("nope")).err, /no project matches/);
+});
+
+test("the names it prunes by are its writers' names", async () => {
+ const bv = await import("umtool-report-to-video/build-video");
+ const ce = await import("umtool-report-to-video/chunked-encode");
+ const tf = await import("./takeFrom.mjs");
+ assert.equal(XFADE_FROM_FILE, bv.XFADE_FROM_FILE);
+ assert.equal(KEEP_FRAMES_DIR, tf.KEEP_FRAMES_DIR);
+ assert.equal(bv.DEFAULT_VARIANT, "sourced");
+ assert.equal(ce.CHUNKS_DIR, "chunks");
+ assert.equal(ce.HASH_MEMO_FILE, ".content-hashes.json");
+});
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -49,6 +49,12 @@ process.env.E2E_AVAILABILITY_GAP_MS ??= "50";
// The same for a build's network clip fetches (report-to-video/build-video.mjs,
// pacedClipFetch): 0 against the stub, not the real 30 s per clip.
process.env.E2E_CLIP_FETCH_GAP_MS ??= "0";
+// No disk guard before a fixture's render (lib/report/takePrune.mjs): on a
+// near-full disk it would prune the fixture's takes, or refuse the render, and
+// a spec would fail for the machine, not the code. Nor the prune after a take
+// is made: a spec that reads a take's out/ reads what its own steps left.
+process.env.UMTOOL_DISK_GUARD ??= "0";
+process.env.UMTOOL_PRUNE_AFTER_BUILD ??= "0";
// START MODE BY DEFAULT, as the editor suite (plans/e2e-speed.md, S1): `next
// dev` compiles each route on first use and again after a change, and the
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -6702,6 +6702,22 @@ async function renderSlot() {
return withRenderSlot;
}
+// A render's two guards (umtool/lib/report/takePrune.mjs), loaded the same way
+// as the gate: a build lock in its --out while it runs, so `umtool prune` (and
+// a take build's own prune) leaves the work it is making alone; and, in the
+// slot, right before the render starts, the disk guard -- under
+// UMTOOL_DISK_GUARD_GB (30) free it prunes takes' work by each project's
+// policy and says what that freed; still under UMTOOL_DISK_FLOOR_GB (10) the
+// render is refused with a sentence. UMTOOL_DISK_GUARD=0 turns it off.
+async function guardedRender(out, manifestPath, build) {
+ const href = new URL("../lib/report/takePrune.mjs", pathToFileURL(process.argv[1])).href;
+ const prune = await import(/* webpackIgnore: true */ href);
+ return prune.withBuildLock(out ? path.resolve(out) : null, { by: "build-video" }, async () => {
+ await prune.guardBeforeRender({ out, manifestPath, say: (message) => EMIT("note", { message }) });
+ return build();
+ });
+}
+
async function main() {
const argv = process.argv.slice(2);
const manifestPath = argv.find((a) => !a.startsWith("--"));
@@ -6796,7 +6812,7 @@ async function main() {
const fetchOnly = flag("--fetch-only");
const build = () => buildVideo({ manifestPath, opts, out: flag("--out"), only, fetchOnly });
const { failures } = takesHeavySlot({ opts, only, fetchOnly })
- ? await (await renderSlot())(["build-video", ...argv], build)
+ ? await (await renderSlot())(["build-video", ...argv], () => guardedRender(flag("--out"), manifestPath, build))
: await build();
// Non-zero on a partial run, so a caller that ignores the events still learns
// the build did not produce what was asked for.
diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs
@@ -84,6 +84,37 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date() } =
return { sequences, work, bytes };
}
+/**
+ * Record `names` (sequences in `chromeDir` about to be removed by somebody
+ * else -- `umtool prune`, lib/report/takePrune.mjs) in `chrome/pruned.json`,
+ * MERGED over what an earlier prune recorded: each sequence's frame count and
+ * key as of now. A name with no directory is left as it was recorded.
+ *
+ * @param {string} chromeDir
+ * @param {string[]} names `<layer>-frames` directory names
+ * @returns {Promise<string[]>} the names recorded
+ */
+export async function recordPrunedSequences(chromeDir, names, { now = () => new Date() } = {}) {
+ const prev = await readRecord(chromeDir);
+ const dirs = { ...(prev?.dirs && typeof prev.dirs === "object" ? prev.dirs : {}) };
+ const recorded = [];
+ for (const name of [...names].sort()) {
+ if (!name.endsWith("-frames")) continue;
+ const dir = path.join(chromeDir, name);
+ const files = await readdir(dir).catch(() => null);
+ if (!files) continue;
+ const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null);
+ dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key };
+ recorded.push(name);
+ }
+ if (!recorded.length) return recorded;
+ const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs };
+ const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`);
+ await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
+ await rename(tmp, path.join(chromeDir, PRUNED_RECORD));
+ return recorded;
+}
+
// The record's entry for a pruned sequence -- unless the cut was written AFTER
// the prune (`since`: the final file's mtime in ms), which means a later build
// that rendered no chrome (`--no-chrome`) made it, and the record is not about