Archilyzer · Source

archilyzer

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

commit 61e03863002e2da495c7ad5d7f1e5aaacf8cef83
parent dd4a6b6cdbdf90756a491008dab298f538baf2e3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 17:08:35 -0500

umtool reels track their source: each beat's anchor (what it was cut against), a reel history sidecar, and each beat classified against the take it plays now

A reel is an edit of a master that keeps changing. A beat stays addressed in
its clip's source seconds; its ANCHOR (lib/report/reelAnchor.mjs) is
provenance: the take, its build (take.json builtAt) and its master's mtime,
the source span the clip's segment played (its cut record's start/end/gaps),
the segment's content key (segKey), a fingerprint of the chrome and fx over
the segment (the schedule's entry and the receipts/zoom it carries, timed
from the segment's start, so a shift is not a change), the master span it
resolved to, and when. The beats' writer stamps it on a beat added or edited
against a take (the route's `take`; `anchorFor`), keeps it through edits made
without one, and anchors a whole reel (`anchor` op, anchorTrailerBeats).

classifyBeat / reelStatus (pure, unit-tested) say each beat against the take
now: unanchored, orphan (its clip is gone), clipped (the clip's new limits cut
into it; clampPatch fits it back), edges (the clip's edges or gaps moved, the
beat still fits: old vs new), look (the chrome or fx over it changed),
rerendered (another render, the clip identical: still good), unchanged; and
the reel's line ("cut against draft-6; take draft-7 changes beats 7").
reelPlayView carries it per row (`status`) and for the reel.

Every write (and every undo) appends to promo/<name>-beats.history.json
(lib/report/reelHistory.mjs, modelled on common/lib/metadataHistory.ts):
append-only, per beat each field's old and new, adds/removes/order, the
settings, the take it was written against; 200 entries, newest last.

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

Diffstat:
Mumtool/app/api/report/trailer-beats/route.ts | 23++++++++++++++++++++---
Aumtool/lib/report/reelAnchor.mjs | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelAnchor.test.mjs | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/reelHistory.mjs | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/reelPlay.mjs | 23+++++++++++++++++++++++
Mumtool/lib/report/trailerBeats.mjs | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
6 files changed, 533 insertions(+), 15 deletions(-)

diff --git a/umtool/app/api/report/trailer-beats/route.ts b/umtool/app/api/report/trailer-beats/route.ts @@ -1,10 +1,12 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; +import { anchorContextOf } from "@/lib/report/reelPlay.mjs"; import { BeatsStale, DEFAULT_REEL, TRAILER_LIMITS, addTrailerBeat, + anchorTrailerBeats, beatsToken, createReel, introSecondsOf, @@ -43,6 +45,10 @@ export const dynamic = "force-dynamic"; // order {} the cut's order // settings { limit?, xfade?, intro?, title?, take? } null: the default again // undo {} the reel as it was before its last write +// anchor { only? } anchor beats (all, or the 0-based `only`) to `take` +// `take` on add / set / anchor: the take the edit was made against -- each +// beat written gets its anchor (lib/report/reelAnchor.mjs), so the reel can +// say later what changed under it. `set`'s patch may re-point a beat (`id`). // new-reel { name, from?, title? } a new reel (empty, or a copy of `from`) // A stale token is a 409. @@ -94,13 +100,18 @@ export async function POST(request: Request) { if (!isReelId(reel)) return Response.json({ error: "reel is a reel name (lower case, digits and dashes)" }, { status: 400 }); const token = typeof body.token === "string" ? body.token : null; try { + // The take this edit was made against: its anchors go on the beats written. + const take = typeof body.take === "string" && body.take ? body.take : null; + const ctx = take && ["add", "set", "anchor"].includes(String(body.op)) ? await anchorContextOf(dir, take) : null; + if (take && body.op === "anchor" && !ctx) return Response.json({ error: `take ${take} has no finished master to anchor to` }, { status: 400 }); + const anchorFor = ctx?.anchorFor ?? null; let did: Record<string, unknown> = {}; switch (body.op) { case "add": - await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest, reel }); + await addTrailerBeat(dir, (body.beat ?? {}) as Record<string, unknown>, { token, at: typeof body.at === "number" ? body.at : null, manifest: r.manifest, reel, anchorFor }); break; case "set": - await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token, reel }); + await updateTrailerBeat(dir, Number(body.index), (body.patch ?? {}) as Record<string, unknown>, { token, reel, anchorFor }); break; case "remove": await removeTrailerBeat(dir, Number(body.index), { token, reel }); @@ -114,6 +125,12 @@ export async function POST(request: Request) { case "settings": await setTrailerSettings(dir, Object.fromEntries(["limit", "xfade", "intro", "title", "take"].filter((k) => k in body).map((k) => [k, body[k]])), { token, reel }); break; + case "anchor": { + if (!anchorFor) return Response.json({ error: "anchor needs the take to anchor to (take)" }, { status: 400 }); + const only = Array.isArray(body.only) ? body.only.map(Number) : null; + await anchorTrailerBeats(dir, anchorFor, { token, reel, only, take: take ?? "" }); + break; + } case "undo": { const u = await undoTrailerBeats(dir, { token, reel }); did = { undone: u.undone }; @@ -126,7 +143,7 @@ export async function POST(request: Request) { break; } default: - return Response.json({ error: "op must be add, set, remove, move, order, settings, undo or new-reel" }, { status: 400 }); + return Response.json({ error: "op must be add, set, remove, move, order, settings, anchor, undo or new-reel" }, { status: 400 }); } return Response.json({ ok: true, ...did, ...(await view(dir, r.manifest, reel)) }, { headers: noStore }); } catch (e) { diff --git a/umtool/lib/report/reelAnchor.mjs b/umtool/lib/report/reelAnchor.mjs @@ -0,0 +1,200 @@ +// REELS TRACK THEIR SOURCE (lane/reel-bench, 2 Nov). +// +// A reel is an edit of a rendered master that keeps changing: a new take, a +// clip's edges moved, a clip taken out of the cut, the chrome or the fx over +// a clip changed. A beat stays ADDRESSED in its clip's source seconds -- that +// is what survives a re-render -- and carries an ANCHOR: what it was cut +// against when it was made or last edited. The anchor is provenance, never +// the address: +// +// take, build, masterMtimeMs the take, its build (take.json builtAt), and +// its master's mtime +// clip { start, end, gaps } the source seconds the clip's segment played +// (its cut record: start/end, the gaps it left out) +// seg the segment's content key (the cut record's +// segKey: the picture and sound of the clip) +// fx a fingerprint of the chrome and the fx over +// the clip's segment (the schedule's entry for it +// and the receipts/zoom it carries, timed from the +// segment's start -- so a shift is not a change) +// master { start, end } the master span the beat resolved to +// at when +// +// On load each beat is CLASSIFIED against the take the reel plays now +// (classifyBeat, pure): +// +// unanchored written before anchors (or by hand): nothing to compare +// orphan its clip is gone from the cut -- remove it, or re-point it +// clipped the clip's new limits cut into the beat -- clamp, or re-place +// edges the clip's edges or gaps moved; the beat still fits (old vs new) +// look the chrome or fx in its span changed -- look at it +// rerendered another render, this clip identical -- still good +// unchanged the very master it was cut against +// +// Plain ESM: the page's view, the writer's route and `umtool trailer-beats +// status` read it. +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { recordGaps } from "umtool-report-to-video/gaps"; +import { TrailerError, loadTakeBuild, parseBeats, planTrailer } from "umtool-report-to-video/trailer"; + +export const BEAT_STATES = Object.freeze(["unanchored", "orphan", "clipped", "edges", "look", "rerendered", "unchanged"]); +/** The states that ask for a person: the walk's "changed beats" filter. */ +export const CHANGED_STATES = Object.freeze(["orphan", "clipped", "edges", "look"]); + +const r3 = (n) => Number(Number(n).toFixed(3)); +const EPS = 0.02; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const sha = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 16); + +/** The chrome and fx over one clip's segment, timed from the segment's start: their fingerprint. */ +export function fxFingerprint(schedule, id) { + const seg = (schedule?.segments ?? []).find((s) => s?.id === id); + if (!seg) return null; + const { start, end, duration, ...chrome } = seg; + const rel = (t) => (Number.isFinite(t) ? r3(t - start) : t); + const fx = {}; + for (const [k, v] of Object.entries(schedule?.fx ?? {})) { + if (!isObj(v) || !Array.isArray(v.clips)) continue; + const mine = v.clips + .filter((c) => c?.segment === id) + .map((c) => ({ ...c, in: rel(c.in), out: rel(c.out), markAt: rel(c.markAt), cards: (c.cards ?? []).map((x) => ({ ...x, at: rel(x.at) })) })); + if (mine.length) fx[k] = { ...v, clips: mine }; + } + return sha({ chrome, fx }); +} + +/** What a take's build says of one clip now: present, the source span its segment plays, its content key, its fx. */ +export function clipSnapshot(build, id) { + const rec = build.records.get(id); + const inSchedule = (build.schedule?.segments ?? []).some((s) => s?.id === id); + if (!rec || !inSchedule || !Number.isFinite(rec.start) || !Number.isFinite(rec.end)) return { present: false }; + return { + present: true, + clip: { start: r3(rec.start), end: r3(rec.end), gaps: recordGaps(rec).map((g) => ({ from: r3(g.from), to: r3(g.to) })) }, + seg: typeof rec.segKey === "string" ? rec.segKey : sha({ start: rec.start, end: rec.end, gaps: recordGaps(rec) }), + fx: fxFingerprint(build.schedule, id), + }; +} + +/** + * A take's anchoring context: its build, and `anchorFor(beat)` -- the anchor + * a beat gets when it is written against this take (null when the beat does + * not map onto it: the beat is written without one, and says so on load). + * + * @param {string} takeDir + * @param {{ take: string, masterMtimeMs?: number | null, now?: () => string, build?: any }} o `build`: loadTakeBuild's, when it is read already + */ +export async function anchorContext(takeDir, { take, masterMtimeMs = null, now = () => new Date().toISOString(), build: loaded = null }) { + const build = loaded ?? (await loadTakeBuild(takeDir)); + const meta = await readFile(path.join(takeDir, "take.json"), "utf8").then(JSON.parse, () => null); + const buildId = typeof meta?.builtAt === "string" ? meta.builtAt : null; + const anchorFor = (beat) => { + let piece = null; + try { + const [b] = parseBeats([beat]); + piece = planTrailer({ schedule: build.schedule, records: build.records, beats: [b], xfade: 0, snap: false }).pieces[0]; + } catch (e) { + if (e instanceof TrailerError) return null; + throw e; + } + const base = { take, build: buildId, masterMtimeMs, master: { start: piece.master.start, end: piece.master.end }, at: now() }; + if (beat.id === undefined) return base; + const s = clipSnapshot(build, beat.id); + if (!s.present) return null; + return { ...base, clip: s.clip, seg: s.seg, fx: s.fx }; + }; + // Named by its take, for the history the writer keeps (trailerBeats.mjs anchorTake). + anchorFor.take = take; + return { take, build: buildId, masterMtimeMs, schedule: build.schedule, records: build.records, anchorFor, snapshot: (id) => clipSnapshot(build, id) }; +} + +const sameGaps = (a = [], b = []) => a.length === b.length && a.every((g, i) => Math.abs(g.from - b[i].from) < EPS && Math.abs(g.to - b[i].to) < EPS); + +/** + * One beat against the take it plays now. Pure. + * + * @param {Record<string, any>} beat the reel file's beat (its `anchor`, if any) + * @param {{ take: string, build: string | null, masterMtimeMs: number | null, snapshot: (id: string) => ReturnType<typeof clipSnapshot> }} now + * @returns {{ state: string, why: string, was?: any, now?: any }} + */ +export function classifyBeat(beat, now) { + const a = isObj(beat?.anchor) ? beat.anchor : null; + const isClip = beat?.id !== undefined; + const snap = isClip ? now.snapshot(beat.id) : null; + // Gone from the cut is said whether or not the beat was anchored. + if (isClip && !snap.present) return { state: "orphan", why: `${beat.id} is not in take ${now.take}'s cut any more — remove the beat, or re-point it to another clip`, was: a?.clip ?? null }; + if (isClip) { + const c = snap.clip; + if (beat.start < c.start - EPS || beat.end > c.end + EPS) { + return { + state: "clipped", + why: `${beat.id} now plays source ${c.start}–${c.end}${a?.clip ? ` (was ${a.clip.start}–${a.clip.end})` : ""}: the beat ${beat.start}–${beat.end} reaches past it — clamp it, or re-place it`, + was: a?.clip ?? null, + now: c, + }; + } + } + if (!a) return { state: "unanchored", why: "written before beats were anchored: nothing to compare (anchor it to this take)" }; + if (isClip) { + const c = snap.clip; + if (a.clip && (Math.abs(a.clip.start - c.start) > EPS || Math.abs(a.clip.end - c.end) > EPS || !sameGaps(a.clip.gaps, c.gaps))) { + const moved = [ + Math.abs(a.clip.start - c.start) > EPS ? `start ${a.clip.start} → ${c.start}` : null, + Math.abs(a.clip.end - c.end) > EPS ? `end ${a.clip.end} → ${c.end}` : null, + !sameGaps(a.clip.gaps, c.gaps) ? "its gaps" : null, + ].filter(Boolean); + return { state: "edges", why: `${beat.id}'s ${moved.join(", ")} since take ${a.take}; the beat still fits — check its edges`, was: a.clip, now: c }; + } + if ((a.fx ?? null) !== (snap.fx ?? null) || (a.seg && snap.seg && a.seg !== snap.seg)) { + return { state: "look", why: `the ${a.fx !== snap.fx ? "chrome or fx" : "picture or sound"} over ${beat.id} changed since take ${a.take} — look at it`, was: { seg: a.seg, fx: a.fx }, now: { seg: snap.seg, fx: snap.fx } }; + } + } + if (a.take !== now.take || (a.build ?? null) !== (now.build ?? null) || (a.masterMtimeMs ?? null) !== (now.masterMtimeMs ?? null)) { + return { state: "rerendered", why: `cut against take ${a.take}${a.take === now.take ? " (rendered again since)" : ""}; ${isClip ? `${beat.id} is the same in take ${now.take}` : "a master beat: its seconds are as written"}` }; + } + return { state: "unchanged", why: `the master it was cut against (take ${a.take})` }; +} + +/** + * Every beat of a reel against the take it plays now, and the reel's line: + * which takes it was cut against, and the beats that changed. + * + * @param {any[]} beats + * @param {Parameters<typeof classifyBeat>[1]} now + */ +export function reelStatus(beats, now) { + const rows = (beats ?? []).map((b, i) => ({ n: i + 1, id: b?.id ?? null, ...classifyBeat(b, now) })); + const against = [...new Set((beats ?? []).map((b) => b?.anchor?.take).filter((t) => typeof t === "string"))]; + const changed = rows.filter((r) => CHANGED_STATES.includes(r.state)).map((r) => r.n); + const counts = Object.fromEntries(BEAT_STATES.map((s) => [s, rows.filter((r) => r.state === s).length])); + const others = against.filter((t) => t !== now.take); + const line = !rows.length + ? "no beats" + : others.length + ? `cut against ${others.join(", ")}; take ${now.take} ${changed.length ? `changes beat${changed.length === 1 ? "" : "s"} ${changed.join(", ")}` : "changes none of them"}` + : changed.length + ? `take ${now.take} changes beat${changed.length === 1 ? "" : "s"} ${changed.join(", ")}` + : counts.unanchored === rows.length + ? "no beat is anchored yet" + : `every anchored beat matches take ${now.take}`; + return { take: now.take, against, changed, counts, line, rows }; +} + +/** + * The fix a status offers, as a beat patch (or null): `clamp` pulls a clipped + * beat inside the clip's new limits (its gaps kept where they still fit), + * `repoint` names another clip of the cut for it (the seconds kept; refused + * by the writer when they do not fit that clip). + * + * @param {Record<string, any>} beat + * @param {{ clip: { start: number, end: number } }} snap clipSnapshot's, present + */ +export function clampPatch(beat, snap) { + const start = Math.max(beat.start, snap.clip.start); + const end = Math.min(beat.end, snap.clip.end); + if (!(end - start >= 0.2)) return null; + const gaps = (beat.gaps ?? []).filter((g) => g.from >= start + 0.5 && g.to <= end - 0.5); + return { start: Number(start.toFixed(2)), end: Number(end.toFixed(2)), ...(beat.gaps ? { gaps } : {}) }; +} diff --git a/umtool/lib/report/reelAnchor.test.mjs b/umtool/lib/report/reelAnchor.test.mjs @@ -0,0 +1,142 @@ +// Reels track their source (reelAnchor.mjs, reelHistory.mjs; lane/reel-bench): +// a beat's anchor, its classification against the take the reel plays now, the +// reel's line, the clamp; the writer stamping anchors and keeping the history. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { anchorContext, clampPatch, classifyBeat, clipSnapshot, fxFingerprint, reelStatus } from "./reelAnchor.mjs"; +import { diffReel, readReelHistory } from "./reelHistory.mjs"; +import { anchorTrailerBeats, readTrailerBeats, updateTrailerBeat } from "./trailerBeats.mjs"; + +const schedule = (aEnd = 10, extra = 0) => ({ + version: 1, kind: "deck", fps: 30, transition: 0, total: 30 + extra, + segments: [ + { id: "a", type: "clip", start: 0, duration: aEnd, end: aEnd, title: "A", subtitle: "the stream · 1 Oct" }, + { id: "b", type: "clip", start: aEnd, duration: 10, end: aEnd + 10, title: "B" }, + { id: "c", type: "clip", start: aEnd + 10, duration: 10, end: aEnd + 20, title: "C" }, + ], + fx: { keys: ["receipts"], receipts: { clips: [{ segment: "c", in: aEnd + 12, out: aEnd + 15, cards: [{ shot: "x.png", at: aEnd + 12 }] }] } }, +}); +const records = (aEnd = 110) => new Map([ + ["a", { id: "a", start: 100, end: aEnd, segKey: `a-${aEnd}` }], + ["b", { id: "b", start: 200, end: 210, segKey: "b" }], + ["c", { id: "c", start: 300, end: 310, segKey: "c" }], +]); +const build = (o = {}) => ({ schedule: o.schedule ?? schedule(), records: o.records ?? records() }); +const nowOf = (b, take = "t2", extra = {}) => ({ take, build: "2026-11-02T12:00:00Z", masterMtimeMs: 2, snapshot: (id) => clipSnapshot(b, id), ...extra }); +const anchorOf = (b, beat, take = "t1") => { + const s = clipSnapshot(b, beat.id); + return { take, build: "2026-11-01T12:00:00Z", masterMtimeMs: 1, master: { start: 0, end: 1 }, clip: s.clip, seg: s.seg, fx: s.fx, at: "x" }; +}; + +test("fx: the chrome and fx over a segment, timed from its start -- a shift is not a change, an edit is", () => { + const s1 = schedule(10); + const s2 = schedule(12.5); // everything after a moves 2.5 s later + assert.equal(fxFingerprint(s1, "c"), fxFingerprint(s2, "c")); + assert.equal(fxFingerprint(s1, "b"), fxFingerprint(s2, "b")); + const s3 = schedule(10); + s3.fx.receipts.clips[0].cards[0].shot = "y.png"; + assert.notEqual(fxFingerprint(s1, "c"), fxFingerprint(s3, "c")); + const s4 = schedule(10); + s4.segments[1].title = "B, retitled"; + assert.notEqual(fxFingerprint(s1, "b"), fxFingerprint(s4, "b")); + assert.equal(fxFingerprint(s1, "zz"), null); +}); + +test("each beat against the take now: unchanged, rerendered, edges, clipped, look, orphan, unanchored -- and the reel's line", () => { + const was = build(); + const beats = [ + { id: "a", start: 101, end: 105 }, + { id: "b", start: 201, end: 205 }, + { id: "c", start: 301, end: 305 }, + { id: "a", start: 106, end: 109.9 }, + { id: "b", start: 202, end: 203 }, + ].map((b) => ({ ...b, anchor: anchorOf(was, b) })); + beats.push({ id: "c", start: 302, end: 304 }); // never anchored + + // The same master: unchanged. + assert.equal(classifyBeat(beats[0], nowOf(was, "t1", { build: "2026-11-01T12:00:00Z", masterMtimeMs: 1 })).state, "unchanged"); + // Rendered again, a's end moved 110 → 112.5 (the kf3c case): a's beats flagged, nothing else. + const later = build({ schedule: schedule(12.5, 2.5), records: records(112.5) }); + const st = reelStatus(beats, nowOf(later)); + assert.deepEqual(st.rows.map((r) => r.state), ["edges", "rerendered", "rerendered", "edges", "rerendered", "unanchored"]); + assert.deepEqual(st.changed, [1, 4]); + assert.match(st.rows[0].why, /a's end 110 → 112.5 since take t1; the beat still fits/); + assert.deepEqual(st.rows[0].was, { start: 100, end: 110, gaps: [] }); + assert.equal(st.line, "cut against t1; take t2 changes beats 1, 4"); + // a's end pulled IN past a beat: clipped, with the clamp that fits it. + const shorter = build({ schedule: schedule(8), records: records(108) }); + const c = classifyBeat(beats[3], nowOf(shorter)); + assert.equal(c.state, "clipped"); + assert.match(c.why, /a now plays source 100–108 \(was 100–110\)/); + assert.deepEqual(clampPatch(beats[3], clipSnapshot(shorter, "a")), { start: 106, end: 108 }); + // The receipts over c changed: look. + const fx = build(); + fx.schedule.fx.receipts.clips[0].cards[0].shot = "z.png"; + assert.equal(classifyBeat(beats[2], nowOf(fx)).state, "look"); + // b gone from the cut: orphan (anchored or not). + const noB = build(); + noB.schedule = { ...noB.schedule, segments: noB.schedule.segments.filter((s) => s.id !== "b") }; + assert.equal(classifyBeat(beats[1], nowOf(noB)).state, "orphan"); + assert.equal(classifyBeat({ id: "b", start: 201, end: 202 }, nowOf(noB)).state, "orphan"); + // A master beat anchored: rerendered when the master is another. + assert.equal(classifyBeat({ at: 1, dur: 2, anchor: { take: "t1", build: "x", masterMtimeMs: 1 } }, nowOf(was)).state, "rerendered"); +}); + +test("diffReel: per beat old and new, adds, removes, the order, the settings", () => { + const a = { beats: [{ id: "a", start: 1, end: 2 }, { id: "b", start: 3, end: 4 }], settings: { limit: 140 } }; + const b = { beats: [{ id: "a", start: 1.5, end: 2, gaps: [{ from: 1.6, to: 1.8 }] }, { id: "b", start: 3, end: 4, verdict: "confirmed", anchor: { take: "t2" } }], settings: { limit: 90 } }; + const d = diffReel(a, b); + assert.deepEqual(d.changes, [ + { n: 1, id: "a", field: "start", old: 1, new: 1.5 }, + { n: 1, id: "a", field: "gaps", old: null, new: [{ from: 1.6, to: 1.8 }] }, + { n: 2, id: "b", field: "verdict", old: null, new: "confirmed" }, + { n: 2, id: "b", field: "anchor", old: null, new: "t2" }, + ]); + assert.deepEqual(d.settings, { limit: [140, 90] }); + const r = diffReel(a, { beats: [{ id: "b", start: 3, end: 4 }, { id: "c", start: 5, end: 6 }] }); + assert.deepEqual(r.changes.map((x) => x.op), ["remove", "add"]); + assert.deepEqual(diffReel(a, { beats: [a.beats[1], a.beats[0]] }).changes, [{ op: "order", old: ["a", "b"], new: ["b", "a"] }]); +}); + +test("the writer stamps a beat with the take it was edited against, anchors a reel to a take, and keeps the history", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-anchor-")); + try { + const take = path.join(dir, "takes", "t1"); + await mkdir(path.join(take, "out", "sourced", "segments"), { recursive: true }); + await writeFile(path.join(take, "video.manifest.json"), JSON.stringify({ slug: "s", render: { fps: 30 }, timeline: [] })); + await writeFile(path.join(take, "take.json"), JSON.stringify({ id: "t1", builtAt: "2026-11-01T12:00:00Z" })); + await writeFile(path.join(take, "out", "sourced", "schedule.json"), JSON.stringify(schedule())); + for (const [id, rec] of records()) await writeFile(path.join(take, "out", "sourced", "segments", `${id}.cut.json`), JSON.stringify(rec)); + await mkdir(path.join(dir, "promo"), { recursive: true }); + await writeFile(path.join(dir, "promo", "trailer-beats.json"), JSON.stringify([{ id: "a", start: 101, end: 105 }, { id: "c", start: 301, end: 305 }])); + const ctx = await anchorContext(take, { take: "t1", masterMtimeMs: 7, now: () => "2026-11-02T00:00:00Z" }); + await updateTrailerBeat(dir, 0, { end: 106 }, { anchorFor: ctx.anchorFor }); + let doc = await readTrailerBeats(dir); + assert.deepEqual(doc.beats[0].anchor, { + take: "t1", build: "2026-11-01T12:00:00Z", masterMtimeMs: 7, master: { start: 1, end: 6 }, at: "2026-11-02T00:00:00Z", + clip: { start: 100, end: 110, gaps: [] }, seg: "a-110", fx: fxFingerprint(schedule(), "a"), + }); + assert.equal(doc.beats[1].anchor, undefined); + // An edit with no take keeps the anchor it had. + await updateTrailerBeat(dir, 0, { verdict: "confirmed" }); + doc = await readTrailerBeats(dir); + assert.equal(doc.beats[0].anchor.take, "t1"); + await anchorTrailerBeats(dir, ctx.anchorFor, { take: "t1" }); + doc = await readTrailerBeats(dir); + assert.equal(doc.beats[1].anchor.take, "t1"); + const st = reelStatus(doc.beats, { take: "t1", build: ctx.build, masterMtimeMs: 7, snapshot: ctx.snapshot }); + assert.deepEqual(st.rows.map((r) => r.state), ["unchanged", "unchanged"]); + const h = await readReelHistory(dir, path.join("promo", "trailer-beats.json")); + assert.deepEqual(h.map((e) => e.what), ["beat 1: end", "beat 1: verdict", "anchor every beat to take t1"]); + assert.equal(h[0].take, "t1"); + assert.deepEqual(h[0].changes.map((c) => c.field), ["end", "anchor"]); + assert.deepEqual(h[2].changes, [{ n: 2, id: "c", field: "anchor", old: null, new: "t1" }]); + assert.ok((await readFile(path.join(dir, "promo", "trailer-beats.history.json"), "utf8")).includes('"entries"')); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/reelHistory.mjs b/umtool/lib/report/reelHistory.mjs @@ -0,0 +1,92 @@ +// A REEL'S HISTORY (lane/reel-bench): every write to a reel's beats file, +// append-only, beside it -- `promo/<name>-beats.history.json`, modelled on +// common/lib/metadataHistory.ts: one entry per write whose beats or settings +// changed, the OLD and NEW value of each field that moved (by beat), capped at +// REEL_HISTORY_CAP, newest last. The undo points (`promo/.<file>.undo.json`) +// put a reel back; this says what changed, when and against which take, +// across sessions -- an agent and a person can audit a reel's edits from it. +// +// diffReel is pure; the writer (trailerBeats.mjs beatsWrite, undo) appends. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const REEL_HISTORY_CAP = 200; +const FIELDS = ["id", "start", "end", "gaps", "at", "dur", "label", "verdict"]; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null); +/** A beat as the history keeps it: its seconds, never its anchor whole (only the take it names). */ +const compact = (b) => (isObj(b) ? Object.fromEntries([...FIELDS.filter((k) => b[k] !== undefined).map((k) => [k, b[k]]), ...(isObj(b.anchor) ? [["anchor", b.anchor.take ?? null]] : [])]) : b); +const keyOf = (b) => JSON.stringify([b?.id ?? null, b?.start ?? b?.at ?? null, b?.end ?? b?.dur ?? null]); + +/** + * What changed between two versions of a reel: per beat, each field's old and + * new (`anchor` the take it names), beats added and removed, the order, and the + * settings. Empty `changes` and `settings`: nothing moved. + * + * @param {{ beats: any[], settings?: Record<string, any> }} before + * @param {{ beats: any[], settings?: Record<string, any> }} after + */ +export function diffReel(before, after) { + const a = before.beats ?? []; + const b = after.beats ?? []; + /** @type {any[]} */ + const changes = []; + if (a.length === b.length && a.every((x, i) => (x?.id ?? null) === (b[i]?.id ?? null))) { + b.forEach((nb, i) => { + const ob = a[i]; + for (const k of FIELDS) if (!same(ob?.[k], nb?.[k])) changes.push({ n: i + 1, id: nb?.id ?? null, field: k, old: ob?.[k] ?? null, new: nb?.[k] ?? null }); + const ot = isObj(ob?.anchor) ? ob.anchor.take ?? null : null; + const nt = isObj(nb?.anchor) ? nb.anchor.take ?? null : null; + if (!same(ob?.anchor, nb?.anchor)) changes.push({ n: i + 1, id: nb?.id ?? null, field: "anchor", old: ot, new: nt }); + }); + } else { + const before = new Map(a.map((x, i) => [keyOf(x), i])); + const afterKeys = new Set(b.map(keyOf)); + a.forEach((x, i) => { + if (!afterKeys.has(keyOf(x))) changes.push({ op: "remove", n: i + 1, beat: compact(x) }); + }); + b.forEach((x, i) => { + if (!before.has(keyOf(x))) changes.push({ op: "add", n: i + 1, beat: compact(x) }); + }); + const kept = b.filter((x) => before.has(keyOf(x))).map(keyOf); + const was = a.filter((x) => afterKeys.has(keyOf(x))).map(keyOf); + if (!same(kept, was)) changes.push({ op: "order", old: a.map((x) => x?.id ?? null), new: b.map((x) => x?.id ?? null) }); + } + /** @type {Record<string, [any, any]>} */ + const settings = {}; + const sa = before.settings ?? {}; + const sb = after.settings ?? {}; + for (const k of new Set([...Object.keys(sa), ...Object.keys(sb)])) if (!same(sa[k], sb[k])) settings[k] = [sa[k] ?? null, sb[k] ?? null]; + return { changes, settings }; +} + +export const historyFileOf = (dir, rel) => path.join(dir, path.dirname(rel), `${path.basename(rel, ".json")}.history.json`); + +/** A reel's history, oldest first; [] when it has none (or it does not read). */ +export async function readReelHistory(dir, rel) { + try { + const j = JSON.parse(await readFile(historyFileOf(dir, rel), "utf8")); + return Array.isArray(j?.entries) ? j.entries : []; + } catch { + return []; + } +} + +/** + * Append one entry (when something moved): `{ at, what, take?, changes, settings }`. + * @param {string} dir + * @param {string} rel the reel's file, relative to the project + * @param {{ what: string, take?: string | null, before: { beats: any[], settings?: any }, after: { beats: any[], settings?: any }, at?: string }} e + */ +export async function appendReelHistory(dir, rel, { what, take = null, before, after, at = new Date().toISOString() }) { + const d = diffReel(before, after); + if (!d.changes.length && !Object.keys(d.settings).length) return null; + const entry = { at, what, ...(take ? { take } : {}), changes: d.changes, ...(Object.keys(d.settings).length ? { settings: d.settings } : {}) }; + const file = historyFileOf(dir, rel); + const entries = [...(await readReelHistory(dir, rel)), entry].slice(-REEL_HISTORY_CAP); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify({ file: rel, entries }, null, 1) + "\n", "utf8"); + await rename(tmp, file); + return entry; +} diff --git a/umtool/lib/report/reelPlay.mjs b/umtool/lib/report/reelPlay.mjs @@ -33,6 +33,7 @@ import { trailerOutPath, trailerRecordPath, } from "umtool-report-to-video/trailer"; +import { anchorContext, reelStatus } from "./reelAnchor.mjs"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { listTakes, takesDirOf } from "./takes.mjs"; import { DEFAULT_REEL, TRAILER_LIMIT_DEFAULT, readTrailerBeats, reelFileOf } from "./trailerBeats.mjs"; @@ -308,7 +309,15 @@ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } return { ...base, take: { id: chosen.id, why: chosen.why, label: m.label }, noMaster: { why: e instanceof TrailerError || e instanceof Error ? e.message : String(e), take: chosen.id } }; } const plan = reelPlan(build, doc.beats, { intro: settings.intro === true, xfade: base.xfade }); + // Each beat against this take (reelAnchor.mjs): what it was cut against, and what changed since. + const ctx = await anchorContext(m.dir, { take: chosen.id, masterMtimeMs: m.masterMtimeMs, build }).catch(() => null); + const status = ctx ? reelStatus(doc.beats, ctx) : null; + if (status) for (const r of plan.rows) { + const st = status.rows[r.n - 1]; + r.status = st ? { state: st.state, why: st.why, ...(st.was ? { was: st.was } : {}), ...(st.now ? { now: st.now } : {}) } : null; + } return { + status: status ? { take: status.take, against: status.against, changed: status.changed, counts: status.counts, line: status.line } : null, ...base, take: { id: chosen.id, @@ -324,6 +333,20 @@ export async function reelPlayView(project, { reel = DEFAULT_REEL, take = null } }; } +/** + * A take's anchoring context (reelAnchor.mjs anchorContext), by its id: the + * anchor a beat written against it gets, and what it says of each clip now. + * Null when the take has no finished master. + * + * @param {string} projectDir + * @param {string} take + */ +export async function anchorContextOf(projectDir, take) { + const m = (await takeMasters(projectDir)).find((x) => x.id === take); + if (!m?.built) return null; + return anchorContext(m.dir, { take, masterMtimeMs: m.masterMtimeMs }); +} + /** A reel's cut may take this long on the runner: one ffmpeg pass over spans of a master, in the heavy slot (it may wait there). */ export const REEL_CUT_TIMEOUT_MS = 45 * 60 * 1000; diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -38,6 +38,7 @@ import path from "node:path"; import { gappedLength, gapsOf } from "umtool-report-to-video/gaps"; import { TRAILER_XFADE_DEFAULT, TrailerError, beatGaps, parseBeats } from "umtool-report-to-video/trailer"; import { indentOf } from "./patchMarkers.mjs"; +import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; @@ -194,7 +195,7 @@ function withBeatsLock(fn) { * settings)` (which throws to refuse), every beat checked by the trailer's own * parseBeats, a `.bak` of the file as it was, then tmp + rename. */ -async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit" } = {}) { +async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an edit", take = null } = {}) { return withBeatsLock(async () => { const current = await beatsToken(dir, reel); if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current); @@ -220,6 +221,8 @@ async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); + // The history (reelHistory.mjs): what moved, old and new, by beat. + await appendReelHistory(dir, reelFileOf(reel), { what, take, before: { beats: read.beats, settings: read.settings }, after: { beats, settings } }).catch(() => null); return { ...result, beats, settings, token: await beatsToken(dir, reel) }; }); } @@ -239,6 +242,7 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL const last = points.pop(); if (!last) throw new Error(`nothing to undo on the reel ${reel}`); const file = beatsFile(dir, reel); + const before = await readTrailerBeats(dir, { reel }).catch(() => null); if (last.text === null) await rm(file, { force: true }); else { const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; @@ -246,6 +250,8 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL await rename(tmp, file); } await writeUndo(dir, reel, points); + const after = await readTrailerBeats(dir, { reel }).catch(() => null); + if (before && after) await appendReelHistory(dir, reelFileOf(reel), { what: `undo: ${last.what}`, before, after }).catch(() => null); return { undone: last.what, at: last.at, left: points.length, token: await beatsToken(dir, reel) }; }); } @@ -282,6 +288,9 @@ export async function createReel(dir, name, { from = null, title = null } = {}) }, { reel: name, what: from ? `new reel ${name}, from ${from}` : `new reel ${name}` }); } +/** A beat's anchor (lib/report/reelAnchor.mjs: what it was cut against), carried as written. */ +const anchorOf = (b) => (isObj(b.anchor) ? { anchor: b.anchor } : {}); + /** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */ function cleanBeat(b) { if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }"); @@ -298,9 +307,38 @@ function cleanBeat(b) { } catch (e) { throw new Error(e instanceof Error ? e.message : String(e)); } - return { id: String(b.id), start, end, ...(gaps.length ? { gaps } : {}), ...label, ...verdict }; + return { id: String(b.id), start, end, ...(gaps.length ? { gaps } : {}), ...label, ...verdict, ...anchorOf(b) }; } - return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict }; + return { at: r2(b.at), dur: r2(b.dur), ...label, ...verdict, ...anchorOf(b) }; +} + +/** @typedef {((beat: Record<string, any>) => Record<string, any> | null) | null} AnchorFor */ + +/** The take an anchorFor writes against (anchorContext tags it), for the history. */ +const anchorTake = (anchorFor) => (anchorFor && typeof anchorFor.take === "string" ? anchorFor.take : null); + +/** A beat with the anchor of the take it was written against (reelAnchor.mjs anchorContext); none when it does not map there. */ +function stamp(b, anchorFor) { + if (!anchorFor) return b; + const { anchor: _old, ...rest } = b; + const a = anchorFor(rest); + return a ? { ...rest, anchor: a } : rest; +} + +/** + * Anchor beats to a take (reelAnchor.mjs anchorContext's `anchorFor`): all of + * them, or the 0-based `only`. A beat that does not map onto the take loses + * its anchor (it is said on load). + * @param {string} dir + * @param {NonNullable<AnchorFor>} anchorFor + * @param {BeatsWriteOpts & { only?: number[] | null, take?: string }} [opts] + */ +export async function anchorTrailerBeats(dir, anchorFor, { token = null, reel = DEFAULT_REEL, only = null, take = "" } = {}) { + return beatsWrite(dir, token, (beats) => { + const which = only ?? beats.map((_, k) => k); + for (const k of which) beats[indexIn(beats, k)] = stamp(beats[k], anchorFor); + return { anchored: which.length }; + }, { reel, what: `anchor ${only ? `beat${only.length === 1 ? "" : "s"} ${only.map((k) => k + 1).join(", ")}` : "every beat"}${take ? ` to take ${take}` : ""}`, take: take || null }); } const indexIn = (beats, i, what = "beat") => { @@ -313,11 +351,11 @@ const indexIn = (beats, i, what = "beat") => { * Add a beat at index `at` (default: where the cut's order puts it, else the end). * @param {string} dir * @param {Record<string, unknown>} beat - * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null, reel?: string }} [opts] + * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null, reel?: string, anchorFor?: AnchorFor }} [opts] */ -export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL } = {}) { +export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { - const b = cleanBeat(beat); + const b = stamp(cleanBeat(beat), anchorFor); let i = beats.length; if (at !== null && at !== undefined) { i = Number(at); @@ -333,7 +371,7 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif } beats.splice(i, 0, b); return { index: i, beat: b }; - }, { reel, what: `add ${beat?.id ?? "a master beat"}` }); + }, { reel, what: `add ${beat?.id ?? "a master beat"}`, take: anchorTake(anchorFor) }); } /** @@ -341,14 +379,20 @@ export async function addTrailerBeat(dir, beat, { token = null, at = null, manif * @param {string} dir * @param {number} i * @param {Record<string, unknown>} patch - * @param {BeatsWriteOpts} [opts] + * @param {BeatsWriteOpts & { anchorFor?: AnchorFor }} [opts] `anchorFor`: the take the edit was made against (its anchor is written) */ -export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL } = {}) { +export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DEFAULT_REEL, anchorFor = null } = {}) { return beatsWrite(dir, token, (beats) => { const n = indexIn(beats, i); - if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, gaps?, label?, verdict? }"); + if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, gaps?, id?, label?, verdict? }"); const b = { ...beats[n] }; for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k]; + // Re-pointed to another clip of the cut (a beat whose clip is gone): its seconds go with it. + if (patch.id !== undefined) { + if (b.id === undefined) throw new Error("a master beat has no clip to re-point"); + if (typeof patch.id !== "string" || !patch.id) throw new Error("id is a clip id"); + b.id = patch.id; + } // The beat's gaps, the whole list ([] or null: none). A clip beat only. if (patch.gaps !== undefined) { if (b.id === undefined) throw new Error("only a clip beat has source seconds to take out; a master beat is { at, dur }"); @@ -360,9 +404,9 @@ export async function updateTrailerBeat(dir, i, patch, { token = null, reel = DE if (patch[k] === null || patch[k] === "") delete b[k]; else b[k] = patch[k]; } - beats[n] = cleanBeat(b); + beats[n] = stamp(cleanBeat(b), anchorFor); return { index: n, beat: beats[n] }; - }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}` }); + }, { reel, what: `beat ${Number(i) + 1}: ${Object.keys(isObj(patch) ? patch : {}).join(", ") || "set"}`, take: anchorTake(anchorFor) }); } /**