// THE CLIP DECK'S STORE (release 34 N1): `/montage-rulings.json`, the // operator's verdict on each montage instance, written by ear on the clip deck // (`/projects//clips`) or `umtool rulings`. The shape, the key rule and how a // render applies it are report-to-video/montage-rulings.mjs; this is the ONE // writer. // // - every write is queued in-process, read-modify-write, tmp + rename; // - a file that does not parse (or is not the shape) is an ERROR: never // overwritten, never read as empty; // - a ruling is set whole ({verdict, reason, match?}, `at` stamped here) or // removed (null) -- the deck's undo is "set it back as it was". // // IMPORT. Before the deck, the operator ruled in chat and the rulings went into // the seed's `edits.json` beside the manifest ({exclude: [{videoId, near, why}], // match: [{videoId, near, match, why}]}, `near` the instance's start). Those map // to moments: the clip whose video matches and whose cutStart (else start) is // within 30 s; a moment the seed already left out of the manifest is found in // the seed's `instances.json` ({slug, videoId, start}) when there is one. An // exclude becomes not-him / read-aloud / cut by its words; a match keeps the // clip with the wider phrase. Moments already ruled are left as they are, so // the offer counts only what is new -- once imported, it is not offered again. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { MONTAGE_RULINGS_FILE, RULINGS_VERSION, RULING_MATCH_LIMIT, RULING_REASON_LIMIT, RULING_VERDICTS, applyMontageRulings, clipMomentKey, isMomentKey, momentKey, montageRulingsFileOf, parseMontageRulings, rulingsLines, } from "umtool-report-to-video/montage-rulings"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const EDITS_FILE = "edits.json"; export const INSTANCES_FILE = "instances.json"; /** How far an earlier ruling's `near` may be from the clip's cut start. */ export const IMPORT_NEAR_SECONDS = 30; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); let queue = Promise.resolve(); /** @template T @param {() => Promise} fn @returns {Promise} */ function withRulingsLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, () => undefined, ); return run; } /** * The rulings as the page reads them: `{ exists, doc, error }`. A bad file is * `error` (the page says so and refuses to write), never an empty doc. * @param {string} projectDir * @returns {Promise<{ exists: boolean, doc: { version: 1, rulings: Record }, error: string | null }>} */ export async function readRulingsState(projectDir) { let text = null; try { text = await readFile(montageRulingsFileOf(projectDir), "utf8"); } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") return { exists: true, doc: emptyDoc(), error: String(err) }; } if (text === null) return { exists: false, doc: emptyDoc(), error: null }; try { return { exists: true, doc: parseMontageRulings(JSON.parse(text)), error: null }; } catch (e) { return { exists: true, doc: emptyDoc(), error: `${MONTAGE_RULINGS_FILE} does not parse or is not the shape: ${e instanceof Error ? e.message : String(e)}` }; } } /** @returns {{ version: 1, rulings: Record }} */ const emptyDoc = () => ({ version: /** @type {1} */ (RULINGS_VERSION), rulings: {} }); async function readForWrite(file) { let text = null; try { text = await readFile(file, "utf8"); } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw err; } if (text === null) return emptyDoc(); try { return parseMontageRulings(JSON.parse(text)); } catch { throw new Error(`${MONTAGE_RULINGS_FILE} does not parse or is not the shape; not overwriting it`); } } async function writeDoc(file, doc) { await mkdir(path.dirname(file), { recursive: true }); // Keys in order, so the file diffs as the deck walks. const rulings = Object.fromEntries(Object.entries(doc.rulings).sort(([a], [b]) => a.localeCompare(b))); const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ version: RULINGS_VERSION, rulings }, null, 2) + "\n", "utf8"); await rename(tmp, file); } /** * One ruling, checked and normalised: `{verdict, reason, match?, at}`. Throws a * sentence. * @param {unknown} input * @param {Date} now */ export function normaliseRuling(input, now = new Date()) { if (!isObj(input)) throw new Error("a ruling is { verdict, reason?, match? }"); const verdict = input.verdict; if (!RULING_VERDICTS.includes(/** @type {any} */ (verdict))) throw new Error(`verdict must be one of ${RULING_VERDICTS.join(", ")}`); const reason = input.reason === undefined || input.reason === null ? "" : input.reason; if (typeof reason !== "string") throw new Error("reason must be a string"); /** @type {{ verdict: string, reason: string, match?: string, at: string }} */ const out = { verdict: /** @type {string} */ (verdict), reason: reason.trim().slice(0, RULING_REASON_LIMIT), at: now.toISOString() }; if (input.match !== undefined && input.match !== null && input.match !== "") { if (typeof input.match !== "string" || !input.match.trim()) throw new Error("match must be a phrase"); const m = input.match.trim().replace(/\s+/g, " "); if (m.length > RULING_MATCH_LIMIT) throw new Error(`match is over ${RULING_MATCH_LIMIT} characters`); out.match = m; } return out; } /** * Set one moment's ruling (or remove it with `null`). Returns the whole doc. * @param {string} projectDir * @param {string} key * @param {null | { verdict: string, reason?: string, match?: string | null }} ruling * @param {{ now?: Date }} [opts] */ export async function setMontageRuling(projectDir, key, ruling, { now = new Date() } = {}) { if (!isMomentKey(key)) throw new Error("not a moment key (/