// THE DRAFTS REVIEW — one file of verdicts on every drafted field of a cut, // and the gate a build applies with it (release 28, M0; release 25's // narration review, generalised). // // /drafts.review.json beside video.manifest.json // { "//": { "verdict": "approved" | "rejected" | null, // "note": string, "key": "", "text": "", "at": ISO } } // // The address is drafted.mjs's `reviewAddress`: the field's own task (narrate, // onscreen, teaser, cut, flips, threads, youtube), the entry it is on (`*` for a // manifest field), the field -- `narrate//narration` for a card's // narration. The shape and its rules are the narration review's: every row // carries every key, a row with no verdict and no note is REMOVED, its own // write queue, tmp + rename, a file that does not parse is an ERROR (never // overwritten, never read as empty), and a rejection needs its note. // // A verdict is about THE VALUE IT WAS GIVEN ON: the row keeps its key // (`draftKey`: a card's narration by narration.mjs `narrationKey` -- the words // and the voice; any other field by drafted.mjs `fieldKey`), so an edit or a // re-draft leaves it "edited", not approved, without anything having to // remember to clear it. // // RELEASE 25's FILES READ UNCHANGED. `narration.review.json` ({ "": // row }) is read beside the drafts file, its rows as `narrate//narration`; // the drafts file wins on an address both have. Every write goes to the drafts // file -- a cleared row whose address the old file still approves is kept in // the drafts file as an empty verdict, so the old approval does not show // through. // // THE GATE (`draftsReviewProblems`), per field the cut carries: // - a DRAFTED field (it carries a drafted mark) must be approved on its // current value. Unapproved (unreviewed, or edited since): a WARNING in a // preview or fast build, an ERROR in a `final` one unless // `--drafts-unreviewed` (`--narration-unreviewed` for a narration). Rejected: // an ERROR in `final` (no flag lets it through), a warning otherwise; // - a NARRATION with no drafted mark (written by hand, or before release 28) // keeps release 25's rule in every build: until the cut's narration has a // review (a narration row in either file) it is a warning; once it has one, // every narrated card must be approved -- unreviewed or edited refuses unless // `--narration-unreviewed` (or `--drafts-unreviewed`), rejected refuses always. // // Pure but for the files' read and write. import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { draftedFields, fieldKey, isCodeDraft, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { narrationsOf } from "./narration.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const DRAFTS_REVIEW_FILE = "drafts.review.json"; /** Release 25's file, read unchanged; never written any more. */ export const NARRATION_REVIEW_FILE = "narration.review.json"; export const REVIEW_VERDICTS = Object.freeze(["approved", "rejected"]); export const REVIEW_NOTE_LIMIT = 2000; /** `/drafts.review.json`. */ export const draftsReviewFileOf = (manifestDir) => path.join(manifestDir, DRAFTS_REVIEW_FILE); /** The narration review address of a card. */ export const narrationAddress = (cardId) => reviewAddress({ entry: cardId, field: "narration" }); const str = (v) => (typeof v === "string" ? v : ""); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); /** One row, cleaned to the contract's shape. */ export function cleanRow(row) { return { verdict: REVIEW_VERDICTS.includes(row?.verdict) ? row.verdict : null, note: str(row?.note), key: str(row?.key), text: str(row?.text), at: str(row?.at), }; } /** A drafts file's rows: those whose address is an address, cleaned. */ export function cleanDraftsReview(raw) { const out = {}; if (!isObj(raw)) return out; for (const [address, row] of Object.entries(raw)) { if (!parseReviewAddress(address) || !isObj(row)) continue; out[address] = cleanRow(row); } return out; } const isCardId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200; /** Release 25's file: rows by card id, cleaned. */ export function cleanNarrationRows(raw) { const out = {}; if (!isObj(raw)) return out; for (const [id, row] of Object.entries(raw)) { if (!isCardId(id) || !isObj(row)) continue; out[id] = cleanRow(row); } return out; } async function readJson(file, name) { let text; try { text = await readFile(file, "utf8"); } catch (err) { if (err?.code === "ENOENT") return { exists: false, value: null }; return { exists: true, value: null, error: `${name} cannot be read: ${err?.message ?? err}` }; } try { return { exists: true, value: JSON.parse(text) }; } catch { return { exists: true, value: null, error: `${name} does not parse; fix or remove it` }; } } /** * The review of a cut: both files merged by address. * exists either file is there * rows address → row (the drafts file wins) * files which of the two are there * narration the cut's narration has a review (release 25's rule) * error a file that does not parse -- a build must not read that as * "nothing approved", nor a writer overwrite it * * @param {string} manifestDir */ export async function readDraftsReview(manifestDir) { const [drafts, legacy] = await Promise.all([ readJson(draftsReviewFileOf(manifestDir), DRAFTS_REVIEW_FILE), readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE), ]); const files = { drafts: drafts.exists, narration: legacy.exists }; const error = drafts.error ?? legacy.error; if (error) return { exists: true, rows: {}, files, narration: true, error }; const rows = {}; for (const [id, row] of Object.entries(cleanNarrationRows(legacy.value))) rows[narrationAddress(id)] = row; Object.assign(rows, cleanDraftsReview(drafts.value)); return reviewOf(rows, files); } function reviewOf(rows, files) { const narration = files.narration || Object.keys(rows).some((a) => parseReviewAddress(a)?.field === "narration"); return { exists: files.drafts || files.narration, rows, files, narration }; } /** * A release 25 narration review (`{ exists, rows: { : row }, error? }`, * narration-review.mjs `readNarrationReview`) as a drafts review. */ export function draftsReviewFromNarration(review) { if (!review) return null; if (review.error) return { exists: true, rows: {}, files: { drafts: false, narration: true }, narration: true, error: review.error }; const rows = {}; for (const [id, row] of Object.entries(review.rows ?? {})) rows[narrationAddress(id)] = cleanRow(row); return { ...reviewOf(rows, { drafts: false, narration: !!review.exists }), exists: !!review.exists }; } /** * The key a verdict on this field is given on: a card's narration by its * words and voice (narrationKey), anything else by its value (fieldKey). * * @param {any} manifest * @param {{ entry?: string | null, field: string }} target */ export function draftKey(manifest, target) { if (target.field === "narration" && target.entry) { return narrationsOf(manifest).find((n) => n.id === target.entry)?.key ?? fieldKey(manifest, target); } return fieldKey(manifest, target); } /** A row's state on a field's current key: approved, rejected, edited (judged on another value) or unreviewed. */ export function draftReviewState(key, row) { if (!row?.verdict) return "unreviewed"; if (row.key !== key) return "edited"; return row.verdict; } /** The words a verdict is given on: a short text of the field's value. */ export function judgedText(field, value) { if (value === undefined || value === null) return ""; if (field === "narration") return str(value?.text).trim(); if (field === "onscreen") return [value?.title, value?.subtitle].filter((s) => typeof s === "string" && s).join(" — "); if (field === "lines" && Array.isArray(value)) return value.map((l) => (typeof l === "string" ? l : str(l?.text))).join(" / "); if (field === "publish.youtube") return str(value?.title); if (field === "publish.x" || field === "publish.bluesky") return [str(value?.post), ...(Array.isArray(value?.thread) ? value.thread.map(str) : [])].join(" / "); if (field === "timeline" && Array.isArray(value)) return value.map((e) => e?.id).join(", "); return JSON.stringify(value).slice(0, 500); } /** How a field reads in a sentence. */ export const FIELD_LABELS = Object.freeze({ onscreen: "on-screen text", narration: "narration", lines: "teaser lines", timeline: "cut (its order)", "render.chrome.flips": "flips", "render.chrome.threads": "threads", "publish.youtube": "YouTube title and description", "publish.x": "X post", "publish.bluesky": "Bluesky post", }); /** * Every field the review covers, in timeline order then the manifest's: each * drafted field (drafted.mjs `draftedFields`) and each narrated card (drafted * or not, as the narration page lists them). Each row: * { address, entry, field, provenance (null: not drafted), key, text, row, state } * * @param {any} manifest * @param {{ rows?: Record } | null} review */ export function draftsReviewRows(manifest, review) { const out = []; const seen = new Set(); const push = (entry, field, provenance, value) => { const address = reviewAddress({ entry, field }); if (seen.has(address)) return; seen.add(address); const key = draftKey(manifest, { entry, field }); const row = review?.rows?.[address] ?? null; out.push({ address, entry, field, provenance, key, text: judgedText(field, value), row, state: draftReviewState(key, row) }); }; // A field a CODE path made (the converter's timeline, release 28 M1) needs // no approval: no row, so no badge and no gate. const drafted = draftedFields(manifest).filter((d) => !isCodeDraft(d.provenance)); const byAddress = new Map(drafted.map((d) => [reviewAddress(d), d])); // Narration rows in timeline order, interleaved with the other entry fields. const narrated = new Map(narrationsOf(manifest).map((n) => [n.id, n])); for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { for (const field of ["onscreen", "narration", "lines"]) { const d = byAddress.get(reviewAddress({ entry: e?.id, field })); if (d) push(d.entry, field, d.provenance, d.value); else if (field === "narration" && narrated.has(e?.id)) push(e.id, "narration", null, e.narration); } } for (const d of drafted) if (d.entry === null) push(null, d.field, d.provenance, d.value); return out; } const whereOf = (r) => (r.entry ? `timeline ${r.entry}` : r.field); const LIST_AT_MOST = 8; /** * What the review says about building this cut: `errors` refuse it, `notes` * and `warnings` are said. * * @param {any} manifest the cut * @param {{ exists: boolean, rows: Record, narration?: boolean, error?: string } | null} review * null: not read (a run that says nothing about reviews) * @param {{ final?: boolean, allowUnreviewed?: boolean, allowNarrationUnreviewed?: boolean, only?: string | null }} [opts] */ export function draftsReviewProblems(manifest, review, { final = false, allowUnreviewed = false, allowNarrationUnreviewed = false, only = null } = {}) { const errors = []; const notes = []; const warnings = []; if (!review) return { errors, notes, warnings }; const rows = draftsReviewRows(manifest, review).filter((r) => !only || r.entry === only); if (!rows.length) return { errors, notes, warnings }; if (review.error) return { errors: [review.error], notes, warnings }; // Release 25's rule, for a narration nobody drafted. const hand = rows.filter((r) => r.field === "narration" && !r.provenance); if (hand.length && !review.narration) { warnings.push( `the narration (${hand.length} card${hand.length === 1 ? "" : "s"}) has no review — ${DRAFTS_REVIEW_FILE} has no narration verdicts; ` + "review it card by card on umtool's narration page before it is published", ); } else if (hand.length) { for (const r of hand) { if (r.state === "approved") continue; if (r.state === "rejected") { errors.push( `timeline ${r.entry}: its narration was rejected${r.row?.note ? ` ("${r.row.note}")` : ""} — rewrite it and approve it, or take the narration out`, ); continue; } const why = r.state === "edited" ? "edited since it was approved" : "not reviewed"; if (allowNarrationUnreviewed || allowUnreviewed) { notes.push(`timeline ${r.entry}: its narration is ${why} — built anyway (${allowNarrationUnreviewed ? "--narration-unreviewed" : "--drafts-unreviewed"})`); } else errors.push(`timeline ${r.entry}: its narration is ${why} — approve it on umtool's narration page, or build with --narration-unreviewed`); } } // The drafted fields. const pending = []; for (const r of rows.filter((x) => x.provenance)) { if (r.state === "approved") continue; const what = `${whereOf(r)}: its ${FIELD_LABELS[r.field] ?? r.field} (drafted by ${r.provenance.model})`; if (r.state === "rejected") { const said = `${what} was rejected${r.row?.note ? ` ("${r.row.note}")` : ""}`; if (final) errors.push(`${said} — redraft or rewrite it and approve it; a final build takes no rejected draft`); else warnings.push(`${said} — a final build refuses it`); continue; } const why = r.state === "edited" ? "changed since it was approved" : "not approved"; if (!final) { pending.push(r); continue; } const flag = allowUnreviewed ? "--drafts-unreviewed" : allowNarrationUnreviewed && r.field === "narration" ? "--narration-unreviewed" : null; if (flag) notes.push(`${what} is ${why} — built anyway (${flag})`); else errors.push(`${what} is ${why} — approve it on umtool's review page, or build with --drafts-unreviewed`); } if (pending.length) { const names = pending.slice(0, LIST_AT_MOST).map((r) => r.address); warnings.push( `${pending.length} drafted field${pending.length === 1 ? " is" : "s are"} not approved (${names.join(", ")}` + `${pending.length > LIST_AT_MOST ? `, and ${pending.length - LIST_AT_MOST} more` : ""}) — a final build refuses ${pending.length === 1 ? "it" : "them"} until approved`, ); } return { errors, notes, warnings }; } /** @type {Promise} */ let queue = Promise.resolve(); function withReviewLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, () => undefined, ); return run; } /** * Set one field's review. `patch.verdict` "approved" | "rejected" | null (null * clears it); `note` replaces the note; `key` and `text` are the value the * verdict is about (a key is required with a verdict). A rejection needs its * note. Returns the row as stored (null when removed) and every row of the * merged review. Writes the drafts file only. * * @param {string} manifestDir * @param {string} address * @param {{ verdict?: string | null, note?: string, key?: string, text?: string }} patch */ export async function setDraftReview(manifestDir, address, patch) { if (!parseReviewAddress(address)) throw new Error(`${JSON.stringify(address)} is not a review address (//)`); if (patch.verdict !== undefined && patch.verdict !== null && !REVIEW_VERDICTS.includes(patch.verdict)) { throw new Error(`verdict must be one of ${REVIEW_VERDICTS.join(", ")} or null`); } if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string"); if (patch.verdict && !(typeof patch.key === "string" && patch.key && typeof patch.text === "string")) { throw new Error("a verdict is given on words: key and text are required"); } const file = draftsReviewFileOf(manifestDir); return withReviewLock(async () => { const cur = await readDraftsReview(manifestDir); if (cur.error) throw new Error(cur.error); const own = await readJson(file, DRAFTS_REVIEW_FILE); if (own.error) throw new Error(own.error); const map = cleanDraftsReview(own.value); const prev = cur.rows[address] ?? { verdict: null, note: "", key: "", text: "", at: "" }; const row = { verdict: patch.verdict === undefined ? prev.verdict : patch.verdict, note: patch.note === undefined ? prev.note : patch.note.slice(0, REVIEW_NOTE_LIMIT).trim(), key: patch.verdict ? patch.key : patch.verdict === null ? "" : prev.key, text: patch.verdict ? patch.text : patch.verdict === null ? "" : prev.text, at: new Date().toISOString(), }; if (row.verdict === "rejected" && !row.note) { throw new Error("a rejection needs its note: say what is wrong with the words"); } // An empty row goes -- unless release 25's file still has this address, // whose row would show through: then the empty row stays, and wins. const target = parseReviewAddress(address); let legacyHas = false; if (target.field === "narration" && target.entry && cur.files.narration) { const legacy = await readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE); legacyHas = isObj(legacy.value) && isObj(legacy.value[target.entry]); } if (row.verdict === null && !row.note && !legacyHas) delete map[address]; else map[address] = row; const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); await rename(tmp, file); const stored = row.verdict === null && !row.note ? null : row; const rows = { ...cur.rows, ...map }; if (!map[address]) delete rows[address]; return { entry: stored, rows }; }); }