commit 15bcd92e777f2c65e81d78f3f9f15ff91ede30c1
parent ee38bba035376071aa6c6c23c00bbdd66871d09e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 14:04:12 -0500
umtool: the version and idle-work passes fail closed, honour every verdict, wait out a grace, and read the operator's word again before each delete
Review of lane/housekeeping (it runs unattended weekly and deletes data):
- readVerdictsStrict (takes.mjs): a verdicts.json that cannot be read or is
not an object is an error, not the lenient reader's {} that loses every
pick. The version pass skips such a project whole; planPrune gives every
take "verdicts-unreadable", which --idle-work never overrides.
- Any operator verdict keeps a take in the version pass: like, maybe, no,
or a verdict note alone (a supersede mark is not one).
- projectActivity walks the project: every top-level file (notes.json,
cuts.json, the manifest, play state, logs) and the subdirectories' files
but the render scratch and fetched media (out, clips, share-*,
posts-media, …), plus each take's own top-level files (its manifest,
take.json = its patch) but pruned-work.json; over 50 000 entries counts
as active.
- The newest of a line is its highest version number (digits as numbers:
draft-10 over draft-9; a draft-3 rebuilt after draft-4 does not supersede
it); builtAt only breaks a tie. Older takes stay until the newest is
--grace old (default 7d; `umtool prune --versions --grace`).
- pruneVersions reads picks, verdicts and notes again for each take right
before deleteTake; a take claimed since the plan goes to `raced`, an
outcome, not a failure. pruneProject's "a build started since the plan"
entry is marked raced, and `umtool prune` exits 0 for both.
Tests: unreadable verdicts (both passes), each verdict kind, activity from a
notes-only edit, a source file, a draft and a take's manifest but not from
scratch or the pruner's record, the numeric order, the grace and its flag,
the raced re-check, and the work pass's race through the CLI (exit 0).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 409 insertions(+), 69 deletions(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -106,7 +106,7 @@
// 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] [--idle-work 3d] [--yes] [--json]
-// umtool prune [<project> | --all] --versions [--idle 3d] [--idle-work 3d] [--yes] [--json]
+// umtool prune [<project> | --all] --versions [--idle 3d] [--grace 7d] [--idle-work 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]
@@ -1041,10 +1041,11 @@ function usage() {
" 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. --idle-work D: in a project untouched for D, the newest/picked takes' work goes too",
- " umtool prune [<project> | --all] --versions [--idle 3d] [--idle-work 3d] [--yes] [--json]",
+ " umtool prune [<project> | --all] --versions [--idle 3d] [--grace 7d] [--idle-work 3d] [--yes] [--json]",
" whole SUPERSEDED takes, through `takes delete`: per version line (the id, digits folded:",
- " draft-# ; letters never: v6c ≠ v6d) the newest built is kept, and any take picked, pinned,",
- " rendering, a base, noted on or refused; a project touched within --idle is skipped",
+ " draft-# ; letters never: v6c ≠ v6d) the highest built number is kept, older ones while it is",
+ " younger than --grace, and any take picked, judged, rendering, a base, noted on or refused;",
+ " a project touched within --idle, or whose verdicts.json cannot be read, is skipped",
" 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]",
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -2499,27 +2499,39 @@ the prune rather than guess.
`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).
- **Weekly, by `archilyzer housekeeping`** (OPERATING.md, "Free disk"): `umtool prune --all
- --versions --idle 3d --idle-work 3d --yes`, below.
-
-**An idle project** (`--idle-work <age>`). A project nothing has touched for that long — every
-take's `builtAt`, take.json and preview, the project's `video.manifest.json` and
-`takes/verdicts.json`, and a live build lock counts as now (`projectActivity`) — is not being
-worked on, so the newest, picked and current takes' work goes too. A running build and the take
-it builds from keep theirs, and so does a pin in `takes/prune.json`. The renders and previews stay
-as always: a later `--from` or rebuild renders the work again.
+ --versions --idle 3d --grace 7d --idle-work 3d --yes`, below.
+
+**An idle project** (`--idle-work <age>`). A project nothing has touched for that long is not
+being worked on, so the newest, picked and current takes' work goes too. "Touched"
+(`projectActivity`) is the newest of: every take's `builtAt` and its own top-level files (take.json —
+a take's patch, `umtool set --take` —, its `video.manifest.json`, its preview; not
+`pruned-work.json`, the pruner's own record); a live build lock, as now; and every file of the
+project outside its render scratch and fetched media (`out/`, `clips/`, `share-*`, `posts-media/`
+and the like are not walked): `video.manifest.json`, `notes.json`, `cuts.json`, drafts,
+revisions, `takes/verdicts.json`. A running build and the take it builds from keep their work, and
+so does a pin in `takes/prune.json`; a `takes/verdicts.json` that cannot be read keeps every take's
+(which take is picked is unknown). The renders and previews stay as always: a later `--from` or
+rebuild renders the work again.
**Superseded takes** (`umtool prune --versions`, `lib/report/takeVersions.mjs`) delete WHOLE takes,
each through `deleteTake` — the path `umtool takes delete` takes, never `--force`. A take's
**version line** is its id with every digit run folded to `#` (`draft-3` → `draft-#`,
`final-1027-v6-blurred` → `final-#-v#-blurred`). A letter is never folded: `v6c` and `v6d` are
alternatives the operator chose between, `release-6u` is `release-6`'s uncensored twin — each a line
-of its own. Per line the newest BUILT take is kept, and so is any take that is picked or pinned
-(verdicts.json), rendering or a running render's base, being built or a build's base, the project's
-manifest's take, pinned in `takes/prune.json`, noted on by the operator (any note in the project's
-`notes.json` whose anchor names the take or a file under `takes/<id>/`), the `--from` base of a kept
-take, or not built at all. A take `umtool takes delete` refuses (a project reached through a link,
-say) is kept with the refusal's words. A project with anything modified within `--idle` (default
-3d) is skipped whole. Its verdict rows and notes stay, as with any deleted take.
+of its own. Per line the newest BUILT take is kept — the highest version number, its digits read
+as numbers left to right (`draft-10` over `draft-9`; a `draft-3` rebuilt after `draft-4` does not
+supersede it), `builtAt` only breaking a tie — and every older take stays until that newest one was
+built `--grace` ago (default 7d). Kept too: any take that is picked or pinned or carries ANY verdict
+of the operator's (like, maybe, no, or a verdict note), rendering or a running render's base, being
+built or a build's base, the project's manifest's take, pinned in `takes/prune.json`, noted on by
+the operator (any note in the project's `notes.json` whose anchor names the take or a file under
+`takes/<id>/`), the `--from` base of a kept take, or not built at all. A take `umtool takes delete`
+refuses (a project reached through a link, say) is kept with the refusal's words. A project touched
+within `--idle` (default 3d; as for `--idle-work` above) is skipped whole, and so is one whose
+`takes/verdicts.json` cannot be read. Right before each delete the build state, the verdicts and the
+notes are read again: a take claimed since the plan is kept and said (`raced`), which is not a
+failure, and a build that starts in a take after the work plan is the same. Its verdict rows and
+notes stay, as with any deleted take.
**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
diff --git a/umtool/lib/report/pruneCli.mjs b/umtool/lib/report/pruneCli.mjs
@@ -34,7 +34,7 @@ import {
export const PRUNE_USAGE = [
"usage: umtool prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--idle-work 3d] [--yes] [--json]",
" umtool prune --all [--keep N] [--older-than 3d] [--idle-work 3d] [--yes] [--json]",
- " umtool prune <project> | --all --versions [--idle 3d] [--idle-work 3d] [--yes] [--json]",
+ " umtool prune <project> | --all --versions [--idle 3d] [--grace 7d] [--idle-work 3d] [--yes] [--json]",
"",
"Each take's WORK files -- clip segments, chrome frames, crossfade batches, encode chunks, raw clip",
"copies, work-from-*, the rail's <slug>.prerail*.mp4 base -- measured by inode (a file hard-linked",
@@ -52,17 +52,21 @@ export const PRUNE_USAGE = [
"--versions: whole SUPERSEDED takes deleted, as `umtool takes delete` deletes one. A take's version",
"line is its id with every digit run folded (draft-3 -> draft-#, final-1027-v6-blurred ->",
"final-#-v#-blurred); a letter is never folded (v6c and v6d, release-6u and release-6 are lines of",
- "their own). Kept: the newest BUILT take of each line, and any take picked or pinned, rendering, a",
- "render's or build's base, being built, the project's manifest's, pinned in takes/prune.json, with",
- "operator notes on it, the --from base of a kept take, or refused by `umtool takes delete`. A",
- "project with anything modified within --idle (default 3d) is skipped whole. With --idle-work too,",
- "the work pass runs after; without it, --versions is the only pass.",
+ "their own). Kept: the newest BUILT take of each line -- the highest version number (draft-10 over",
+ "draft-9; a rebuilt draft-3 does not supersede draft-4), builtAt breaking a tie -- and every older",
+ "take while that newest is younger than --grace (default 7d); any take picked, pinned or with any",
+ "verdict of the operator's, rendering, a render's or build's base, being built, the project's",
+ "manifest's, pinned in takes/prune.json, with operator notes on it, the --from base of a kept take,",
+ "or refused by `umtool takes delete`. A project with anything modified within --idle (default 3d:",
+ "its files, notes, takes, picks) is skipped whole, and so is one whose verdicts.json cannot be read.",
+ "Picks, verdicts and notes are read again before each delete. With --idle-work too, the work pass",
+ "runs after; without it, --versions is the only pass.",
].join("\n");
class CliError extends Error {}
function parse(args) {
- const valued = new Set(["--take", "--keep", "--older-than", "--idle", "--idle-work"]);
+ const valued = new Set(["--take", "--keep", "--older-than", "--idle", "--idle-work", "--grace"]);
/** @type {Record<string, string[]>} */
const flags = {};
const positional = [];
@@ -149,10 +153,11 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
const versions = p.has("--versions");
if (versions && (takes.length || p.has("--anyway"))) throw new CliError("--versions judges every take of a project: no --take or --anyway");
if (p.has("--idle") && !versions) throw new CliError("--idle is --versions' (a project active within it is skipped); the work pass's is --idle-work");
+ if (p.has("--grace") && !versions) throw new CliError("--grace is --versions' (how old the superseding take must be)");
if (p.has("--idle-work") && takes.length) throw new CliError("--idle-work judges every take of a project: no --take");
const idleWork = p.has("--idle-work") ? p.one("--idle-work") : null;
const { parseAge } = await import("./takePrune.mjs");
- for (const [flag, v] of [["--idle", p.one("--idle")], ["--idle-work", idleWork]]) {
+ for (const [flag, v] of [["--idle", p.one("--idle")], ["--idle-work", idleWork], ["--grace", p.one("--grace")]]) {
if (v === undefined || v === null) continue;
try {
parseAge(v);
@@ -171,7 +176,14 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
let vr = null;
if (versions) {
const { pruneVersionsAll } = await import("./takeVersions.mjs");
- vr = await pruneVersionsAll({ reportsRoot, dryRun: !apply, ...(p.has("--idle") ? { idleDays: p.one("--idle") } : {}), ...(project ? { only: [project] } : {}), ...deps });
+ vr = await pruneVersionsAll({
+ reportsRoot,
+ dryRun: !apply,
+ ...(p.has("--idle") ? { idleDays: p.one("--idle") } : {}),
+ ...(p.has("--grace") ? { graceDays: p.one("--grace") } : {}),
+ ...(project ? { only: [project] } : {}),
+ ...deps,
+ });
}
// Pass 2, the work files: always without --versions; with it, only when --idle-work asks.
@@ -190,7 +202,10 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
const workFreed = (results ?? []).reduce((s, r) => s + (apply ? r.freedBytes ?? 0 : r.plan?.totals.prunable.freedBytes ?? 0), 0);
const versionsFreed = vr ? (apply ? vr.totals.freedBytes : vr.totals.bytes) : 0;
const freed = workFreed + versionsFreed;
- const failed = (results ?? []).flatMap((r) => (r.failed ?? []).map((f) => ({ project: r.project.id, ...f })));
+ // A take a build started in since the plan is kept: an outcome, said, not a failure.
+ const allFailed = (results ?? []).flatMap((r) => (r.failed ?? []).map((f) => ({ project: r.project.id, ...f })));
+ const failed = allFailed.filter((f) => !f.raced);
+ const raced = [...allFailed.filter((f) => f.raced), ...(vr ? vr.results.flatMap((r) => (r.raced ?? []).map((x) => ({ project: r.project.id, path: `takes/${x.id}/`, error: x.why }))) : [])];
const errors = (results ?? []).filter((r) => r.error);
const vFailed = vr ? vr.results.flatMap((r) => [...r.failed.map((f) => ({ project: r.project.id, path: `takes/${f.id}/`, error: f.error })), ...(r.error ? [{ project: r.project.id, path: "", error: r.error }] : [])]) : [];
const free = await freeBytesAt(reportsRoot);
@@ -203,8 +218,9 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
? {
versions: {
idleDays: vr.idleDays,
+ graceDays: vr.graceDays,
totals: vr.totals,
- projects: vr.results.map((r) => (r.error ? { project: r.project, error: r.error } : { ...r.plan, ...(apply ? { deleted: r.deleted, failed: r.failed, freedBytes: r.freedBytes } : {}) })),
+ projects: vr.results.map((r) => (r.error ? { project: r.project, error: r.error } : { ...r.plan, ...(apply ? { deleted: r.deleted, failed: r.failed, raced: r.raced, freedBytes: r.freedBytes } : {}) })),
},
}
: {}),
@@ -242,8 +258,8 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
const t = vr.totals;
log(
apply
- ? `superseded takes: ${t.deleted} deleted (${fmtBytes(t.freedBytes)}), ${t.keep} kept, ${t.skipped} project(s) active and skipped${t.failed ? `, ${t.failed} not deleted` : ""}`
- : `superseded takes: ${t.delete} to delete (${fmtBytes(t.bytes)}), ${t.keep} kept, ${t.skipped} project(s) active and skipped`,
+ ? `superseded takes: ${t.deleted} deleted (${fmtBytes(t.freedBytes)}), ${t.keep} kept${t.raced ? `, ${t.raced} kept since the plan` : ""}, ${t.skipped} project(s) skipped${t.failed ? `, ${t.failed} not deleted` : ""}`
+ : `superseded takes: ${t.delete} to delete (${fmtBytes(t.bytes)}), ${t.keep} kept, ${t.skipped} project(s) skipped`,
);
if (results) log("");
}
@@ -257,6 +273,7 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con
if (apply) for (const pr of r.pruned ?? []) log(` freed ${pr.id}: ${pr.paths.join(", ")}`);
log("");
}
+ for (const f of raced) log(`kept: ${f.project}/${f.path} — ${f.error}`);
for (const f of [...vFailed, ...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}`);
diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs
@@ -90,7 +90,7 @@ 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";
+import { TAKES_DIR, isTakeId, parseTake, readVerdictsStrict, takesDirOf } from "./takes.mjs";
/** The project's prune settings: `takes/prune.json`. */
export const POLICY_FILE = "prune.json";
@@ -617,10 +617,14 @@ export async function planPrune(project, opts = {}) {
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),
+ const [verdictsRead, projectManifest] = await Promise.all([
+ readVerdictsStrict(project.dir).then(
+ (v) => ({ v, error: null }),
+ (e) => ({ v: /** @type {Record<string, any>} */ ({}), error: e instanceof Error ? e.message : String(e) }),
+ ),
readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null),
]);
+ const verdicts = verdictsRead.v;
const procs = opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" });
/** @type {Map<string, KeepReason[]>} */
@@ -648,9 +652,13 @@ export async function planPrune(project, opts = {}) {
}
for (const id of opts.protect ?? []) why(id, "just-built", "just built");
- // The picked take, and the take whose manifest the project's is.
+ // The picked take, and the take whose manifest the project's is. A
+ // verdicts.json that cannot be read keeps every take: which one is picked is
+ // unknown (fail closed; an idle project's override never passes it).
+ if (verdictsRead.error) notes.push(`${verdictsRead.error}: every take keeps its work until it is fixed`);
for (const d of dirs) {
if (d.link) continue;
+ if (verdictsRead.error) why(d.id, "verdicts-unreadable", `${TAKES_DIR}/verdicts.json cannot be read: which take is picked is unknown`);
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);
@@ -718,8 +726,9 @@ export async function planPrune(project, opts = {}) {
overridden = keep.filter((r) => !r.hard);
keep = keep.filter((r) => r.hard);
} else if (idle?.idle) {
- overridden = keep.filter((r) => !r.hard && r.code !== "pinned");
- keep = keep.filter((r) => r.hard || r.code === "pinned");
+ const stays = (r) => r.hard || r.code === "pinned" || r.code === "verdicts-unreadable";
+ overridden = keep.filter((r) => !stays(r));
+ keep = keep.filter(stays);
}
const work = d.link ? { roots: [], notes: [] } : await workPathsOf(d.dir, roots);
const status = work.roots.length === 0 ? "no-work" : keep.length ? "kept" : "prunable";
@@ -777,11 +786,24 @@ export async function planPrune(project, opts = {}) {
};
}
+/** What projectActivity does not walk: render scratch and fetched media, re-made by machines, not a person. */
+const ACTIVITY_SKIP = new Set(["takes", "out", "clips", "clips-raw", "node_modules", ".git", "posts-media", "bench-excerpts", ".cache", "cache"]);
+const ACTIVITY_DEPTH = 4;
+const ACTIVITY_MAX_ENTRIES = 50000;
+
/**
- * WHEN A PROJECT WAS LAST WORKED ON: the newest of every take's builtAt,
- * take.json and preview mtimes (a take with no take.json: its out/), the
- * project's video.manifest.json and takes/verdicts.json, and -- as "now" -- a
- * live build lock. `what` names the newest. Reads only.
+ * WHEN A PROJECT WAS LAST WORKED ON (housekeeping's idle test), the newest of:
+ * - every take's builtAt and its own top-level files (take.json -- a take's
+ * patch, `umtool set --take` --, its video.manifest.json, its preview, its
+ * undo points; not pruned-work.json, the pruner's own record), and a
+ * take with no take.json: its out/;
+ * - a live build lock, as now;
+ * - the project's own files: every top-level file (video.manifest.json,
+ * notes.json, cuts.json, the play state, logs) and the files of every
+ * subdirectory but the render scratch and fetched media (ACTIVITY_SKIP,
+ * share-*): drafts, revisions, takes/verdicts.json and the rest.
+ * Links are not followed. `what` names the newest. Reads only. A walk past
+ * ACTIVITY_MAX_ENTRIES stops there and counts as now (fail closed).
*
* @param {string} projectDir
* @param {{ now?: () => Date, host?: string, alive?: (pid: number) => boolean, dirs?: Awaited<ReturnType<typeof readTakeDirs>> }} [opts]
@@ -794,12 +816,34 @@ export async function projectActivity(projectDir, opts = {}) {
const see = (ms, what) => {
if (ms > best.ms) best = { ms, what };
};
+ const filesIn = async (dir) => readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []);
for (const d of dirs) {
if (d.locks.some((l) => l.live)) see(now, `take ${d.id} is being built`);
see(d.modifiedMs, `take ${d.id}`);
+ if (d.link) continue;
+ for (const e of await filesIn(d.dir)) {
+ if (!e.isFile() || e.name === PRUNE_RECORD) continue;
+ see(await mtimeOf(path.join(/* turbopackIgnore: true */ d.dir, e.name)), `takes/${d.id}/${e.name}`);
+ }
}
- see(await mtimeOf(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")), "the project's video.manifest.json");
see(await mtimeOf(path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), "verdicts.json")), "takes/verdicts.json (a pick or a verdict)");
+ for (const e of await filesIn(takesDirOf(projectDir))) {
+ if (e.isFile()) see(await mtimeOf(path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), e.name)), `takes/${e.name}`);
+ }
+ let seen = 0;
+ const stack = [{ dir: projectDir, rel: "", depth: 0 }];
+ while (stack.length) {
+ const { dir, rel, depth } = /** @type {{ dir: string, rel: string, depth: number }} */ (stack.pop());
+ for (const e of await filesIn(dir)) {
+ if (++seen > ACTIVITY_MAX_ENTRIES) {
+ see(now, `the project has over ${ACTIVITY_MAX_ENTRIES} files outside its render scratch: taken as active`);
+ return { ms: best.ms, at: new Date(best.ms).toISOString(), what: best.what };
+ }
+ const r = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isFile()) see(await mtimeOf(path.join(/* turbopackIgnore: true */ dir, e.name)), r === "video.manifest.json" ? "the project's video.manifest.json" : r);
+ else if (e.isDirectory() && depth < ACTIVITY_DEPTH && !ACTIVITY_SKIP.has(e.name) && !e.name.startsWith("share-")) stack.push({ dir: path.join(/* turbopackIgnore: true */ dir, e.name), rel: r, depth: depth + 1 });
+ }
+ }
return { ms: best.ms, at: best.ms ? new Date(best.ms).toISOString() : null, what: best.what };
}
@@ -964,7 +1008,8 @@ export async function pruneProject(project, opts = {}) {
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" });
+ // Kept, as the plan would keep it now: an outcome, not a failure (`raced`).
+ failed.push({ path: `${TAKES_DIR}/${t.id}/`, error: "a build started in it (or from it) since the plan: kept", raced: true });
continue;
}
const work = await workPathsOf(takeDir, roots);
diff --git a/umtool/lib/report/takeVersions.mjs b/umtool/lib/report/takeVersions.mjs
@@ -12,10 +12,20 @@
// Folding letters too was a real mistake, caught by hand on 6 Nov.
//
// WHAT IS KEPT, per take, every reason said:
-// - the newest BUILT take of its line (by builtAt); a take with no builtAt
-// is not judged at all (a build that never finished, or one running);
-// - picked or pinned (verdicts.json), rendering now, or the base a running
-// render is made from (takeHousekeeping.mjs renderHolds -- `takes ls`);
+// - the NEWEST BUILT take of its line: the highest version number (the
+// folded digits read as numbers, left to right: draft-10 is newer than
+// draft-9, and a draft-3 rebuilt after draft-4 does not supersede it);
+// builtAt only breaks a tie between takes of the same number. A take with
+// no builtAt is not judged at all (a build that never finished, or one
+// running);
+// - every older take of a line whose newest was built less than `grace`
+// ago (default 7 d): the operator may still go back to it;
+// - picked or pinned, or with ANY verdict of the operator's (like, maybe,
+// no, or a verdict note) in verdicts.json; a verdicts.json that cannot be
+// read skips the whole project (the lenient reader's {} would lose every
+// pick);
+// - rendering now, or the base a running render is made from
+// (takeHousekeeping.mjs renderHolds -- `takes ls`);
// - being built (a live build lock or a pipeline process in it), the base of
// a take being built, the project's manifest's take, a pin in
// takes/prune.json, a take dir that is a link (takePrune.mjs planPrune);
@@ -26,7 +36,10 @@
// - anything `umtool takes delete` refuses (delete.mjs planTakeDelete: the
// project reached through a link, a render holding it, the manifest's take)
// -- its refusal is the reason, word for word. Deletion is deleteTake, the
-// same path `umtool takes delete` takes, never --force.
+// same path `umtool takes delete` takes, never --force, after reading the
+// build state, the verdicts and the notes once more for that take: a take
+// one of them claims since the plan is kept (`raced`, an outcome, not a
+// failure).
// And a whole project is skipped while it is ACTIVE: anything in it modified
// within `idleDays` (default 3; takePrune.mjs projectActivity), so a video
// being worked on is never touched.
@@ -41,9 +54,10 @@ import { namesProject, pipelineProcesses } from "./busy.mjs";
import { DeleteRefused, deleteBlocked, deleteTake, planTakeDelete } from "./delete.mjs";
import { renderHolds, takesOverview } from "./takeHousekeeping.mjs";
import { agoWords, fmtBytes, parseAge, pidAlive, planPrune, projectActivity, resolvePolicy, readPolicyFile } from "./takePrune.mjs";
-import { takesDirOf } from "./takes.mjs";
+import { readVerdictsStrict, takesDirOf } from "./takes.mjs";
export const DEFAULT_IDLE_DAYS = 3;
+export const DEFAULT_GRACE_DAYS = 7;
const DAY = 24 * 3600 * 1000;
/** A take id's version line: its digit runs folded to `#`, its letters kept. */
@@ -51,6 +65,30 @@ export function versionLine(id) {
return String(id).toLowerCase().replace(/\d+/g, "#");
}
+/** A take id's version number: its digit runs as numbers, left to right (`final-1027-v6` -> [1027, 6]). */
+export function versionNumber(id) {
+ return (String(id).match(/\d+/g) ?? []).map(Number);
+}
+
+/** Newer first: the higher version number, then (the same number) the later builtAt, then the id. */
+export function compareVersions(a, b) {
+ const x = versionNumber(a.id);
+ const y = versionNumber(b.id);
+ for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
+ const d = (y[i] ?? -1) - (x[i] ?? -1);
+ if (d) return d;
+ }
+ return (Date.parse(b.builtAt ?? "") || 0) - (Date.parse(a.builtAt ?? "") || 0) || b.id.localeCompare(a.id);
+}
+
+/** What an operator's verdict row says, or null when it says nothing a pruner must keep. */
+function verdictWords(v) {
+ if (!v) return null;
+ if (v.verdict) return `the operator's verdict "${v.verdict}"${v.note ? `: ${JSON.stringify(v.note.length > 60 ? `${v.note.slice(0, 57)}…` : v.note)}` : ""} (verdicts.json)`;
+ if (v.note) return `the operator's verdict note ${JSON.stringify(v.note.length > 60 ? `${v.note.slice(0, 57)}…` : v.note)} (verdicts.json)`;
+ return null;
+}
+
/**
* The takes the operator's notes name: `take -> { total, open }`. An anchor
* names a take by its `take` field (take, moment, cut, reel) or by a `file`
@@ -99,7 +137,7 @@ export async function takesWithNotes(projectDir) {
* WHAT DELETING A PROJECT'S SUPERSEDED TAKES WOULD DO. Reads only.
*
* @param {{ id: string, dir: string }} project
- * @param {{ idleDays?: number | string, now?: () => Date, reportsRoot?: string, mediaRoot?: string,
+ * @param {{ idleDays?: number | string, graceDays?: number | string, now?: () => Date, reportsRoot?: string, mediaRoot?: string,
* processes?: { pid: number, args: string[], cwd: string | null }[], host?: string, alive?: (pid: number) => boolean,
* env?: NodeJS.ProcessEnv }} [opts]
* @returns {Promise<VersionPlan>}
@@ -108,17 +146,25 @@ export async function planVersions(project, opts = {}) {
const nowDate = (opts.now ?? (() => new Date()))();
const now = nowDate.getTime();
const idleDays = parseAge(opts.idleDays ?? DEFAULT_IDLE_DAYS);
+ const graceDays = parseAge(opts.graceDays ?? DEFAULT_GRACE_DAYS);
const host = opts.host ?? os.hostname();
const alive = opts.alive ?? pidAlive;
const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT };
const notes = [];
const act = await projectActivity(project.dir, { now: () => nowDate, host, alive });
- const base = { project: { id: project.id, dir: project.dir }, idleDays, lastActivityAt: act.at, lastActivity: act.what };
+ const base = { project: { id: project.id, dir: project.dir }, idleDays, graceDays, lastActivityAt: act.at, lastActivity: act.what };
const empty = { lines: [], totals: { takes: 0, delete: 0, keep: 0, bytes: 0 }, notes };
if (act.ms && now - act.ms < idleDays * DAY) {
return { ...base, skipped: `active: ${act.what} modified ${agoWords(now - act.ms)} ago (--idle ${idleDays} d)`, ...empty };
}
+ // Fail closed: picks and verdicts that cannot be read keep the whole project.
+ let verdicts;
+ try {
+ verdicts = await readVerdictsStrict(project.dir);
+ } catch (e) {
+ return { ...base, skipped: `${e instanceof Error ? e.message : e}: every take kept until it is fixed`, ...empty };
+ }
const [overview, noted] = await Promise.all([takesOverview(project.dir), takesWithNotes(project.dir)]);
if (noted === null) notes.push(`${NOTES_FILENAME} does not parse: every take is kept until it does`);
for (const s of overview.skipped) notes.push(`takes/${s.dir}: not a take umtool lists (${s.why}) — not judged`);
@@ -146,13 +192,20 @@ export async function planVersions(project, opts = {}) {
}
for (const [line, rows] of lines) {
const built = rows.filter((r) => r.builtAt && Number.isFinite(Date.parse(r.builtAt)));
- built.sort((a, b) => Date.parse(b.builtAt) - Date.parse(a.builtAt) || b.id.localeCompare(a.id));
- if (built[0]) why(built[0].id, "newest", built.length > 1 ? `the newest built of line ${line}` : `the only built take of line ${line}`);
+ built.sort(compareVersions);
+ const top = built[0];
+ if (top) why(top.id, "newest", built.length > 1 ? `the newest built of line ${line}` : `the only built take of line ${line}`);
+ const topAge = top ? now - Date.parse(top.builtAt) : 0;
+ if (top && topAge < graceDays * DAY) {
+ for (const r of built.slice(1)) why(r.id, "grace", `superseded by ${top.id}, built ${agoWords(topAge)} ago: it goes once that is ${graceDays} d old (--grace)`);
+ }
for (const r of rows) if (!built.includes(r)) why(r.id, "not-built", "no builtAt: not built (or still building) — not judged");
}
for (const r of overview.rows) {
if (r.picked) why(r.id, "picked", `picked${r.pinned ? " and pinned" : ""} (verdicts.json)`);
+ const vw = verdictWords(verdicts[r.id]);
+ if (vw) why(r.id, "verdict", vw);
for (const h of r.holds ?? []) why(r.id, r.rendering && h.startsWith("it is rendering") ? "rendering" : "render-base", h);
for (const k of pruneOf.get(r.id)?.keep ?? []) if (FROM_PRUNE.has(k.code)) why(r.id, k.code, k.why);
const n = noted === null ? null : noted.get(r.id);
@@ -191,7 +244,7 @@ export async function planVersions(project, opts = {}) {
const s = sizes.get(r.id);
return /** @type {VersionTake} */ ({ id: r.id, line, builtAt: r.builtAt ?? null, action: keep.length ? "keep" : "delete", keep, bytes: s?.bytes ?? 0, files: s?.files ?? 0 });
})
- .sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")) || a.id.localeCompare(b.id));
+ .sort(compareVersions);
out.push({ line, takes });
}
const all = out.flatMap((l) => l.takes);
@@ -211,13 +264,16 @@ export async function planVersions(project, opts = {}) {
* process or a render has started in it since.
*
* @param {{ id: string, dir: string }} project
- * @param {Parameters<typeof planVersions>[1]} [opts]
+ * @param {Parameters<typeof planVersions>[1] & { plan?: VersionPlan }} [opts]
*/
export async function pruneVersions(project, opts = {}) {
- const plan = await planVersions(project, opts);
+ // `opts.plan`: one made earlier (shown, then confirmed); each take is still re-read before it goes.
+ const plan = opts.plan ?? (await planVersions(project, opts));
const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT };
const deleted = [];
const failed = [];
+ /** @type {{ id: string, why: string }[]} kept: claimed since the plan (an outcome, not a failure) */
+ const raced = [];
const doomed = plan.lines.flatMap((l) => l.takes).filter((t) => t.action === "delete");
const procs = doomed.length ? opts.processes ?? pipelineProcesses() : [];
for (const t of doomed) {
@@ -225,8 +281,21 @@ export async function pruneVersions(project, opts = {}) {
const realDir = await realpath(/* turbopackIgnore: true */ dir).catch(() => dir);
const busy = procs.filter((p) => namesProject(p.args, p.cwd, { dir, realDir })).map((p) => p.pid);
const holds = await renderHolds(project.dir, t.id, { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) });
- if (busy.length || holds.length) {
- failed.push({ id: t.id, error: `started since the plan: ${[...holds, ...(busy.length ? [`a build process is working in it (pid ${busy.join(", ")})`] : [])].join("; ")} — kept` });
+ // The operator's word, read again now: a pick, a verdict or a note since the plan keeps it.
+ const claims = [];
+ try {
+ const v = (await readVerdictsStrict(project.dir))[t.id];
+ if (v?.picked) claims.push("picked since the plan");
+ const vw = verdictWords(v);
+ if (vw) claims.push(`${vw}, since the plan`);
+ } catch (e) {
+ claims.push(`${e instanceof Error ? e.message : e}`);
+ }
+ const noted = await takesWithNotes(project.dir);
+ if (noted === null) claims.push(`${NOTES_FILENAME} does not parse now`);
+ else if (noted.has(t.id)) claims.push("an operator note on it since the plan");
+ if (busy.length || holds.length || claims.length) {
+ raced.push({ id: t.id, why: `${[...holds, ...(busy.length ? [`a build process is working in it (pid ${busy.join(", ")})`] : []), ...claims].join("; ")} — kept` });
continue;
}
try {
@@ -237,7 +306,7 @@ export async function pruneVersions(project, opts = {}) {
failed.push({ id: t.id, error: e instanceof DeleteRefused ? e.message : e instanceof Error ? e.message : String(e) });
}
}
- return { plan, deleted, failed, freedBytes: deleted.reduce((s, d) => s + d.bytes, 0) };
+ return { plan, deleted, failed, raced, freedBytes: deleted.reduce((s, d) => s + d.bytes, 0) };
}
/**
@@ -260,16 +329,17 @@ export async function pruneVersionsAll(opts = {}) {
if (!has) continue;
const project = { id: p.id, dir: p.dir };
try {
- if (opts.dryRun) results.push({ project, plan: await planVersions(project, opts), deleted: [], failed: [], freedBytes: 0 });
+ if (opts.dryRun) results.push({ project, plan: await planVersions(project, opts), deleted: [], failed: [], raced: [], freedBytes: 0 });
else results.push({ project, ...(await pruneVersions(project, opts)) });
} catch (e) {
- results.push({ project, error: e instanceof Error ? e.message : String(e), deleted: [], failed: [], freedBytes: 0 });
+ results.push({ project, error: e instanceof Error ? e.message : String(e), deleted: [], failed: [], raced: [], freedBytes: 0 });
}
}
const plans = results.filter((r) => r.plan).map((r) => r.plan);
return {
dryRun: !!opts.dryRun,
idleDays: parseAge(opts.idleDays ?? DEFAULT_IDLE_DAYS),
+ graceDays: parseAge(opts.graceDays ?? DEFAULT_GRACE_DAYS),
results,
totals: {
projects: results.length,
@@ -278,6 +348,7 @@ export async function pruneVersionsAll(opts = {}) {
keep: plans.reduce((s, p) => s + p.totals.keep, 0),
bytes: plans.reduce((s, p) => s + p.totals.bytes, 0),
deleted: results.reduce((s, r) => s + r.deleted.length, 0),
+ raced: results.reduce((s, r) => s + (r.raced?.length ?? 0), 0),
freedBytes: results.reduce((s, r) => s + r.freedBytes, 0),
failed: results.reduce((s, r) => s + r.failed.length + (r.error ? 1 : 0), 0),
},
@@ -293,12 +364,13 @@ export function versionLines(plan, { compact = false, applied = null } = {}) {
if (compact && !l.takes.some((t) => t.action === "delete")) continue;
lines.push(` ${l.line}`);
for (const t of l.takes) {
- const done = applied?.deleted?.some((d) => d.id === t.id) ? "deleted " : applied?.failed?.find((f) => f.id === t.id) ? "NOT deleted " : "";
+ const done = applied?.deleted?.some((d) => d.id === t.id) ? "deleted " : applied?.raced?.some((r) => r.id === t.id) ? "kept " : applied?.failed?.find((f) => f.id === t.id) ? "NOT deleted " : "";
if (t.action === "delete") lines.push(` ${t.id.padEnd(28)} ${done || "delete "}${fmtBytes(t.bytes)}${t.builtAt ? ` (built ${t.builtAt.slice(0, 10)})` : ""}`);
else lines.push(` ${t.id.padEnd(28)} keep ${t.keep.map((r) => r.why).join("; ")}`);
}
}
for (const n of plan.notes) lines.push(` note: ${n}`);
+ for (const r of applied?.raced ?? []) lines.push(` kept ${r.id}: ${r.why}`);
for (const f of applied?.failed ?? []) lines.push(` not deleted ${f.id}: ${f.error}`);
return lines;
}
diff --git a/umtool/lib/report/takeVersions.test.mjs b/umtool/lib/report/takeVersions.test.mjs
@@ -5,7 +5,7 @@
//
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
-import { lstat, mkdir, mkdtemp, readFile, rm, symlink, utimes, writeFile } from "node:fs/promises";
+import { lstat, mkdir, mkdtemp, readFile, readdir, rm, symlink, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import test, { after } from "node:test";
@@ -37,6 +37,14 @@ async function root() {
}
const age = (p, when = OLD) => utimes(p, when, when);
+/** Every file under `dir` dated `when` (links not followed): a project nobody touched since. */
+async function ageTree(dir, when = OLD) {
+ for (const e of await readdir(dir, { withFileTypes: true })) {
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) await ageTree(p, when);
+ else if (e.isFile()) await age(p, when);
+ }
+}
const exists = (p) => lstat(p).then(() => true, () => false);
/** A built take, its files dated `when`, with a little work in out/. */
@@ -49,7 +57,7 @@ async function mkTake(dir, id, { builtAt = "2026-10-01T00:00:00Z", from, when =
await writeFile(path.join(t, "preview.mp4"), Buffer.alloc(8 * KiB, "p"));
await writeFile(path.join(t, "video.manifest.json"), JSON.stringify({ slug: "fx", take: id }) + "\n");
await writeFile(path.join(v, "segments", "s01.mp4"), Buffer.alloc(16 * KiB, "s"));
- for (const f of ["take.json", "preview.mp4"]) await age(path.join(t, f), when);
+ await ageTree(t, when);
return t;
}
@@ -116,6 +124,7 @@ test("every keep reason: picked, notes, a --from base, rendering, the manifest's
await age(path.join(dir, "video.manifest.json"));
// draft-7 pinned in takes/prune.json.
await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: ["draft-7"] }));
+ await ageTree(dir);
assert.deepEqual([...(await takesWithNotes(dir))].sort(), [["draft-2", { total: 1, open: 0 }], ["draft-4", { total: 1, open: 1 }]]);
// A live build lock is activity: this project is busy now. Judged with a wide-open idle.
@@ -139,6 +148,7 @@ test("a notes.json that does not parse keeps every take", async () => {
await mkTake(dir, "draft-1");
await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" });
await writeFile(path.join(dir, "notes.json"), "{ not json");
+ await ageTree(dir);
const plan = await planVersions(project, opts);
assert.equal(plan.totals.delete, 0);
assert.deepEqual(codes(plan, "draft-1"), ["notes"]);
@@ -155,21 +165,23 @@ test("an active project is skipped whole, and --yes deletes nothing in it", asyn
const r = await pruneVersions(project, opts);
assert.equal(r.deleted.length, 0);
assert.ok(await exists(path.join(dir, "takes", "draft-1")));
- // A shorter --idle judges it.
- assert.equal((await planVersions(project, { ...opts, idleDays: "12h" })).totals.delete, 1);
+ // A shorter --idle judges it -- once the superseding take is past --grace.
+ assert.match(take(await planVersions(project, { ...opts, idleDays: "12h" }), "draft-1").keep[0].why, /superseded by draft-2, built 24 h ago: it goes once that is 7 d old/);
+ assert.equal((await planVersions(project, { ...opts, idleDays: "12h", graceDays: 0 })).totals.delete, 1);
});
test("deleting goes through deleteTake: the take's directory goes, its verdict row and the kept takes stay", async () => {
const { dir, project, opts } = await root();
await mkTake(dir, "draft-1");
await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" });
- await verdicts(dir, { "draft-1": { verdict: "no", note: "too long", at: "2026-10-01T00:00:00Z" } });
+ // A supersede mark is no verdict: it folds the take away, it does not keep it.
+ await verdicts(dir, { "draft-1": { verdict: null, note: "", at: "2026-10-01T00:00:00Z", superseded: { by: "draft-2", at: "2026-10-02T00:00:00Z" } } });
const r = await pruneVersions(project, opts);
assert.deepEqual(r.deleted.map((d) => d.id), ["draft-1"]);
assert.ok(r.freedBytes > 0);
assert.equal(await exists(path.join(dir, "takes", "draft-1")), false);
assert.ok(await exists(path.join(dir, "takes", "draft-2", "preview.mp4")));
- assert.match(await readFile(path.join(dir, "takes", "verdicts.json"), "utf8"), /too long/);
+ assert.match(await readFile(path.join(dir, "takes", "verdicts.json"), "utf8"), /"by":"draft-2"/);
});
test("a project reached through a link: `umtool takes delete` refuses, so the take is kept with its words", async () => {
@@ -216,6 +228,7 @@ test("--idle-work: an idle project's newest and picked takes' work goes; a pin,
await mkTake(dir, "d", { builtAt: "2026-10-04T00:00:00Z" });
await verdicts(dir, { b: { verdict: null, note: "", at: "2026-10-01T00:00:00Z", picked: true } });
await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: ["a"] }));
+ await ageTree(dir);
// Without --idle-work the policy keeps a (pin), b (picked), c and d (newest 2).
const plain = await planPrune(project, { ...opts, measure: "none" });
assert.deepEqual(plain.takes.filter((t) => t.status === "prunable").map((t) => t.id), []);
@@ -227,6 +240,7 @@ test("--idle-work: an idle project's newest and picked takes' work goes; a pin,
// A build from c running now: c is its base, and the project is not idle any more.
await mkTake(dir, "e", { builtAt: "2026-10-05T00:00:00Z", from: "c" });
await writeFile(path.join(dir, "takes", "e", BUILD_LOCK), JSON.stringify({ pid: process.pid, from: "c" }));
+ await ageTree(dir);
const busy = await planPrune(project, { ...opts, measure: "none", idleWorkDays: "3d" });
assert.equal(busy.idle.idle, false);
// Even forced idle (a zero age), the build and its base keep theirs.
@@ -275,3 +289,156 @@ test("umtool prune --versions: a dry run says, --yes deletes, --json carries bot
assert.equal(await pruneCommand(["proj", "--versions", "--take", "draft-2"], io), 2);
assert.equal(await pruneCommand(["--all", "--versions", "--idle", "soon"], io), 2);
});
+
+// ---- review fixes (6 Nov) ----------------------------------------------------
+
+import { readVerdictsStrict } from "./takes.mjs";
+import { compareVersions } from "./takeVersions.mjs";
+
+test("fail closed: a verdicts.json that cannot be read skips the version pass and keeps every take's work under --idle-work", async () => {
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "draft-1");
+ await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" });
+ await writeFile(path.join(dir, "takes", "verdicts.json"), "{ broken");
+ await ageTree(dir);
+ await assert.rejects(readVerdictsStrict(dir), /verdicts\.json does not parse/);
+ const plan = await planVersions(project, opts);
+ assert.match(plan.skipped ?? "", /verdicts\.json does not parse.*every take kept/);
+ assert.equal((await pruneVersions(project, opts)).deleted.length, 0);
+ assert.ok(await exists(path.join(dir, "takes", "draft-1")));
+ const idle = await planPrune(project, { ...opts, measure: "none", idleWorkDays: "3d", flags: { keep: 0, olderThan: 0 } });
+ assert.equal(idle.idle.idle, true);
+ assert.deepEqual(idle.takes.filter((t) => t.status === "prunable").map((t) => t.id), [], "no take's work goes");
+ assert.ok(idle.takes.every((t) => t.keep.some((r) => r.code === "verdicts-unreadable")));
+ // An array is not a verdicts file either.
+ await writeFile(path.join(dir, "takes", "verdicts.json"), "[]");
+ await assert.rejects(readVerdictsStrict(dir), /is not an object/);
+});
+
+test("any verdict of the operator's keeps a take: like, maybe, no, or a verdict note alone", async () => {
+ const { dir, project, opts } = await root();
+ for (let i = 1; i <= 6; i += 1) await mkTake(dir, `draft-${i}`, { builtAt: `2026-10-0${i}T00:00:00Z` });
+ await verdicts(dir, {
+ "draft-1": { verdict: "like", note: "", at: "x" },
+ "draft-2": { verdict: "maybe", note: "", at: "x" },
+ "draft-3": { verdict: "no", note: "", at: "x" },
+ "draft-4": { verdict: null, note: "the cold open works here", at: "x" },
+ });
+ await ageTree(dir);
+ const plan = await planVersions(project, opts);
+ for (const id of ["draft-1", "draft-2", "draft-3", "draft-4"]) assert.deepEqual(codes(plan, id), ["verdict"], id);
+ assert.match(take(plan, "draft-3").keep[0].why, /the operator's verdict "no"/);
+ assert.match(take(plan, "draft-4").keep[0].why, /verdict note "the cold open works here"/);
+ assert.equal(take(plan, "draft-5").action, "delete");
+});
+
+test("project activity: a notes-only edit, a source file, a draft, a take's manifest keep it active; render scratch does not", async () => {
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "draft-1");
+ await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" });
+ await mkdir(path.join(dir, "drafts"), { recursive: true });
+ await mkdir(path.join(dir, "out", "clips"), { recursive: true });
+ await mkdir(path.join(dir, "clips"), { recursive: true });
+ await writeFile(path.join(dir, "notes.json"), "{}");
+ await writeFile(path.join(dir, "cuts.json"), "{}");
+ await writeFile(path.join(dir, "drafts", "d.json"), "{}");
+ await writeFile(path.join(dir, "out", "clips", "w.mp4"), "x");
+ await writeFile(path.join(dir, "clips", "c.mp4"), "x");
+ await ageTree(dir);
+ assert.equal((await planVersions(project, opts)).skipped, null, "nothing recent: judged");
+ const recent = new Date("2026-11-06T06:00:00Z");
+ // Render scratch and fetched media are not a person's work.
+ for (const f of [path.join(dir, "out", "clips", "w.mp4"), path.join(dir, "clips", "c.mp4"), path.join(dir, "takes", "draft-1", "pruned-work.json")]) {
+ await writeFile(f, "{}");
+ await age(f, recent);
+ }
+ assert.equal((await planVersions(project, opts)).skipped, null, "scratch, fetches and the pruner's own record are not activity");
+ for (const [f, what] of [
+ ["notes.json", /active: notes\.json modified 6 h ago/],
+ ["cuts.json", /active: cuts\.json/],
+ ["drafts/d.json", /active: drafts\/d\.json/],
+ ["takes/draft-1/video.manifest.json", /active: takes\/draft-1\/video\.manifest\.json/],
+ ]) {
+ await ageTree(dir);
+ await age(path.join(dir, f), recent);
+ assert.match((await planVersions(project, opts)).skipped ?? "", what, f);
+ }
+ await ageTree(dir);
+});
+
+test("the newest of a line is its highest number: draft-10 over draft-9, and a rebuilt draft-3 does not supersede draft-4", async () => {
+ assert.ok(compareVersions({ id: "draft-10", builtAt: "2026-10-01T00:00:00Z" }, { id: "draft-9", builtAt: "2026-10-05T00:00:00Z" }) < 0);
+ assert.ok(compareVersions({ id: "final-1027-v6-x", builtAt: "a" }, { id: "final-1104-v2-x", builtAt: "a" }) > 0);
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "draft-3", { builtAt: "2026-10-09T00:00:00Z" }); // rebuilt after draft-4
+ await mkTake(dir, "draft-4", { builtAt: "2026-10-04T00:00:00Z" });
+ await mkTake(dir, "draft-9", { builtAt: "2026-10-05T00:00:00Z" });
+ await mkTake(dir, "draft-10", { builtAt: "2026-10-01T00:00:00Z" });
+ await ageTree(dir);
+ const plan = await planVersions(project, opts);
+ assert.deepEqual(codes(plan, "draft-10"), ["newest"]);
+ assert.deepEqual(plan.lines[0].takes.map((t) => t.id), ["draft-10", "draft-9", "draft-4", "draft-3"]);
+ assert.deepEqual(plan.lines[0].takes.filter((t) => t.action === "delete").map((t) => t.id), ["draft-9", "draft-4", "draft-3"]);
+});
+
+test("grace: superseded takes stay until the take that supersedes them is --grace old (default 7 d)", async () => {
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "draft-1", { builtAt: "2026-10-01T00:00:00Z" });
+ await mkTake(dir, "draft-2", { builtAt: "2026-11-01T12:00:00Z" }); // 5 days before NOW
+ await ageTree(dir);
+ const plan = await planVersions(project, opts);
+ assert.equal(plan.graceDays, 7);
+ assert.deepEqual(codes(plan, "draft-1"), ["grace"]);
+ assert.match(take(plan, "draft-1").keep[0].why, /superseded by draft-2, built 5\.0 d ago/);
+ assert.equal(take(await planVersions(project, { ...opts, graceDays: "4d" }), "draft-1").action, "delete");
+ const out = [];
+ const io = { reportsRoot: path.dirname(dir), log: (s) => out.push(s), err: () => {}, deps: { processes: [], alive: opts.alive, now } };
+ assert.equal(await pruneCommand(["proj", "--versions", "--grace", "4d", "--json"], io), 0);
+ assert.equal(JSON.parse(out.join("\n")).versions.graceDays, 4);
+ assert.equal(await pruneCommand(["proj", "--grace", "4d"], io), 2, "--grace is --versions'");
+});
+
+test("a pick, a verdict or a note since the plan keeps the take: raced, an outcome, never a failure", async () => {
+ const { dir, project, opts } = await root();
+ await mkTake(dir, "draft-1");
+ await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" });
+ await mkTake(dir, "draft-3", { builtAt: "2026-10-03T00:00:00Z" });
+ await ageTree(dir);
+ const plan = await planVersions(project, opts);
+ assert.deepEqual(plan.lines[0].takes.filter((t) => t.action === "delete").map((t) => t.id), ["draft-2", "draft-1"]);
+ // Between the plan and the delete: a verdict on draft-2, a note on draft-1.
+ await verdicts(dir, { "draft-2": { verdict: "like", note: "", at: "x" } });
+ await writeFile(
+ path.join(dir, "notes.json"),
+ JSON.stringify({ format: "umtool-notes", version: 1, subject: { kind: "video-project", project: "proj" }, notes: [{ id: "n_bbbb1", status: "open", author: "operator", text: "t", at: "x", updatedAt: "x", anchor: { kind: "take", take: "draft-1" }, replies: [] }] }),
+ );
+ const r = await pruneVersions(project, { ...opts, plan });
+ assert.deepEqual(r.deleted, []);
+ assert.deepEqual(r.failed, []);
+ assert.deepEqual(r.raced.map((x) => x.id).sort(), ["draft-1", "draft-2"]);
+ assert.match(r.raced.find((x) => x.id === "draft-2").why, /verdict "like".*since the plan/);
+ assert.match(r.raced.find((x) => x.id === "draft-1").why, /an operator note on it since the plan/);
+ assert.ok(await exists(path.join(dir, "takes", "draft-1")) && await exists(path.join(dir, "takes", "draft-2")));
+});
+
+test("the work pass: a build that starts in a take after the plan keeps it, and `umtool prune --yes` still exits 0", async () => {
+ const { reports, dir } = await root();
+ await mkTake(dir, "a", { builtAt: "2026-10-01T00:00:00Z" });
+ await mkTake(dir, "b", { builtAt: "2026-10-02T00:00:00Z" });
+ await mkTake(dir, "c", { builtAt: "2026-10-03T00:00:00Z" });
+ await writeFile(path.join(dir, "takes", "a", BUILD_LOCK), JSON.stringify({ pid: 77777 }));
+ await ageTree(dir);
+ // pid 77777 is gone when the plan reads the lock, and alive by the time a's work would go.
+ let asked = 0;
+ const alive = (pid) => pid === process.pid || (pid === 77777 && ++asked > 1);
+ const out = [];
+ const errs = [];
+ const io = { reportsRoot: reports, log: (s) => out.push(s), err: (s) => errs.push(s), deps: { processes: [], alive, now } };
+ assert.equal(await pruneCommand(["proj", "--yes", "--json"], io), 0, errs.join("\n"));
+ const j = JSON.parse(out.join("\n"));
+ const f = j.projects[0].failed;
+ assert.equal(f.length, 1);
+ assert.equal(f[0].raced, true);
+ assert.match(f[0].error, /since the plan: kept/);
+ assert.ok(await exists(path.join(dir, "takes", "a", "out", "sourced", "segments", "s01.mp4")));
+});
diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs
@@ -319,6 +319,32 @@ async function writeVerdicts(file, map) {
}
/**
+ * verdicts.json for a DELETER (housekeeping, 2026-11-06): `{}` when absent, an
+ * ERROR when it is there and cannot be read or is not an object -- the lenient
+ * reader's `{}` would lose every pick and verdict, and a pruner would then
+ * delete what they keep.
+ * @param {string} projectDir
+ */
+export async function readVerdictsStrict(projectDir) {
+ const file = verdictsFileOf(projectDir);
+ let text = null;
+ try {
+ text = await readFile(file, "utf8");
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw new Error(`${TAKES_DIR}/${VERDICTS_FILE} cannot be read (${err instanceof Error ? err.message : err})`);
+ }
+ if (text === null) return {};
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (err) {
+ throw new Error(`${TAKES_DIR}/${VERDICTS_FILE} does not parse (${err instanceof Error ? err.message : err})`);
+ }
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${TAKES_DIR}/${VERDICTS_FILE} is not an object`);
+ return cleanVerdicts(raw);
+}
+
+/**
* @param {string} projectDir
* @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true, superseded?: { by: string | null, at: string } }>>}
*/