commit 72933ac42fbf28f2ce0ac101da7845d906786b76
parent f2e4c7f7337b0068d37178b53363105ee02b6281
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 17:10:46 -0500
umtool: saved versions freeze -- takes save/open/freeze, the draft's parent (L3 S1)
A take saved from the working draft is FROZEN now: `umtool takes save` copies
video.manifest.json byte for byte to takes/v<N>/base.manifest.json (take.json
`version: true`, patch null, window full) and names it the draft's parent in
takes/draft.json {from, hash, at}. resolveTakeManifest and composeTake lay a
version over its base, never over the draft as it is now; a legacy take (no
base) resolves exactly as it did. cachedTakeManifest keys on the base too.
- versions.mjs: saveVersion, openVersion (the draft saved first when it has
edits since its parent, one undo point every time, the parent restored by
Undo through a snapshot sidecar), freezeTakes (opt-in, dry run by default,
each take's difference from today said), nextVersionId (v1, v2, ... above
every v<N> directory).
- readWorkingCut: the parent is draft.json's `from`, else the newest working
take; edits counted by cutDiff (a hash only short-cuts 0). A working take
rendered from the draft becomes its parent.
- pickTake uses an unrendered version's base; a rendered version stays a
version; isWorkingTake admits versions.
- Snapshots in one second get the milliseconds (and a counter), never "wait a
second"; the manifest lock is exported for one-hold writers.
- CLI: umtool takes save | open | freeze, each with --json (cli.md row).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
14 files changed, 967 insertions(+), 85 deletions(-)
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -14,7 +14,6 @@ import TakesBench, { type Take, type TakeVerdict } from "./TakesBench";
import { LatestLine } from "./review/WhatPlays";
import { readWorkingCut } from "@/lib/report/workingCut.mjs";
import PlayLink from "./PlayLink";
-import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
import { readCancelled, takeWorkDirs } from "@/lib/report/takeCancel.mjs";
import { variantFamily } from "@/lib/report/variantFork.mjs";
import { REPORTS_ROOT } from "@/lib/paths.mjs";
@@ -50,7 +49,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
// What a running render names (take housekeeping): the card says so, and relabel/delete refuse.
const holds = new Map(await Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await renderHolds(project.dir, t.id)] as const)));
// The working cut's name: the latest whole-cut take and the edits since it (lib/report/workingCut.mjs).
- const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null);
+ const working = await readWorkingCut(project.dir, { manifestText }).catch(() => null);
// Cancel, fork, compare (UI notes item 19): first renders in progress or cancelled, each take's
// last-render-cancelled mark, and every take of the project and its variants (variantFork.mjs).
// Every render records itself (lib/report/renderRecord.mjs), and the queue holds what waits to run (lib/queue/).
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -70,6 +70,7 @@ Inbox cannot disagree about what is wrong with one.
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) |
| `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
+| `takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \| --all] [--apply] [--json]` | **the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions)) |
| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) |
diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts
@@ -16,7 +16,6 @@ import { gapWalls } from "umtool-report-to-video/gaps";
import { deckOn } from "umtool-report-to-video/deck";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import { readWorkingCut } from "@/lib/report/workingCut.mjs";
-import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
import type { ProjectRef } from "@/lib/project-types";
// THE CLIP BENCH'S DATA, in one place: what `/projects/<p>/clip/<id>` renders
@@ -275,7 +274,7 @@ export async function clipBenchData(
// The working cut's name: the bench edits the project's manifest, the latest take is what it was made into.
data.working = take
? null
- : await readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null);
+ : await readWorkingCut(project.dir).catch(() => null);
const top: BenchTopSpec = {
trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }],
back: { href: back, label: take ? `take ${take}` : project.name },
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -21,7 +21,7 @@
// a silent overwrite -- somebody may have run `resolve-windows --write` in
// between, and losing that is losing human judgement.
import { statSync } from "node:fs";
-import { copyFile, readFile, rename, stat, writeFile } from "node:fs/promises";
+import { copyFile, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import {
POPULATIONS,
@@ -118,7 +118,7 @@ let queue = Promise.resolve();
* @param {() => Promise<T>} fn
* @returns {Promise<T>}
*/
-function withManifestLock(fn) {
+export function withManifestLock(fn) {
const run = queue.then(fn, fn);
queue = run.then(
() => undefined,
@@ -4605,16 +4605,28 @@ export async function updateVariants(dir, variants, { token = null } = {}) {
* @param {{ token?: string | null, op?: string }} [opts]
*/
export async function replaceManifest(dir, manifest, { token = null, op = "replace" } = {}) {
+ return withManifestLock(() => replaceManifestLocked(dir, manifest, { token, op }));
+}
+
+/**
+ * replaceManifest's body, for a caller that ALREADY holds the manifest lock
+ * (withManifestLock; versions.mjs openVersion saves the draft and opens a
+ * version in one hold). `every`: the undo point's throttle (autoSnapshot);
+ * 0 takes one whatever was taken before.
+ *
+ * @param {string} dir
+ * @param {Record<string, unknown>} manifest
+ * @param {{ token?: string | null, op?: string, every?: number }} [opts]
+ */
+export async function replaceManifestLocked(dir, manifest, { token = null, op = "replace", every = undefined } = {}) {
if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw new Error("a manifest is an object");
if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`);
- return withManifestLock(async () => {
- const current = await manifestToken(dir);
- if (token !== null && current !== token) throw new StaleToken(token, current);
- const next = JSON.parse(JSON.stringify(manifest));
- const snapshot = await autoSnapshot(dir, op);
- const nextToken = await writeManifestAtomic(dir, next);
- return { snapshot, token: nextToken };
- });
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const next = JSON.parse(JSON.stringify(manifest));
+ const snapshot = await autoSnapshot(dir, op, every === undefined ? {} : { every });
+ const nextToken = await writeManifestAtomic(dir, next);
+ return { snapshot, token: nextToken };
}
/**
@@ -4680,6 +4692,24 @@ export async function undoStructural(dir, { token = null } = {}) {
await rename(tmp, file);
const undone = target.rel.replace(`-${target.label}.manifest.json`, `-undone-${op}.manifest.json`);
await rename(path.join(dir, target.rel), path.join(dir, undone)).catch(() => {});
- return { restored: target.rel, op, saved, token: await manifestToken(dir) };
+ // An undo point that carries the DRAFT POINTER as it was (versions.mjs openVersion: `<snapshot>.draft.json`):
+ // the draft's parent goes back with the manifest, so "Undo open v1" leaves the draft named as it was.
+ const sidecar = path.join(dir, target.rel.replace(/\.manifest\.json$/, ".draft.json"));
+ const side = await readFile(sidecar, "utf8").then((t) => JSON.parse(t), () => undefined);
+ let draft = undefined;
+ if (side !== undefined) {
+ const draftFile = path.join(dir, "takes", "draft.json");
+ if (side && typeof side === "object" && typeof side.from === "string" && side.from) {
+ const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmpD, JSON.stringify(side, null, 2) + "\n", "utf8");
+ await rename(tmpD, draftFile);
+ draft = side;
+ } else {
+ await rm(draftFile, { force: true });
+ draft = null;
+ }
+ await rename(sidecar, path.join(dir, undone.replace(/\.manifest\.json$/, ".draft.json"))).catch(() => {});
+ }
+ return { restored: target.rel, op, saved, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) };
});
}
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -139,9 +139,7 @@ export async function playView(project, { take = null, bare = false } = {}) {
export async function playViewWith(project, { take = null, bare = false, postFor = null } = {}) {
const base = await readManifest(project.dir);
if (!base) return { error: "this project has no video.manifest.json" };
- const working = await readWorkingCut(project.dir, {
- resolveNow: async (id) => (await resolveTakeManifest(project.dir, id, { base })).manifest,
- }).catch(() => null);
+ const working = await readWorkingCut(project.dir).catch(() => null);
const defaulted = !take && !bare && !!working?.latest;
if (defaulted) take = working.latest.id;
let manifest = base;
diff --git a/umtool/lib/report/snapshots.mjs b/umtool/lib/report/snapshots.mjs
@@ -9,6 +9,7 @@
// unlabelled snapshots. Reported, never renamed, never guessed at.
//
// Plain ESM: `umtool snapshot` and `umtool diff` run from a terminal.
+import { constants as fsConstants } from "node:fs";
import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { MANIFEST_NAME } from "../projects/report.mjs";
@@ -23,9 +24,15 @@ export function stampOf(d = new Date()) {
const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
-/** A snapshot's file name, or null when the name is not one. */
+/**
+ * A snapshot's file name, or null when the name is not one. The stamp is the
+ * second (`20260825-143012`), and -- when another snapshot already took that
+ * second -- its milliseconds and a counter after a dot (`20260825-143012.457`,
+ * `20260825-143012.457.2`): two undo points in one second are two files, never
+ * one lost (createSnapshot).
+ */
export function parseSnapshotName(name) {
- const m = name.match(/^(\d{8}-\d{6})(?:-(.+))?\.manifest\.json$/);
+ const m = name.match(/^(\d{8}-\d{6}(?:\.\d{3}(?:\.\d+)?)?)(?:-(.+))?\.manifest\.json$/);
if (!m) return null;
return { stamp: m[1], label: m[2] ?? null };
}
@@ -68,7 +75,8 @@ export async function listSnapshots(dir) {
if (!st?.isFile()) continue;
out.push({ rel: name, name, stamp: null, label: p.label, legacy: true, mtimeMs: st.mtimeMs, size: st.size });
}
- return out.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name));
+ // Newest first; two in the same instant by their stamp (the later name is the later snapshot).
+ return out.sort((a, b) => b.mtimeMs - a.mtimeMs || (b.stamp ?? "").localeCompare(a.stamp ?? "", "en", { numeric: true }) || a.name.localeCompare(b.name));
}
/** Resolve a project-relative snapshot name to a path, refusing anything else. */
@@ -95,10 +103,20 @@ export async function createSnapshot(dir, { label = null, now = new Date() } = {
const src = path.join(dir, MANIFEST_NAME);
if (!(await stat(src).then((s) => s.isFile(), () => false))) throw new Error(`no ${MANIFEST_NAME} in ${dir}`);
await mkdir(path.join(dir, REVISIONS_DIR), { recursive: true });
- const name = `${stampOf(now)}${label ? `-${label}` : ""}.manifest.json`;
+ // A second another snapshot already took: its milliseconds, then a counter (parseSnapshotName).
+ const taken = new Set(await readdir(path.join(dir, REVISIONS_DIR)).catch(() => []));
+ const tail = `${label ? `-${label}` : ""}.manifest.json`;
+ const sec = stampOf(now);
+ const secTaken = [...taken].some((n) => parseSnapshotName(n)?.stamp.slice(0, 15) === sec);
+ let stamp = sec;
+ if (secTaken) {
+ const ms = `${sec}.${String(now.getMilliseconds()).padStart(3, "0")}`;
+ stamp = ms;
+ for (let n = 2; taken.has(`${stamp}${tail}`) || [...taken].some((x) => parseSnapshotName(x)?.stamp === stamp); n += 1) stamp = `${ms}.${n}`;
+ }
+ const name = `${stamp}${tail}`;
const dst = path.join(dir, REVISIONS_DIR, name);
- if (await stat(dst).then(() => true, () => false)) throw new Error(`${name} already exists — wait a second`);
- await copyFile(src, dst);
+ await copyFile(src, dst, fsConstants.COPYFILE_EXCL);
return { rel: path.posix.join(REVISIONS_DIR, name), name };
}
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -15,6 +15,7 @@
// umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force]
// umtool takes styles [--json]
// umtool takes pick <project> <take> [--anyway] [--json]
+// umtool takes save <project> [--label L] · open <project> <take> · freeze <project> [<take>…|--all] [--apply]
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
@@ -127,6 +128,14 @@ export const TAKES_USAGE = [
" parent's fetched media linked, and the take itself (its preview hard-linked)",
" umtool takes compare <project> <a> <b> [--json] two takes side by side: <take> of this project or",
" <project>:<take> (a variant's): the facts, the cut's changes A → B, the look's differences",
+ " umtool takes save <project> [--label L] [--force] [--json] the working draft (video.manifest.json) saved",
+ " as the next version v<N>, frozen (takes/v<N>/base.manifest.json); nothing when it has no edits",
+ " since its parent unless --force; the pick is never touched",
+ " umtool takes open <project> <take> [--json] that version copied into the draft: the draft saved first as",
+ " the next v<N> when it has edits since its parent; one undo point (`umtool timeline <p> undo`)",
+ " umtool takes freeze <project> [<take>… | --all] [--apply] [--json] legacy takes given a frozen base (the",
+ " manifest each was rendered from, else the draft now): a dry run unless --apply, each take's",
+ " difference from how it resolves today said",
].join("\n");
class CliError extends Error {}
@@ -451,6 +460,64 @@ async function importItems(project, id, p, { reportsRoot, log, err }) {
}
}
+/**
+ * `umtool takes save|open|freeze` (versions.mjs): the working draft and its saved versions.
+ * EXIT 0 done (or nothing to do) · 1 refused · 2 usage.
+ */
+async function versionsCommand(sub, rest, p, { reportsRoot, log, err }) {
+ const project = await pickProject(rest[0], reportsRoot);
+ const v = await import("./versions.mjs");
+ const json = p.has("--json");
+ try {
+ if (sub === "save") {
+ if (rest.length > 1) throw new CliError("umtool takes save <project> [--label L] [--force]: the label is --label");
+ const r = await v.saveVersion(project, { label: p.one("--label") ?? null, force: p.has("--force") });
+ if (json) log(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2));
+ else if (!r.saved) log(`${project.id}: ${r.why} (--force saves it all the same)`);
+ else log(`${project.id}: the draft saved as ${r.id} — "${r.label}"${r.parent ? ` (from ${r.parent}${r.edits ? `, ${r.edits.count} edit${r.edits.count === 1 ? "" : "s"}` : ""})` : ""}; frozen in takes/${r.id}/base.manifest.json`);
+ return 0;
+ }
+ if (sub === "open") {
+ const take = rest[1];
+ if (!take) throw new CliError("which version? `umtool takes open <project> <take>`");
+ const r = await v.openVersion(project, take);
+ if (json) log(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2));
+ else if (r.unchanged) log(`${project.id}: the draft is ${take} already (no edits since) — nothing written`);
+ else {
+ if (r.saved) log(`${project.id}: the draft (${r.edits ?? "?"} edit${r.edits === 1 ? "" : "s"}) saved first as ${r.saved}`);
+ log(`${project.id}: ${take} opened in the draft (${r.how === "frozen" ? "its frozen manifest" : r.how === "rendered" ? "the manifest it was rendered from" : "its patch over the draft"})${r.snapshot?.rel ? `; undo: umtool timeline ${project.id} undo (${r.snapshot.rel})` : ""}`);
+ }
+ return 0;
+ }
+ // freeze
+ const ids = rest.slice(1);
+ if (!ids.length && !p.has("--all")) throw new CliError("which takes? `umtool takes freeze <project> <take>… | --all [--apply]`");
+ if (ids.length && p.has("--all")) throw new CliError("<take>… or --all, not both");
+ const r = await v.freezeTakes(project, { ids: ids.length ? ids : null, apply: p.has("--apply") });
+ if (json) log(JSON.stringify({ ok: !r.missing.length, ...r }, null, 2));
+ else {
+ for (const x of r.rows) {
+ if (x.action === "already") log(`${x.id}: frozen already`);
+ else if (x.action === "refused") err(`${x.id}: not frozen — ${x.why}`);
+ else {
+ const what = x.source === "rendered" ? "the manifest it was rendered from" : "the draft as it is now";
+ const diff = x.differs ? ` — resolves differently from today: ${x.differs} change${x.differs === 1 ? "" : "s"} (${(x.words ?? []).slice(0, 6).join("; ")}${(x.words ?? []).length > 6 ? "; …" : ""})` : " — resolves as it does today";
+ log(`${x.id}: ${x.action === "frozen" ? "frozen on" : "would freeze on"} ${what}${diff}`);
+ }
+ }
+ for (const m of r.missing) err(`${m}: no such take`);
+ if (!r.apply) log("a dry run: nothing written (--apply freezes them)");
+ }
+ return r.missing.length ? 1 : 0;
+ } catch (e) {
+ if (e instanceof v.VersionRefused) {
+ err(e.message);
+ return 1;
+ }
+ throw e;
+ }
+}
+
/** `umtool take <p> --id X --promote [--anyway]`: make the take the cut (takeEdit.mjs promoteTake). */
async function promote(project, id, p, log, err) {
const { PromoteStale, promoteTake } = await import("./takeEdit.mjs");
@@ -511,10 +578,9 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
const project = await pickProject(rest[0], reportsRoot);
const { takesOverview, takeLine } = await import("./takeHousekeeping.mjs");
const { readWorkingCut, workingCutLine } = await import("./workingCut.mjs");
- const { resolveTakeManifest } = await import("./takeManifest.mjs");
const [o, working] = await Promise.all([
takesOverview(project.dir),
- readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }),
+ readWorkingCut(project.dir),
]);
if (p.has("--json")) log(JSON.stringify({ project: project.id, working, ...o }, null, 2));
else {
@@ -631,6 +697,7 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
throw e;
}
}
+ if (sub === "save" || sub === "open" || sub === "freeze") return await versionsCommand(sub, rest, p, { reportsRoot, log, err });
if (sub === "pick") {
const project = await pickProject(rest[0], reportsRoot);
const take = rest[1];
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -58,7 +58,7 @@ import { REPORTS_ROOT } from "../paths.mjs";
import { replaceManifest } from "./manifest.mjs";
import { incorrectClips, incorrectWhy } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
-import { autoPickTake, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs";
+import { autoPickTake, frozenBaseText, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, BASE_FILE, DRAFT_FILE, TAKE_FILE, TAKE_KINDS } from "./takes.mjs";
export const MANIFEST = "video.manifest.json";
export const PREVIEW = "preview.mp4";
@@ -606,7 +606,10 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
*/
export async function composeTake(projectDir, spec, opts = {}) {
const log = opts.log ?? (() => {});
- const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8");
+ // A SAVED VERSION renders its frozen manifest (takes/<id>/base.manifest.json), never the draft as it is now.
+ const frozenText = await frozenBaseText(projectDir, spec.id);
+ const baseText = frozenText ?? (await readFile(path.join(projectDir, MANIFEST), "utf8"));
+ if (frozenText !== null) log(`${spec.id}: a saved version — rendering its frozen ${BASE_FILE}, not the draft`);
const base = JSON.parse(baseText);
const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {});
let stylePatch = null;
@@ -661,7 +664,7 @@ export async function composeTake(projectDir, spec, opts = {}) {
if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`);
renderDoc = windowManifest(ruled.manifest, ids);
}
- return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered };
+ return { baseText, base, styles, manifest, changes, kind, patches, ruled, renderDoc, covered, frozen: frozenText !== null };
}
/** makeTake's body; `onTakeDir` is called once the take's directory exists, before anything is linked or rendered. */
@@ -682,7 +685,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
const fromTake = opts.from ? await import("./takeFrom.mjs") : null;
if (fromTake) await fromTake.fromTakeSourced(projectDir, spec.id, opts.from);
- const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered } = await composeTake(projectDir, spec, { styles: opts.styles, log });
+ const { baseText, styles, manifest, changes, kind, patches, renderDoc: composed, covered, frozen } = await composeTake(projectDir, spec, { styles: opts.styles, log });
let renderDoc = composed;
if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER));
// A clip ruled incorrect (the walk's verdict) still in what would render:
@@ -825,10 +828,23 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
renderSeconds,
// Which cut its post items are (post-slurs.mjs): censored, or the uncensored one (`umtool take … --uncensored`).
...(cutSlurState(manifest) ? { slurs: cutSlurState(manifest) } : {}),
+ // A SAVED VERSION rendered (versions.mjs): still that version -- its frozen base is what was rendered.
+ ...(previous?.version === true
+ ? {
+ version: true,
+ ...(typeof previous.savedAt === "string" ? { savedAt: previous.savedAt } : {}),
+ ...(typeof previous.draftedFrom === "string" && previous.draftedFrom ? { draftedFrom: previous.draftedFrom } : {}),
+ }
+ : {}),
};
const tmp = `${takeFile}.tmp-${process.pid}`;
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
await rename(tmp, takeFile);
+ // A whole-cut take of the DRAFT as it is (not a frozen version re-rendered) is the draft's parent now (versions.mjs).
+ if (!frozen && isWorkingTake(doc)) {
+ const { writeDraft } = await import("./versions.mjs");
+ await writeDraft(projectDir, { from: spec.id, hash: doc.baseHash, at: doc.builtAt }).catch(() => {});
+ }
// A whole-cut take of the manifest is its group's pick now (takes.mjs autoPickTake): mark only.
const group = ((listing ?? (await listTakes(projectDir))).takes ?? []).filter((t) => t.group === doc.group).map((t) => t.id);
const pick = await autoPickTake(projectDir, { ...doc, id: spec.id }, group).catch((e) => ({ picked: false, why: e instanceof Error ? e.message : String(e) }));
@@ -1077,6 +1093,30 @@ export async function takeIsStale(projectDir, take) {
}
/**
+ * A SAVED VERSION's manifest as the draft would hold it: its frozen base
+ * (takes/<id>/base.manifest.json) byte for byte, or -- when a style or a patch
+ * was laid over the version since (a "No intro" toggle) -- the base with them
+ * merged (RFC 7386, no preset resolved: the draft names its preset as the base
+ * did). null for a take with no frozen base.
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @returns {Promise<null | { text: string, manifest: Record<string, any>, exact: boolean }>}
+ */
+export async function versionManifestOf(projectDir, takeId) {
+ const baseText = await frozenBaseText(projectDir, takeId);
+ if (baseText === null) return null;
+ const base = JSON.parse(baseText);
+ const doc = await readJson(path.join(takesDirOf(projectDir), takeId, TAKE_FILE));
+ let stylePatch = null;
+ if (typeof doc?.style === "string" && doc.style.trim()) stylePatch = (await loadMontageStyles()).styles[doc.style.trim()]?.patch ?? null;
+ const patches = [stylePatch, isObj(doc?.patch) ? doc.patch : null].filter(Boolean);
+ if (!patches.length) return { text: baseText, manifest: base, exact: true };
+ const manifest = /** @type {Record<string, any>} */ (patches.reduce((m, p) => mergePatch(m, p), base));
+ return { text: serialise(manifest), manifest, exact: false };
+}
+
+/**
* "Use this take": the take's video.manifest.json over the project's, through
* the manifest writer (replaceManifest: the auto snapshot `auto-before-pick-take`,
* so "Undo last edit" takes it back) inside withEditNotes, then the pick in
@@ -1096,9 +1136,11 @@ export async function pickTake(project, takeId, { anyway = false, token = null,
const listing = await listTakes(project.dir);
const take = listing.takes.find((t) => t.id === takeId);
if (!take) throw new Error(`no take ${takeId}`);
+ // A SAVED VERSION (versions.mjs) is its frozen base, rendered or not: that is what a pick copies.
+ const frozen = await versionManifestOf(project.dir, takeId);
// A draft has no rendered manifest to use: "Make this the cut" (takeEdit.mjs promoteTake) applies its patch.
- if (take.draft) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`);
- const text = await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null);
+ if (take.draft && !frozen) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`);
+ const text = frozen ? frozen.text : await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null);
if (text === null) throw new Error(`take ${takeId} has no ${MANIFEST} to use`);
const manifest = JSON.parse(text);
if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${takeId}'s ${MANIFEST} is not a manifest`);
diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs
@@ -9,6 +9,11 @@
// takes/recipe.json, a take not made yet: its spec in a recipe
// takes/all-styles.recipe.json (parseRecipe's shape)
//
+// A SAVED VERSION (versions.mjs) is frozen: when takes/<id>/base.manifest.json
+// is there, the take resolves over THAT -- the draft as it was when it was
+// saved -- and never over the project's manifest as it is now. A legacy take
+// (no base) resolves exactly as it always did.
+//
// A style that is no longer installed falls back to the take's own
// takes/<id>/video.manifest.json (the manifest it was rendered from), and
// says so; a take with neither is an error. Nothing here writes but
@@ -20,7 +25,9 @@ import { resolvePresetLayers } from "umtool-report-to-video/presets";
import { readFile, stat, writeFile, rename } from "node:fs/promises";
import path from "node:path";
import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs";
-import { isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs";
+import { BASE_FILE, frozenBaseText, isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+export { frozenBaseText };
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
@@ -98,20 +105,35 @@ export async function playableTakes(projectDir) {
}
/**
- * The take's manifest: the project's manifest now + the style's patch + the
- * take's patch. Throws (an Error whose message is the reason) when the take
- * is not named anywhere or the project has no manifest.
+ * The take's manifest: its base + the style's patch + the take's patch. The
+ * base is the version's frozen manifest when it has one (`frozen`, the
+ * default), else the project's manifest now (`base`, when the caller has read
+ * it already). Throws (an Error whose message is the reason) when the take is
+ * not named anywhere or there is no manifest to lay it on.
+ *
+ * `frozen: false` lays the take over the project's manifest even when it is a
+ * frozen version: "this take's patch, over the draft as it is now" -- what
+ * the working cut's edit count compares (workingCut.mjs).
*
* @param {string} projectDir
* @param {string} id
- * @param {{ styles?: Record<string, { patch: Record<string, unknown> }> | null, base?: Record<string, unknown> | null }} [opts]
- * @returns {Promise<{ manifest: Record<string, any>, take: NonNullable<Awaited<ReturnType<typeof takeSpecOf>>>, note: string | null }>}
+ * @param {{ styles?: Record<string, { patch: Record<string, unknown> }> | null, base?: Record<string, unknown> | null, frozen?: boolean }} [opts]
+ * @returns {Promise<{ manifest: Record<string, any>, take: NonNullable<Awaited<ReturnType<typeof takeSpecOf>>>, note: string | null, frozen: boolean }>}
*/
-export async function resolveTakeManifest(projectDir, id, { styles = null, base = null } = {}) {
+export async function resolveTakeManifest(projectDir, id, { styles = null, base = null, frozen: preferFrozen = true } = {}) {
if (!isTakeId(id)) throw new Error(`"${id}" is not a take id`);
const take = await takeSpecOf(projectDir, id);
if (!take) throw new Error(`no take ${id} (no takes/${id}/${TAKE_FILE}, and no recipe names it)`);
- const project = base ?? (await readJson(path.join(projectDir, MANIFEST)));
+ const frozenText = preferFrozen && take.made ? await frozenBaseText(projectDir, id) : null;
+ let frozenDoc = null;
+ if (frozenText !== null) {
+ try {
+ frozenDoc = JSON.parse(frozenText);
+ } catch (e) {
+ throw new Error(`take ${id}: its takes/${id}/${BASE_FILE} does not parse (${e instanceof Error ? e.message : e})`);
+ }
+ }
+ const project = frozenDoc ?? base ?? (await readJson(path.join(projectDir, MANIFEST)));
if (!isObj(project)) throw new Error(`the project has no ${MANIFEST}`);
let stylePatch = null;
let note = null;
@@ -120,15 +142,45 @@ export async function resolveTakeManifest(projectDir, id, { styles = null, base
stylePatch = all[take.style]?.patch ?? null;
if (!stylePatch) {
// The style is gone: the manifest the take was rendered from, as it was.
- const frozen = take.made ? await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)) : null;
- if (!isObj(frozen)) throw new Error(`take ${id}: its style "${take.style}" is not installed, and it has no rendered manifest`);
- return { manifest: frozen, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from` };
+ // A frozen version keeps its own base; only the style is gone.
+ if (frozenDoc) {
+ const m = resolvePresetLayers(frozenDoc, [take.patch]);
+ if (!isObj(m) || !Array.isArray(m.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`);
+ return { manifest: /** @type {Record<string, any>} */ (m), take, note: `the style "${take.style}" is not installed: playing the version without it`, frozen: true };
+ }
+ const rendered = take.made ? await readJson(path.join(takesDirOf(projectDir), id, MANIFEST)) : null;
+ if (!isObj(rendered)) throw new Error(`take ${id}: its style "${take.style}" is not installed, and it has no rendered manifest`);
+ return { manifest: rendered, take, note: `the style "${take.style}" is not installed: playing the manifest the take was rendered from`, frozen: true };
}
}
// preset → manifest → style → take patch (presets.mjs).
const manifest = resolvePresetLayers(project, [stylePatch, take.patch]);
if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${id}: the patched manifest has no timeline`);
- return { manifest: /** @type {Record<string, any>} */ (manifest), take, note };
+ return { manifest: /** @type {Record<string, any>} */ (manifest), take, note, frozen: frozenDoc !== null };
+}
+
+/**
+ * A take FROZEN, as it plays: a saved version's frozen base with its patches
+ * (resolveTakeManifest), else -- a legacy take -- the manifest it was rendered
+ * from (takes/<id>/video.manifest.json, the fallback the working cut has
+ * always compared with). null when it has neither (a legacy draft never
+ * rendered: it follows the project's manifest).
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @returns {Promise<null | { manifest: Record<string, any>, source: "base" | "rendered" }>}
+ */
+export async function frozenManifestOf(projectDir, id) {
+ if (!isTakeId(id)) return null;
+ if ((await frozenBaseText(projectDir, id)) !== null) {
+ try {
+ return { manifest: (await resolveTakeManifest(projectDir, id)).manifest, source: "base" };
+ } catch {
+ return null;
+ }
+ }
+ const rendered = await readJson(path.join(takesDirOf(projectDir), id, MANIFEST));
+ return isObj(rendered) ? { manifest: rendered, source: "rendered" } : null;
}
// One merged manifest per (take, the files it is made from), for the media
@@ -141,7 +193,9 @@ const mtimeOf = (f) => stat(/* turbopackIgnore: true */ f).then((s) => s.mtimeMs
export async function cachedTakeManifest(projectDir, id) {
const dir = takesDirOf(projectDir);
const key = (
- await Promise.all([path.join(projectDir, MANIFEST), path.join(dir, id, TAKE_FILE), path.join(dir, RECIPE_FILE), path.join(dir, ALL_STYLES_RECIPE)].map(mtimeOf))
+ await Promise.all(
+ [path.join(projectDir, MANIFEST), path.join(dir, id, TAKE_FILE), path.join(dir, id, BASE_FILE), path.join(dir, RECIPE_FILE), path.join(dir, ALL_STYLES_RECIPE)].map(mtimeOf),
+ )
).join("|");
const slot = `${projectDir}\0${id}`;
const hit = memo.get(slot);
diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs
@@ -23,6 +23,15 @@ import { inside } from "../paths.mjs";
export const TAKES_DIR = "takes";
export const TAKE_FILE = "take.json";
export const VERDICTS_FILE = "verdicts.json";
+/**
+ * A SAVED VERSION's frozen manifest (lib/report/versions.mjs): the project's
+ * video.manifest.json as it was when the version was saved, byte for byte.
+ * When it is there, the take resolves over IT (takeManifest.mjs), never over
+ * the project's manifest as it is now.
+ */
+export const BASE_FILE = "base.manifest.json";
+/** The working draft's parent pointer (versions.mjs): `takes/draft.json` -- a file, so never listed as a take. */
+export const DRAFT_FILE = "draft.json";
/** A take id is its directory's name, and one url-safe segment. */
export const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
@@ -44,6 +53,31 @@ export const verdictsFileOf = (projectDir) => path.join(takesDirOf(projectDir),
const str = (v) => (typeof v === "string" ? v.trim() : "");
/**
+ * The working draft's parent pointer, takes/draft.json `{ from, hash, at }`
+ * (versions.mjs writes it): the version the draft was last saved as or opened
+ * from, the hash of the manifest it wrote, when. null when absent or not that
+ * shape -- the working cut then falls back to the newest working take.
+ *
+ * @param {string} projectDir
+ * @returns {Promise<{ from: string, hash: string | null, at: string | null } | null>}
+ */
+export async function readDraftFile(projectDir) {
+ try {
+ const j = JSON.parse(await readFile(path.join(takesDirOf(projectDir), DRAFT_FILE), "utf8"));
+ if (!j || typeof j !== "object" || !isTakeId(j.from)) return null;
+ return { from: j.from, hash: typeof j.hash === "string" && j.hash ? j.hash : null, at: typeof j.at === "string" && j.at ? j.at : null };
+ } catch {
+ return null;
+ }
+}
+
+/** A saved version's frozen manifest (takes/<id>/base.manifest.json) as text, or null when the take has none. */
+export async function frozenBaseText(projectDir, id) {
+ if (!isTakeId(id)) return null;
+ return readFile(path.join(takesDirOf(projectDir), id, BASE_FILE), "utf8").catch(() => null);
+}
+
+/**
* One take.json, checked. `{ take }` or `{ error }` -- never a partial take.
*
* Required: id (== the directory), group, order, label, kind, preview.
@@ -101,6 +135,9 @@ export function parseTake(dirName, raw) {
// render is older than the take.
if (j.draft !== undefined && typeof j.draft !== "boolean") return { error: "draft is not true or false" };
if (j.editedAt !== undefined && j.editedAt !== null && typeof j.editedAt !== "string") return { error: "editedAt is not a string" };
+ // A SAVED VERSION (versions.mjs): the draft frozen into takes/<id>/base.manifest.json.
+ if (j.version !== undefined && typeof j.version !== "boolean") return { error: "version is not true or false" };
+ if (j.savedAt !== undefined && j.savedAt !== null && typeof j.savedAt !== "string") return { error: "savedAt is not a string" };
return {
take: {
id: dirName,
@@ -120,6 +157,8 @@ export function parseTake(dirName, raw) {
quick: j.quick === true,
draft: j.draft === true,
editedAt: typeof j.editedAt === "string" && j.editedAt ? j.editedAt : null,
+ version: j.version === true,
+ savedAt: typeof j.savedAt === "string" && j.savedAt ? j.savedAt : null,
},
};
}
@@ -440,11 +479,17 @@ export async function setTakePicked(projectDir, takeId, group, { now = new Date(
* new one is its group's pick (autoPickTake). A partial window, a style take
* or a take with its own timeline is a variant, never the cut.
*
- * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null } | null | undefined} t
+ * A SAVED VERSION (versions.mjs, `version: true`) is one too, rendered or
+ * not: it IS the draft as it was, frozen -- unless a style or a timeline of
+ * its own was laid over it since.
+ *
+ * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null, version?: boolean } | null | undefined} t
*/
export function isWorkingTake(t) {
+ const ownTimeline = !!(t?.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline));
+ if (t?.version === true) return t.window === "full" && !t.style && !ownTimeline && t.quick !== true;
if (!t || t.window !== "full" || t.draft === true || t.quick === true || !t.baseHash || t.style) return false;
- return !(t.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline));
+ return !ownTimeline;
}
/**
diff --git a/umtool/lib/report/takes.test.mjs b/umtool/lib/report/takes.test.mjs
@@ -73,6 +73,8 @@ test("parseTake accepts the contract and fills the optional fields", () => {
quick: false,
draft: false,
editedAt: null,
+ version: false,
+ savedAt: null,
});
const min = parseTake("x", { id: "x", group: "g", order: 0, label: "X", kind: "reference", preview: "p.mp4" });
assert.ok("take" in min);
diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs
@@ -0,0 +1,328 @@
+// THE WORKING DRAFT AND ITS SAVED VERSIONS (umtool redesign, lane L3; operator,
+// 1 Nov 2026: "Most of the time I'll only really be working on the latest
+// cut/draft rather than the picked one").
+//
+// The project's video.manifest.json IS the draft: every UI edit lands in it.
+// A take is a SAVED VERSION of it, frozen:
+//
+// takes/<id>/base.manifest.json the draft as it was, byte for byte -- the
+// version resolves over THIS, never over the
+// draft as it is now (takeManifest.mjs)
+// takes/<id>/take.json `version: true, draft: true, patch: null,
+// window: "full"`, its baseHash the base's
+// takes/draft.json the draft's PARENT `{ from, hash, at }`: the
+// version it was last saved as or opened from
+// (a file, so listTakes never lists it)
+//
+// saveVersion(project, { label }) the draft frozen as the next `v<N>`
+// openVersion(project, id) a version copied INTO the draft -- the
+// draft saved first when it has edits
+// since its parent, one undo point
+// freezeTakes(project, { apply }) legacy takes given a frozen base
+// (opt-in, a dry run by default)
+//
+// VERSION IDS are `v1`, `v2`, … -- the next number above every `v<N>`
+// directory under takes/ (made or not), so a name is never reused and never
+// collides with a take an agent named by hand.
+//
+// Both writers hold the MANIFEST LOCK (manifest.mjs withManifestLock), the one
+// every manifest write takes in this process, so a save and an open are each
+// one step against the bench's edits; across processes the token is the guard.
+//
+// Plain ESM: `umtool takes save|open|freeze` runs it under bare node.
+import { createHash } from "node:crypto";
+import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { applyStructural, manifestToken, replaceManifestLocked, StaleToken, withManifestLock } from "./manifest.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { BASE_FILE, DRAFT_FILE, frozenBaseText, isTakeId, listTakes, readDraftFile, takesDirOf, TAKE_FILE } from "./takes.mjs";
+import { readWorkingCut } from "./workingCut.mjs";
+
+const MANIFEST = "video.manifest.json";
+export const VERSION_RE = /^v(\d{1,6})$/;
+const hashText = (text) => createHash("sha256").update(text).digest("hex");
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+export class VersionRefused extends Error {
+ /** @param {string} message */
+ constructor(message) {
+ super(message);
+ this.name = "VersionRefused";
+ }
+}
+
+/** The draft's parent pointer (takes/draft.json), or null. */
+export const readDraft = readDraftFile;
+
+/**
+ * Write takes/draft.json (tmp + rename). `from` null removes it.
+ * @param {string} projectDir
+ * @param {{ from: string | null, hash?: string | null, at?: string | null }} d
+ */
+export async function writeDraft(projectDir, { from, hash = null, at = null }) {
+ const file = path.join(takesDirOf(projectDir), DRAFT_FILE);
+ if (!from) {
+ await rm(file, { force: true });
+ return null;
+ }
+ if (!isTakeId(from)) throw new Error(`"${from}" is not a take id`);
+ await mkdir(path.dirname(file), { recursive: true });
+ const doc = { from, hash, at: at ?? new Date().toISOString() };
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+ return doc;
+}
+
+/** The next free version id: `v<N+1>` over every `v<N>` directory under takes/ (made or not). */
+export async function nextVersionId(projectDir) {
+ const names = await readdir(takesDirOf(projectDir)).catch(() => []);
+ const taken = new Set(names);
+ let n = Math.max(0, ...names.map((x) => Number(VERSION_RE.exec(x)?.[1] ?? 0))) + 1;
+ while (taken.has(`v${n}`)) n += 1;
+ return `v${n}`;
+}
+
+async function writeAtomic(file, text) {
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, text, "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * saveVersion's body, inside the manifest lock: the draft's text copied byte
+ * for byte to takes/<id>/base.manifest.json, then take.json (LAST: until then
+ * the directory is a work dir the listing ignores), then draft.json.
+ *
+ * @param {string} projectDir
+ * @param {{ label?: string | null, now?: Date, force?: boolean, why?: string | null }} opts
+ */
+async function saveVersionLocked(projectDir, { label = null, now = new Date(), force = false, why = null } = {}) {
+ const text = await readFile(path.join(projectDir, MANIFEST), "utf8").catch(() => null);
+ if (text === null) throw new VersionRefused(`the project has no ${MANIFEST} to save`);
+ try {
+ if (!isObj(JSON.parse(text))) throw new Error("not an object");
+ } catch (e) {
+ throw new VersionRefused(`${MANIFEST} does not parse; not saving it (${e instanceof Error ? e.message : e})`);
+ }
+ const working = await readWorkingCut(projectDir, { manifestText: text });
+ if (!force && working.parent && working.edits?.count === 0) {
+ return { saved: false, id: working.parent.id, why: `no edits since ${working.parent.id}: nothing to save`, edits: working.edits, parent: working.parent.id };
+ }
+ const id = await nextVersionId(projectDir);
+ const { takes } = await listTakes(projectDir);
+ const parentTake = working.parent ? takes.find((t) => t.id === working.parent?.id) : null;
+ const group = parentTake?.group ?? takes.filter((t) => t.window === "full").at(-1)?.group ?? "takes";
+ const order = Math.max(0, ...takes.map((t) => t.order)) + 1;
+ const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim().slice(0, 200) : "";
+ const iso = now.toISOString();
+ const baseHash = hashText(text);
+ const dir = path.join(takesDirOf(projectDir), id);
+ await mkdir(dir, { recursive: true });
+ await writeAtomic(path.join(dir, BASE_FILE), text);
+ const doc = {
+ id,
+ group,
+ order,
+ label: l || (why ? why : working.parent ? `Saved draft (from ${working.parent.id})` : "Saved draft"),
+ kind: "reference",
+ summary: "",
+ changes: working.edits?.words?.length ? working.edits.words.slice(0, 40) : [],
+ preview: "preview.mp4",
+ seconds: null,
+ builtAt: null,
+ style: null,
+ patch: null,
+ window: "full",
+ version: true,
+ draft: true,
+ draftedAt: iso,
+ savedAt: iso,
+ baseHash,
+ ...(working.parent ? { draftedFrom: working.parent.id } : {}),
+ };
+ await writeAtomic(path.join(dir, TAKE_FILE), JSON.stringify(doc, null, 2) + "\n");
+ await writeDraft(projectDir, { from: id, hash: baseHash, at: iso });
+ return { saved: true, id, label: doc.label, edits: working.edits, parent: working.parent?.id ?? null, baseHash };
+}
+
+/**
+ * SAVE THE DRAFT AS A VERSION: the next `v<N>`, frozen. Nothing is saved when
+ * the draft has no edits since its parent (`saved: false`, naming it) unless
+ * `force`. The pick (verdicts.json) is never touched: saving never unpins.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ label?: string | null, now?: Date, force?: boolean }} [opts]
+ */
+export async function saveVersion(project, { label = null, now = new Date(), force = false } = {}) {
+ return withManifestLock(() => saveVersionLocked(project.dir, { label, now, force }));
+}
+
+/**
+ * What opening take `id` would write into the draft, and how:
+ * "frozen" a saved version: its base (with any patch laid over it since)
+ * "rendered" a legacy rendered take of the cut's own timeline: the manifest it was
+ * rendered from (pickTake's copy, "Use this take")
+ * "merge" a legacy take with a timeline of its own, or one never rendered: its
+ * patch over the draft as it is now (promoteTake's merge) -- so a walk
+ * made since its render is what opens
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {Record<string, any>} draft the draft, parsed
+ */
+export async function openedManifestOf(projectDir, id, draft) {
+ const { versionManifestOf } = await import("./takeMaker.mjs");
+ const v = await versionManifestOf(projectDir, id);
+ if (v) return { manifest: v.manifest, how: /** @type {const} */ ("frozen") };
+ const { resolveTakeManifest, takeSpecOf } = await import("./takeManifest.mjs");
+ const spec = await takeSpecOf(projectDir, id);
+ if (!spec) throw new VersionRefused(`no take ${id}`);
+ if (!spec.made) throw new VersionRefused(`take ${id} is only named by a recipe — nothing made to open`);
+ const ownTimeline = isObj(spec.patch) && Array.isArray(spec.patch.timeline);
+ const doc = JSON.parse(await readFile(path.join(takesDirOf(projectDir), id, TAKE_FILE), "utf8"));
+ const renderedText = doc.draft === true ? null : await readFile(path.join(takesDirOf(projectDir), id, MANIFEST), "utf8").catch(() => null);
+ if (!ownTimeline && renderedText !== null) {
+ const m = JSON.parse(renderedText);
+ if (isObj(m) && Array.isArray(m.timeline)) return { manifest: m, how: /** @type {const} */ ("rendered") };
+ }
+ const { manifest: merged } = await resolveTakeManifest(projectDir, id, { base: draft, frozen: false });
+ // The build's structure rules, over the draft becoming the take's (promoteTake's check).
+ const next = JSON.parse(JSON.stringify(draft));
+ applyStructural(next, (m) => {
+ for (const k of Object.keys(m)) delete m[k];
+ Object.assign(m, JSON.parse(JSON.stringify(merged)));
+ });
+ return { manifest: next, how: /** @type {const} */ ("merge") };
+}
+
+/** The undo point's sidecar: the draft pointer as it was before the write the snapshot takes back. */
+export const draftSidecarOf = (snapshotRel) => snapshotRel.replace(/\.manifest\.json$/, ".draft.json");
+
+/**
+ * OPEN A VERSION IN THE DRAFT, under the manifest lock:
+ * 1. the draft saved as the next version first when it has edits since its
+ * parent (or has no parent at all) -- nothing in it is lost;
+ * 2. the version's manifest written over the draft (openedManifestOf), through
+ * the manifest writer with an undo point taken EVERY time (`every: 0`,
+ * `auto-before-open-<id>`; "Undo open <id>" restores the draft as it was,
+ * and the draft pointer beside it);
+ * 3. takes/draft.json naming the opened version.
+ * The pick and the pins (verdicts.json) are never touched: opening is not
+ * "Use this take". Opening the draft's own parent with no edits writes nothing.
+ *
+ * @param {{ id: string, dir: string, kind?: string }} project
+ * @param {string} id
+ * @param {{ token?: string | null, now?: Date }} [opts]
+ */
+export async function openVersion(project, id, { token = null, now = new Date() } = {}) {
+ if (!isTakeId(id)) throw new VersionRefused(`"${id}" is not a take id`);
+ const run = () =>
+ withManifestLock(async () => {
+ const current = await manifestToken(project.dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const { takes } = await listTakes(project.dir);
+ if (!takes.some((t) => t.id === id)) throw new VersionRefused(`no take ${id} in this project`);
+ const text = await readFile(path.join(project.dir, MANIFEST), "utf8");
+ const working = await readWorkingCut(project.dir, { manifestText: text });
+ if (working.parent?.id === id && working.edits?.count === 0) {
+ return { opened: id, how: "unchanged", saved: null, snapshot: null, token: current, unchanged: true, edits: 0 };
+ }
+ const edits = working.edits?.count ?? null;
+ let saved = null;
+ if (!working.parent || working.edits === null || working.edits.count > 0) {
+ const r = await saveVersionLocked(project.dir, { now, force: true, why: `Draft before opening ${id}` });
+ saved = r.saved ? r.id : null;
+ }
+ const draftBefore = await readDraftFile(project.dir);
+ const { manifest, how } = await openedManifestOf(project.dir, id, JSON.parse(text));
+ const op = `open-${id}`.slice(0, 40).replace(/-+$/, "");
+ const r = await replaceManifestLocked(project.dir, manifest, { op, every: 0 });
+ // The undo point remembers the draft pointer, so Undo puts the parent back too (manifest.mjs undoStructural).
+ const rel = /** @type {any} */ (r.snapshot)?.rel;
+ if (rel && !(/** @type {any} */ (r.snapshot).skipped)) {
+ await writeFile(path.join(project.dir, draftSidecarOf(rel)), JSON.stringify(draftBefore ?? { from: null }, null, 2) + "\n", "utf8").catch(() => {});
+ }
+ const written = await readFile(path.join(project.dir, MANIFEST), "utf8");
+ await writeDraft(project.dir, { from: id, hash: hashText(written), at: now.toISOString() });
+ return { opened: id, how, saved, snapshot: r.snapshot, token: r.token, unchanged: false, edits, undo: `Undo open ${id}` };
+ });
+ // The generated-manifest guard, as every whole-manifest writer runs inside (edit-guard.mjs).
+ if (project.kind) {
+ const { result, editNotes } = await withEditNotes(/** @type {any} */ (project), run);
+ return { ...result, editNotes };
+ }
+ return run();
+}
+
+/**
+ * FREEZE LEGACY TAKES (opt-in; a dry run unless `apply`): a take made before
+ * versions follows the project's manifest as it is now (its patch over it).
+ * Frozen, it gets a base of its own -- the manifest it was RENDERED from
+ * (takes/<id>/video.manifest.json) when it has one, else the draft as it is
+ * now -- and `version: true`; its style and patch stay, laid over the base.
+ * Each row says what the take resolves to today against what it would
+ * resolve to frozen (cutDiff, in words), so nothing changes unseen.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ ids?: string[] | null, apply?: boolean, now?: Date }} [opts] `ids` null: every take
+ */
+export async function freezeTakes(project, { ids = null, apply = false, now = new Date() } = {}) {
+ return withManifestLock(async () => {
+ const { takes, skipped } = await listTakes(project.dir);
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ const { resolvePresetLayers } = await import("umtool-report-to-video/presets");
+ const { loadMontageStyles } = await import("./takeMaker.mjs");
+ const { cutDiff } = await import("./workingCut.mjs");
+ const draftText = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null);
+ const wanted = ids ? takes.filter((t) => ids.includes(t.id)) : takes;
+ const missing = ids ? ids.filter((x) => !takes.some((t) => t.id === x)) : [];
+ /** @type {Array<{ id: string, action: "frozen" | "would-freeze" | "already" | "refused", source?: "rendered" | "draft", differs?: number, words?: string[], why?: string }>} */
+ const rows = [];
+ let styles = null;
+ for (const t of wanted) {
+ if ((await frozenBaseText(project.dir, t.id)) !== null) {
+ rows.push({ id: t.id, action: "already" });
+ continue;
+ }
+ const rendered = t.draft ? null : await readFile(path.join(takesDirOf(project.dir), t.id, MANIFEST), "utf8").catch(() => null);
+ const baseText = rendered ?? draftText;
+ if (baseText === null) {
+ rows.push({ id: t.id, action: "refused", why: "no rendered manifest, and the project has no manifest" });
+ continue;
+ }
+ let today = null;
+ try {
+ today = (await resolveTakeManifest(project.dir, t.id)).manifest;
+ } catch (e) {
+ today = null;
+ }
+ let after = null;
+ try {
+ let stylePatch = null;
+ if (t.style) {
+ styles ??= (await loadMontageStyles()).styles;
+ stylePatch = styles[t.style]?.patch ?? null;
+ }
+ after = resolvePresetLayers(JSON.parse(baseText), [stylePatch, t.patch]);
+ } catch (e) {
+ rows.push({ id: t.id, action: "refused", why: `its base does not resolve: ${e instanceof Error ? e.message : e}` });
+ continue;
+ }
+ const d = today && after ? cutDiff(today, after) : null;
+ const row = { id: t.id, action: /** @type {"frozen" | "would-freeze"} */ (apply ? "frozen" : "would-freeze"), source: /** @type {"rendered" | "draft"} */ (rendered !== null ? "rendered" : "draft"), differs: d ? d.count : 0, words: d ? d.words : [] };
+ if (apply) {
+ const dir = path.join(takesDirOf(project.dir), t.id);
+ const takeFile = path.join(dir, TAKE_FILE);
+ const doc = JSON.parse(await readFile(takeFile, "utf8"));
+ await writeAtomic(path.join(dir, BASE_FILE), baseText);
+ doc.version = true;
+ doc.frozenAt = now.toISOString();
+ doc.frozenFrom = row.source;
+ await writeAtomic(takeFile, JSON.stringify(doc, null, 2) + "\n");
+ }
+ rows.push(row);
+ }
+ return { project: project.id, apply, rows, missing, skipped };
+ });
+}
diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs
@@ -0,0 +1,254 @@
+// The working draft and its saved versions (versions.mjs): a version freezes,
+// the draft knows its parent, opening a version never loses the draft or an
+// undo point, and a legacy take resolves exactly as it always did.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { freezeTakes, nextVersionId, openVersion, readDraft, saveVersion } from "./versions.mjs";
+import { composeTake, checkSpec, makeTake, pickTake } from "./takeMaker.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+import { isWorkingTake, listTakes, readVerdicts, setTakePicked } from "./takes.mjs";
+import { draftLine, readWorkingCut, workingCutLine } from "./workingCut.mjs";
+import { createSnapshot, listSnapshots } from "./snapshots.mjs";
+import { moveEntry, undoStructural, updateClip } from "./manifest.mjs";
+import { PROJECT_KINDS } from "../projects/kinds.mjs";
+import { takesCommand } from "./takeCli.mjs";
+
+const KIND = PROJECT_KINDS.find((k) => k.makesTakes).id;
+const hash = (t) => createHash("sha256").update(t).digest("hex");
+const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: `v-${id}`, start, end, cite: start, section: 0, ...extra });
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "fixture",
+ title: "Fixture",
+ render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30 },
+ timeline: [clip("a", 0, 10), clip("b", 20, 25), clip("c", 40, 50)],
+};
+
+async function project(manifest = MANIFEST) {
+ const root = await mkdtemp(path.join(tmpdir(), "versions-"));
+ const dir = path.join(root, "reports", "proj");
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
+ return { root, dir, proj: { id: "proj", dir, kind: KIND }, reportsRoot: path.join(root, "reports") };
+}
+const text = (dir) => readFile(path.join(dir, "video.manifest.json"), "utf8");
+const json = async (f) => JSON.parse(await readFile(f, "utf8"));
+const ids = async (dir) => (await json(path.join(dir, "video.manifest.json"))).timeline.map((e) => e.id).join(" ");
+
+test("saveVersion: v1 is the draft byte for byte, frozen; the draft knows it is from v1; an edit counts; no edits saves nothing", async () => {
+ const { root, dir, proj } = await project();
+ try {
+ let w = await readWorkingCut(dir);
+ assert.equal(w.parent, null);
+ assert.equal(draftLine(w), "Draft · unsaved");
+ const before = await text(dir);
+ const r = await saveVersion(proj, { label: "First pass" });
+ assert.equal(r.saved, true);
+ assert.equal(r.id, "v1");
+ assert.equal(await readFile(path.join(dir, "takes", "v1", "base.manifest.json"), "utf8"), before);
+ const doc = await json(path.join(dir, "takes", "v1", "take.json"));
+ assert.deepEqual([doc.version, doc.draft, doc.patch, doc.window, doc.baseHash, doc.label], [true, true, null, "full", hash(before), "First pass"]);
+ assert.equal(isWorkingTake(doc), true, "a version is the cut, rendered or not");
+ assert.deepEqual(await readDraft(dir), { from: "v1", hash: hash(before), at: doc.savedAt });
+ w = await readWorkingCut(dir);
+ assert.equal(w.parent?.id, "v1");
+ assert.equal(w.latest, null, "a version not rendered is not the latest render");
+ assert.equal(draftLine(w), "Draft · from v1 · no edits");
+ assert.match(workingCutLine(w), /Draft from v1 · no edits since/);
+ // Nothing to save at no edits; --force saves anyway.
+ const none = await saveVersion(proj);
+ assert.equal(none.saved, false);
+ assert.equal(none.id, "v1");
+ // An edit to the draft: v1 does not follow it.
+ await moveEntry(dir, "c", 0);
+ w = await readWorkingCut(dir);
+ assert.equal(w.edits?.count, 1);
+ assert.equal(draftLine(w), "Draft · from v1 · 1 edit");
+ const v1 = (await resolveTakeManifest(dir, "v1")).manifest;
+ assert.deepEqual(v1.timeline.map((e) => e.id), ["a", "b", "c"], "the version is frozen");
+ const r2 = await saveVersion(proj);
+ assert.equal(r2.id, "v2");
+ assert.equal((await json(path.join(dir, "takes", "v2", "take.json"))).draftedFrom, "v1");
+ assert.deepEqual((await listTakes(dir)).takes.map((t) => t.id), ["v1", "v2"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("nextVersionId: above every v<N> directory, made or not; never a name in use", async () => {
+ const { root, dir } = await project();
+ try {
+ assert.equal(await nextVersionId(dir), "v1");
+ await mkdir(path.join(dir, "takes", "v3"), { recursive: true });
+ await mkdir(path.join(dir, "takes", "v10-tight"), { recursive: true });
+ assert.equal(await nextVersionId(dir), "v4");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("openVersion: the draft saved first as the next version, the version copied in, one undo point that puts the draft AND its parent back", async () => {
+ const { root, dir, proj } = await project();
+ try {
+ await saveVersion(proj); // v1: a b c
+ const v1Text = await text(dir);
+ await moveEntry(dir, "c", 0); // c a b
+ // A pinned pick elsewhere survives.
+ await mkdir(path.join(dir, "takes", "old"), { recursive: true });
+ await writeFile(path.join(dir, "takes", "old", "take.json"), JSON.stringify({ id: "old", group: "takes", order: 0, label: "Old", kind: "reference", preview: "preview.mp4", window: "full", baseHash: "x" }));
+ await setTakePicked(dir, "old", ["old", "v1"], { pinned: true });
+ const preOpen = await text(dir);
+ const r = await openVersion(proj, "v1");
+ assert.equal(r.saved, "v2", "the draft's edit is kept as v2");
+ assert.equal(r.how, "frozen");
+ assert.equal(await readFile(path.join(dir, "takes", "v2", "base.manifest.json"), "utf8"), preOpen);
+ assert.equal(await text(dir), v1Text, "the draft is v1 again, byte for byte");
+ assert.equal((await readDraft(dir))?.from, "v1");
+ assert.match(r.snapshot.rel, /auto-before-open-v1\.manifest\.json$/);
+ let w = await readWorkingCut(dir);
+ assert.equal(w.parent?.id, "v1");
+ assert.equal(w.edits?.count, 0);
+ const v = await readVerdicts(dir);
+ assert.deepEqual([v.old?.picked, v.old?.pinned], [true, true], "opening never moves or unpins the pick");
+ // Opening it again: nothing written.
+ assert.equal((await openVersion(proj, "v1")).unchanged, true);
+ // Undo: the pre-open draft, and the draft's parent is v2 (what it was saved as).
+ const u = await undoStructural(dir);
+ assert.equal(u.op, "open-v1");
+ assert.equal(await text(dir), preOpen);
+ assert.equal((await readDraft(dir))?.from, "v2");
+ w = await readWorkingCut(dir);
+ assert.equal(w.edits?.count, 0);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("openVersion of a legacy take: a rendered one is the manifest it rendered; one with its own timeline merges its patch (promote)", async () => {
+ const { root, dir, proj } = await project();
+ try {
+ const t0 = await text(dir);
+ const mk = async (id, doc, rendered = null) => {
+ await mkdir(path.join(dir, "takes", id), { recursive: true });
+ await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", window: "full", baseHash: hash(t0), ...doc }));
+ if (rendered) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(rendered, null, 2) + "\n");
+ };
+ // Rendered from an older manifest (its baseHash is not the draft's), with a look patch.
+ await mk("rendered", { builtAt: "2026-11-01T00:00:00Z", baseHash: "older", patch: { title: "Rendered" } }, { ...MANIFEST, title: "Rendered", timeline: [clip("a", 0, 10)] });
+ await mk("own", { draft: true, patch: { timeline: [clip("b", 21, 24), clip("z", 1, 2)] } });
+ // Legacy takes resolve as they always did: their patch over the project's manifest now.
+ assert.deepEqual((await resolveTakeManifest(dir, "rendered")).manifest.timeline.map((e) => e.id), ["a", "b", "c"]);
+ const r = await openVersion(proj, "rendered");
+ assert.equal(r.how, "rendered");
+ assert.equal(r.saved, "v1", "the draft differs from its parent (the latest render): saved first");
+ assert.equal(await ids(dir), "a");
+ assert.equal((await json(path.join(dir, "video.manifest.json"))).title, "Rendered");
+ const o = await openVersion(proj, "own");
+ assert.equal(o.how, "merge");
+ assert.equal(await ids(dir), "b z");
+ assert.equal((await json(path.join(dir, "takes", "own", "take.json"))).patch.timeline.length, 2, "the take itself is untouched");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a version renders its frozen base, and pickTake uses an unrendered version", async () => {
+ const { root, dir, proj } = await project();
+ try {
+ await saveVersion(proj); // v1: a b c
+ await moveEntry(dir, "c", 0);
+ const c = await composeTake(dir, checkSpec({ id: "v1", label: "v1", window: "full" }));
+ assert.equal(c.frozen, true);
+ assert.deepEqual(c.manifest.timeline.map((e) => e.id), ["a", "b", "c"]);
+ // Rendered with a stub: still a version, its baseHash the base's, its frozen manifest what it rendered.
+ const calls = [];
+ const render = async (job) => {
+ const doc = JSON.parse(await readFile(job.manifestPath, "utf8"));
+ calls.push(doc.timeline.map((e) => e.id).join(" "));
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, "mp4");
+ return { file };
+ };
+ const base = await readFile(path.join(dir, "takes", "v1", "base.manifest.json"), "utf8");
+ await makeTake(dir, { id: "v1", label: "v1", window: "full" }, { force: true, render, styles: {}, probe: async () => 9, record: false, pruneAfter: false });
+ assert.deepEqual(calls, ["a b c"]);
+ const doc = await json(path.join(dir, "takes", "v1", "take.json"));
+ assert.deepEqual([doc.version, doc.baseHash, doc.draft], [true, hash(base), undefined]);
+ assert.equal((await readDraft(dir))?.from, "v1", "a frozen version re-rendered does not move the draft's parent");
+ // An unrendered version is picked from its base.
+ await saveVersion(proj); // v2: c a b
+ await moveEntry(dir, "a", 0);
+ await pickTake(proj, "v2", { anyway: true });
+ assert.equal(await ids(dir), "c a b");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("freezeTakes: a dry run writes nothing; --apply gives a legacy take the base it was rendered from", async () => {
+ const { root, dir, proj } = await project();
+ try {
+ const t0 = await text(dir);
+ await mkdir(path.join(dir, "takes", "d1"), { recursive: true });
+ await writeFile(path.join(dir, "takes", "d1", "take.json"), JSON.stringify({ id: "d1", group: "takes", order: 1, label: "d1", kind: "reference", preview: "preview.mp4", window: "full", baseHash: hash(t0), builtAt: "2026-11-01T00:00:00Z" }));
+ await writeFile(path.join(dir, "takes", "d1", "video.manifest.json"), t0);
+ await moveEntry(dir, "c", 0);
+ const dry = await freezeTakes(proj, { ids: null });
+ assert.deepEqual(dry.rows.map((x) => [x.id, x.action, x.source, x.differs]), [["d1", "would-freeze", "rendered", 1]]);
+ await assert.rejects(stat(path.join(dir, "takes", "d1", "base.manifest.json")));
+ assert.deepEqual((await resolveTakeManifest(dir, "d1")).manifest.timeline.map((e) => e.id), ["c", "a", "b"], "unfrozen, it follows the draft");
+ const done = await freezeTakes(proj, { ids: ["d1"], apply: true });
+ assert.equal(done.rows[0].action, "frozen");
+ assert.equal(await readFile(path.join(dir, "takes", "d1", "base.manifest.json"), "utf8"), t0);
+ assert.deepEqual((await resolveTakeManifest(dir, "d1")).manifest.timeline.map((e) => e.id), ["a", "b", "c"]);
+ assert.equal((await freezeTakes(proj, { ids: ["d1"] })).rows[0].action, "already");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("snapshots in one second are two undo points, newest first", async () => {
+ const { root, dir } = await project();
+ try {
+ const now = new Date("2026-11-09T10:00:00.120Z");
+ const a = await createSnapshot(dir, { label: "auto-before-trim", now });
+ const b = await createSnapshot(dir, { label: "auto-before-trim", now: new Date("2026-11-09T10:00:00.480Z") });
+ const c = await createSnapshot(dir, { label: "auto-before-move", now: new Date("2026-11-09T10:00:00.480Z") });
+ assert.notEqual(a.name, b.name);
+ assert.notEqual(b.name, c.name);
+ const list = await listSnapshots(dir);
+ assert.deepEqual(list.map((s) => s.name), [c.name, b.name, a.name]);
+ assert.equal(list[0].label, "auto-before-move");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("umtool takes save | open | freeze, with --json", async () => {
+ const { root, dir, reportsRoot } = await project();
+ try {
+ const out = [];
+ const err = [];
+ const run = (args) => takesCommand(args, { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s) });
+ assert.equal(await run(["save", "proj", "--label", "Pass one", "--json"]), 0);
+ assert.equal(JSON.parse(out.pop()).id, "v1");
+ await updateClip(dir, "a", { end: 9 });
+ assert.equal(await run(["save", "proj"]), 0);
+ assert.match(out.pop(), /saved as v2/);
+ assert.equal(await run(["open", "proj", "v1", "--json"]), 0);
+ const o = JSON.parse(out.pop());
+ assert.deepEqual([o.opened, o.saved], ["v1", null]);
+ assert.equal(await run(["freeze", "proj", "--all"]), 0);
+ assert.equal(await run(["freeze", "proj"]), 2);
+ assert.deepEqual((await readdir(path.join(dir, "takes"))).sort(), ["draft.json", "v1", "v2"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs
@@ -1,20 +1,23 @@
// THE WORKING CUT'S NAME (operator, 1 Nov 2026): "Most of the time I'll only
// really be working on the latest cut/draft rather than the picked one".
//
-// The project's video.manifest.json IS the working cut: the bench, Play, the
-// Cut tab and every agent write it, and every take is MADE FROM it (take.json
-// `baseHash`, the hash of the manifest it was made from). So the cut has a
-// name -- the newest WORKING take (takes.mjs isWorkingTake: a whole-cut render
-// of the manifest's own content) -- and a distance from it: the edits made to
-// the manifest since that take was made.
+// The project's video.manifest.json IS the working cut -- the DRAFT: the
+// bench, Play, the Cut tab and every agent write it, and every take is MADE
+// FROM it (take.json `baseHash`, the hash of the manifest it was made from).
+// A saved version (versions.mjs) is the draft frozen. So the cut has a name
+// and a distance from it:
//
-// latest the newest working take, by builtAt (then order)
-// edits 0 when the manifest's hash is the take's baseHash; else the
-// entries added, removed, moved and changed between the manifest
-// the take RENDERED (takes/<id>/video.manifest.json, its patch
-// applied) and the manifest now with the same patch -- in words
-// ("aw3 removed", "mc1 moved"); null when the take's rendered
-// manifest is gone (pruned) and the hashes differ
+// latest the newest working take RENDERED (takes.mjs isWorkingTake), by
+// builtAt (then order)
+// parent what the draft was last saved as or opened from: takes/draft.json
+// `from` (versions.mjs), else `latest`
+// edits since the parent: 0 when a hash says the draft is what it wrote
+// (draft.json's, or the parent's baseHash); else the entries added,
+// removed, moved and changed between the parent frozen (a version's
+// base, or the manifest a legacy take RENDERED) and the draft with
+// the parent's patch -- in words ("aw3 removed", "mc1 moved"); null
+// when there is nothing frozen to compare (a legacy take's rendered
+// manifest pruned)
// picked the group pick in verdicts.json (secondary: "Use this take",
// auto-picked for each new working take unless pinned)
//
@@ -22,7 +25,7 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import path from "node:path";
-import { isWorkingTake, listTakes, readVerdicts, takesDirOf } from "./takes.mjs";
+import { isWorkingTake, listTakes, readDraftFile, readVerdicts } from "./takes.mjs";
const MANIFEST = "video.manifest.json";
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
@@ -122,51 +125,93 @@ async function readJson(file) {
}
/**
- * The working cut: the newest working take, the edits since it, the pick.
+ * The working cut: the newest working take, the draft's PARENT and the edits
+ * since it, the pick.
+ *
+ * THE PARENT (lib/report/versions.mjs): the version the draft was last saved
+ * as or opened from -- takes/draft.json `from` while that take exists -- else
+ * the newest working take, as it always was. `latestWorkingTake` cannot name
+ * it once an older version has been opened.
+ *
+ * THE EDITS are counted by cutDiff, never by a hash alone: re-serialising a
+ * manifest changes its bytes and not what it says. A hash that matches (the
+ * draft.json hash, or the parent's baseHash) is 0 edits at once; otherwise
+ * the parent frozen (its version's base, or the manifest a legacy take was
+ * rendered from) against the draft with the parent's patch laid over it.
*
* @param {string} projectDir
- * @param {{ manifestText?: string | null, resolveNow?: ((takeId: string) => Promise<Record<string, any> | null>) | null }} [opts]
- * `resolveNow`: the manifest as it is now with that take's patch (takeManifest.mjs resolveTakeManifest) --
- * compared with what the take rendered; without it the bare manifest is compared
+ * @param {{ manifestText?: string | null }} [opts]
*/
-export async function readWorkingCut(projectDir, { manifestText = null, resolveNow = null } = {}) {
- const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]);
+export async function readWorkingCut(projectDir, { manifestText = null } = {}) {
+ const [listing, verdicts, draft] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir), readDraftFile(projectDir)]);
const takes = listing.takes;
const latest = latestWorkingTake(takes);
const pickedId = Object.keys(verdicts).find((id) => verdicts[id]?.picked && takes.some((t) => t.id === id)) ?? null;
const picked = pickedId
? { id: pickedId, at: verdicts[pickedId].at || null, pinned: verdicts[pickedId].pinned === true, label: takes.find((t) => t.id === pickedId)?.label ?? pickedId }
: null;
- if (!latest) return { latest: null, edits: null, picked, takes: takes.length };
+ const fromDraft = draft ? takes.find((t) => t.id === draft.from) ?? null : null;
+ const parentTake = fromDraft ?? latest;
+ const latestOut = latest ? { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group } : null;
+ if (!parentTake) return { latest: null, parent: null, edits: null, picked, takes: takes.length };
+ const parent = {
+ id: parentTake.id,
+ label: parentTake.label,
+ builtAt: parentTake.builtAt ?? null,
+ seconds: parentTake.seconds ?? null,
+ group: parentTake.group,
+ version: parentTake.version === true,
+ rendered: !!parentTake.builtAt,
+ // Why it is the parent: the draft pointer, or (no pointer) the newest working take.
+ via: fromDraft ? "draft" : "latest",
+ };
const text = manifestText ?? (await readFile(/* turbopackIgnore: true */ path.join(projectDir, MANIFEST), "utf8").catch(() => null));
let edits = null;
- if (text !== null && hashText(text) === latest.baseHash) edits = { count: 0, words: [], same: true };
- else {
- const rendered = await readJson(path.join(takesDirOf(projectDir), latest.id, MANIFEST));
+ const h = text !== null ? hashText(text) : null;
+ if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true };
+ else if (text !== null) {
+ const { frozenManifestOf, resolveTakeManifest } = await import("./takeManifest.mjs");
+ const frozen = await frozenManifestOf(projectDir, parentTake.id);
let now = null;
try {
- now = resolveNow ? await resolveNow(latest.id) : text !== null ? JSON.parse(text) : null;
+ now = (await resolveTakeManifest(projectDir, parentTake.id, { base: JSON.parse(text), frozen: false })).manifest;
} catch {
now = null;
}
- if (isObj(rendered) && isObj(now)) {
- const d = cutDiff(rendered, now);
- edits = { count: d.count, words: d.words, same: false };
+ if (frozen && isObj(now)) {
+ const d = cutDiff(frozen.manifest, now);
+ edits = { count: d.count, words: d.words, same: d.count === 0 };
}
}
- return {
- latest: { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group },
- edits,
- picked,
- takes: takes.length,
- };
+ return { latest: latestOut, parent, edits, picked, takes: takes.length };
}
-/** "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls` prints first, and the pages show. */
+/**
+ * "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls`
+ * prints first, and the pages show. When the draft's parent is not the newest
+ * working take (an older version opened): "… · the draft is from v5, +2 edits since".
+ */
export function workingCutLine(w) {
- if (!w?.latest) return "Latest: no whole-cut take yet — the manifest is the cut";
+ const edWords = (e) => (!e ? "edits since: unknown (its rendered manifest is gone)" : e.count === 0 ? "no edits since" : `+${e.count} edit${e.count === 1 ? "" : "s"} since`);
+ const p = w?.parent ?? null;
+ if (!w?.latest) {
+ if (p) return `Draft from ${p.id} · ${edWords(w.edits)} (no whole-cut take rendered yet)`;
+ return "Latest: no whole-cut take yet — the manifest is the cut";
+ }
const s = w.latest.seconds;
const len = typeof s === "number" ? ` · ${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : "";
- const ed = !w.edits ? " · edits since: unknown (its rendered manifest is gone)" : w.edits.count === 0 ? " · no edits since" : ` · +${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`;
- return `Latest: ${w.latest.id}${len}${ed}`;
+ if (p && p.id !== w.latest.id) return `Latest: ${w.latest.id}${len} · the draft is from ${p.id}, ${edWords(w.edits)}`;
+ return `Latest: ${w.latest.id}${len} · ${edWords(w.edits)}`;
+}
+
+/**
+ * The draft's own line (Play's header, the bench): "Draft · from v5 · 3 edits",
+ * "Draft · from v5 · no edits", or "Draft · unsaved" (no version yet).
+ */
+export function draftLine(w) {
+ const p = w?.parent ?? null;
+ if (!p) return "Draft · unsaved";
+ const e = w.edits;
+ const n = !e ? "edits unknown" : e.count === 0 ? "no edits" : `${e.count} edit${e.count === 1 ? "" : "s"}`;
+ return `Draft · from ${p.id} · ${n}`;
}