// `umtool lint [--take ]`: THE MANIFEST LINT (report-to-video/lint.mjs, what a build runs before it // renders a frame) from umtool, on the project's manifest or on a TAKE's -- the take's manifest resolved as its // render resolves it (the project's now + its style's and its own patches) and written beside the project's // manifest for the lint, so a relative path in it is read as the render reads it -- plus the FILES the post items // name: a post item whose picked read, attachment or context media is not in the project would render a broken // item (a take's imported items are hard-linked in by `umtool take --import-item`; this says when one is not). // // exit 0 no error (warnings said) · 1 an error · 2 usage import { readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; export const LINT_USAGE = [ "usage: umtool lint [--take ] [--variant sourced|full] [--final] [--json]", " the manifest lint (report-to-video/lint.mjs, what a build runs before it renders) on the project's manifest, or", " with --take on the take's (its patches applied, as its render reads it), and the files its post items name: a", " picked read, an attachment, a context post's media not in the project is an ERROR; another named file a warning.", " And the cast's guard (umtool cast): a picked read that says a cast character in another voice than now is a", " warning (umtool cast reread); a cast voice the project's voice map overrides on purpose is a note.", " A ledger*.json beside a manifest that carries its own `ledger` -- one that parses as rows with ids -- is a warning:", " the manifest's (with --take, the take's) is the live one, what the build and umtool ledger read; the file stale, or", " NEWER when it holds row ids the live ledger lacks (named); local dates; the file is never touched.", " Exit 0 no error · 1 an error · 2 usage.", ].join("\n"); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const exists = async (f) => !!(await stat(f).catch(() => null)); /** * THE LEDGER'S ONE SOURCE OF TRUTH (12 Nov): the build, the instruments and `umtool ledger` read the manifest's * `ledger`; a ledger file beside it (quartering-diet's ledger.draft.json, 30 Aug, 186 rows against the manifest's * 564) is read by none of them. One warning per such file, naming which is live, each one's rows and (local) date. * A file counts only when it parses as a ledger: `ledger*.json`, a list of rows each with an id, or `{rows|ledger: * [...]}` -- never ledgerSchema.json, an empty list, rows without ids, or what does not parse. "NEWER" only when * the file is newer AND holds row ids the live ledger lacks (review 1, S8). Only said when the manifest carries a * ledger. The file is never touched (a project's own script may read it). Under --take, the live count is the take's. * @param {string} dir the project's dir * @param {Record} manifest the project's, or the take's resolved one (`take`) * @param {{ take?: string | null }} [o] * @returns {Promise} */ export async function ledgerFileWarnings(dir, manifest, { take = null } = {}) { if (!Array.isArray(manifest?.ledger)) return []; const names = (await readdir(dir).catch(() => [])).filter((n) => /^ledger.*\.json$/i.test(n) && !/^ledger-?schema\b/i.test(n)).sort(); if (!names.length) return []; const pad = (n) => String(n).padStart(2, "0"); const day = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }; const rows = (n) => `${n} row${n === 1 ? "" : "s"}`; const man = await stat(path.join(dir, "video.manifest.json")).catch(() => null); const liveIds = new Set(manifest.ledger.map((r) => (isObj(r) ? String(r.id ?? "") : "")).filter(Boolean)); const when = man ? `, ${day(man.mtimeMs)}` : ""; const live = take ? `take ${take}'s (video.manifest.json's with its patch; ${rows(manifest.ledger.length)}${when})` : `video.manifest.json's \`ledger\` (${rows(manifest.ledger.length)}${when})`; const out = []; for (const name of names) { const st = await stat(path.join(dir, name)).catch(() => null); // A ledger file, not a dump: past 64 MB it is not read. if (!st?.isFile() || st.size > 64 * 1024 * 1024) continue; let doc; try { doc = JSON.parse(await readFile(path.join(dir, name), "utf8")); } catch { continue; } const list = Array.isArray(doc) ? doc : Array.isArray(doc?.ledger) ? doc.ledger : Array.isArray(doc?.rows) ? doc.rows : null; if (!list?.length || !list.every((r) => isObj(r) && (typeof r.id === "string" || typeof r.id === "number") && String(r.id) !== "")) continue; const extra = [...new Set(list.map((r) => String(r.id)))].filter((id) => !liveIds.has(id)); const it = `${name} (${rows(list.length)}, ${day(st.mtimeMs)})`; const newer = !!man && st.mtimeMs > man.mtimeMs; const few = extra.slice(0, 5).join(", ") + (extra.length > 5 ? `, +${extra.length - 5} more` : ""); out.push( `${name} is not the ledger the build reads: the live ledger is ${live}; ` + (newer && extra.length ? `${it} is NEWER than the manifest and holds ${rows(extra.length)} the live ledger lacks (${few}) -- not in the cut (umtool ledger

add …)` : `${it} is stale${extra.length ? ` -- ${rows(extra.length)} of it not in the live ledger (${few})` : ""}${newer ? " (written after the manifest, nothing in it the live ledger lacks)" : " -- the manifest is newer"}`) + "; the file is left as it is", ); } return out; } /** * The files the post items of `manifest` name that are not in `dir`: `{ errors, warnings }`. * An error: the picked narration take, an attachment (`media[].src`), a context post's or a link's media. * A warning: any other narration take the item keeps. * @param {Record} manifest * @param {string} dir */ export async function namedFileProblems(manifest, dir) { const errors = []; const warnings = []; for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (!isObj(e) || e.type !== "post") continue; const takes = Array.isArray(e.narration?.takes) ? e.narration.takes : []; const pick = Number.isInteger(e.narration?.pick) ? e.narration.pick : 0; for (const [i, t] of takes.entries()) { if (typeof t?.file !== "string" || (await exists(path.join(dir, t.file)))) continue; if (i === pick && e.narration?.off !== true) errors.push(`timeline ${e.id}: its picked read ${t.file} is not in the project`); else warnings.push(`timeline ${e.id}: its take ${i + 1} (${t.file}) is not in the project`); } const media = [ ...(Array.isArray(e.media) ? e.media.map((m, i) => [`media[${i}]`, m]) : []), ...(Array.isArray(e.parents) ? e.parents.flatMap((p, k) => (Array.isArray(p?.media) ? p.media.map((m, i) => [`parents[${k}].media[${i}]`, m]) : [])) : []), ...(Array.isArray(e.links) ? e.links.flatMap((l, k) => (Array.isArray(l?.media) ? l.media.map((m, i) => [`links[${k}].media[${i}]`, m]) : [])) : []), ]; for (const [where, m] of media) { const src = isObj(m) ? m.src : typeof m === "string" ? m : null; if (typeof src !== "string" || /^[a-z][a-z0-9+.-]*:/i.test(src)) continue; if (!(await exists(path.join(dir, src)))) errors.push(`timeline ${e.id}.${where}: ${src} is not in the project`); } } return { errors, warnings }; } /** * THE CAST's CONSISTENCY GUARD (umtool-report-to-video/cast.mjs castDrift): a WARNING for each picked read that says a * cast character in another voice than it reads in now (stale: `umtool cast reread`), a NOTE for each cast voice the * project's map overrides on purpose. A project that reads no cast says nothing. * @param {Record} manifest * @param {{ id: string, dir: string }} project */ export async function castProblems(manifest, project, reportsRoot = REPORTS_ROOT) { const { castForProject } = await import("./castStore.mjs"); const castRead = await castForProject(project.dir, reportsRoot); if (castRead.error) return { warnings: [`the cast is not read (${castRead.error})`], notes: [] }; const { charactersOf, castDrift } = await import("umtool-report-to-video/cast"); if (!charactersOf(castRead.cast).length) return { warnings: [], notes: [] }; const { readVoiceMap } = await import("./postSay.mjs"); const { resolverFor } = await import("./castProject.mjs"); const map = await readVoiceMap(project.dir).catch(() => ({})); // This video's own characters answer before the cast's (cast.mjs: the chain every read asks). const { readProjectCharacters } = await import("./castStore.mjs"); const own = (await readProjectCharacters(project.dir)).doc; const { drift, overrides } = castDrift(manifest, { cast: castRead.cast, map, resolve: resolverFor({ map, cast: castRead.cast, project: own, render: manifest?.render ?? {} }) }); return { warnings: drift.map((d) => `timeline ${d.id}: @${d.handle} (${d.character}) reads in ${d.reads} -- now ${d.want} (${d.from === "project" ? (d.handle in map ? "the project's voice map" : "this video's own character") : d.from === "cast" ? "the cast" : d.from === "item" ? "the item's own character" : d.from}): umtool cast reread ${project.id} ${d.character}`), notes: overrides.map((o) => `@${o.handle} (${o.character}) reads in ${o.project} in this project -- the cast says ${o.cast} (an override on purpose; umtool posts voices ${project.id} remove ${o.handle} follows the cast)`), }; } /** * @param {string[]} args the words after `lint` * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void }} [opts] */ export async function lintCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error } = {}) { const valued = new Set(["--take", "--variant"]); const flags = new Map(); const positional = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (valued.has(a)) { if (args[i + 1] === undefined) { err(`${a} needs a value\n${LINT_USAGE}`); return 2; } flags.set(a, args[++i]); } else if (a.startsWith("--")) flags.set(a, true); else positional.push(a); } if (flags.has("--help") || positional.length !== 1) { (flags.has("--help") ? log : err)(LINT_USAGE); return flags.has("--help") ? 0 : 2; } const variant = String(flags.get("--variant") ?? "sourced"); if (!["sourced", "full"].includes(variant)) { err(`--variant takes sourced or full\n${LINT_USAGE}`); return 2; } const r = await resolveProject(positional[0], reportsRoot); if (r.ambiguous || !r.project) { err(r.ambiguous ? `"${positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id` : `no project matches "${positional[0]}"`); return 2; } const project = r.project; const take = flags.has("--take") ? String(flags.get("--take")) : null; const { lintManifestFile, lintReport } = await import("umtool-report-to-video/lint"); const { selectVariant } = await import("umtool-report-to-video/build-video"); let file = path.join(project.dir, "video.manifest.json"); let manifest; let scratch = null; try { if (take) { const { resolveTakeManifest } = await import("./takeManifest.mjs"); try { manifest = (await resolveTakeManifest(project.dir, take)).manifest; } catch (e) { err(e instanceof Error ? e.message : String(e)); return 1; } // Beside the project's manifest, as the render's own (.take-.render.json) is: its paths read as the render's. scratch = path.join(project.dir, `.take-${take}.lint.json`); await writeFile(scratch, JSON.stringify(manifest, null, 2) + "\n", "utf8"); file = scratch; } else { const { readFile } = await import("node:fs/promises"); manifest = JSON.parse(await readFile(file, "utf8").catch(() => "null")); if (!isObj(manifest)) { err(`${project.id} has no readable video.manifest.json`); return 1; } } const lint = await lintManifestFile(file, { variant, final: flags.has("--final") }); const files = await namedFileProblems(selectVariant(manifest, variant), project.dir); const voices = await castProblems(selectVariant(manifest, variant), project, reportsRoot); const ledgers = await ledgerFileWarnings(project.dir, manifest, { take }); const errors = [...lint.errors, ...files.errors]; const warnings = [...lint.warnings, ...files.warnings, ...voices.warnings, ...ledgers]; if (flags.has("--json")) log(JSON.stringify({ ok: errors.length === 0, project: project.id, take, variant, entries: manifest.timeline?.length ?? 0, errors, warnings, notes: voices.notes }, null, 2)); else { for (const line of lintReport({ errors, warnings })) log(line); for (const n of voices.notes) log(`note: ${n}`); log(`${project.id}${take ? ` take ${take}` : ""}: ${manifest.timeline?.length ?? 0} entries, ${errors.length ? "NOT ready to render" : "ready to render as far as the lint can tell"}`); } return errors.length ? 1 : 0; } finally { if (scratch) await rm(scratch, { force: true }); } }