// A REEL'S HISTORY (lane/reel-bench): every write to a reel's beats file, // append-only, beside it -- `promo/-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/..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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; 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 }} before * @param {{ beats: any[], settings?: Record }} 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} */ 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 = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ file: rel, entries }, null, 1) + "\n", "utf8"); await rename(tmp, file); return entry; }