// THE REVIEW PASS (umtool redesign L7b; the workspace's `?mode=review`): the draft watched block by block, each
// block answered Keep · Fix · Note, and the draft (or a version) given a verdict at the end. It replaces the walk
// as the way through a cut; the clip bench stays the deep tool for one clip.
//
// Where each answer lands -- no new store for what already has one:
//
// Keep on a clip its WALK VERDICT `confirmed` (the bench's writer), and only when it has none or is confirmed
// already: a clip the bench ruled incorrect (a fact error, wrong speaker) is never overwritten
// here -- the bench changes it. Twin: `umtool window
--verdict confirmed`.
// Fix ("needs `/review-pass.json` (this file's) on ANY block, a clip too: `{ mark: "fix", note }` --
// work"), Keep on NEVER a clip's verdict (`incorrect` is the fact-error verdict: a blocking check and `umtool
// anything else corrections`). Twin: `umtool review-pass mark keep|fix|clear` (a clip: fix, clear).
// Note the notes store (notes.json), anchored to the block (`{ kind: "entry", entry }`): `umtool notes`.
// the end verdict takes/verdicts.json, L4's writer (`umtool takes verdict like|maybe|no`).
//
// What the pass walks: the cut's entries in order but the intro (watched, never judged -- the walk's own rule) and
// a clip rejected for a cut reason (it is out of the cut's playback already; the bench re-rules it). A clip ruled
// incorrect stays in the list: it is a Fix. Progress is "N / M reviewed", and the pass resumes on the first block
// with no answer.
//
// Plain ESM: the CLI runs under bare node; the app reads the same functions.
import { createHash } from "node:crypto";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { blockAnswer, reviewBlocks, reviewProgress } from "./reviewPassModel.mjs";
export { blockAnswer, reviewBlocks, reviewProgress };
export const REVIEW_PASS_FILE = "review-pass.json";
export { REVIEW_MARKS } from "./reviewPassModel.mjs";
import { REVIEW_MARKS } from "./reviewPassModel.mjs";
import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs";
/** A Fix's note, at most (a correction is the bench's sixth field; this is its post-and-card twin). */
export const REVIEW_NOTE_LIMIT = 2000;
/** @typedef {import("./reviewPassModel.mjs").ReviewMark} ReviewMark */
/** @typedef {{ version: 1, marks: Record }} ReviewPassDoc */
const empty = () => /** @type {ReviewPassDoc} */ ({ version: 1, marks: {} });
/** Keep only well-formed marks: a hand-edited file never breaks the pass, it loses the rows it garbled. */
function clean(raw) {
const out = empty();
const marks = raw && typeof raw === "object" && raw.marks && typeof raw.marks === "object" ? raw.marks : {};
for (const [id, m] of Object.entries(marks)) {
if (!m || typeof m !== "object" || !REVIEW_MARKS.includes(m.mark)) continue;
out.marks[id] = { mark: m.mark, ...(typeof m.note === "string" && m.note.trim() ? { note: m.note } : {}), ...(typeof m.sig === "string" ? { sig: m.sig } : {}), at: typeof m.at === "string" ? m.at : "" };
}
return out;
}
/** The project's review-pass.json; `{ version: 1, marks: {} }` when absent or unreadable. */
export async function readReviewPass(dir) {
try {
return clean(JSON.parse(await readFile(path.join(dir, REVIEW_PASS_FILE), "utf8")));
} catch {
return empty();
}
}
// One write at a time per file, in this process (the app's route and a CLI run are separate processes: the
// rename keeps a reader from ever seeing half a file, and the last write wins, as with the take verdicts).
const chains = new Map();
function serial(file, fn) {
const prev = chains.get(file) ?? Promise.resolve();
const run = prev.catch(() => {}).then(fn);
chains.set(file, run);
return run.finally(() => {
if (chains.get(file) === run) chains.delete(file);
});
}
/** What the walk and the review pass write on an entry: never part of what was reviewed. */
const REVIEW_KEYS = new Set(["verdict", "correction", "reason", "rejectNote", "walkNote", "star"]);
const canon = (v) => (Array.isArray(v) ? v.map(canon) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v);
/**
* WHAT WAS REVIEWED, as a signature stored with each mark: a clip's source, the span it plays and its gaps; a post's
* or a card's every field but its id (and the review's own). A mark whose block no longer signs the same -- an edge
* moved, a post edited, another version opened into the draft, an id reused -- is "changed since reviewed":
* unanswered again.
*
* @param {Record} e a timeline entry
*/
export function entrySignature(e) {
const what =
e?.type === "clip"
? { type: "clip", channel: e.channel ?? null, video: e.video ?? null, src: e.src ?? null, from: e.cutStart ?? e.start ?? null, to: e.cutEnd ?? e.end ?? null, gaps: e.gaps ?? null }
: Object.fromEntries(Object.entries(e ?? {}).filter(([k]) => k !== "id" && !REVIEW_KEYS.has(k)));
return createHash("sha256").update(JSON.stringify(canon(what))).digest("hex").slice(0, 16);
}
/**
* The marks as they stand against the cut now: each with `stale: true` when its block is gone or no longer signs
* what was reviewed (a mark from before signatures is stale too). The model (reviewPassModel.mjs) reads a stale
* mark as no answer.
*
* @param {ReviewPassDoc} doc
* @param {{ timeline?: Array> } | null} manifest
*/
export function marksAgainst(doc, manifest) {
// A twin id (two entries sharing one) is judged by its FIRST entry, the one setReviewMark signs.
const byId = new Map();
for (const e of manifest?.timeline ?? []) if (e && typeof e.id === "string" && !byId.has(e.id)) byId.set(e.id, e);
return Object.fromEntries(
Object.entries(doc.marks).map(([id, m]) => {
const e = byId.get(id);
return [id, { ...m, ...(!e || !m.sig || m.sig !== entrySignature(e) ? { stale: true } : {}) }];
}),
);
}
/** The timeline entry kinds the pass marks here (a clip: its Fix and its clearing; its Keep is its walk verdict). */
const MARKED_HERE = new Set(["clip", "post", "card", "teaser", "video"]);
/**
* Set (or clear) one block's mark -- any block's Fix, a post's or a card's Keep. Refused: a clip's Keep (its walk
* verdict, `umtool window --verdict confirmed`), a block the timeline does not hold, a Fix with no note (say what
* needs fixing -- the rule the walk's `incorrect` has). A twin id's mark is its first entry's.
*
* @param {string} dir
* @param {{ timeline?: Array> } | null} manifest
* @param {string} block
* @param {"keep" | "fix" | null} mark null clears it
* @param {{ note?: string, now?: Date }} [o]
* @returns {Promise<{ doc: ReviewPassDoc, mark: ReviewMark | null }>}
*/
export async function setReviewMark(dir, manifest, block, mark, { note, now = new Date() } = {}) {
const e = (manifest?.timeline ?? []).find((x) => x && x.id === block);
if (!e) throw new Error(`no block "${block}" in the cut`);
if (e.type === "clip" && mark === "keep") {
throw new Error(`${block} is a clip: its Keep is its walk verdict (umtool window ${block} --verdict confirmed); a Fix or a clear is a mark here`);
}
if (!MARKED_HERE.has(String(e.type))) throw new Error(`${block} is a ${e.type}: the review pass does not mark it`);
if (mark !== null && !REVIEW_MARKS.includes(mark)) throw new Error(`mark must be one of ${REVIEW_MARKS.join(", ")} (or clear)`);
const text = typeof note === "string" ? note.trim().slice(0, REVIEW_NOTE_LIMIT) : "";
if (mark === "fix" && !text) throw new Error("a Fix says what needs work (--note)");
const file = path.join(dir, REVIEW_PASS_FILE);
return serial(file, async () => {
const doc = await readReviewPass(dir);
if (mark === null) delete doc.marks[block];
else doc.marks[block] = { mark, ...(text ? { note: text } : {}), sig: entrySignature(e), at: now.toISOString() };
await mkdir(dir, { recursive: true });
const tmp = tmpPathFor(file);
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
await rename(tmp, file);
return { doc, mark: doc.marks[block] ?? null };
});
}
export const REVIEW_PASS_USAGE = [
"umtool review-pass [ls] [--json]",
"umtool review-pass mark keep|fix|clear [--note T]",
"umtool review-pass verdict like|maybe|no|clear [--note T] [--json]",
];
/**
* `umtool review-pass`: the pass's blocks with their answers and where it resumes (`ls`), one block's mark (`mark`:
* any block's Fix, a post's or a card's Keep), or the draft's verdict (`verdict`). A clip's Keep is its walk
* verdict -- `umtool window` writes it.
*
* @param {string[]} args
* @param {{ resolve?: (p: string) => Promise<{ id: string, dir: string } | null>, log?: Function, err?: Function }} [o]
*/
export async function reviewPassCommand(args, { resolve, log = console.log, err = console.error } = {}) {
const json = args.includes("--json");
const noteAt = args.indexOf("--note");
const note = noteAt >= 0 ? args[noteAt + 1] : undefined;
const pos = args.filter((a, i) => !a.startsWith("--") && !(noteAt >= 0 && i === noteAt + 1));
const [projectArg, verb = "ls", block, what] = pos;
if (!projectArg || args.includes("--help") || args.includes("-h")) {
(projectArg ? log : err)(REVIEW_PASS_USAGE.map((l) => `usage: ${l}`).join("\n"));
return projectArg ? 0 : 2;
}
const find = resolve ?? (async (a) => (await (await import("../projects/core.mjs")).resolveProject(a)).project ?? null);
const p = await find(projectArg);
if (!p) {
err(`no project "${projectArg}" (or more than one answers to that name: use its id)`);
return 2;
}
const manifest = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
if (verb === "mark") {
if (!block || !what || !["keep", "fix", "clear"].includes(what)) {
err(`usage: ${REVIEW_PASS_USAGE[1]}`);
return 2;
}
try {
const r = await setReviewMark(p.dir, manifest, block, what === "clear" ? null : /** @type {"keep" | "fix"} */ (what), { note });
if (json) log(JSON.stringify({ project: p.id, block, mark: r.mark }));
else log(r.mark ? `${block}: ${r.mark.mark}${r.mark.note ? ` — ${r.mark.note}` : ""}` : `${block}: cleared`);
return 0;
} catch (e) {
err(e instanceof Error ? e.message : String(e));
return 1;
}
}
if (verb === "verdict") {
// The pass's end: the draft's verdict (versions.mjs judgeDraft -- its parent when it differs only by review
// fields, else saved as the next version first). `block` is the verdict word here.
const word = block;
if (!word || !["like", "maybe", "no", "clear"].includes(word)) {
err(`usage: ${REVIEW_PASS_USAGE[2]}`);
return 2;
}
const { judgeDraft } = await import("./versions.mjs");
try {
const r = await judgeDraft(p, word === "clear" ? null : /** @type {"like" | "maybe" | "no"} */ (word), { note });
if (json) log(JSON.stringify({ project: p.id, judged: r.judged, saved: r.saved, verdict: r.entry?.verdict ?? null }));
else log(r.saved ? `saved ${r.judged} and judged it: ${word}` : `judged ${r.judged}: ${word}`);
return 0;
} catch (e) {
err(e instanceof Error ? e.message : String(e));
return 1;
}
}
if (verb !== "ls") {
err(`unknown: review-pass ${verb}\n${REVIEW_PASS_USAGE.map((l) => `usage: ${l}`).join("\n")}`);
return 2;
}
const doc = await readReviewPass(p.dir);
const timeline = Array.isArray(manifest.timeline) ? manifest.timeline : [];
const marks = marksAgainst(doc, manifest);
const prog = reviewProgress(timeline, marks);
const rows = reviewBlocks(timeline).map((e) => ({ id: e.id, type: e.type, answer: blockAnswer(e, marks), ...(marks[e.id]?.stale ? { changed: true } : {}) }));
if (json) {
log(JSON.stringify({ project: p.id, done: prog.done, total: prog.total, next: prog.next, blocks: rows }, null, 2));
return 0;
}
log(`${p.id}: ${prog.done} / ${prog.total} reviewed${prog.next ? ` · resumes at ${prog.next}` : " · every block answered: the verdict is next"}`);
for (const r of rows) {
const a = r.answer;
const said = !a ? (r.changed ? "— changed since reviewed" : "—") : a.mark === "fix" ? "needs work" : a.mark === "ruled" ? `${a.verdict} (the bench)` : a.mark;
log(` ${r.id === prog.next ? "→" : " "} ${r.id.padEnd(10)} ${String(r.type).padEnd(6)} ${said}${a?.note ? ` ${a.note}` : ""}`);
}
return 0;
}