// 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 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 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, in words ("aw3 removed", "mc1 moved"): a saved // version as the draft would hold it (versionManifestOf: its base // with any patch merged) against the draft AS IT IS; a legacy take // opened in the draft, what the open wrote against the draft as it // is; any other legacy take (main's rule), the manifest it RENDERED // against the draft with its patch -- 0 at once when a hash says the // draft is what was written; 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) // // Plain ESM: the CLI (`umtool takes ls`) reads it under bare node. import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { frozenBaseText, isWorkingTake, listTakes, readDraftFile, readVerdicts } from "./takes.mjs"; const hasFrozenBase = async (dir, id) => (await frozenBaseText(dir, id)) !== null; const MANIFEST = "video.manifest.json"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const hashText = (text) => createHash("sha256").update(text).digest("hex"); /** * The newest working take of a listing (listTakes's `takes`), or null. * * @template {{ id: string, builtAt?: string | null, order?: number }} T * @param {T[]} takes * @returns {T | null} */ export function latestWorkingTake(takes) { const ok = (takes ?? []).filter((t) => isWorkingTake(/** @type {any} */ (t)) && t.builtAt); ok.sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt)) || (b.order ?? 0) - (a.order ?? 0) || b.id.localeCompare(a.id)); return ok[0] ?? null; } /** What changed on an entry, as a word: a trim, gaps, the verdict, or an edit. */ function changeWord(a, b) { const differs = (k) => JSON.stringify(a?.[k] ?? null) !== JSON.stringify(b?.[k] ?? null); if (["start", "end", "cutStart", "cutEnd"].some(differs)) return "trimmed"; if (differs("gaps")) return "gaps"; if (["verdict", "reason", "correction"].some(differs)) return "verdict"; return "edited"; } /** * The edits from timeline `before` to `after`, by entry id: added, removed, * moved (not on the longest run kept in order) and changed (same id, other * fields), plus whether anything outside the timeline changed. `count` is the * number of entries touched (+1 for the rest of the manifest); `words` one * phrase per entry, in the order of `after`. * * @param {Record} before * @param {Record} after */ export function cutDiff(before, after) { const A = (Array.isArray(before?.timeline) ? before.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); const B = (Array.isArray(after?.timeline) ? after.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); const inA = new Map(A.map((e) => [e.id, e])); const inB = new Map(B.map((e) => [e.id, e])); const removed = A.filter((e) => !inB.has(e.id)).map((e) => e.id); const added = B.filter((e) => !inA.has(e.id)).map((e) => e.id); // The longest run of common ids kept in order: everything off it moved. const a = A.map((e) => e.id).filter((id) => inB.has(id)); const b = B.map((e) => e.id).filter((id) => inA.has(id)); const posA = new Map(a.map((id, i) => [id, i])); const seq = b.map((id) => posA.get(id)); // Patience LIS over positions. const tails = []; const prevIdx = new Array(seq.length).fill(-1); const tailIdx = []; seq.forEach((v, i) => { let lo = 0; let hi = tails.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (tails[mid] < v) lo = mid + 1; else hi = mid; } tails[lo] = v; tailIdx[lo] = i; prevIdx[i] = lo > 0 ? tailIdx[lo - 1] : -1; }); const kept = new Set(); for (let i = tailIdx[tails.length - 1] ?? -1; i >= 0; i = prevIdx[i]) kept.add(b[i]); const moved = b.filter((id) => !kept.has(id)); const changed = b.filter((id) => JSON.stringify(inA.get(id)) !== JSON.stringify(inB.get(id))).map((id) => ({ id, what: changeWord(inA.get(id), inB.get(id)) })); const { timeline: _a, ...restA } = isObj(before) ? before : {}; const { timeline: _b, ...restB } = isObj(after) ? after : {}; const rest = JSON.stringify(restA) !== JSON.stringify(restB); const words = []; const movedSet = new Set(moved); const changedOf = new Map(changed.map((c) => [c.id, c.what])); for (const e of B) { const parts = []; if (!inA.has(e.id)) parts.push("added"); else { if (movedSet.has(e.id)) parts.push("moved"); if (changedOf.has(e.id)) parts.push(changedOf.get(e.id)); } if (parts.length) words.push(`${e.id} ${parts.join(", ")}`); } for (const id of removed) words.push(`${id} removed`); if (rest) words.push("the look or the deck changed"); const touched = new Set([...added, ...removed, ...moved, ...changed.map((c) => c.id)]); return { added, removed, moved, changed, rest, count: touched.size + (rest ? 1 : 0), words }; } async function readJson(file) { try { return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); } catch { return null; } } /** * 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 }} [opts] */ 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; 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; const h = text !== null ? hashText(text) : null; const diffOf = (a, b) => { const d = cutDiff(a, b); return { count: d.count, words: d.words, same: d.count === 0 }; }; if (text !== null && (await hasFrozenBase(projectDir, parentTake.id))) { // A SAVED VERSION: the version as the draft would hold it (its base, with any patch laid over it since -- a // "No intro" toggle) against the draft AS IT IS. Never the version's patch over the draft: a key the patch // sets would mask the draft's own edit of it. try { const { versionManifestOf } = await import("./takeMaker.mjs"); const v = await versionManifestOf(projectDir, parentTake.id); edits = v && v.exact && hashText(v.text) === h ? { count: 0, words: [], same: true } : v ? diffOf(v.manifest, JSON.parse(text)) : null; } catch { edits = null; } } else if (text !== null && fromDraft && draft?.base) { // A legacy take opened in the draft: the edits since the open, against what it wrote (as it is, no patch). try { edits = draft.hash === h ? { count: 0, words: [], same: true } : diffOf(draft.base, JSON.parse(text)); } catch { edits = null; } } else if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true }; else if (text !== null) { // A legacy take (main's rule): the manifest it rendered against the draft with its patch laid over it. const { frozenManifestOf, resolveTakeManifest } = await import("./takeManifest.mjs"); const frozen = await frozenManifestOf(projectDir, parentTake.id); let now = null; try { now = (await resolveTakeManifest(projectDir, parentTake.id, { base: JSON.parse(text), frozen: false })).manifest; } catch { now = null; } if (frozen && isObj(now)) edits = diffOf(frozen.manifest, now); } 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. 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) { 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")}` : ""; 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}`; }