// `umtool measure` (weight video rev 9): the measure slice a cut's // instruments would draw from (report-to-video measure-slice.mjs), printed -- // every event at its cut second, the hidden rows, and the totals. Reads only. // // umtool measure [--take ] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json] // // The cut's seconds: the take's built schedule (takes//out/sourced/ // schedule.json) when there is one, else an estimate from the manifest. Each // figure is timed by its clip's words (measure-words.mjs: the project's // channels tree, then the corpus) -- read off disk, never fetched. import { readFile, stat } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { CHANNELS_DIR } from "../paths.mjs"; import { resolveTakeManifest, takePlayDir } from "./takeManifest.mjs"; import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; import { estimateSchedule, playWindow } from "umtool-report-to-video/deck"; import { renderGaps } from "umtool-report-to-video/gaps"; import { measureSlice, pinnedRows } from "umtool-report-to-video/measure-slice"; import { measureClipWords } from "umtool-report-to-video/measure-words"; import { SHADOW_CHANNELS, channelsDirFor } from "umtool-report-to-video/sources"; export const MEASURE_USAGE = [ "usage: umtool measure [--take ] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]", "", "The measure slice of the cut (render.chrome.deck.measure; --scopes / --scale / --as-of override it): every ledger row", "in scope the cut shows, at the cut second its figure is said (its clip's words; else the quote's start),", "the rows no entry shows, the state after each, and the totals -- the odometer's runs (the highest real-time", "loss claim of each run, summed), NET, the goals, the diets, the promises. The cut's seconds are the take's", "built schedule.json with --take, else an estimate. --json prints the slice itself.", ].join("\n"); class CliError extends Error {} const exists = (p) => stat(p).then(() => true, () => false); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const clock = (t) => { const s = Math.max(0, Math.round(t)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; }; /** * @param {string[]} args the words after `measure` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, channelsDir?: string }} [opts] * @returns {Promise} the exit code */ export async function measureCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), channelsDir = CHANNELS_DIR } = {}) { const valued = new Set(["--take", "--scopes", "--scale", "--as-of"]); const flags = new Map(); const words = []; for (let i = 0; i < args.length; i += 1) { if (valued.has(args[i])) { flags.set(args[i], args[i + 1] ?? ""); i += 1; } else if (!args[i].startsWith("--")) words.push(args[i]); } const json = args.includes("--json"); try { const [projectArg] = words; if (!projectArg || args.includes("--help")) { err(MEASURE_USAGE); return 2; } const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${projectArg}"`); const project = r.project; const take = flags.get("--take") ?? null; const base = take ? (await resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir); if (!base) throw new CliError(`${project.id} has no manifest`); if (!isObj(base.ledgerSchema) || base.ledgerSchema.kind !== "measure") throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure")`); // The settings the slice is made with: the manifest's, with the flags over them. const m = JSON.parse(JSON.stringify(base)); m.render = isObj(m.render) ? m.render : {}; const chrome = isObj(m.render.chrome) ? m.render.chrome : { engine: "hyperframes", layout: "deck", deck: {} }; const deck = isObj(chrome.deck) ? chrome.deck : {}; const measure = { ...(isObj(deck.measure) ? deck.measure : {}) }; if (flags.has("--scopes")) measure.scopes = String(flags.get("--scopes")).split(",").map((s) => s.trim()).filter(Boolean); if (flags.has("--as-of")) measure.asOf = flags.get("--as-of"); if (flags.has("--scale")) { const m2 = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(flags.get("--scale"))); if (!m2) throw new CliError("--scale is MIN-MAX, in the ledger's unit (220-400)"); measure.scale = { min: Number(m2[1]), max: Number(m2[2]) }; } m.render.chrome = { ...chrome, layout: "deck", deck: { ...deck, measure } }; const cut = selectVariant(m, DEFAULT_VARIANT); const entries = cut.timeline ?? []; // The cut's seconds: the take's built schedule, else an estimate. let schedule = null; let from = "an estimate from the manifest"; if (take) { const p = path.join(takePlayDir(project.dir, take), "out", DEFAULT_VARIANT, "schedule.json"); const doc = await readFile(p, "utf8").then((t) => JSON.parse(t), () => null); if (Array.isArray(doc?.segments)) { schedule = doc; from = `take ${take}'s schedule.json`; } } if (!schedule) schedule = estimateSchedule(cut); const ledger = cut.measureLedger ?? base.ledger ?? []; const ids = new Set(pinnedRows(entries, ledger).keys()); const own = channelsDirFor(project.dir, base, { shadowExists: await exists(path.join(project.dir, SHADOW_CHANNELS)) }); const wordsOf = await measureClipWords({ entries, ids, provenance: base.provenance ?? {}, channelsDirs: [own, channelsDir] }); const clk = new Map(entries.filter((e) => e.type === "clip").map((e) => [e.id, playWindow(e, cut.render).from])); const gaps = new Map(entries.filter((e) => e.type === "clip" && renderGaps(e, cut.render).length).map((e) => [e.id, renderGaps(e, cut.render)])); const slice = measureSlice({ ...cut, ledger }, schedule, { words: wordsOf, clock: clk, gaps, asOf: measure.asOf ?? null }); if (json) { out(JSON.stringify(slice, null, 2)); return 0; } const by = slice.events.reduce((a, e) => ((a[e.tFrom] = (a[e.tFrom] ?? 0) + 1), a), {}); out(`${project.id}${take ? ` · take ${take}` : ""} · the cut's seconds: ${from}`); out(`scopes ${slice.scopes.join(", ")} · scale ${slice.scale.min}–${slice.scale.max} ${slice.unit} · as of ${slice.asOfRender}`); out(`${slice.events.length} event(s) on camera (timed by: ${Object.entries(by).map(([k, n]) => `${k} ${n}`).join(", ")}) · ${slice.hidden.length} hidden`); out(""); for (const e of slice.events) { out(` ${clock(e.t).padStart(6)} ${String(e.row).padEnd(6)} ${String(e.kind).padEnd(12)} ${String(e.display ?? "").padEnd(24)} ${e.run !== null ? `run ${e.run}`.padEnd(7) : "".padEnd(7)} ${String(e.tFrom).padEnd(7)} ${e.segment}`); } const t = slice.totals; out(""); out(`lost (his words): ${t.lost} ${slice.unit} across ${t.runs} run(s) — ${t.lostRuns.map((x) => `${x.start} ${x.peak} (${x.row})`).join(" · ")}`); out(`net: ${t.net.from ?? "—"} → ${t.net.to ?? "—"} = ${t.net.value ?? "—"} ${slice.unit} (${t.net.fromRow ?? "—"} → ${t.net.toRow ?? "—"})`); out(`goals: ${t.goals}${Object.keys(t.goalRepeats).length ? ` (${Object.entries(t.goalRepeats).map(([k, n]) => `"${k}" ×${n}`).join(", ")})` : ""} · diets: ${t.diets} · peak drift: ${t.peakDrift.join(" → ") || "—"} · under 300: ${t.under300.said}${t.under300.rows.length ? ` (${t.under300.rows.join(", ")})` : ""}`); for (const p of t.promises) out(`promise ${p.row}, said ${p.said}: "${p.what}"${p.due ? ` · due ${p.due}` : ""} · ${p.kept ? "KEPT" : "not kept"}${p.checks.length ? ` · checked ${p.checks.join(", ")}` : ""}${(p.claims ?? []).map((c) => ` · ${c.speaker ?? "he"} says ${c.label ?? c.row}${c.paidOn ? ` (paid ${c.paidOn})` : ""}`).join("")}${p.outcome ? ` · ${String(p.outcome.kind).toUpperCase()} ${p.outcome.date ?? ""} (${p.outcome.row})` : ""}`); out(`span: ${t.span.from ?? "—"} → ${t.span.to ?? "—"}`); return 0; } catch (e) { err(`umtool measure: ${e instanceof Error ? e.message : String(e)}`); return 1; } }