Archilyzer · Source

archilyzer

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

commit 4ee40d8fd477fa87c1ae4683f1e4b4487f289611
parent 6b9c06c191898ca8bd239a28815fd8f8dc236b12
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri,  6 Nov 2026 12:56:43 -0500

umtool: prune --versions deletes superseded takes; --idle-work frees an idle project's newest takes' work

On 6 Nov the operator asked to "drop all but the latest of each version of
a take for every video", and the orchestrator did it by hand with a
throwaway plan script (reports/CLEANUP-2026-11-06.md). Now it is a pass of
`umtool prune` that a cheaper model, or a timer, can run:
- `--versions` (lib/report/takeVersions.mjs): a take's version line is its
  id with digit runs folded (draft-# , final-#-v#-blurred); a letter is
  never folded (v6c and v6d, release-6u and release-6 are lines of their
  own -- the mistake caught by hand). Per line the newest BUILT take stays,
  and any take picked or pinned, rendering or a render's base, being built
  or a build's base, the manifest's, pinned in takes/prune.json, with
  operator notes on it, the --from base of a kept take, unbuilt, or refused
  by `umtool takes delete` (its words). Deletion is deleteTake, never
  forced, after asking once more for a render or a pipeline process. A
  project touched within --idle (default 3d) is skipped whole.
- `--idle-work <age>` (takePrune.mjs): in a project untouched that long
  (projectActivity: takes' builds, take.json and previews, the manifest,
  verdicts.json, a live lock as now) every policy reason but a pin is
  overridden, as `--take X --anyway` was over each take by hand. A running
  build and its base keep theirs; renders, previews, take.json and
  manifests stay as always. The prerail base was already work.
The CLI runs --versions first and the work pass after only with
--idle-work; --json carries both passes and the free bytes before/after.

`umtool takes delete` has no notes guard: the two huck takes the cleanup
record says notes kept were refused because the project is a link. The
version pass keeps noted takes itself, and keeps the link refusal's words.

Docs: report-video.md (an idle project, superseded takes), prune's usage
and help. Tests: the line fold, every keep reason, a notes file that does
not parse, the active skip, deletion through deleteTake, a linked project,
a render seen by the plan, the walk, --idle-work's overrides, the CLI.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/bin/umtool.mjs | 16+++++++++++-----
Mumtool/docs/report-video.md | 22++++++++++++++++++++++
Mumtool/lib/report/pruneCli.mjs | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mumtool/lib/report/takePrune.mjs | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/report/takeVersions.mjs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeVersions.test.mjs | 277+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 793 insertions(+), 36 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -105,7 +105,8 @@ // <slug>/<id>] evicts those cached windows first // 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] +// 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] // 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] @@ -1035,10 +1036,15 @@ 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 prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--idle-work 3d] [--yes] [--json]", + " takes' work files (segments, chrome frames, crossfade batches, encode chunks, the rail's prerail base):", + " 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]", + " 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", " 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 @@ -2498,6 +2498,28 @@ the prune rather than guess. 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). +- **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. + +**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. **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 @@ -4,8 +4,20 @@ // kept and why). A dry run unless --yes. The Takes page's "Free work files" // calls the same writer (pruneProject). // +// Housekeeping (2026-11-06) added two passes, which `archilyzer housekeeping` +// runs weekly over every project: +// --versions whole SUPERSEDED takes deleted (lib/report/takeVersions.mjs: +// the newest built take of each version line kept, and +// anything picked, pinned, rendering, a base, noted on, or +// refused by `umtool takes delete`), in projects idle --idle +// (default 3d); +// --idle-work D in a project idle D, the newest / picked / current takes' +// work files go too (never a running build's or its base's, +// never a takes/prune.json pin). +// // umtool prune <project> [--take X …] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json] // umtool prune --all [--keep N] [--older-than 3d] [--yes] [--json] +// umtool prune <project> | --all --versions [--idle 3d] [--idle-work 3d] [--yes] [--json] // // Plain ESM: the CLI runs it with bare node. import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; @@ -20,23 +32,37 @@ import { } 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]", + "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]", "", "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).", + "copies, work-from-*, the rail's <slug>.prerail*.mp4 base -- 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).", + "", + "--idle-work D: in a project nothing has touched for D (every take's build, take.json and preview,", + "the project's manifest, takes/verdicts.json), the newest, picked and current takes' work goes too", + "-- never a running build's or its base's, never a pin in takes/prune.json.", + "", + "--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.", ].join("\n"); class CliError extends Error {} function parse(args) { - const valued = new Set(["--take", "--keep", "--older-than"]); + const valued = new Set(["--take", "--keep", "--older-than", "--idle", "--idle-work"]); /** @type {Record<string, string[]>} */ const flags = {}; const positional = []; @@ -120,36 +146,81 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con 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 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("--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]]) { + if (v === undefined || v === null) continue; + try { + parseAge(v); + } catch (e) { + throw new CliError(`${flag}: ${e instanceof Error ? e.message : e}`); + } + } 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 }; + const common = { reportsRoot, flags, ...(idleWork !== null ? { idleWorkDays: idleWork } : {}), ...deps }; + const project = all ? null : await pickProject(p.positional[0], reportsRoot); + const freeBefore = await freeBytesAt(reportsRoot); - /** @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" }) }]; + // Pass 1, --versions: whole superseded takes. + 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 }); } - 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); + // Pass 2, the work files: always without --versions; with it, only when --idle-work asks. + /** @type {{ project: { id: string, dir: string }, plan?: any, pruned?: any[], removed?: string[], failed?: any[], freedBytes?: number, error?: string }[] | null} */ + let results = null; + if (!versions || idleWork !== null) { + if (all) { + results = (await pruneAllProjects({ ...common, dryRun: !apply, by: "cli", measure: apply ? "prunable" : "all" })).results; + } else { + const one = /** @type {{ id: string, dir: string }} */ (project); + const opts = { ...common, takes: takes.length ? takes : null, anyway: p.has("--anyway"), by: "cli" }; + results = [apply ? { project: one, ...(await pruneProject(one, opts)) } : { project: one, plan: await planPrune(one, { ...opts, measure: "all" }) }]; + } + } + + 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 }))); + 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); 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 } : {}) }, - ), + ...(vr + ? { + versions: { + idleDays: vr.idleDays, + 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 } : {}) })), + }, + } + : {}), + ...(results + ? { + 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 } : {}) }, + ), + } + : {}), + workFreedBytes: workFreed, + versionsFreedBytes: versionsFreed, freedBytes: freed, + freeBytesBefore: freeBefore, freeBytes: free, }, null, @@ -157,7 +228,26 @@ export async function pruneCommand(args, { reportsRoot = REPORTS_ROOT, log = con ), ); } else { - for (const r of results) { + if (vr) { + const { versionLines } = await import("./takeVersions.mjs"); + for (const r of vr.results) { + if (r.error) { + err(`${r.project.id}: ${r.error}`); + continue; + } + if (all && !r.plan.skipped && r.plan.totals.delete === 0) continue; + for (const line of versionLines(r.plan, { compact: all, applied: apply ? r : null })) log(line); + log(""); + } + 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`, + ); + if (results) log(""); + } + for (const r of results ?? []) { if (r.error) { err(`${r.project.id}: ${r.error}`); continue; @@ -167,13 +257,13 @@ 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 failed) err(`not removed: ${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}`); 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; + return failed.length || errors.length || vFailed.length ? 1 : 0; } catch (e) { if (e instanceof CliError) { err(e.message); diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -58,6 +58,16 @@ // `--anyway` (the UI's "free anyway") overrides the reasons that are policy, // never the two that are a running build. // +// AN IDLE PROJECT (`--idle-work <age>`, housekeeping, 2026-11-06). A project +// nothing has touched for that long (projectActivity: every take's builtAt, +// take.json and preview, the project's manifest and takes/verdicts.json, a live +// build lock) is not being worked on, so the newest, picked and current takes' +// work goes too -- what the 6 Nov cleanup did by hand with `--take X --anyway` +// over every take. Overridden as `--anyway` is: never a running build or the +// take one builds from, and never a pin in takes/prune.json (a pin is a person +// saying "keep this take's work"). The renders, preview.mp4, take.json and the +// manifests stay, as always. +// // 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 @@ -587,12 +597,15 @@ async function readTakeDirs(projectDir, { host, alive }) { * @param {{ * policy?: ReturnType<typeof resolvePolicy>, flags?: { keep?: unknown, olderThan?: unknown }, env?: NodeJS.ProcessEnv, * takes?: string[] | null, anyway?: boolean, protect?: string[], measure?: "all" | "prunable" | "none", + * idleWorkDays?: number | string | null, * 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. + * their policy reasons are overridden; `protect`: kept as just built; + * `idleWorkDays`: a project idle that long has every policy reason but a pin + * overridden (the top of the file, "An idle project"). */ export async function planPrune(project, opts = {}) { const now = (opts.now ?? (() => new Date()))().getTime(); @@ -681,6 +694,16 @@ export async function planPrune(project, opts = {}) { } } + // An idle project: its newest, picked and current takes' work goes too. + let idle = null; + if (opts.idleWorkDays !== undefined && opts.idleWorkDays !== null) { + const days = parseAge(opts.idleWorkDays); + const act = await projectActivity(project.dir, { now: () => new Date(now), host, alive, dirs }); + const isIdle = act.ms > 0 && now - act.ms >= days * DAY_MS; + idle = { days, idle: isIdle, lastActivityAt: act.at, lastActivity: act.what }; + if (isIdle) notes.push(`idle ${agoWords(now - act.ms)} (since ${act.what}; --idle-work ${policyAge(days)}): every take's work goes but a running build's, its base's and a pin's`); + } + const named = opts.takes ? new Set(opts.takes) : null; const measure = opts.measure ?? "all"; /** @type {TakePlan[]} */ @@ -694,6 +717,9 @@ export async function planPrune(project, opts = {}) { if (named && opts.anyway) { 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 work = d.link ? { roots: [], notes: [] } : await workPathsOf(d.dir, roots); const status = work.roots.length === 0 ? "no-work" : keep.length ? "kept" : "prunable"; @@ -736,6 +762,7 @@ export async function planPrune(project, opts = {}) { project: { id: project.id, dir: project.dir }, policy, at: new Date(now).toISOString(), + ...(idle ? { idle } : {}), takes, // Bytes over several takes count each inode once (`du` of them together). totals: { @@ -750,6 +777,36 @@ export async function planPrune(project, opts = {}) { }; } +/** + * 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. + * + * @param {string} projectDir + * @param {{ now?: () => Date, host?: string, alive?: (pid: number) => boolean, dirs?: Awaited<ReturnType<typeof readTakeDirs>> }} [opts] + * @returns {Promise<{ ms: number, at: string | null, what: string | null }>} + */ +export async function projectActivity(projectDir, opts = {}) { + const now = (opts.now ?? (() => new Date()))().getTime(); + const dirs = opts.dirs ?? (await readTakeDirs(projectDir, { host: opts.host ?? os.hostname(), alive: opts.alive ?? pidAlive })); + let best = { ms: 0, what: /** @type {string | null} */ (null) }; + const see = (ms, what) => { + if (ms > best.ms) best = { ms, what }; + }; + 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}`); + } + 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)"); + return { ms: best.ms, at: best.ms ? new Date(best.ms).toISOString() : null, what: best.what }; +} + +const DAY_MS = 24 * 3600 * 1000; +/** An age for a person: `5 h`, `3.2 d`. */ +export const agoWords = (ms) => (ms < 48 * 3600000 ? `${Math.max(0, Math.round(ms / 3600000))} h` : `${(ms / DAY_MS).toFixed(1)} d`); + 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`); diff --git a/umtool/lib/report/takeVersions.mjs b/umtool/lib/report/takeVersions.mjs @@ -0,0 +1,305 @@ +// 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 (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`); +// - 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/<id>/), 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. +// 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 { takesDirOf } from "./takes.mjs"; + +export const DEFAULT_IDLE_DAYS = 3; +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, "#"); +} + +/** + * 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/<id>/`. 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<Map<string, { total: number, open: number }> | 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<string, unknown>} */ (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, 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>} + */ +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 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 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 }; + } + + 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<string, Reason[]>} */ + 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((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}`); + 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)`); + 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<string, { bytes: number, files: number }>} */ + 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((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")) || a.id.localeCompare(b.id)); + 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<typeof planVersions>[1]} [opts] + */ +export async function pruneVersions(project, opts = {}) { + const plan = await planVersions(project, opts); + const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT }; + const deleted = []; + const failed = []; + 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 } : {}) }); + 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` }); + 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, 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<typeof planVersions>[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 { walkProjects } = await import("../projects/walk.mjs"); + refs = await walkProjects(reportsRoot); + } + 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: [], 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 }); + } + } + const plans = results.filter((r) => r.plan).map((r) => r.plan); + return { + dryRun: !!opts.dryRun, + idleDays: parseAge(opts.idleDays ?? DEFAULT_IDLE_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), + 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?.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 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 @@ -0,0 +1,277 @@ +// Superseded takes (takeVersions.mjs) and the idle project's work files +// (takePrune.mjs --idle-work): the version line (digits fold, letters never), +// every keep reason, the active-project skip, deletion through deleteTake, and +// `umtool prune --versions` / `--idle-work`. Every project is a temp directory. +// +// 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 { tmpdir } from "node:os"; +import path from "node:path"; +import test, { after } from "node:test"; + +import { planVersions, pruneVersions, pruneVersionsAll, takesWithNotes, versionLine } from "./takeVersions.mjs"; +import { BUILD_LOCK, planPrune, projectActivity, pruneProject } from "./takePrune.mjs"; +import { pruneCommand } from "./pruneCli.mjs"; + +const DAY = 24 * 3600 * 1000; +const KiB = 1024; +// Everything below is dated 2026-10-01..10; this clock is a month on. +const NOW = new Date("2026-11-06T12:00:00Z"); +const now = () => NOW; +const OLD = new Date("2026-10-01T00:00:00Z"); +const quiet = { processes: [], alive: (pid) => pid === process.pid, now }; + +const made = []; +after(() => Promise.all(made.map((d) => rm(d, { recursive: true, force: true })))); + +async function root() { + const r = await mkdtemp(path.join(tmpdir(), "takeversions-")); + 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"); + await age(path.join(dir, "video.manifest.json")); + return { r, reports, dir, project: { id: "proj", dir }, opts: { reportsRoot: reports, mediaRoot: reports, ...quiet } }; +} + +const age = (p, when = OLD) => utimes(p, when, when); +const exists = (p) => lstat(p).then(() => true, () => false); + +/** A built take, its files dated `when`, with a little work in out/. */ +async function mkTake(dir, id, { builtAt = "2026-10-01T00:00:00Z", from, when = OLD, built = true } = {}) { + const t = path.join(dir, "takes", id); + const v = path.join(t, "out", "sourced"); + await mkdir(path.join(v, "segments"), { recursive: true }); + const doc = { id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", ...(built ? { builtAt } : {}), ...(from ? { from } : {}) }; + await writeFile(path.join(t, "take.json"), JSON.stringify(doc) + "\n"); + 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); + return t; +} + +const verdicts = (dir, rows) => writeFile(path.join(dir, "takes", "verdicts.json"), JSON.stringify(rows) + "\n").then(() => age(path.join(dir, "takes", "verdicts.json"))); + +const take = (plan, id) => plan.lines.flatMap((l) => l.takes).find((t) => t.id === id); +const codes = (plan, id) => take(plan, id).keep.map((r) => r.code).sort(); + +test("a version line folds digit runs and never a letter", () => { + assert.equal(versionLine("draft-3"), "draft-#"); + assert.equal(versionLine("draft-3"), versionLine("draft-12")); + assert.equal(versionLine("final-1027-v6-blurred"), "final-#-v#-blurred"); + assert.equal(versionLine("final-1027-v6-blurred"), versionLine("final-1104-v7-blurred")); + // Alternatives the operator chose between, and an uncensored twin: each its own line + // (the 6 Nov cleanup caught folding these by hand). + assert.notEqual(versionLine("final-1027-v6c-blurred"), versionLine("final-1027-v6d-blurred")); + assert.notEqual(versionLine("v6c"), versionLine("v6d")); + assert.notEqual(versionLine("release-6u"), versionLine("release-6")); + assert.notEqual(versionLine("short-19-uncensored"), versionLine("short-19")); +}); + +test("only the newest built take of each line goes on; letter lines and twins are their own", 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-10-02T00:00:00Z" }); + await mkTake(dir, "draft-10", { builtAt: "2026-10-03T00:00:00Z" }); + await mkTake(dir, "v6c", { builtAt: "2026-10-01T00:00:00Z" }); + await mkTake(dir, "v6d", { builtAt: "2026-10-02T00:00:00Z" }); + await mkTake(dir, "release-6", { builtAt: "2026-10-01T00:00:00Z" }); + await mkTake(dir, "release-6u", { builtAt: "2026-10-02T00:00:00Z" }); + await mkTake(dir, "release-7", { builtAt: "2026-10-04T00:00:00Z" }); + const plan = await planVersions(project, opts); + assert.equal(plan.skipped, null); + const del = plan.lines.flatMap((l) => l.takes).filter((t) => t.action === "delete").map((t) => t.id).sort(); + assert.deepEqual(del, ["draft-1", "draft-2", "release-6"]); + assert.deepEqual(codes(plan, "draft-10"), ["newest"]); + assert.deepEqual(codes(plan, "v6c"), ["newest"]); + assert.deepEqual(codes(plan, "v6d"), ["newest"]); + assert.deepEqual(codes(plan, "release-6u"), ["newest"]); + assert.ok(take(plan, "draft-1").bytes > 0, "a delete is measured"); + assert.equal(plan.totals.delete, 3); +}); + +test("every keep reason: picked, notes, a --from base, rendering, the manifest's take, a prune.json pin, unbuilt", async () => { + const { dir, project, opts } = await root(); + for (let i = 1; i <= 9; i += 1) await mkTake(dir, `draft-${i}`, { builtAt: `2026-10-0${i}T00:00:00Z`, ...(i === 9 ? { from: "draft-3" } : {}) }); + await mkTake(dir, "draft-20", { built: false }); + await verdicts(dir, { "draft-1": { verdict: null, note: "", at: "2026-10-01T00:00:00Z", picked: true } }); + // An operator note on draft-2 (resolved: still a note on it), and a moment on draft-4's preview. + const note = (id, anchor, status = "open") => ({ id, status, author: "operator", text: "t", at: "2026-10-01T00:00:00Z", updatedAt: "2026-10-01T00:00:00Z", anchor, replies: [] }); + await writeFile( + path.join(dir, "notes.json"), + JSON.stringify({ + format: "umtool-notes", + version: 1, + subject: { kind: "video-project", project: "proj" }, + notes: [note("n_aaaa1", { kind: "take", take: "draft-2" }, "resolved"), note("n_aaaa2", { kind: "moment", file: "takes/draft-4/preview.mp4", t: 3 })], + }), + ); + // draft-5 renders now (a live lock: this process). + await writeFile(path.join(dir, "takes", "draft-5", BUILD_LOCK), JSON.stringify({ pid: process.pid, startedAt: "2026-10-05T00:00:00Z" })); + // draft-6 is the project's manifest. + await writeFile(path.join(dir, "video.manifest.json"), await readFile(path.join(dir, "takes", "draft-6", "video.manifest.json"), "utf8")); + 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"] })); + + 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. + const plan = await planVersions(project, { ...opts, idleDays: 0 }); + assert.deepEqual(codes(plan, "draft-1"), ["picked"]); + assert.deepEqual(codes(plan, "draft-2"), ["notes"]); + assert.match(take(plan, "draft-2").keep[0].why, /1 operator note on it/); + assert.deepEqual(codes(plan, "draft-3"), ["base"]); + assert.deepEqual(codes(plan, "draft-4"), ["notes"]); + assert.ok(codes(plan, "draft-5").includes("rendering") && codes(plan, "draft-5").includes("building")); + assert.deepEqual(codes(plan, "draft-6").filter((c) => c !== "refused"), ["current"]); + assert.deepEqual(codes(plan, "draft-7"), ["pinned"]); + assert.equal(take(plan, "draft-8").action, "delete"); + assert.deepEqual(codes(plan, "draft-9"), ["newest"]); + assert.deepEqual(codes(plan, "draft-20"), ["not-built"]); + assert.deepEqual(plan.lines.flatMap((l) => l.takes).filter((t) => t.action === "delete").map((t) => t.id), ["draft-8"]); +}); + +test("a notes.json that does not parse keeps every take", 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, "notes.json"), "{ not json"); + const plan = await planVersions(project, opts); + assert.equal(plan.totals.delete, 0); + assert.deepEqual(codes(plan, "draft-1"), ["notes"]); +}); + +test("an active project is skipped whole, and --yes deletes nothing in it", async () => { + const { dir, project, opts } = await root(); + await mkTake(dir, "draft-1"); + await mkTake(dir, "draft-2", { builtAt: "2026-11-05T12:00:00Z", when: new Date("2026-11-05T12:00:00Z") }); + const act = await projectActivity(dir, { now }); + assert.equal(act.what, "take draft-2"); + const plan = await planVersions(project, opts); + assert.match(plan.skipped ?? "", /active: take draft-2 modified 24 h ago/); + 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); +}); + +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" } }); + 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/); +}); + +test("a project reached through a link: `umtool takes delete` refuses, so the take is kept with its words", async () => { + const { reports, dir, opts } = await root(); + await mkTake(dir, "draft-1"); + await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" }); + await mkdir(path.join(reports, "folder")); + await symlink(dir, path.join(reports, "folder", "linked")); + const plan = await planVersions({ id: "folder/linked", dir: path.join(reports, "folder", "linked") }, opts); + assert.deepEqual(codes(plan, "draft-1"), ["refused"]); + assert.match(take(plan, "draft-1").keep[0].why, /umtool takes delete refuses: .* is a link/); +}); + +test("a take a render starts in after the plan is kept", async () => { + const { dir, project, opts } = await root(); + await mkTake(dir, "draft-1"); + await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" }); + const r = await pruneVersions(project, { ...opts, processes: [{ pid: 4242, args: ["node", "build-video.mjs", path.join(dir, "takes", "draft-1", "video.manifest.json")], cwd: null }] }); + // The plan already sees the process (planPrune's "building"): kept, never planned to go. + assert.equal(r.deleted.length, 0); + assert.ok(await exists(path.join(dir, "takes", "draft-1"))); +}); + +test("pruneVersionsAll walks the projects and totals them", async () => { + const { reports, dir, opts } = await root(); + await mkTake(dir, "draft-1"); + await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" }); + const other = path.join(reports, "folder", "other"); + await mkdir(path.join(other, "takes"), { recursive: true }); + await writeFile(path.join(other, "video.manifest.json"), "{}\n"); + await mkTake(other, "cut-1", { when: new Date("2026-11-06T06:00:00Z") }); + const r = await pruneVersionsAll({ ...opts, dryRun: true }); + assert.equal(r.totals.projects, 2); + assert.equal(r.totals.skipped, 1); + assert.equal(r.totals.delete, 1); + assert.equal(r.totals.deleted, 0); +}); + +test("--idle-work: an idle project's newest and picked takes' work goes; a pin, a running build and its base stay", async () => { + const { dir, project, opts } = 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 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"] })); + // 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), []); + const idle = await planPrune(project, { ...opts, measure: "none", idleWorkDays: "3d" }); + assert.equal(idle.idle.idle, true); + assert.deepEqual(idle.takes.filter((t) => t.status === "prunable").map((t) => t.id), ["b", "c", "d"]); + assert.deepEqual(idle.takes.find((t) => t.id === "a").keep.map((r) => r.code), ["pinned"]); + assert.ok(idle.notes.some((n) => /^idle /.test(n))); + // 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" })); + 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. + const forced = await planPrune(project, { ...opts, measure: "none", idleWorkDays: 0 }); + assert.deepEqual(forced.takes.find((t) => t.id === "c").keep.map((r) => r.code), ["base-of-building"]); + assert.ok(forced.takes.find((t) => t.id === "e").keep.some((r) => r.code === "building")); + // The renders and the preview stay when the work goes. + await rm(path.join(dir, "takes", "e", BUILD_LOCK)); + const r = await pruneProject(project, { ...opts, idleWorkDays: "3d" }); + assert.ok(r.pruned.some((p) => p.id === "d")); + assert.equal(await exists(path.join(dir, "takes", "d", "out", "sourced", "segments", "s01.mp4")), false); + assert.ok(await exists(path.join(dir, "takes", "d", "preview.mp4"))); + assert.ok(await exists(path.join(dir, "takes", "a", "out", "sourced", "segments", "s01.mp4")), "a pin keeps its work"); +}); + +test("umtool prune --versions: a dry run says, --yes deletes, --json carries both passes", async () => { + const { reports, dir, opts } = await root(); + await mkTake(dir, "draft-1"); + await mkTake(dir, "draft-2", { builtAt: "2026-10-02T00:00:00Z" }); + const out = []; + const errs = []; + const io = { reportsRoot: reports, log: (s) => out.push(s), err: (s) => errs.push(s), deps: { processes: [], alive: opts.alive, now } }; + assert.equal(await pruneCommand(["--all", "--versions"], io), 0); + assert.ok(out.some((l) => /draft-1 +delete/.test(l)), out.join("\n")); + assert.ok(out.some((l) => /superseded takes: 1 to delete/.test(l))); + assert.ok(await exists(path.join(dir, "takes", "draft-1"))); + + out.length = 0; + assert.equal(await pruneCommand(["--all", "--versions", "--idle-work", "3d", "--json"], io), 0); + const j = JSON.parse(out.join("\n")); + assert.equal(j.dryRun, true); + assert.equal(j.versions.totals.delete, 1); + assert.ok(Array.isArray(j.projects), "the work pass ran too"); + assert.ok(j.freedBytes >= j.versionsFreedBytes && j.versionsFreedBytes > 0); + + out.length = 0; + assert.equal(await pruneCommand(["proj", "--versions", "--yes", "--json"], io), 0); + const y = JSON.parse(out.join("\n")); + assert.equal(y.projects, undefined, "--versions alone is the only pass"); + assert.deepEqual(y.versions.projects[0].deleted.map((d) => d.id), ["draft-1"]); + assert.equal(await exists(path.join(dir, "takes", "draft-1")), false); + + errs.length = 0; + assert.equal(await pruneCommand(["--all", "--idle", "3d"], io), 2); + assert.match(errs.join("\n"), /--idle is --versions'/); + assert.equal(await pruneCommand(["proj", "--versions", "--take", "draft-2"], io), 2); + assert.equal(await pruneCommand(["--all", "--versions", "--idle", "soon"], io), 2); +});