// WALK A TAKE: the take's own edits, and making it the cut. // // A take is the project's manifest with a style's patch, then its own, merged // (takeManifest.mjs resolveTakeManifest -- the merge the take build uses). The // clip bench can walk one (`/projects/

/takes//walk`); everything the // walk writes -- a verdict, a trim, an attribution fix, a clip removed or // moved -- goes into the TAKE's patch, in takes//take.json, and the // project's manifest is never touched: // // updateTakeClip(dir, take, clip, patch) the bench's window/verdict save (updateClip's rules) // moveTakeEntry / removeTakeEntry the structure (applyStructural, the build's checks) // undoTakeEdit(dir, take) the newest edit taken back, byte for byte // promoteTake(project, take) "Make this the cut": the take over the project's // manifest through replaceManifest (one undo) // // THE TIMELINE IS THE PATCH'S. A merge patch replaces an array whole, so a // take's timeline is `patch.timeline` when it has one, else the project's. // Every edit here resolves the take's manifest as it is now, applies the edit // to its timeline with the project writer's own functions (patchClipEntry, // applyStructural -- manifest.mjs), and writes the WHOLE edited timeline back // as `patch.timeline`. A take whose patch had no timeline (a style take) gets // one on its first edit: from then on its timeline is its own, and an edit to // the project's timeline no longer reaches it. // // UNDO. Every write first copies take.json, as it still is, into // takes//revisions/--auto-before-.take.json -- every write, // not one per two minutes as the project's structural snapshots are: a walk is // many small edits and Undo means the last of them. undoTakeEdit restores the // newest such copy, keeps the take.json it replaces as `…-undo-saved…`, and // renames the restored one `…-undone-…` so the next undo goes one further. // // THE TOKEN is take.json's mtime, as the project's is its manifest's: a write // carrying a stale one is a StaleToken (a 409), never a silent overwrite. // // Plain ESM: `umtool window --take`, `umtool timeline --take` and // `umtool take --promote` run it under bare node. import { createHash } from "node:crypto"; import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { StaleToken, applyStructural, entryFromSpec, entryIndex, moveIn, patchClipEntry, removeIn, replaceManifest, setAnalysisIn, } from "./manifest.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { stampOf } from "./snapshots.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TAKE_REVISIONS_DIR = "revisions"; const AUTO = "auto-before-"; const REV_RE = /^(\d{8}-\d{6}-\d{3}(?:-\d+)?)-(.+)\.take\.json$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const serialise = (v) => JSON.stringify(v, null, 2) + "\n"; const clone = (v) => JSON.parse(JSON.stringify(v)); export const takeFileOf = (projectDir, id) => path.join(takesDirOf(projectDir), id, TAKE_FILE); export const takeRevisionsDirOf = (projectDir, id) => path.join(takesDirOf(projectDir), id, TAKE_REVISIONS_DIR); /** The mtime a client hands back to be allowed to write the take; null when there is no take.json. */ export async function takeToken(projectDir, id) { if (!isTakeId(id)) return null; const st = await stat(takeFileOf(projectDir, id)).catch(() => null); return st ? String(Math.round(st.mtimeMs)) : null; } // One queue per process, as manifest.mjs and takes.mjs keep their own: within // a process it serialises read-modify-write; across processes the tmp + rename // and the token are the guard. /** @type {Promise} */ let queue = Promise.resolve(); /** * @template T * @param {() => Promise} fn * @returns {Promise} */ export function withTakeEditLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, () => undefined, ); return run; } /** take.json as text and as an object; throws a sentence when there is none. */ async function readTakeDoc(projectDir, id) { if (!isTakeId(id)) throw new Error(`"${id}" is not a take id`); const text = await readFile(takeFileOf(projectDir, id), "utf8").catch(() => null); if (text === null) throw new Error(`no take ${id} (no takes/${id}/${TAKE_FILE}) — record one with \`umtool take --id ${id} --patch F --draft\``); let doc; try { doc = JSON.parse(text); } catch (e) { throw new Error(`takes/${id}/${TAKE_FILE} does not parse; not writing over it (${e instanceof Error ? e.message : e})`); } if (!isObj(doc)) throw new Error(`takes/${id}/${TAKE_FILE} is not an object`); return { text, doc }; } /** A revision name no other one has: the stamp, the milliseconds, and a counter if need be. */ async function freshRevisionName(revDir, label, now) { const base = `${stampOf(now)}-${String(now.getMilliseconds()).padStart(3, "0")}`; const taken = new Set(await readdir(revDir).catch(() => [])); for (let n = 0; ; n += 1) { const name = `${base}${n ? `-${n}` : ""}-${label}.take.json`; if (!taken.has(name)) return name; } } /** Copy take.json's text into the take's revisions/ as `-

--take insert --after `. * @param {string} projectDir * @param {string} id the take * @param {string | null} afterId * @param {unknown} spec * @param {{ token?: string | null, at?: number | null, now?: Date }} [opts] */ export async function insertTakeEntry(projectDir, id, afterId, spec, { token = null, at = null, now = new Date() } = {}) { return editTakeTimeline( projectDir, id, "insert", token, (m) => applyStructural(m, (x) => { const i = afterId ? entryIndex(x.timeline, afterId, at) + 1 : 0; const entry = entryFromSpec(x.timeline, spec); x.timeline.splice(i, 0, entry); return { id: entry.id, at: i, entry }; }), { now }, ); } /** * SET a video entry's knobs in a TAKE's timeline (video-entry.mjs * applyVideoPatch), checked as the build checks it; an undo point of the take's. */ export async function updateTakeVideoEntry(projectDir, id, entryId, patch, { token = null, at = null, now = new Date() } = {}) { const { applyVideoPatch, validateVideoEntry } = await import("umtool-report-to-video/video-entry"); if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change"); return editTakeTimeline( projectDir, id, "video", token, (m) => applyStructural(m, (x) => { const i = entryIndex(x.timeline, entryId, at); const e = x.timeline[i]; if (e.type !== "video") throw new Error(`${entryId} is a ${e.type ?? "non-video"} entry, not a video`); const next = applyVideoPatch(e, patch); const errors = validateVideoEntry(next, `timeline[${i}] (${entryId})`); if (errors.length) throw new Error(errors.join("; ")); x.timeline[i] = next; return { id: entryId, at: i, entry: next }; }), { now }, ); } /** * SET an analysis item's keys in a TAKE's timeline (manifest.mjs setAnalysisIn), checked as the build checks it * against the take's ledger and cut; an undo point of the take's. */ export async function updateTakeAnalysisEntry(projectDir, id, entryId, patch, { token = null, at = null, now = new Date() } = {}) { if (!patch || typeof patch !== "object" || !Object.keys(patch).length) throw new Error("nothing to change"); return editTakeTimeline(projectDir, id, "analysis", token, (m) => applyStructural(m, (x) => setAnalysisIn(x, entryId, patch, at)), { now }); } /** A take's label: one line, at most this long. */ export const TAKE_LABEL_MAX = 200; /** * RELABEL a take (UI notes 2026-10-30, item 19: "draft 9…" on draft-10): its * take.json `label`, with an undo point of the take's own first (`umtool * timeline

--take undo` takes it back). Refused while the take is * rendering: the render writes take.json LAST, from the label it started * with, and would put the old one back (takeHousekeeping.mjs renderHolds). * * @param {string} projectDir * @param {string} id * @param {string} label * @param {{ token?: string | null, now?: Date, holds?: string[] }} [opts] `holds`: renderHolds's sentences */ export async function relabelTake(projectDir, id, label, { token = null, now = new Date(), holds = [] } = {}) { const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim() : ""; if (!l) throw new Error("a take's label is a few words, not nothing"); if (l.length > TAKE_LABEL_MAX) throw new Error(`a take's label is at most ${TAKE_LABEL_MAX} characters (this one is ${l.length})`); if (holds.length) throw new Error(`take ${id} is not relabelled: ${holds.join("; ")}`); return withTakeEditLock(async () => { const current = await takeToken(projectDir, id); if (token !== null && current !== token) throw new StaleToken(token, current); const { text, doc } = await readTakeDoc(projectDir, id); const was = typeof doc.label === "string" ? doc.label : ""; if (was === l) return { id, label: l, was, token: current, revision: null }; const revision = await keepRevision(projectDir, id, text, `${AUTO}relabel`, now); doc.label = l; const nextToken = await writeTakeAtomic(projectDir, id, doc); return { id, label: l, was, token: nextToken, revision }; }); } /** * Take back the take's newest edit: its newest `auto-before-` revision * restored over take.json, byte for byte (see the top of the file). * * @param {string} projectDir * @param {string} id * @param {{ token?: string | null, now?: Date }} [opts] */ export async function undoTakeEdit(projectDir, id, { token = null, now = new Date() } = {}) { return withTakeEditLock(async () => { const current = await takeToken(projectDir, id); if (token !== null && current !== token) throw new StaleToken(token, current); const { text } = await readTakeDoc(projectDir, id); const target = (await listTakeRevisions(projectDir, id)).find((r) => r.auto); if (!target) throw new Error(`nothing to undo: take ${id} has no edit to take back`); const op = target.label.slice(AUTO.length); const dir = takeRevisionsDirOf(projectDir, id); const restored = await readFile(path.join(dir, target.name), "utf8"); JSON.parse(restored); // a revision that does not parse is not restored over a take.json that does const saved = await keepRevision(projectDir, id, text, "undo-saved", now); const file = takeFileOf(projectDir, id); const tmp = tmpPathFor(file); await writeFile(tmp, restored, "utf8"); await rename(tmp, file); const undone = target.name.replace(`-${target.label}.take.json`, `-undone-${op}.take.json`); await rename(path.join(dir, target.name), path.join(dir, undone)).catch(() => {}); return { restored: target.rel, op, saved: saved.rel, token: await takeToken(projectDir, id) }; }); } /** Did the take's walk write anything? (editedAt, and the undo points it left.) */ export async function takeEditState(projectDir, id) { const revisions = await listTakeRevisions(projectDir, id); return { undoable: revisions.filter((r) => r.auto).length, revisions }; } export class PromoteStale extends Error { /** @param {string} message */ constructor(message) { super(message); this.name = "PromoteStale"; } } const hashText = (text) => createHash("sha256").update(text).digest("hex"); /** * "Make this the cut": the take's manifest -- the project's as it is now, with * the take's style patch and its own (walked) patch applied, the same merge a * render makes -- written over the project's through replaceManifest (the lock, * the token, ONE auto snapshot `auto-before-promote-take`, so the Cut tab's * "Undo last edit" takes the whole promotion back), inside the generated- * manifest guard, then recorded as the take's group's pick in verdicts.json. * * Not "Use this take" (pickTake): that copies the manifest the take was * RENDERED from; this applies the take's patch now, so a draft, and a take * walked since its render, promote exactly what was walked. * * Checked by the build's structure rules (refused only for what the * promotion breaks). REFUSED (PromoteStale) when the take's patch replaces the * timeline and the project's manifest changed since the take was made -- the * promotion would throw away whatever the cut's timeline gained since -- * unless `anyway`. * * @param {{ id: string, dir: string, kind: string }} project * @param {string} id * @param {{ anyway?: boolean, token?: string | null, now?: Date }} [opts] */ export async function promoteTake(project, id, { anyway = false, token = null, now = new Date() } = {}) { const { doc } = await readTakeDoc(project.dir, id); const masterText = await readFile(path.join(project.dir, "video.manifest.json"), "utf8"); const master = JSON.parse(masterText); const { manifest: merged, note } = await resolveTakeManifest(project.dir, id, { base: master }); const replacesTimeline = isObj(doc.patch) && Array.isArray(doc.patch.timeline); if (!anyway && replacesTimeline) { if (typeof doc.baseHash !== "string" || !doc.baseHash) { throw new PromoteStale(`take ${id} does not record which manifest it was made from, and its timeline replaces the cut's`); } if (hashText(masterText) !== doc.baseHash) { throw new PromoteStale(`the project's manifest changed since take ${id} was made: its timeline would replace the cut's, and what the cut gained since would go`); } } // The build's structure rules, over the project's manifest becoming the take's. const next = clone(master); applyStructural(next, (m) => { for (const k of Object.keys(m)) delete m[k]; Object.assign(m, clone(merged)); }); const { result, editNotes } = await withEditNotes(project, () => replaceManifest(project.dir, next, { token, op: "promote-take" })); const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === id); const group = take ? listing.takes.filter((t) => t.group === take.group).map((t) => t.id) : [id]; const { verdicts } = await setTakePicked(project.dir, id, group, { now }); const clips = (next.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").length; return { take: id, snapshot: result.snapshot, token: result.token, editNotes, verdicts, note, clips, entries: (next.timeline ?? []).length }; }