Archilyzer · Source

archilyzer

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

commit 9e89455caea86f05f15f10b42c589d5699b4c49b
parent 52031712c36df4442ab51854b89febbb6c21ed65
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 14:33:26 -0400

umtool: walk a take -- draft takes, the take's own edits with undo, promote, and the CLI twins

- umtool take <p> --id X --patch F --draft (--no-render): the take recorded,
  nothing rendered; a later umtool take <p> --id X --full (or --rebuild with a
  window flag) renders it from its stored, possibly walked, patch.
- takeEdit.mjs: updateTakeClip / moveTakeEntry / removeTakeEntry write into the
  take's patch.timeline through the project writer's own rules (patchClipEntry,
  applyStructural), each with an undo point in takes/<id>/revisions/;
  undoTakeEdit takes the newest back byte for byte; the manifest is untouched.
- promoteTake (umtool take <p> --id X --promote [--anyway]): the take's patch
  applied to the manifest through replaceManifest, one auto snapshot, so the
  Cut tab's Undo takes it back; refused when the cut moved on and the take
  replaces its timeline.
- walkData.mjs: the walk of the cut or of a take (order, verdicts, fetched,
  who is on it; all=1 walks every fetched clip) -- umtool walk <p> [--take X].
- umtool window <p> <clip> --take X and umtool timeline <p> --take X
  ls|move|remove|undo.
- A windowed render of a take whose timeline holds none of the entries the
  window covers is timed over its own timeline instead of refused.

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

Diffstat:
Mumtool/bin/umtool.mjs | 36++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeCli.mjs | 64+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Aumtool/lib/report/takeEdit.mjs | 306+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeEdit.test.mjs | 322+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 107++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/report/takeMaker.test.mjs | 11+++++++----
Mumtool/lib/report/takes.mjs | 9+++++++++
Mumtool/lib/report/takes.test.mjs | 2++
Mumtool/lib/report/timelineCli.mjs | 58+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/report/walkCli.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/walkData.mjs | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 1114 insertions(+), 15 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -23,6 +23,8 @@ // [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q] // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// [--take <id>] a take's clip: the edit goes into the take's patch (walk a take) +// umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched // umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, // marks=<json> mark.add=<verdict>[@<sec>] mark.remove=<id> mark.verdict=<v> [--mark <id>], // audio.offset|gain|fadeIn|fadeOut (`key=` clears) (docs/knobs.md) @@ -56,6 +58,7 @@ // the operator's notes, and the agent's answers // umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] // [--at S --dur S | --full] [--force] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take +// [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] // umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] // [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master @@ -73,6 +76,7 @@ // umtool timeline <project> [ls | insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--title …] // [--date …] [--quote …] [--cite S] | move <id> --to <index> | remove <id> | duplicate <id> | // post <json|@file> | post-remove <id> | teaser <id> <patch-json> | undo] the cut's structure +// [--take <id>] ls | move | remove | undo on a take's timeline (its patch, not the manifest) // umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--json] cuts + black spans, source seconds // umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag …] a post from the archive import process from "node:process"; @@ -722,6 +726,10 @@ function usage() { " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --cut-start S --cut-end E --lock-cut the cut the video renders", " an empty value (--title '') deletes the field", + " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's", + " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched", + " umtool walk <project> [--take <id>] [--all] [--json] the clip bench's walk: every clip in walk order,", + " its verdict, fetched or not, and (→) the ones the walk visits; --take walks a take (a draft too)", " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):", " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp", " claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]", @@ -772,6 +780,10 @@ function usage() { " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]", " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;", " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)", + " --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later", + " (`umtool take <p> --id <id> --full` renders a draft from its stored patch)", + " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the", + " manifest, one undo point (revisions/…-auto-before-promote-take)", " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]", " a trailer cut from the take's finished master: the master's own frames, so the deck shows the", @@ -804,6 +816,8 @@ function usage() { " umtool timeline <project> post <json|@file> | post-remove <id> | teaser <id> <patch-json|@file> | undo", " the Cut tab's structure (POST /api/report/timeline's writers): each write snapshots the", " manifest first (revisions/…-auto-before-<op>), is checked by the build, notes a generated cut", + " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:", + " the writes go into its patch (takes/<id>/take.json), each with an undo point of its own", " umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 | --from S --to S] [--json]", " scene cuts (scdet) and black spans (blackdetect) in the clip's fetched window, in SOURCE", " seconds — for blur.from/blur.to and trims; nothing fetched (`umtool fetch` first)", @@ -822,6 +836,8 @@ function usage() { const COMMANDS = { ls: cmdLs, window: cmdWindow, + // The clip bench's walk, of the cut or of a take (walk a take): lib/report/walkCli.mjs. + walk: async () => process.exit(await (await import("../lib/report/walkCli.mjs")).walkCommand(argv.slice(argv.indexOf("walk") + 1))), link: cmdLink, // The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs. set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))), @@ -956,6 +972,26 @@ async function cmdWindow() { } if (!Object.keys(patch).length) die("nothing to change"); + // --take <id>: the clip is the TAKE's (walk a take), and the edit goes into + // the take's patch (takes/<id>/take.json) through the walk's writer -- the + // same rules, an undo point first -- never into the project's manifest. + const take = val("--take"); + if (take !== undefined) { + try { + const { updateTakeClip } = await import("../lib/report/takeEdit.mjs"); + const res = await updateTakeClip(p.dir, take, clipId, patch); + if (json) return out({ ok: true, take, ...res }); + console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`); + if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`); + if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${clipVerdict(res.entry)}`); + if (res.entry.correction) console.log(` correction: ${res.entry.correction}`); + console.log(` undo point: takes/${take}/${res.revision.rel} (umtool timeline ${p.id} --take ${take} undo)`); + return; + } catch (e) { + die(e?.message ?? String(e)); + } + } + try { // Through the SAME writer the bench uses: 2 dp, the CLI's own formatting, // tmp+rename, one .bak. A second implementation here is how the two would diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -23,6 +23,7 @@ import { RECIPE_FILE, TakeStale, allStylesRecipe, + draftTake, loadMontageStyles, makeTake, makeTakes, @@ -38,7 +39,15 @@ export const TAKE_USAGE = [ " [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]", " [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]", " [--from TAKE] [--keep-frames]", - " umtool take <project> --id <id> --rebuild [--from TAKE] [--keep-frames] made again from its own take.json", + " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames]", + " made again from its own take.json (its stored patch, walked edits included); a window", + " flag renders it over that window instead of its own", + " umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,", + " nothing rendered: it can be walked (/projects/<p>/takes/<id>/walk, `umtool walk <p> --take <id>`)", + " and its clips edited into its patch; `umtool take <p> --id <id> --full` renders it later", + " umtool take <project> --id <id> --promote [--anyway] [--json] make this the cut: the take's manifest", + " (its patch applied to the project's manifest now) over the project's -- one undo point", + " (revisions/…-auto-before-promote-take; `umtool timeline <p> undo` takes it back)", "", "A take is the project's manifest with a style's patch, then the take's own, applied (JSON merge", "patches), rendered into takes/<id>/. The window renders the entries it covers; --full the whole", @@ -194,21 +203,28 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons const out = reporter(p, log, err); const id = p.one("--id"); if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)"); + if (p.has("--promote")) return await promote(project, id, p, log, err); + const draft = p.has("--draft") || p.has("--no-render"); + const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); + // A DRAFT named with no patch of its own is rendered from what it stores -- + // its patch as the walk left it -- as --rebuild is: `umtool take <p> --id X --full`. + const patchGiven = ["--patch", "--patch-json", "--set", "--style", "--effect"].some((n) => p.has(n)); + const fromStored = p.has("--rebuild") || (!draft && prev?.draft === true && !patchGiven); + if (draft && p.has("--rebuild")) throw new CliError("--draft or --rebuild, not both"); let spec; - if (p.has("--rebuild")) { - const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); + if (fromStored) { if (!prev) throw new CliError(`${project.id} has no take ${id} to rebuild`); spec = { id, - label: prev.label, + label: p.one("--label") ?? prev.label, group: prev.group, order: prev.order, kind: prev.kind === "similar" ? "similar" : undefined, summary: prev.summary, style: prev.style ?? null, patch: prev.patch ?? null, - window: prev.window ?? undefined, - quick: prev.quick === true, + window: windowOf(p) ?? prev.window ?? undefined, + quick: p.has("--quick") || prev.quick === true, }; } else { spec = { @@ -223,8 +239,20 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons quick: p.has("--quick"), }; } + if (draft) { + const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) }); + if (p.has("--json")) { + log(JSON.stringify({ ok: true, draft: true, ...d }, null, 2)); + return 0; + } + out.log(`take ${id}: a draft, nothing rendered — ${d.clips} clip(s), ${d.entries} entr${d.entries === 1 ? "y" : "ies"}`); + for (const c of d.take.changes.slice(0, 8)) out.log(` ${c}`); + out.log(`walk it: umtool walk ${project.id} --take ${id} (the bench: /projects/${project.id}/takes/${id}/walk)`); + out.log(`render it: umtool take ${project.id} --id ${id} --full`); + return 0; + } const r = await makeTake(project.dir, spec, { - force: p.has("--force") || p.has("--rebuild"), + force: p.has("--force") || fromStored, from: p.one("--from") ?? null, keepFrames: p.has("--keep-frames"), emit: out.emit, @@ -243,6 +271,28 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons } } +/** `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"); + try { + const r = await promoteTake(project, id, { anyway: p.has("--anyway") }); + if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); + else { + log(`${project.id}: take ${id} is the cut now — ${r.clips} clip(s), ${r.entries} entr${r.entries === 1 ? "y" : "ies"}`); + if (r.note) log(` ${r.note}`); + if (r.snapshot?.rel && !r.snapshot.skipped) log(` undo point: ${r.snapshot.rel} (umtool timeline ${project.id} undo)`); + else if (r.snapshot?.error) log(` NO undo point: ${r.snapshot.error}`); + } + return 0; + } catch (e) { + if (e instanceof PromoteStale) { + err(`${e.message} — pass --anyway to make it the cut all the same`); + return 1; + } + throw e; + } +} + /** * `umtool takes …` * @param {string[]} args everything after `takes` diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -0,0 +1,306 @@ +// 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/<p>/takes/<take>/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/<id>/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/<id>/revisions/<stamp>-<ms>-auto-before-<op>.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-<op>…` 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, + moveIn, + patchClipEntry, + removeIn, + replaceManifest, +} from "./manifest.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { resolveTakeManifest } from "./takeManifest.mjs"; +import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { stampOf } from "./snapshots.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<unknown>} */ +let queue = Promise.resolve(); +/** + * @template T + * @param {() => Promise<T>} fn + * @returns {Promise<T>} + */ +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 <project> --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 `<stamp>-<label>.take.json`. */ +async function keepRevision(projectDir, id, text, label, now) { + const dir = takeRevisionsDirOf(projectDir, id); + await mkdir(dir, { recursive: true }); + const name = await freshRevisionName(dir, label, now); + await writeFile(path.join(dir, name), text, "utf8"); + return { rel: path.posix.join(TAKE_REVISIONS_DIR, name), name }; +} + +async function writeTakeAtomic(projectDir, id, doc) { + const file = takeFileOf(projectDir, id); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, serialise(doc), "utf8"); + await rename(tmp, file); + return takeToken(projectDir, id); +} + +/** + * The take's revisions, newest first: `{ rel, name, stamp, label, auto }`. + * `auto` is an undo point (`auto-before-<op>`). + */ +export async function listTakeRevisions(projectDir, id) { + if (!isTakeId(id)) return []; + const names = await readdir(takeRevisionsDirOf(projectDir, id)).catch(() => []); + return names + .map((name) => { + const m = REV_RE.exec(name); + return m ? { rel: path.posix.join(TAKE_REVISIONS_DIR, name), name, stamp: m[1], label: m[2], auto: m[2].startsWith(AUTO) } : null; + }) + .filter((r) => r !== null) + .sort((a, b) => b.stamp.localeCompare(a.stamp, "en", { numeric: true }) || b.name.localeCompare(a.name)); +} + +/** + * One write to the take's timeline: the token, the take's manifest resolved + * as it is now, `mutate` over it (which throws to refuse), the undo point, + * then `patch.timeline` and `editedAt` written into take.json. + * + * @template T + * @param {string} projectDir + * @param {string} id + * @param {string} op + * @param {string | null} token + * @param {(manifest: Record<string, any>) => T} mutate + * @param {{ now?: Date }} [opts] + * @returns {Promise<T & { token: string | null, revision: { rel: string, name: string } }>} + */ +async function editTakeTimeline(projectDir, id, op, token, mutate, { now = new Date() } = {}) { + 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 resolved = await resolveTakeManifest(projectDir, id); + const manifest = clone(resolved.manifest); + const result = mutate(manifest); + const revision = await keepRevision(projectDir, id, text, `${AUTO}${op}`, now); + doc.patch = { ...(isObj(doc.patch) ? doc.patch : {}), timeline: manifest.timeline }; + doc.editedAt = now.toISOString(); + const nextToken = await writeTakeAtomic(projectDir, id, doc); + return { ...result, token: nextToken, revision }; + }); +} + +/** + * The bench's save, on a take: one clip's window, locks, attribution, + * verdict and the rest -- updateClip's whitelist and its rules + * (patchClipEntry), written into the take's patch. + * + * @param {string} projectDir + * @param {string} id the take + * @param {string} clipId + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null, edit?: string, now?: Date }} [opts] + */ +export async function updateTakeClip(projectDir, id, clipId, patch, { token = null, edit = "trim", now = new Date() } = {}) { + if (!isObj(patch)) throw new Error("a clip patch is an object"); + return editTakeTimeline( + projectDir, + id, + edit === "trim" ? "clip" : edit, + token, + (m) => patchClipEntry(m, clipId, patch, { edit, now: now.toISOString() }), + { now }, + ); +} + +/** Move one of the take's entries to `toIndex` (its index after the move). */ +export async function moveTakeEntry(projectDir, id, entryId, toIndex, { token = null, at = null, now = new Date() } = {}) { + return editTakeTimeline(projectDir, id, "move", token, (m) => applyStructural(m, (x) => moveIn(x, entryId, toIndex, at)), { now }); +} + +/** Remove one of the take's entries (refused when something the take keeps still names it). */ +export async function removeTakeEntry(projectDir, id, entryId, { token = null, at = null, now = new Date() } = {}) { + return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at)), { now }); +} + +/** + * Take back the take's newest edit: its newest `auto-before-<op>` 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 = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + 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 }; +} diff --git a/umtool/lib/report/takeEdit.test.mjs b/umtool/lib/report/takeEdit.test.mjs @@ -0,0 +1,322 @@ +// Walk a take: a draft recorded without rendering, the walk's edits written +// into the take's patch (never the project's manifest) with an undo point +// each, undone byte for byte, a draft rendered from its edited patch, the +// walk's reading (walkData, what GET /api/report/walk and `umtool walk` +// answer), and "Make this the cut" (promoteTake) with its one undo. +// +// Run with: node --test lib/report/takeEdit.test.mjs +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { StaleToken, StructureRefused, undoStructural } from "./manifest.mjs"; +import { draftTake } from "./takeMaker.mjs"; +import { + PromoteStale, + listTakeRevisions, + moveTakeEntry, + promoteTake, + removeTakeEntry, + takeToken, + undoTakeEdit, + updateTakeClip, +} from "./takeEdit.mjs"; +import { listTakes, readVerdicts } from "./takes.mjs"; +import { resolveTakeManifest } from "./takeManifest.mjs"; +import { takeCommand } from "./takeCli.mjs"; +import { timelineCommand } from "./timelineCli.mjs"; +import { walkCommand } from "./walkCli.mjs"; +import { walkJson, walkNeighbours, walkOf } from "./walkData.mjs"; +import { PROJECT_KINDS } from "../projects/kinds.mjs"; + +const TAKES_KIND = PROJECT_KINDS.find((k) => k.makesTakes).id; +const clip = (id, start, end, extra = {}) => ({ type: "clip", id, channel: "chan", video: "vid", start, end, cite: start, ...extra }); + +const MANIFEST = { + schemaVersion: 1, + slug: "fixture", + title: "Fixture", + render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30 }, + timeline: [clip("c01", 100, 160, { verdict: "confirmed" }), clip("c02", 200, 260, { verdict: "confirmed" }), clip("c03", 300, 360)], +}; + +/** The tight version: sub-windows of the master's clips, a whole `timeline` merge patch. */ +const TIGHT = { + timeline: [ + clip("t01a", 105, 115, { verdict: "confirmed" }), + clip("t01b", 130, 150, { verdict: "confirmed" }), + clip("t02a", 210, 230), + clip("t03a", 310, 320), + ], +}; + +async function project(manifest = MANIFEST) { + const root = await mkdtemp(path.join(tmpdir(), "takeedit-")); + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "proj"); + // One fetched window holding c01..c02's span (and so t01a, t01b, t02a); nothing for c03 / t03a. + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await writeFile(path.join(dir, "out", "clips-raw", "vid_90.00-270.00.mp4"), "media"); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); + const ref = { id: "proj", dir, kind: TAKES_KIND }; + return { root, dir, reportsRoot, ref }; +} + +const masterText = (dir) => readFile(path.join(dir, "video.manifest.json"), "utf8"); +const takeJson = async (dir, id) => JSON.parse(await readFile(path.join(dir, "takes", id, "take.json"), "utf8")); + +function stubRender() { + const calls = []; + const render = async (job) => { + const doc = JSON.parse(await readFile(job.manifestPath, "utf8")); + calls.push({ ...job, doc }); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "render"); + return { file }; + }; + return { render, calls }; +} + +test("a draft take is recorded, not rendered: listed as a draft, its manifest is the project's with its patch", async () => { + const { root, dir } = await project(); + try { + const d = await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + assert.equal(d.clips, 4); + const t = await takeJson(dir, "tight"); + assert.equal(t.draft, true); + assert.equal(t.builtAt, null); + assert.equal(t.window, null, "a draft says its window when it is rendered"); + assert.ok(t.baseHash); + assert.deepEqual(await readdir(path.join(dir, "takes", "tight")), ["take.json"], "nothing rendered, no manifest copied"); + const listed = (await listTakes(dir)).takes; + assert.equal(listed.length, 1); + assert.equal(listed[0].draft, true); + assert.equal(listed[0].previewSize, null); + const { manifest } = await resolveTakeManifest(dir, "tight"); + assert.deepEqual(manifest.timeline.map((e) => e.id), ["t01a", "t01b", "t02a", "t03a"]); + // Again: refused, then --force records it again; a RENDERED take is never drafted over. + await assert.rejects(draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }), /exists \(a draft\)/); + await draftTake(dir, { id: "tight", label: "Tight 2", patch: TIGHT }, { force: true }); + assert.equal((await takeJson(dir, "tight")).label, "Tight 2"); + await assert.rejects(draftTake(dir, { id: "x", label: "X", patch: { timeline: "no" } }), /no timeline/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("the walk's edits go into the take's patch with an undo point each; the project's manifest is untouched", async () => { + const { root, dir } = await project(); + try { + await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + const before = await masterText(dir); + const token = await takeToken(dir, "tight"); + const r = await updateTakeClip(dir, "tight", "t02a", { end: 233.456, verdict: "confirmed" }, { token }); + assert.equal(r.entry.end, 233.46, "2 dp, the project writer's rule"); + assert.equal(r.before.end, 230); + assert.notEqual(r.token, token); + let t = await takeJson(dir, "tight"); + const e = t.patch.timeline.find((x) => x.id === "t02a"); + assert.equal(e.end, 233.46); + assert.equal(e.verdict, "confirmed"); + assert.ok(t.editedAt); + assert.equal(t.draft, true, "still a draft"); + assert.equal(await masterText(dir), before, "the project's manifest is never written"); + // The project writer's own refusals. + await assert.rejects(updateTakeClip(dir, "tight", "t03a", { verdict: "incorrect" }), /needs its note/); + await assert.rejects(updateTakeClip(dir, "tight", "t03a", { start: 319.9 }), /at least half a second/); + await assert.rejects(updateTakeClip(dir, "tight", "c01", { end: 150 }), /no timeline entry with id c01/, "the master's clip is not the take's"); + // A stale token is refused, not written over. + await assert.rejects(updateTakeClip(dir, "tight", "t03a", { verdict: "confirmed" }, { token }), StaleToken); + // Structure: move and remove, checked by the build's rules. + await moveTakeEntry(dir, "tight", "t03a", 0); + await removeTakeEntry(dir, "tight", "t01b"); + t = await takeJson(dir, "tight"); + assert.deepEqual(t.patch.timeline.map((x) => x.id), ["t03a", "t01a", "t02a"]); + const revs = await listTakeRevisions(dir, "tight"); + assert.deepEqual(revs.map((x) => x.label), ["auto-before-remove", "auto-before-move", "auto-before-clip"]); + // Undo: newest first, byte for byte, one step further each time. + let u = await undoTakeEdit(dir, "tight"); + assert.equal(u.op, "remove"); + assert.deepEqual((await takeJson(dir, "tight")).patch.timeline.map((x) => x.id), ["t03a", "t01a", "t01b", "t02a"]); + u = await undoTakeEdit(dir, "tight"); + assert.equal(u.op, "move"); + u = await undoTakeEdit(dir, "tight"); + assert.equal(u.op, "clip"); + assert.deepEqual((await takeJson(dir, "tight")).patch, TIGHT, "back to the patch as drafted"); + await assert.rejects(undoTakeEdit(dir, "tight"), /nothing to undo/); + assert.equal(await masterText(dir), before); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a take whose patch has no timeline (a style take) gets the cut's timeline on its first edit", async () => { + const { root, dir } = await project(); + try { + await draftTake(dir, { id: "crisp", label: "Crisp", patch: { render: { crf: 33 } } }); + await updateTakeClip(dir, "crisp", "c03", { verdict: "confirmed" }); + const t = await takeJson(dir, "crisp"); + assert.equal(t.patch.render.crf, 33, "the rest of the patch is kept"); + assert.deepEqual(t.patch.timeline.map((x) => x.id), ["c01", "c02", "c03"]); + assert.equal(t.patch.timeline[2].verdict, "confirmed"); + assert.equal(JSON.parse(await masterText(dir)).timeline[2].verdict, undefined); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a refused structure edit writes nothing; removing a clip a post is attached to is the build's sentence", async () => { + const { root, dir } = await project({ ...MANIFEST, posts: [{ id: "p1", platform: "x", date: "2026-01-01", text: "hi", url: "https://x.com/a/status/1", attachTo: "t01a" }] }); + try { + await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + const t0 = await readFile(path.join(dir, "takes", "tight", "take.json"), "utf8"); + await assert.rejects(removeTakeEntry(dir, "tight", "t01a"), StructureRefused); + assert.equal(await readFile(path.join(dir, "takes", "tight", "take.json"), "utf8"), t0); + assert.deepEqual(await listTakeRevisions(dir, "tight"), []); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("draft, walk, then render: the render reads the edited patch, and the take is made", async () => { + const { root, dir, reportsRoot } = await project(); + const r = stubRender(); + const out = []; + const err = []; + const io = { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s), deps: { render: r.render, probe: async () => 42 } }; + try { + await writeFile(path.join(root, "patch.json"), JSON.stringify(TIGHT)); + assert.equal(await takeCommand(["proj", "--id", "tight", "--patch", path.join(root, "patch.json"), "--draft", "--label", "Tight — walk"], io), 0, err.join("\n")); + assert.match(out.join("\n"), /a draft, nothing rendered — 4 clip\(s\)/); + assert.equal(r.calls.length, 0, "a draft renders nothing"); + await updateTakeClip(dir, "tight", "t01a", { start: 104 }); + await removeTakeEntry(dir, "tight", "t03a"); + // `umtool take <p> --id X --full`: the draft, from what it stores. + assert.equal(await takeCommand(["proj", "--id", "tight", "--full"], io), 0, err.join("\n")); + assert.equal(r.calls.length, 1); + assert.equal(r.calls[0].full, true); + assert.deepEqual(r.calls[0].doc.timeline.map((e) => [e.id, e.start]), [["t01a", 104], ["t01b", 130], ["t02a", 210]]); + const t = await takeJson(dir, "tight"); + assert.equal(t.draft, undefined, "made now"); + assert.equal(t.label, "Tight — walk"); + assert.equal(t.window, "full"); + assert.equal(t.seconds, 42); + const listed = (await listTakes(dir)).takes[0]; + assert.equal(listed.draft, false); + assert.ok(listed.previewSize > 0); + // --rebuild takes a window flag now. + assert.equal(await takeCommand(["proj", "--id", "tight", "--rebuild", "--at", "0", "--dur", "5"], io), 0, err.join("\n")); + assert.deepEqual((await takeJson(dir, "tight")).window, { at: 0, dur: 5 }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("walkOf: the take's clips in walk order, the walk visiting the fetched unjudged ones (all: every fetched one)", async () => { + const { root, dir, ref } = await project(); + try { + await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + const w = await walkOf(ref, { take: "tight" }); + assert.equal(w.take.id, "tight"); + assert.equal(w.take.draft, true); + assert.equal(w.take.editable, true); + assert.deepEqual(w.order, ["t01a", "t01b", "t02a", "t03a"]); + assert.deepEqual(w.clips.map((c) => [c.id, c.verdict, c.fetched, c.onWalk]), [ + ["t01a", "confirmed", true, false], + ["t01b", "confirmed", true, false], + ["t02a", "unreviewed", true, true], + ["t03a", "unreviewed", false, false], + ]); + assert.equal(w.first, "t02a"); + assert.equal(w.needing, 2); + assert.equal(w.ready, 1); + assert.equal(w.token, await takeToken(dir, "tight")); + assert.equal(w.seconds, 60); + const all = await walkOf(ref, { take: "tight", all: true }); + assert.equal(all.first, "t01a"); + assert.deepEqual(walkNeighbours(all.order, all.onWalk, "t01b"), { prev: "t01a", next: "t02a" }); + assert.deepEqual(walkNeighbours(all.order, all.onWalk, "t03a"), { prev: "t02a", next: null }); + // The route's JSON: no manifest, no Set. + const j = walkJson(all); + assert.equal(j.manifest, undefined); + assert.equal(j.onWalk, undefined); + assert.ok(JSON.stringify(j)); + // The project's own walk is unchanged by the take. + const master = await walkOf(ref); + assert.equal(master.take, null); + assert.deepEqual(master.order, ["c01", "c02", "c03"]); + await assert.rejects(walkOf(ref, { take: "nope" }), /no take nope/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("promoteTake: the take's patch over the project's manifest, one undo point; refused when the cut moved on, unless anyway", async () => { + const { root, dir, ref } = await project(); + try { + await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + await updateTakeClip(dir, "tight", "t03a", { verdict: "incorrect", correction: "not her" }); + const before = await masterText(dir); + const r = await promoteTake(ref, "tight"); + assert.equal(r.clips, 4); + assert.match(r.snapshot.rel, /auto-before-promote-take/); + const m = JSON.parse(await masterText(dir)); + assert.deepEqual(m.timeline.map((e) => e.id), ["t01a", "t01b", "t02a", "t03a"]); + assert.equal(m.timeline[3].correction, "not her", "the walk's edits are what is promoted"); + assert.equal(m.render.crf, 30, "the rest of the manifest is the project's"); + assert.equal((await readVerdicts(dir)).tight.picked, true); + // One undo takes the whole promotion back, byte for byte. + await undoStructural(dir); + assert.equal(await masterText(dir), before); + + // The cut changed since the take was made: refused, then made all the same with anyway. + const changed = JSON.parse(before); + changed.timeline[2].verdict = "confirmed"; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(changed, null, 2) + "\n"); + await assert.rejects(promoteTake(ref, "tight"), PromoteStale); + await promoteTake(ref, "tight", { anyway: true }); + assert.equal(JSON.parse(await masterText(dir)).timeline[0].id, "t01a"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --promote", async () => { + const { root, dir, reportsRoot } = await project(); + const out = []; + const err = []; + const io = { root: reportsRoot, out: (s) => out.push(s), err: (s) => err.push(s) }; + try { + await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }); + assert.equal(await walkCommand(["proj", "--take", "tight"], io), 0, err.join("\n")); + const text = out.join("\n"); + assert.match(text, /take tight "Tight" \(draft\) · 4 clip\(s\)/); + assert.match(text, /→ +3 +t02a/); + assert.match(text, /NOT FETCHED/); + assert.match(text, /\/projects\/proj\/takes\/tight\/walk/); + out.length = 0; + assert.equal(await walkCommand(["proj", "--take", "tight", "--all", "--json"], io), 0, err.join("\n")); + assert.equal(JSON.parse(out.join("\n")).first, "t01a"); + + out.length = 0; + assert.equal(await timelineCommand(["proj", "--take", "tight", "move", "t03a", "--to", "0"], io), 0, err.join("\n")); + assert.match(out.join("\n"), /take tight: moved t03a: 3 -> 0/); + assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); + assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "--after", "-", "chan/vid@1-5"], io), 2, "only ls, move, remove, undo on a take"); + out.length = 0; + assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n")); + assert.match(out.join("\n"), /4 entries in take tight of proj$/, "the move was undone: nothing left to undo"); + + const log = []; + const before = await masterText(dir); + assert.equal(await takeCommand(["proj", "--id", "tight", "--promote"], { reportsRoot, log: (s) => log.push(s), err: (s) => err.push(s) }), 0, err.join("\n")); + assert.match(log.join("\n"), /take tight is the cut now — 4 clip\(s\)/); + assert.notEqual(await masterText(dir), before); + const st = await stat(path.join(dir, "revisions")); + assert.ok(st.isDirectory()); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -536,7 +536,19 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { const [schedSt, manSt] = await Promise.all([stat(scheduleFile).catch(() => null), stat(path.join(projectDir, MANIFEST)).catch(() => null)]); log(`${spec.id}: ${windowBasisLine(covered, { schedule: !!schedule, scheduleOlder: !!(schedSt && manSt && schedSt.mtimeMs < manSt.mtimeMs) })}`); const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id)); - const ids = withPatchEntries(ruled.manifest.timeline, base.timeline, covered.ids).filter((id) => present.has(id)); + let ids = withPatchEntries(ruled.manifest.timeline, base.timeline, covered.ids).filter((id) => present.has(id)); + // A take whose patch REPLACES the timeline with entries of its own (a + // tight version, walked) holds none of the project's entries to cover: + // its window is timed over its OWN timeline instead (by the estimates -- + // the deck's schedule names the project's entries). + if (!ids.length && isObj(spec.patch) && Array.isArray(spec.patch.timeline) && !covered.ids.some((id) => present.has(id))) { + covered = windowEntries(ruled.manifest.timeline, spec.window, null); + log( + `${spec.id}: none of those is in the take's own timeline — the window covers ${covered.ids.length} of ITS entries ` + + `(${covered.ids.join(", ")}), timed by their own lengths`, + ); + ids = covered.ids.filter((id) => present.has(id)); + } 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); } @@ -634,6 +646,84 @@ export async function makeTake(projectDir, rawSpec, opts = {}) { return { id: spec.id, skipped: false, take: doc }; } +/** + * A DRAFT take (walk a take): the take recorded -- its label, group, style, + * patch and window -- with NOTHING rendered, so it can be walked (the bench + * on the take's own timeline, takeEdit.mjs) before anybody pays for a build. + * `umtool take <p> --id X --draft`; a later `umtool take <p> --id X --full` + * renders it from its stored patch, edits and all (makeTake over it). + * + * takes/<id>/take.json `draft: true`, `preview` naming where the render + * will go, `seconds`/`builtAt` null, and the + * baseHash of the manifest it was drafted against + * + * The patch is applied here once, to check it makes a manifest with a + * timeline (a patch that does not is refused now, not at the render), and to + * write the take's `changes` lines. No take.json is written over a RENDERED + * take (its preview would then sit beside a take that says it has none); + * over a draft only with `force`. + * + * @param {string} projectDir + * @param {TakeSpec} rawSpec `window` absent: the render's window is said when it is rendered + * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date }} [opts] + */ +export async function draftTake(projectDir, rawSpec, opts = {}) { + const spec = checkSpec(rawSpec); + const window = rawSpec?.window === undefined || rawSpec?.window === null ? null : spec.window; + const now = opts.now ?? (() => new Date()); + const takeDir = path.join(takesDirOf(projectDir), spec.id); + const takeFile = path.join(takeDir, TAKE_FILE); + const previous = await readJson(takeFile); + if (previous && previous.draft !== true) throw new Error(`take ${spec.id} is rendered — a draft needs an id of its own`); + if (previous && !opts.force) throw new Error(`take ${spec.id} exists (a draft) — pass --force to record it again`); + + const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); + const base = JSON.parse(baseText); + const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); + let stylePatch = null; + if (spec.style) { + stylePatch = styles[spec.style]?.patch ?? null; + if (!stylePatch) { + const known = Object.keys(styles); + throw new Error(`unknown style "${spec.style}"${known.length ? ` — one of ${known.join(", ")}` : " (no montage styles are installed)"}`); + } + } + const patches = [stylePatch, spec.patch].filter(Boolean); + const manifest = patches.reduce((m, p) => mergePatch(m, p), base); + if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the patched manifest has no timeline"); + const changes = changeLines(base, manifest, patches); + const styleLabel = spec.style ? styles[spec.style]?.label : null; + const listing = await listTakes(projectDir); + const order = + spec.order ?? + (typeof previous?.order === "number" ? previous.order : Math.max(0, ...listing.takes.filter((t) => t.id !== spec.id).map((t) => t.order)) + 1); + const doc = { + id: spec.id, + group: spec.group, + order, + label: spec.label, + kind: changes.length === 0 ? "reference" : (spec.kind ?? "different"), + summary: spec.summary || (spec.style ? styles[spec.style]?.summary ?? "" : ""), + changes: [...(styleLabel ? [`style: ${styleLabel}`] : []), ...changes], + preview: PREVIEW, + seconds: null, + builtAt: null, + style: spec.style, + patch: spec.patch, + window, + ...(spec.quick ? { quick: true } : {}), + draft: true, + draftedAt: now().toISOString(), + baseHash: hashText(baseText), + }; + await mkdir(takeDir, { recursive: true }); + const tmp = `${takeFile}.tmp-${process.pid}`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, takeFile); + const clips = manifest.timeline.filter((e) => isObj(e) && e.type === "clip").length; + return { id: spec.id, take: doc, clips, entries: manifest.timeline.length }; +} + /** Remove `file` when it is a hard link of `of` (the same inode); anything else is left. */ async function unlinkIfSameFile(file, of) { const [a, b] = await Promise.all([lstat(file).catch(() => null), lstat(of).catch(() => null)]); @@ -811,6 +901,8 @@ 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 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 (text === null) throw new Error(`take ${takeId} has no ${MANIFEST} to use`); const manifest = JSON.parse(text); @@ -868,10 +960,19 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds = if (typeof req.rebuild === "string") { const t = existing.find((x) => x.id === req.rebuild); if (!t) throw new Error(`no take ${req.rebuild}`); + // `window`: render it over this window rather than its own (a draft's + // Render full / Render a window: a draft may not say one yet). + const win = req.window === undefined || req.window === null ? null : req.window === "full" ? "full" : normalizeWindow(req.window); + const full = (win ?? t.window) === "full"; return { - kind: `take ${project.id} ${t.id} (rebuild)`, + kind: `take ${project.id} ${t.id} (${/** @type {any} */ (t).draft ? "render" : "rebuild"})`, takes: [t.id], - steps: [{ ...base, label: `rebuild take ${t.id}`, argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", "--progress", "ndjson"], timeoutMs: takeTimeoutMs(t.window === "full", clipCount, seconds) }], + steps: [{ + ...base, + label: `${/** @type {any} */ (t).draft ? "render" : "rebuild"} take ${t.id}`, + argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), "--progress", "ndjson"], + timeoutMs: takeTimeoutMs(full, clipCount, seconds), + }], }; } if (isObj(req.allStyles)) { diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -289,11 +289,14 @@ test("makeTake refuses an unknown style, a bad id, and a window the patch emptie await assert.rejects(makeTake(dir, { id: "x", label: "X", style: "nope" }, opts(r, { styles: {} })), /no montage styles are installed/); await assert.rejects(makeTake(dir, { id: "Bad", label: "X" }, opts(r)), /id must be/); await assert.rejects(makeTake(dir, { id: "x", label: "" }, opts(r)), /needs a label/); - await assert.rejects( - makeTake(dir, { id: "x", label: "X", window: { at: 0, dur: 5 }, patch: { timeline: [clip("s04", 0, 5)] } }, opts(r)), - /removed every entry the window covers/, - ); assert.equal(r.calls.length, 0); + // A patch whose timeline holds none of the entries the window covers is + // timed over its OWN timeline (walk a take: a tight version's sub-windows), + // rather than refused as emptied. + const own = await makeTake(dir, { id: "x", label: "X", window: { at: 0, dur: 5 }, patch: { timeline: [clip("s04", 0, 5), clip("s05", 7, 9)] } }, opts(r)); + assert.equal(own.skipped, false); + assert.deepEqual(r.calls[0].doc.timeline.map((e) => e.id), ["s04"]); + assert.ok(r.logs.some((l) => /none of those is in the take's own timeline — the window covers 1 of ITS entries \(s04\)/.test(l)), r.logs.join("\n")); } finally { await rm(root, { recursive: true, force: true }); } diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -94,6 +94,13 @@ export function parseTake(dirName, raw) { } const window = parseWindow(j.window); if (window === undefined) return { error: 'window is not "full" or { at, dur }' }; + // A DRAFT (walk a take): recorded, not rendered -- `umtool take … --draft`. + // Its `preview` names where the render will go; the file is not there yet, + // which the listing already says (previewSize null). `editedAt` is the + // walk's last write to its patch (takeEdit.mjs): later than `builtAt`, the + // 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" }; return { take: { id: dirName, @@ -111,6 +118,8 @@ export function parseTake(dirName, raw) { window, baseHash: typeof j.baseHash === "string" && j.baseHash ? j.baseHash : null, quick: j.quick === true, + draft: j.draft === true, + editedAt: typeof j.editedAt === "string" && j.editedAt ? j.editedAt : null, }, }; } diff --git a/umtool/lib/report/takes.test.mjs b/umtool/lib/report/takes.test.mjs @@ -71,6 +71,8 @@ test("parseTake accepts the contract and fills the optional fields", () => { window: null, baseHash: null, quick: false, + draft: false, + editedAt: 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/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -72,13 +72,18 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> post-remove <id>", " umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)", " umtool timeline <project> undo restore the newest automatic snapshot", + " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]", + " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),", + " each write with an undo point of the take's own; the project's manifest is untouched", "", "Every write snapshots the manifest first (revisions/…-auto-before-<op>), is checked by the build's own", "validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.", ].join("\n"); const VERBS = ["ls", "insert", "move", "remove", "duplicate", "post", "post-remove", "teaser", "undo"]; -const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url"]); +const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take"]); +/** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ +const TAKE_VERBS = ["ls", "move", "remove", "undo"]; class CliError extends Error {} @@ -310,6 +315,7 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`); const project = await projectOf(projectArg, root); + if (flags.has("--take")) return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); @@ -447,6 +453,56 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } } +/** + * `umtool timeline <p> --take <id> ls|move|remove|undo`: a take's timeline + * (walk a take). The writes go into the take's patch through takeEdit.mjs -- + * the same structure rules, an undo point of the take's own first -- and the + * project's manifest is never written. Errors are thrown to the caller's catch. + */ +async function takeTimeline(project, take, verb, rest, flags, { out, json }) { + if (!TAKE_VERBS.includes(verb)) throw new CliError(`on a take: timeline --take ${take} ${TAKE_VERBS.join(" | ")} (not ${verb})`); + const edit = await import("./takeEdit.mjs"); + const at = intFlag(flags, "--at"); + if (verb === "ls") { + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + const { manifest } = await resolveTakeManifest(project.dir, take); + const rows = timelineRows(manifest); + if (json) { + out(JSON.stringify({ project: project.id, take, token: await edit.takeToken(project.dir, take), timeline: rows }, null, 2)); + return 0; + } + for (const line of timelineLines(rows)) out(line); + const { undoable } = await edit.takeEditState(project.dir, take); + out(`${rows.length} entr${rows.length === 1 ? "y" : "ies"} in take ${take} of ${project.id}${undoable ? ` · ${undoable} edit(s) to undo` : ""}`); + return 0; + } + const token = await edit.takeToken(project.dir, take); + let result; + if (verb === "move") { + const id = rest[0]; + if (!id) throw new CliError("move needs an entry id"); + const to = intFlag(flags, "--to"); + if (to === null) throw new CliError(`move needs --to <index> (\`umtool timeline ${project.id} --take ${take}\` lists them)`); + result = await edit.moveTakeEntry(project.dir, take, id, to, { token, at }); + } else if (verb === "remove") { + const id = rest[0]; + if (!id) throw new CliError("remove needs an entry id"); + result = await edit.removeTakeEntry(project.dir, take, id, { token, at }); + } else { + result = await edit.undoTakeEdit(project.dir, take, { token }); + } + if (json) { + out(JSON.stringify({ ok: true, op: verb, take, ...result }, null, 2)); + return 0; + } + if (verb === "undo") out(`take ${take}: undid ${result.op}: restored ${result.restored} (the state before the undo kept as ${result.saved})`); + else { + out(`take ${take}: ${summaryOf(verb, result, null)}`); + out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`); + } + return 0; +} + function summaryOf(verb, r, attribution) { switch (verb) { case "insert": { diff --git a/umtool/lib/report/walkCli.mjs b/umtool/lib/report/walkCli.mjs @@ -0,0 +1,78 @@ +// `umtool walk <project> [--take <id>] [--all] [--json]`: the walk from a +// terminal -- every clip in walk order with its verdict, whether it is fetched, +// and which ones the walk visits -- read by walkData.mjs, the reading the bench +// page and GET /api/report/walk make. The edits are `umtool window <p> <clip> +// [--take <id>] --verdict …` and `umtool timeline <p> [--take <id>] move|remove|undo`. +// +// Plain ESM: the CLI runs under bare node. +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { hms } from "umtool-report-to-video/attribution"; +import { walkJson, walkOf } from "./walkData.mjs"; + +export const WALK_USAGE = [ + "usage: umtool walk <project> [--take <id>] [--all] [--json]", + "", + "The clip bench's walk: every clip in walk order (by source), its window, its verdict, whether a", + "fetched file holds it, and (→) the ones the walk visits -- the fetched clips still needing a verdict;", + "--all: every fetched clip. --take walks a take: the project's manifest with the take's patch applied", + "(a draft too); its edits go to the take (`umtool window <p> <clip> --take <id> …`,", + "`umtool timeline <p> --take <id> move|remove|undo`), never the project's manifest.", +].join("\n"); + +class CliError extends Error {} + +/** + * @param {string[]} args the words after `walk` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] + * @returns {Promise<number>} + */ +export async function walkCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--take") { + if (i + 1 >= args.length) throw new CliError("--take needs a take id"); + flags.set(a, args[++i]); + } else if (a.startsWith("--")) flags.set(a, true); + else words.push(a); + } + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(WALK_USAGE); + return flags.has("--help") ? 0 : 2; + } + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + const take = flags.has("--take") ? String(flags.get("--take")) : null; + const w = await walkOf(project, { take, all: flags.has("--all") }); + if (flags.has("--json")) { + out(JSON.stringify(walkJson(w), null, 2)); + return 0; + } + const what = w.take + ? `take ${w.take.id} "${w.take.label}"${w.take.draft ? " (draft)" : w.take.made ? "" : " (in a recipe, not made — read only)"}` + : "the cut"; + out(`${project.id} · ${what} · ${w.total} clip(s) · ${hms(w.seconds)} · ${w.reviewed} reviewed · ${w.needing} need a verdict, ${w.ready} of them fetched`); + if (w.note) out(` ${w.note}`); + const idW = Math.max(2, ...w.clips.map((c) => c.id.length)); + for (const c of w.clips) { + const win = `${hms(c.start)}–${hms(c.end)}`; + const cut = c.cutStart != null ? ` cut ${hms(c.cutStart)}–${hms(c.cutEnd)}` : ""; + out( + `${c.onWalk ? "→" : " "} ${String(c.cut ?? "").padStart(3)} ${c.id.padEnd(idW)} ${win.padEnd(22)}${cut} ${c.seconds.toFixed(1).padStart(6)}s ` + + `${c.verdict.padEnd(10)} ${c.fetched ? "fetched" : "NOT FETCHED"}${c.correction ? ` note: ${c.correction}` : ""}`, + ); + } + const enc = project.id.split("/").map(encodeURIComponent).join("/"); + const base = w.take ? `/projects/${enc}/takes/${encodeURIComponent(w.take.id)}/walk` : `/projects/${enc}/clip/${encodeURIComponent(w.first ?? "")}`; + if (w.first) out(`\nthe walk starts at ${w.first}: ${w.take ? `${base}${w.all ? "?all=1" : ""}` : base}`); + else out(`\nnothing on the walk${w.all ? "" : " (every fetched clip has a verdict; --all walks them all)"}`); + return 0; + } catch (e) { + err(`umtool walk: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/walkData.mjs b/umtool/lib/report/walkData.mjs @@ -0,0 +1,136 @@ +// THE WALK, as data: which clips a walk visits, in what order, and where `p` +// and `n` go -- for the project's own cut, or for a TAKE (walk a take): the +// project's manifest with the take's patches applied, resolveTakeManifest's +// merge (takeManifest.mjs), the one the take build makes. +// +// One reading for the bench page (ClipBenchPage), the walk's data route +// (GET /api/report/walk) and `umtool walk`, so a terminal and the page cannot +// disagree about what is left to judge. +// +// WHAT THE WALK VISITS (umtool/docs/clip-bench.md, "What the walk skips"): +// the clips that still NEED JUDGEMENT (no verdict) and are FETCHED (a cached +// file holds the clip's own window end to end), in walk order (by source -- +// lib/projects/report.mjs walkOrder). `all` widens it to every FETCHED clip, +// judged or not: a take's clips are new windows, often carrying the verdict +// of the clip they were cut from, and "watch the tight version through" is a +// walk of all of them. +// +// Plain ESM: `umtool walk` runs it under bare node. +import { clipVerdict, readClipDetail, readManifest, walkOrder, walkReadiness } from "../projects/report.mjs"; +import { manifestToken } from "./manifest.mjs"; + +/** + * The manifest a walk reads: the project's, or the take's. + * + * @param {{ dir: string }} project + * @param {string | null} take + * @returns {Promise<{ manifest: Record<string, any>, token: string | null, take: null | { id: string, label: string, draft: boolean, made: boolean, editable: boolean }, note: string | null }>} + */ +export async function walkManifest(project, take = null) { + if (!take) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new Error("the project has no video.manifest.json"); + return { manifest, token: await manifestToken(project.dir), take: null, note: null }; + } + const [{ resolveTakeManifest }, { takeToken }, { listTakes }] = await Promise.all([ + import("./takeManifest.mjs"), + import("./takeEdit.mjs"), + import("./takes.mjs"), + ]); + const r = await resolveTakeManifest(project.dir, take); + const token = await takeToken(project.dir, take); + const listed = (await listTakes(project.dir)).takes.find((t) => t.id === take); + return { + manifest: r.manifest, + token, + take: { + id: take, + label: r.take.label, + draft: !!listed?.draft, + made: !!listed && !listed.draft, + // Edits land in takes/<id>/take.json: a take a recipe only names has none to land in. + editable: token !== null, + }, + note: r.note, + }; +} + +/** + * Where `p` and `n` go from `clipId`: the nearest clip on the walk either side + * in walk order (never the clip itself). `order` is walk order; `onWalk` the + * ids the walk visits. + * + * @param {string[]} order + * @param {Set<string>} onWalk + * @param {string} clipId + */ +export function walkNeighbours(order, onWalk, clipId) { + const i = order.indexOf(clipId); + const ok = (id) => id !== clipId && onWalk.has(id); + const prev = [...order.slice(0, Math.max(0, i))].reverse().find(ok) ?? null; + const next = (i < 0 ? order : order.slice(i + 1)).find(ok) ?? null; + return { prev, next }; +} + +/** + * The walk of a project's cut or of a take. + * + * @param {{ id: string, dir: string }} project + * @param {{ take?: string | null, all?: boolean }} [opts] + */ +export async function walkOf(project, { take = null, all = false } = {}) { + const base = await walkManifest(project, take); + const detail = await readClipDetail(project.dir, { manifest: base.manifest }); + if (!detail) throw new Error("the project has no video.manifest.json"); + const ordered = walkOrder(detail.entries); + const readiness = walkReadiness(ordered); + const onWalk = new Set(all ? ordered.filter((e) => !!e.fetched).map((e) => e.id) : readiness.readyIds); + const cutIndex = new Map( + (detail.entries ?? []).filter((e) => e.kind === "clip").map((e, i) => [e.id, i + 1]), + ); + const clips = ordered.map((e) => ({ + id: e.id, + /** 1-based place among the cut's clips (the timeline's order). */ + cut: cutIndex.get(e.id) ?? null, + channel: e.channel ?? null, + video: e.video, + start: e.start, + end: e.end, + seconds: Number((Number(e.cutEnd ?? e.end) - Number(e.cutStart ?? e.start)).toFixed(2)), + cutStart: e.cutStart ?? null, + cutEnd: e.cutEnd ?? null, + verdict: clipVerdict(e), + correction: typeof e.correction === "string" && e.correction.trim() ? e.correction.trim() : null, + quote: typeof e.quote === "string" ? e.quote : null, + fetched: !!e.fetched, + onWalk: onWalk.has(e.id), + })); + const order = clips.map((c) => c.id); + const first = order.find((id) => onWalk.has(id)) ?? null; + const reviewed = clips.filter((c) => c.verdict !== "unreviewed").length; + return { + project: project.id, + take: base.take, + note: base.note, + all, + token: base.token, + manifest: base.manifest, + detail, + clips, + order, + onWalk, + first, + /** Clips that need an answer, and how many of them can be judged today (fetched). */ + needing: readiness.needing, + ready: readiness.ready, + reviewed, + total: clips.length, + seconds: Number(clips.reduce((s, c) => s + c.seconds, 0).toFixed(2)), + }; +} + +/** walkOf's answer as JSON for the route and `umtool walk --json`: no manifest, no detail, no Set. */ +export function walkJson(w) { + const { manifest: _m, detail: _d, onWalk: _o, ...rest } = w; + return rest; +}