// A take patch's deck markers follow the cut (UI notes 2026-10-30, #6). // // A take made with `umtool take … --patch draft-1.patch.json` merges that file // over the manifest (RFC 7386), and a merge patch REPLACES an array: so a // patch that carries `render.chrome.deck.markers` carries the whole list, each // marker `after` a clip id. Removing a clip re-anchors the MANIFEST's markers // (manifest.mjs reanchorAfterRemove) -- and left the patch's naming a clip // that is gone, so the next take was refused ("draft-9 was refused") until the // patch was synced by hand, after every section change. // // Two halves, one rule: // - the structural writers re-anchor the project's `*.patch.json` the way // they re-anchor the manifest: a marker after a removed clip moves to the // clip before it (the same boundary), or is dropped when none is left; // - the check reports a patch whose markers name a clip that is not in the // cut (`patch-markers-stale`, lib/projects/report.mjs) -- a hand edit, a // patch written before this existed, a clip removed by hand. // // Only a patch with no `timeline` of its own: one that replaces the timeline // names ITS clips, which the manifest knows nothing about. Only the project's // own directory (the convention: draft-1.patch.json beside the manifest). // // Plain ESM: the CLI runs it under bare node. import { readdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); // A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows. const isClip = (e) => isObj(e) && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); /** The project's take patches: `*.patch.json` beside the manifest, by name. */ export async function patchFilesOf(dir) { const names = await readdir(dir).catch(() => []); return names.filter((n) => PATCH_FILE_RE.test(n)).sort(); } /** A patch's deck markers, or null when it carries none (or its own timeline). */ export function patchMarkersOf(patch) { if (!isObj(patch) || patch.timeline !== undefined) return null; const markers = patch?.render?.chrome?.deck?.markers; return Array.isArray(markers) ? markers : null; } /** * The clips a structural edit took out, each with the clip a marker after it * should now follow: the nearest clip BEFORE it (in the old order) that is * still in the cut -- reanchorAfterRemove's "same boundary" -- or null. * * @param {Array>} before the timeline before the edit * @param {Array>} after the timeline after it * @returns {Map} */ export function removedAnchors(before, after) { const still = new Set((after ?? []).filter(isClip).map((e) => e.id)); const out = new Map(); (before ?? []).forEach((e, i) => { if (!isClip(e) || !e.id || still.has(e.id)) return; let anchor = null; for (let k = i - 1; k >= 0; k -= 1) { const p = before[k]; if (isClip(p) && still.has(p.id)) { anchor = p.id; break; } } out.set(e.id, anchor); }); return out; } /** * Re-anchor one patch's markers in place. Returns one sentence per change. * * @param {Record} patch * @param {Map} anchors removedAnchors()'s answer * @returns {string[]} */ export function reanchorPatch(patch, anchors) { const markers = patchMarkersOf(patch); if (!markers || !anchors.size) return []; const notes = []; const next = markers.filter((mk, k) => { const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; if (!anchors.has(after)) return true; const to = anchors.get(after); const name = `deck marker ${k}${mk.label ? ` ("${mk.label}")` : ""}`; if (to) { mk.after = to; notes.push(`${name} moved from after ${after} to after ${to} (the same boundary)`); return true; } notes.push(`${name} dropped: no clip before ${after}`); return false; }); if (notes.length) patch.render.chrome.deck.markers = next; return notes; } /** * After a structural write: re-anchor every take patch in the project whose * markers named a clip the write took out. Each changed file is rewritten * whole (2-space JSON and a newline, tmp + rename). Never fatal: a patch that * does not read is reported, and the manifest's write stands. * * @param {string} dir * @param {Array>} before * @param {Array>} after * @returns {Promise>} */ export async function syncPatchMarkers(dir, before, after) { const anchors = removedAnchors(before, after); if (!anchors.size) return []; const out = []; for (const name of await patchFilesOf(dir)) { const file = path.join(dir, name); let patch; try { patch = JSON.parse(await readFile(file, "utf8")); } catch (e) { out.push({ file: name, notes: [], error: `does not read: ${e instanceof Error ? e.message : String(e)}` }); continue; } const notes = reanchorPatch(patch, anchors); if (!notes.length) continue; try { const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, file); out.push({ file: name, notes }); } catch (e) { out.push({ file: name, notes, error: `not written: ${e instanceof Error ? e.message : String(e)}` }); } } return out; } /** * The check's half: every take patch marker after a clip that is not in the * cut, and every patch that does not read. * * @param {string} dir * @param {Record} manifest * @returns {Promise, error?: string }>>} */ export async function stalePatchMarkers(dir, manifest) { const ids = new Set((manifest?.timeline ?? []).filter(isClip).map((e) => e.id)); const out = []; for (const name of await patchFilesOf(dir)) { let patch; try { patch = JSON.parse(await readFile(path.join(dir, name), "utf8")); } catch (e) { out.push({ file: name, markers: [], error: e instanceof Error ? e.message : String(e) }); continue; } const markers = patchMarkersOf(patch); if (!markers) continue; const gone = []; markers.forEach((mk, index) => { const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; if (after && !ids.has(after)) gone.push({ index, label: typeof mk.label === "string" ? mk.label : null, after }); }); if (gone.length) out.push({ file: name, markers: gone }); } return out; } /** * Settle a stale patch: every marker after a clip that is not in the cut * takes the `after` of the CUT's marker with the same label (the manifest's * own markers are re-anchored by every structural write, so they say where * that section starts now). A marker no marker of the cut shares a label with * is left as it is, and named. The file is rewritten whole, tmp + rename. * * @param {string} dir * @param {Record} manifest * @param {string} file a `*.patch.json` beside the manifest, by name * @returns {Promise<{ file: string, notes: string[], left: Array<{ index: number, label: string | null, after: string }> }>} */ export async function fixStalePatchMarkers(dir, manifest, file) { if (!PATCH_FILE_RE.test(String(file ?? ""))) throw new Error(`${file} is not a take patch beside the manifest (*.patch.json)`); const full = path.join(dir, file); const patch = JSON.parse(await readFile(full, "utf8")); const markers = patchMarkersOf(patch); if (!markers) return { file, notes: [], left: [] }; const ids = new Set((manifest?.timeline ?? []).filter(isClip).map((e) => e.id)); const cut = Array.isArray(manifest?.render?.chrome?.deck?.markers) ? manifest.render.chrome.deck.markers : []; const byLabel = new Map(cut.filter((mk) => isObj(mk) && typeof mk.label === "string" && ids.has(String(mk.after ?? "").trim())).map((mk) => [mk.label.trim(), String(mk.after).trim()])); const notes = []; const left = []; markers.forEach((mk, index) => { const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; if (!after || ids.has(after)) return; const label = typeof mk.label === "string" ? mk.label : null; const to = label ? byLabel.get(label.trim()) : undefined; if (to) { mk.after = to; notes.push(`deck marker ${index} ("${label}") moved from after ${after} to after ${to}, where the cut's "${label}" is`); } else left.push({ index, label, after }); }); if (notes.length) { const tmp = tmpPathFor(full); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, full); } return { file, notes, left }; } // ---- a section edit's markers (lane/ui-cut-editing, UI notes item 1) ------- // // A section edit (manifest.mjs moveToSection / addSection / moveSectionBoundary / // removeSection / updateSection / splitClip / flashForward) removes no clip, so // removedAnchors has nothing to say: the markers themselves moved. The rule is // deliberately narrow: a patch whose markers were IN STEP with the manifest's // before the edit (the same list, byte for byte) gets the new list; a patch whose // markers already differed is somebody's deliberate variant, left as it is and // named, never rewritten by a guess. A patch with no markers, or with a timeline // of its own (patchMarkersOf), is not touched. The patch's own indent is kept. /** The indent a JSON file was written with (its first nested line), else 2: a rewrite keeps it. */ export const indentOf = (text) => /^[[{]\r?\n( +)\S/.exec(String(text ?? ""))?.[1].length ?? 2; /** * Bring every in-step patch's markers to `after` (the manifest's after the * edit; [] or null: the patch's markers removed with them). * * @param {string} dir the project * @param {unknown[] | null | undefined} before the manifest's markers before the edit * @param {unknown[] | null | undefined} after the manifest's markers after it * @returns {Promise<{ synced: string[], skipped: { file: string, why: string }[] }>} */ export async function syncSectionMarkers(dir, before, after) { const synced = []; const skipped = []; const was = JSON.stringify(before ?? []); const now = JSON.stringify(after ?? []); if (was === now) return { synced, skipped }; for (const name of await patchFilesOf(dir)) { const file = path.join(dir, name); let doc; let text = ""; try { text = await readFile(file, "utf8"); doc = JSON.parse(text); } catch (e) { skipped.push({ file: name, why: `does not parse (${e instanceof Error ? e.message : e}): not touched` }); continue; } const mine = patchMarkersOf(doc); if (!mine) continue; if (JSON.stringify(mine) !== was) { skipped.push({ file: name, why: "its markers were not the manifest's before this edit (a deliberate variant?): left as they are" }); continue; } const deck = doc.render.chrome.deck; if (Array.isArray(after) && after.length) deck.markers = JSON.parse(now); else delete deck.markers; const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, indentOf(text)) + "\n", "utf8"); await rename(tmp, file); synced.push(name); } return { synced, skipped }; }