// SUPERSEDED TAKES (housekeeping, 2026-11-06): whole takes deleted when a // newer take of the same VERSION LINE is built -- what the operator asked for // on 6 Nov ("drop all but the latest of each version of a take for every // video") and the orchestrator did by hand (reports/CLEANUP-2026-11-06.md). // `umtool prune --versions` and `archilyzer housekeeping` call it. // // THE VERSION LINE is the take id with every run of digits folded to `#`: // draft-3 and draft-4 are `draft-#`, final-1027-v6-blurred and // final-1104-v7-blurred are `final-#-v#-blurred`. A LETTER IS NEVER FOLDED: // v6c and v6d are alternatives the operator chose between (`v#c`, `v#d`), and // release-6u is release-6's uncensored twin (`release-#u` is not `release-#`). // 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: 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); // - one with operator notes on it (the project's notes.json: an anchor that // names the take, or a file under takes//), open or not -- a note is a // person's reading of that take; // - the --from base of a kept take, transitively; // - 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, 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. // // Plain ESM: the CLI runs it with bare node. import { realpath } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { MEDIA_ROOT, NOTES_FILENAME, REPORTS_ROOT } from "../paths.mjs"; import { readNotes } from "../annotations/store.mjs"; 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 { 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. */ 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` * under `takes//`. A notes.json that is there and does not parse names * EVERY take (null): not knowing which takes a note is on keeps them all. * * @param {string} projectDir * @returns {Promise | null>} */ export async function takesWithNotes(projectDir) { const r = await readNotes(path.join(/* turbopackIgnore: true */ projectDir, NOTES_FILENAME)); if (r.error) return null; const out = new Map(); for (const n of r.doc?.notes ?? []) { const a = /** @type {Record} */ (n.anchor ?? {}); const ids = new Set(); if (typeof a.take === "string") ids.add(a.take); if (typeof a.file === "string") { const m = /^takes\/([^/]+)\//.exec(a.file); if (m) ids.add(m[1]); } for (const id of ids) { const c = out.get(id) ?? { total: 0, open: 0 }; c.total += 1; if (n.status === "open") c.open += 1; out.set(id, c); } } return out; } /** * @typedef {{ code: string, why: string }} Reason * @typedef {{ id: string, line: string, builtAt: string | null, action: "keep" | "delete", keep: Reason[], bytes: number, files: number }} VersionTake * @typedef {{ * project: { id: string, dir: string }, * idleDays: number, lastActivityAt: string | null, lastActivity: string | null, * skipped: string | null, * lines: { line: string, takes: VersionTake[] }[], * totals: { takes: number, delete: number, keep: number, bytes: number }, * notes: string[], * }} VersionPlan */ /** * WHAT DELETING A PROJECT'S SUPERSEDED TAKES WOULD DO. Reads only. * * @param {{ id: string, dir: string }} project * @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} */ 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, 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`); // planPrune's reading of the build state, the manifest, prune.json pins and // the --from bases (with no newest-K and no recent rule: those are the // work-file policy's, not this one's). const policy = { ...resolvePolicy({ file: await readPolicyFile(project.dir), env: opts.env ?? process.env, flags: { keep: 0, olderThan: 0 } }) }; const pp = await planPrune(project, { policy, measure: "none", now: () => nowDate, ...roots, host, alive, ...(opts.processes ? { processes: opts.processes } : {}) }); const pruneOf = new Map(pp.takes.map((t) => [t.id, t])); const FROM_PRUNE = new Set(["building", "base-of-building", "current", "pinned", "link"]); /** @type {Map} */ const reasons = new Map(overview.rows.map((r) => [r.id, []])); const why = (id, code, text) => { const list = reasons.get(id); if (list && !list.some((x) => x.code === code)) list.push({ code, why: text }); }; // The newest built take of each line. const lines = new Map(); for (const r of overview.rows) { const k = versionLine(r.id); if (!lines.has(k)) lines.set(k, []); lines.get(k).push(r); } for (const [line, rows] of lines) { const built = rows.filter((r) => r.builtAt && Number.isFinite(Date.parse(r.builtAt))); 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); if (noted === null) why(r.id, "notes", `${NOTES_FILENAME} does not parse: which takes it names is unknown`); else if (n) why(r.id, "notes", `${n.total} operator note${n.total === 1 ? "" : "s"} on it${n.open ? ` (${n.open} open)` : ""} — umtool notes ${project.id}`); } // The --from bases of a kept take, transitively. for (let changed = true; changed; ) { changed = false; for (const r of overview.rows) { if (!(reasons.get(r.id) ?? []).length) continue; for (const b of pruneOf.get(r.id)?.bases ?? []) { if (!reasons.has(b) || (reasons.get(b) ?? []).some((x) => x.code === "base")) continue; why(b, "base", `the --from base of ${r.id}, which is kept`); changed = true; } } } // What is left goes -- unless `umtool takes delete` refuses it. /** @type {Map} */ const sizes = new Map(); for (const r of overview.rows) { if ((reasons.get(r.id) ?? []).length) continue; const plan = await planTakeDelete(project, r.id, roots).catch((e) => ({ refusals: [{ reason: e instanceof Error ? e.message : String(e), forceable: false }], bytes: 0, files: 0 })); if (deleteBlocked(plan, false)) for (const x of plan.refusals) why(r.id, "refused", `umtool takes delete refuses: ${x.reason}`); else sizes.set(r.id, { bytes: plan.bytes ?? 0, files: plan.files ?? 0 }); } const out = []; for (const [line, rows] of [...lines].sort((a, b) => a[0].localeCompare(b[0]))) { const takes = rows .map((r) => { const keep = reasons.get(r.id) ?? []; 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(compareVersions); out.push({ line, takes }); } const all = out.flatMap((l) => l.takes); const del = all.filter((t) => t.action === "delete"); return { ...base, skipped: null, lines: out, totals: { takes: all.length, delete: del.length, keep: all.length - del.length, bytes: del.reduce((s, t) => s + t.bytes, 0) }, notes, }; } /** * DELETE A PROJECT'S SUPERSEDED TAKES: the plan, then each take through * deleteTake (never forced), after asking once more whether a pipeline * process or a render has started in it since. * * @param {{ id: string, dir: string }} project * @param {Parameters[1] & { plan?: VersionPlan }} [opts] */ export async function pruneVersions(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) { const dir = path.join(/* turbopackIgnore: true */ takesDirOf(project.dir), t.id); 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 } : {}) }); // 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 { const r = await deleteTake(project, t.id, { ...roots, force: false }); if (r.failed.length) failed.push({ id: t.id, error: r.failed.map((f) => `${f.path}: ${f.error}`).join("; ") }); else deleted.push({ id: t.id, bytes: t.bytes, files: t.files }); } catch (e) { failed.push({ id: t.id, error: e instanceof DeleteRefused ? e.message : e instanceof Error ? e.message : String(e) }); } } return { plan, deleted, failed, raced, freedBytes: deleted.reduce((s, d) => s + d.bytes, 0) }; } /** * Every project under `reportsRoot` with a takes/ directory: planned, or * pruned. One project's error is its row's, never the run's. * * @param {Parameters[1] & { dryRun?: boolean, only?: { id: string, dir: string }[] }} [opts] */ export async function pruneVersionsAll(opts = {}) { const reportsRoot = opts.reportsRoot ?? REPORTS_ROOT; let refs = opts.only; if (!refs) { const { sharedWalk } = await import("../projects/walk.mjs"); refs = await sharedWalk(reportsRoot, { since: Date.now() }); } const { stat } = await import("node:fs/promises"); 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 (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: [], 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, skipped: plans.filter((p) => p.skipped).length, delete: plans.reduce((s, p) => s + p.totals.delete, 0), 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), }, }; } /** One project's version plan as lines; `compact` drops lines with nothing to delete. */ export function versionLines(plan, { compact = false, applied = null } = {}) { if (plan.skipped) return [`${plan.project.id} — skipped, ${plan.skipped}`]; const head = `${plan.project.id} — ${plan.totals.delete} superseded take(s)${plan.totals.delete ? `, ${fmtBytes(plan.totals.bytes)}` : ""} · ${plan.totals.keep} kept${plan.lastActivityAt ? ` · last worked on ${plan.lastActivityAt.slice(0, 10)}` : ""}`; const lines = [head]; for (const l of plan.lines) { 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?.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; }