Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit b0fa50fae399c50d40c9aee60bf1d9c7095866d3
parent 80ee64bd70befb4f5598a8c5750f79c01fae36c3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 16:57:44 -0400

umtool: the take maker — New take, Make all styles, Rebuild and Use this take, in the UI and as `umtool take` / `umtool takes`

lib/report/takeMaker.mjs: makeTake copies the project's manifest, applies a montage style's patch (report-to-video/montage-styles.mjs, loaded at run time; none installed = no styles) then the take's own (RFC 7386 merge patch, arrays replace), writes takes/<id>/video.manifest.json and, once the preview exists, take.json (changes[] one plain line per changed leaf, baseHash of the base manifest, style, patch, window, entries). A window renders the entries it covers as a cut of their own (timed by the deck schedule or the manifest's lengths); full renders the whole cut fast. The render (takeRender.mjs) is build-video through queue-lock --heavy, --skip-fetch, into the take's own out/ with clips-raw and narration linked from the project's. Recipes (makeTakes) run one at a time, skip what exists unless forced, carry on past a failure. pickTake puts the take's manifest in the project's place through the new replaceManifest writer (auto snapshot auto-before-pick-take, so Undo last edit takes it back) inside withEditNotes, refuses when the project changed since the take was made (TakeStale) unless anyway, and records one pick per group in verdicts.json (takes.mjs setTakePicked; a row gains picked only when true).

Routes /api/report/takes/make (a job on the app's runner, running the CLI) and /takes/pick; the Takes page gets the New take form, Make all styles, and per take Use this take (Use anyway on a stale base), a picked badge and Rebuild.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/takes/make/route.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/takes/pick/route.ts | 35+++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 9+++++++++
Aumtool/components/projects/NewTakePanel.tsx | 297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesBench.tsx | 102++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/TakesPage.tsx | 35++++++++++++++++++++++++++++++-----
Mumtool/lib/report/manifest.mjs | 25+++++++++++++++++++++++++
Aumtool/lib/report/takeCli.mjs | 299+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeMaker.mjs | 761+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeMaker.test.mjs | 418+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeRender.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takes.mjs | 139++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/takes.test.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 2344 insertions(+), 32 deletions(-)

diff --git a/umtool/app/api/report/takes/make/route.ts b/umtool/app/api/report/takes/make/route.ts @@ -0,0 +1,79 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; +import { loadMontageStyles, takeSteps } from "@/lib/report/takeMaker.mjs"; +import { listTakes } from "@/lib/report/takes.mjs"; + +export const dynamic = "force-dynamic"; + +// MAKING TAKES (release 33) -- the Takes page's New take, Make all styles and +// Rebuild, as ONE job on the app's runner (lib/jobs.ts: one at a time, a log, +// the NDJSON events, Cancel). The job runs the CLI (`umtool take`, `umtool +// takes make`), so the page and a terminal do the same thing; the render +// inside takes the machine's heavy slot (lib/report/takeRender.mjs). +// +// GET ?job=<id>[&since=&sinceEvent=] that job, as /api/report/build?job= shows one +// GET ?project=<id> the styles, and the take job running, if any +// POST { project, take: {…} | allStyles: {…} | rebuild: "<id>", force? } +// (lib/report/takeMaker.mjs takeSteps says what each may carry) +// ?cancel=<job> stop it; a take not finished writes no take.json +export async function GET(request: Request) { + const url = new URL(request.url); + const headers = { "cache-control": "no-store" }; + const id = url.searchParams.get("job"); + if (id) { + const job = getJob(id); + if (!job) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const { styles, error } = await loadMontageStyles(); + const running = runningJob(); + const project = url.searchParams.get("project"); + return Response.json( + { + styles: Object.entries(styles).map(([name, s]) => ({ name, label: s.label, summary: s.summary })), + stylesError: error, + running: running && (!project || running.project === project) && /^takes? /.test(running.kind) ? jobView(running) : null, + }, + { headers }, + ); +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const { cancelJob } = await import("@/lib/jobs"); + return Response.json({ cancelled: cancelJob(cancel) }); + } + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (project.kind !== "report-video") return Response.json({ error: "takes are made of a report video" }, { status: 400 }); + const manifest = await readManifest(project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400 }); + + const [{ styles }, listing] = await Promise.all([loadMontageStyles(), listTakes(project.dir)]); + let plan; + try { + plan = takeSteps(project, body, { + styles, + existing: listing.takes, + clipCount: clipsOf(manifest).length, + }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, takes: plan.takes, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/app/api/report/takes/pick/route.ts b/umtool/app/api/report/takes/pick/route.ts @@ -0,0 +1,35 @@ +import { invalidateProjects, projectRef } from "@/lib/projects"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import { TakeStale, pickTake } from "@/lib/report/takeMaker.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; + +export const dynamic = "force-dynamic"; + +// "USE THIS TAKE" (release 33). POST { project, take, anyway? } +// +// The take's video.manifest.json over the project's, through the manifest +// writer (lib/report/manifest.mjs replaceManifest: the auto snapshot +// `auto-before-pick-take` first, so the Cut tab's "Undo last edit" and the +// History tab's revisions take it back) inside the edit-notes guard; then the +// pick in takes/verdicts.json, one per group. +// +// 409 `{ stale: true }` when the project's manifest is not the one the take +// was made from -- the pick would throw away what changed since -- until the +// operator says `anyway` (a second, explicit click). +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown } | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + try { + const r = await pickTake(project, body.take, { anyway: body.anyway === true }); + invalidateProjects(); + const historyHref = await pieceHrefOfProject(project.id, { tab: "history" }); + return Response.json({ ok: true, ...r, historyHref }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + if (e instanceof TakeStale) return Response.json({ error: e.message, stale: true }, { status: 409 }); + const message = e instanceof Error ? e.message : String(e); + return Response.json({ error: message }, { status: /^no take /.test(message) ? 404 : 400 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -47,6 +47,9 @@ // umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json] // umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id> // the operator's notes, and the agent's answers +// umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …] +// [--at S --dur S | --full] [--force] | --id <id> --rebuild make one take +// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] import process from "node:process"; import { PROJECT_KINDS, @@ -708,6 +711,9 @@ function usage() { " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)", " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)", " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>", + " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]", + " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force)", + " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", " re-fetch an article's scope, see what changed, update: the plan (the editor's);", " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)", @@ -741,6 +747,9 @@ const COMMANDS = { export: cmdExport, "check-sources": cmdCheckSources, notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))), + // The take maker (release 33): lib/report/takeCli.mjs. + take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))), + takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx @@ -0,0 +1,297 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; + +// New take, Make all styles -- and the job either starts (or a card's Rebuild +// starts), watched here until it ends, then the page re-reads the takes. +// +// Everything a model could do here a person does by hand: pick a style (or +// none), say the window, optionally write the patch. Nothing on this page +// calls a model. + +export type MontageStyle = { name: string; label: string; summary: string }; + +type StepView = { label: string; argv: string[] }; +type Ev = Record<string, unknown> & { ev: string; id?: string; phase?: string }; +type JobView = { + id: string; + kind: string; + state: "running" | "done" | "failed"; + stepIndex: number; + steps: StepView[]; + error: string | null; + log: string[]; + next: number; + events: Ev[]; + nextEvent: number; +}; + +/** A card's Rebuild (or anything else on the page) announces the job it started. */ +export const TAKE_JOB_EVENT = "umtool:take-job"; +export function announceTakeJob(job: unknown) { + window.dispatchEvent(new CustomEvent(TAKE_JOB_EVENT, { detail: job })); +} + +/** POST /api/report/takes/make; the job, or the error in words. */ +export async function startTakeJob(body: Record<string, unknown>): Promise<{ job?: JobView; error?: string }> { + const r = await fetch("/api/report/takes/make", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { job?: JobView; error?: string }; + if (!r.ok || !j.job) return { error: j.error ?? `HTTP ${r.status}` }; + announceTakeJob(j.job); + return { job: j.job }; +} + +/** The patch textarea's words: "" is no patch; anything else must be a JSON object. */ +function readPatch(text: string): { patch: Record<string, unknown> | null; error: string | null } { + if (!text.trim()) return { patch: null, error: null }; + try { + const v = JSON.parse(text); + if (!v || typeof v !== "object" || Array.isArray(v)) return { patch: null, error: "The patch is a JSON object: { \"render\": { … } }" }; + return { patch: v, error: null }; + } catch (e) { + return { patch: null, error: `Not JSON: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +export default function NewTakePanel({ + project, + styles, + stylesError, + group: initialGroup, + window: initialWindow = { at: 0, dur: 60 }, +}: { + project: string; + styles: MontageStyle[]; + stylesError?: string | null; + group: string; + window?: { at: number; dur: number }; +}) { + const router = useRouter(); + const [ready, setReady] = useState(false); + const [style, setStyle] = useState(""); + const [label, setLabel] = useState(""); + const [labelTouched, setLabelTouched] = useState(false); + const [group, setGroup] = useState(initialGroup); + const [full, setFull] = useState(false); + const [at, setAt] = useState(String(initialWindow.at)); + const [dur, setDur] = useState(String(initialWindow.dur)); + const [patchText, setPatchText] = useState(""); + const [force, setForce] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const [job, setJob] = useState<JobView | null>(null); + const since = useRef(0); + const sinceEvent = useRef(0); + + useEffect(() => setReady(true), []); + + // Adopt a take job already running (a reload, another tab), and any job a + // card starts. + const adopt = useCallback((j: JobView) => { + since.current = j.next ?? 0; + sinceEvent.current = j.nextEvent ?? 0; + setJob(j); + }, []); + useEffect(() => { + void fetch(`/api/report/takes/make?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => r.json()) + .then((j) => j.running && adopt(j.running as JobView)) + .catch(() => {}); + const on = (e: Event) => adopt((e as CustomEvent).detail as JobView); + window.addEventListener(TAKE_JOB_EVENT, on); + return () => window.removeEventListener(TAKE_JOB_EVENT, on); + }, [project, adopt]); + + useEffect(() => { + if (!job || job.state !== "running") return; + const t = setInterval(async () => { + const r = await fetch(`/api/report/takes/make?job=${job.id}&since=${since.current}&sinceEvent=${sinceEvent.current}`, { cache: "no-store" }); + if (!r.ok) return; + const j = (await r.json()) as JobView; + since.current = j.next; + sinceEvent.current = j.nextEvent; + setJob((prev) => (prev ? { ...j, log: [...prev.log, ...j.log], events: [...prev.events, ...j.events] } : j)); + // The new take is on disk: read the takes again. + if (j.state !== "running") router.refresh(); + }, 800); + return () => clearInterval(t); + }, [job, router]); + + const picked = styles.find((s) => s.name === style) ?? null; + const { patch, error: patchError } = readPatch(patchText); + const windowOf = () => (full ? "full" : { at: Number(at), dur: Number(dur) }); + const windowBad = !full && !(Number(at) >= 0 && Number(dur) > 0); + const running = job?.state === "running"; + + const submit = async (body: Record<string, unknown>) => { + setBusy(true); + setError(null); + const r = await startTakeJob({ project, force, ...body }); + setBusy(false); + if (r.error) setError(r.error); + }; + + const takeEvents = (job?.events ?? []).filter((e) => e.ev === "take"); + const takeIds = [...new Set(takeEvents.map((e) => String(e.id)))]; + const stateOf = (id: string) => { + const last = takeEvents.filter((e) => e.id === id).at(-1)?.phase; + return last === "done" ? "made" : last === "skipped" ? "skipped" : last === "failed" ? "failed" : "rendering"; + }; + + return ( + <section data-new-take="" className="space-y-2"> + <details className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]"> + <summary data-action="new-take-open" className="cursor-pointer px-3 py-2 text-[12.5px] text-text"> + New take + </summary> + <form + className="grid gap-3 border-t border-seam px-3 py-3 sm:grid-cols-2" + onSubmit={(e) => { + e.preventDefault(); + void submit({ take: { label, group, style: style || null, patch, window: windowOf() } }); + }} + > + <Field label="Style" hint={picked?.summary || (styles.length ? undefined : stylesError || "No montage styles are installed.")}> + <Select + data-take-style="" + value={style} + disabled={!ready} + onChange={(e) => { + const next = styles.find((s) => s.name === e.target.value) ?? null; + setStyle(e.target.value); + if (!labelTouched) setLabel(next?.label ?? ""); + }} + > + <option value="">None (the patch below only)</option> + {styles.map((s) => ( + <option key={s.name} value={s.name}> + {s.label} + </option> + ))} + </Select> + </Field> + <Field label="Label"> + <Input + data-take-label="" + value={label} + required + maxLength={80} + disabled={!ready} + onChange={(e) => { + setLabel(e.target.value); + setLabelTouched(true); + }} + /> + </Field> + <Field label="Group"> + <Input data-take-group="" value={group} required maxLength={60} disabled={!ready} onChange={(e) => setGroup(e.target.value)} /> + </Field> + <fieldset className="flex flex-col gap-1"> + <legend className="text-[12px] font-medium text-text-2">Window</legend> + <div className="flex flex-wrap items-center gap-2 text-[12px] text-text-2"> + <label className="flex items-center gap-1"> + <input type="radio" name="take-window" checked={!full} onChange={() => setFull(false)} data-take-window="part" disabled={!ready} /> + from + </label> + <Input + type="number" + min={0} + step={1} + value={at} + disabled={!ready || full} + onChange={(e) => setAt(e.target.value)} + data-take-at="" + aria-label="window starts at, seconds" + className="w-20" + /> + <span>s for</span> + <Input + type="number" + min={1} + step={1} + value={dur} + disabled={!ready || full} + onChange={(e) => setDur(e.target.value)} + data-take-dur="" + aria-label="window length, seconds" + className="w-20" + /> + <span>s</span> + <label className="flex items-center gap-1"> + <input type="radio" name="take-window" checked={full} onChange={() => setFull(true)} data-take-window="full" disabled={!ready} /> + Full cut + </label> + </div> + </fieldset> + <Field label="Patch (JSON, optional)" error={patchError} className="sm:col-span-2"> + <Textarea + data-take-patch="" + rows={3} + spellCheck={false} + placeholder='{ "render": { "montage": { "cut": "flash" } } }' + value={patchText} + disabled={!ready} + onChange={(e) => setPatchText(e.target.value)} + className="font-mono text-[12px]" + /> + </Field> + <div className="flex flex-wrap items-center gap-2 sm:col-span-2"> + <button + type="submit" + data-action="make-take" + disabled={!ready || busy || running || !label.trim() || !!patchError || windowBad} + className={buttonVariants({ size: "sm" })} + > + Make take + </button> + <button + type="button" + data-action="make-all-styles" + disabled={!ready || busy || running || !styles.length || windowBad} + className={buttonVariants({ size: "sm" })} + onClick={() => void submit({ allStyles: { group, window: windowOf() } })} + > + Make all styles{styles.length ? ` (${styles.length})` : ""} + </button> + <label className="flex items-center gap-1 text-[12px] text-text-2"> + <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} data-take-force="" disabled={!ready} /> + make it again if it exists + </label> + </div> + </form> + </details> + {error && ( + <p data-take-error="" role="alert" className="text-[12px] text-reject-text"> + {error} + </p> + )} + {job && ( + <JobProgress + data-take-job={job.id} + label={job.kind} + state={job.state} + status={job.state === "running" ? "rendering" : `${job.state}${job.error ? ` — ${job.error}` : ""}`} + meter={takeIds.length > 1 ? { fraction: takeIds.filter((id) => stateOf(id) !== "rendering").length / takeIds.length, text: `${takeIds.filter((id) => stateOf(id) !== "rendering").length}/${takeIds.length} takes` } : null} + steps={takeIds.map((id) => { + const st = stateOf(id); + const state: JobStepState = st === "made" ? "done" : st === "skipped" ? "skipped" : st === "failed" ? "failed" : job.state === "running" ? "running" : (job.state as JobStepState); + return { id, label: id, state, detail: st === "skipped" ? "exists" : null, attrs: { "data-take-step": id, "data-take-step-state": st } }; + })} + log={job.log.slice(-60)} + logLabel="take log" + onCancel={() => void fetch(`/api/report/takes/make?cancel=${job.id}`, { method: "POST" })} + cancelLabel="Stop" + /> + )} + </section> + ); +} diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -10,6 +10,7 @@ import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo } from "@/lib/format"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import { startTakeJob } from "./NewTakePanel"; // The takes of one project, a group at a time, every preview on screen at once. // @@ -36,10 +37,16 @@ export type Take = { builtAt: string | null; previewSize: number | null; previewMtimeMs: number | null; + /** How the take maker made it (null on a take made by hand). */ + style?: string | null; + window?: "full" | { at: number; dur: number } | null; + baseHash?: string | null; + /** The project's manifest is not the one it was made from (null: it does not say). */ + stale?: boolean | null; }; export type Verdict = "like" | "maybe" | "no"; -export type TakeVerdict = { verdict: Verdict | null; note: string; at: string }; +export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true }; const KIND_TONE: Record<Take["kind"], BadgeVariants["variant"]> = { reference: "on", @@ -87,11 +94,14 @@ export default function TakesBench({ project, groups, initial, + head, children, }: { project: string; groups: { group: string; takes: Take[] }[]; initial: Record<string, TakeVerdict>; + /** Above the groups, in the work column (New take). */ + head?: React.ReactNode; /** Under the groups, in the work column (the takes the listing skipped). */ children?: React.ReactNode; }) { @@ -214,6 +224,7 @@ export default function TakesBench({ <NotesProvider target={{ project }}> <BenchBody verdict={verdictBar}> <div className="space-y-6"> + {head} {groups.map((g) => { const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const) .filter(([, n]) => n > 0) @@ -273,6 +284,7 @@ export default function TakesBench({ if (listenRef.current !== t.id) setListen(t.id); }} save={(patch) => save(t.id, patch)} + onPicked={(v) => setVerdicts(v)} /> ))} </div> @@ -298,6 +310,7 @@ function TakeCard({ onPlay, onUnmute, save, + onPicked, }: { project: string; take: Take; @@ -310,6 +323,7 @@ function TakeCard({ onPlay: () => void; onUnmute: () => void; save: (patch: { verdict?: Verdict | null; note?: string }) => Promise<void>; + onPicked: (verdicts: Record<string, TakeVerdict>) => void; }) { const notes = useSharedNotes({ project }); const router = useRouter(); @@ -346,6 +360,40 @@ function TakeCard({ const current = verdict?.verdict ?? null; const hue = VERDICTS.find((v) => v.id === current)?.tone; + // "Use this take": its manifest becomes the project's. Refused when the + // project changed since the take was made, until "Use anyway". + const [pickState, setPickState] = useState<{ stale?: string; done?: { history: string } } | null>(null); + const pick = async (anyway: boolean) => { + setBusy(true); + setError(null); + try { + const r = await fetch("/api/report/takes/pick", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, take: t.id, anyway }), + cache: "no-store", + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; stale?: boolean; verdicts?: Record<string, TakeVerdict>; historyHref?: string }; + if (r.status === 409 && j.stale) setPickState({ stale: j.error ?? "The project changed since this take was made" }); + else if (!r.ok) setError(j.error ?? `HTTP ${r.status}`); + else { + if (j.verdicts) onPicked(j.verdicts); + setPickState({ done: { history: j.historyHref ?? "" } }); + router.refresh(); + } + } finally { + setBusy(false); + } + }; + const rebuild = async () => { + setBusy(true); + setError(null); + const r = await startTakeJob({ project, rebuild: t.id }); + setBusy(false); + if (r.error) setError(r.error); + }; + const windowWords = t.window === "full" ? "full cut" : t.window ? `${t.window.at}–${t.window.at + t.window.dur} s` : null; + return ( <article data-take={t.id} @@ -379,7 +427,13 @@ function TakeCard({ <span className="num text-[11px] text-[var(--color-dim)]" suppressHydrationWarning> {t.seconds != null && `${t.seconds.toFixed(1)} s`} {t.builtAt && !Number.isNaN(Date.parse(t.builtAt)) && ` · ${fmtAgo(Date.parse(t.builtAt))}`} + {windowWords && ` · ${windowWords}`} </span> + {verdict?.picked && ( + <span data-take-picked="" className={badgeVariants({ variant: "on", size: "sm" })}> + picked + </span> + )} <button type="button" data-action="listen" @@ -434,6 +488,52 @@ function TakeCard({ Both land in the project's notes.json, which the agent that made the takes reads back (`umtool notes`) beside verdicts.json. */} <AnchoredNotes notes={notes} pin={{ kind: "take", take: t.id }} label="take notes" /> + <div className="flex flex-wrap items-center gap-1.5"> + <button + type="button" + data-action="pick" + disabled={!ready || busy} + className={buttonVariants({ size: "sm" })} + onClick={() => void pick(false)} + > + Use this take + </button> + {t.baseHash && ( + <button + type="button" + data-action="rebuild" + disabled={!ready || busy} + className={buttonVariants({ size: "sm" })} + onClick={() => void rebuild()} + > + Rebuild + </button> + )} + </div> + {pickState?.stale && ( + <div data-take-stale="" className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-doubt-text"> + <span>{pickState.stale}.</span> + <button + type="button" + data-action="pick-anyway" + disabled={!ready || busy} + className={buttonVariants({ size: "sm" })} + onClick={() => void pick(true)} + > + Use anyway + </button> + </div> + )} + {pickState?.done && ( + <p data-take-used="" className="text-[11.5px] text-text-2"> + The project&apos;s manifest is this take&apos;s now.{" "} + {pickState.done.history && ( + <a href={pickState.done.history} className="ink-link"> + Revisions + </a> + )} + </p> + )} <div className="flex flex-wrap"> <DeletePlan label={`Delete take ${t.id}`} diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -1,20 +1,43 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; import Link from "next/link"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import { projectsHref } from "@/lib/hrefs"; import { listTakes, readVerdicts } from "@/lib/report/takes.mjs"; import { pieceHrefOfProject } from "@/lib/pieces/article"; import type { ProjectRef } from "@/lib/project-types"; +import { hashText, lastGroup, loadMontageStyles } from "@/lib/report/takeMaker.mjs"; +import NewTakePanel from "./NewTakePanel"; import TakesBench, { type Take, type TakeVerdict } from "./TakesBench"; // `/browse/<project>/takes` -- alternative renders of one part of the cut, // watched side by side and judged like / maybe / no. // -// The takes are made elsewhere (lib/report/takes.mjs says by whom and in what -// shape); this page only reads them, and writes takes/verdicts.json. +// The takes are made by the take maker (lib/report/takeMaker.mjs: New take, +// Make all styles, Rebuild here, or `umtool take`) or by somebody else in the +// same shape (lib/report/takes.mjs); this page reads them, writes +// takes/verdicts.json, and "Use this take" puts one's manifest in the +// project's place. export default async function TakesPage({ project }: { project: ProjectRef }) { - const [listing, verdicts] = await Promise.all([listTakes(project.dir), readVerdicts(project.dir)]); - const takes = listing.takes as Take[]; + const [listing, verdicts, styles, manifestText] = await Promise.all([ + listTakes(project.dir), + readVerdicts(project.dir), + loadMontageStyles(), + readFile(path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), + ]); + const current = manifestText === null ? null : hashText(manifestText); + const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null })); + const byId = new Map(takes.map((t) => [t.id, t])); + const panel = + project.kind === "report-video" ? ( + <NewTakePanel + project={project.id} + styles={Object.entries(styles.styles).map(([name, s]) => ({ name, label: s.label, summary: s.summary }))} + stylesError={styles.error} + group={lastGroup(takes)} + /> + ) : null; const judged = takes.filter((t) => verdicts[t.id]?.verdict).length; // The piece this view belongs to: the article's when an article claims the project (P4a-2). @@ -49,6 +72,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { > {takes.length === 0 ? ( <BenchBody workClassName="space-y-4"> + {panel} <p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]"> No takes yet.{" "} <Link href={back} className="ink-link"> @@ -60,8 +84,9 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { ) : ( <TakesBench project={project.id} - groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes as Take[] }))} + groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes.map((t: { id: string }) => byId.get(t.id) as Take) }))} initial={verdicts as Record<string, TakeVerdict>} + head={panel} > {skipped} </TakesBench> diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -1304,6 +1304,31 @@ export async function updateFactcheck(dir, factcheck, { token = null } = {}) { } /** + * Replace the WHOLE manifest with `manifest` (release 33: "Use this take" puts + * a take's video.manifest.json in the project's place). The same path as a + * structural edit -- the lock, the token, the auto snapshot of the file as it + * still is (`auto-before-<op>`, so the Cut tab's "Undo last edit" takes it + * back), the drafted-mark rule and the atomic write -- without the structure + * checks: the manifest is somebody's whole cut, not one edit to judge. + * + * @param {string} dir + * @param {Record<string, unknown>} manifest + * @param {{ token?: string | null, op?: string }} [opts] + */ +export async function replaceManifest(dir, manifest, { token = null, op = "replace" } = {}) { + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw new Error("a manifest is an object"); + if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const next = JSON.parse(JSON.stringify(manifest)); + const snapshot = await autoSnapshot(dir, op); + const nextToken = await writeManifestAtomic(dir, next); + return { snapshot, token: nextToken }; + }); +} + +/** * Take back the newest structural edit: restore the newest `auto-before-<op>` * snapshot, byte for byte. The manifest as it is now is kept first * (`undo-saved`), and the restored snapshot is renamed `undone-<op>` so the diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -0,0 +1,299 @@ +// `umtool take` and `umtool takes` (release 33): the take maker from a +// terminal. The app's Takes page runs these same commands as jobs, so what a +// button does and what an agent types cannot drift apart. +// +// umtool take <project> --id <id> --label "<l>" [--group G] [--kind K] [--summary S] +// [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …] +// [--at S --dur S | --full] [--force] [--progress ndjson] +// umtool take <project> --id <id> --rebuild made again from its own take.json +// umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson] +// umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force] +// umtool takes styles [--json] +// umtool takes pick <project> <take> [--anyway] [--json] +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { ensureWriteDir } from "./storage.mjs"; +import { + ALL_STYLES_RECIPE, + DEFAULT_WINDOW, + RECIPE_FILE, + TakeStale, + allStylesRecipe, + loadMontageStyles, + makeTake, + makeTakes, + patchFromSets, + pickTake, +} from "./takeMaker.mjs"; +import { TAKE_FILE, takesDirOf } from "./takes.mjs"; + +export const TAKE_USAGE = [ + "usage: umtool take <project> --id <id> --label \"<label>\" [--group G] [--kind similar|different]", + " [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]", + " [--at S --dur S | --full] [--force] [--progress ndjson]", + " umtool take <project> --id <id> --rebuild made again from its own take.json", + "", + "A take is the project's manifest with a style's patch, then the take's own, applied (JSON merge", + "patches), rendered into takes/<id>/. The window renders the entries it covers; --full the whole", + `cut. Default window: --at ${DEFAULT_WINDOW.at} --dur ${DEFAULT_WINDOW.dur}. Nothing is fetched.`, +].join("\n"); + +export const TAKES_USAGE = [ + "usage: umtool takes make <project> [--recipe FILE] [--only ID,ID] [--force] [--progress ndjson]", + ` the recipe's takes, one at a time (default: takes/${RECIPE_FILE}); a take that`, + " exists is skipped unless --force", + " umtool takes make <project> --all-styles [--group G] [--at S --dur S | --full] [--force]", + ` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`, + " umtool takes styles [--json] the montage styles: name, label, summary", + " umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's", +].join("\n"); + +class CliError extends Error {} + +/** The flags of one command line. */ +function parse(args) { + const valued = new Set([ + "--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", + "--at", "--dur", "--recipe", "--only", "--progress", + ]); + /** @type {Record<string, string[]>} */ + const flags = {}; + const positional = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a.startsWith("--")) { + if (valued.has(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + (flags[a] ??= []).push(args[++i]); + } else (flags[a] ??= []).push(""); + } else positional.push(a); + } + const one = (n) => flags[n]?.[flags[n].length - 1]; + const has = (n) => n in flags; + return { flags, positional, one, has }; +} + +async function pickProject(arg, root) { + if (!arg) throw new CliError("which project? pass an id, a name, or a directory"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + if (r.project.kind !== "report-video") throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + return r.project; +} + +/** --at/--dur or --full, else the default window. */ +function windowOf(p) { + if (p.has("--full")) { + if (p.has("--at") || p.has("--dur")) throw new CliError("--full or --at/--dur, not both"); + return "full"; + } + if (!p.has("--at") && !p.has("--dur")) return undefined; + const at = Number(p.one("--at") ?? 0); + const dur = Number(p.one("--dur") ?? DEFAULT_WINDOW.dur); + if (!Number.isFinite(at) || at < 0 || !Number.isFinite(dur) || dur <= 0) throw new CliError("--at ≥ 0 and --dur > 0, in seconds"); + return { at, dur }; +} + +async function patchOf(p) { + const sources = ["--patch", "--patch-json", "--set"].filter((n) => p.has(n)); + if (sources.length > 1) throw new CliError(`${sources.join(" and ")}: one way of giving the patch`); + let patch; + if (p.has("--patch")) { + const file = /** @type {string} */ (p.one("--patch")); + try { + patch = JSON.parse(await readFile(path.resolve(file), "utf8")); + } catch (err) { + throw new CliError(`--patch ${file}: ${err instanceof Error ? err.message : err}`); + } + } else if (p.has("--patch-json")) { + try { + patch = JSON.parse(/** @type {string} */ (p.one("--patch-json"))); + } catch (err) { + throw new CliError(`--patch-json: ${err instanceof Error ? err.message : err}`); + } + } else if (p.has("--set")) { + try { + patch = patchFromSets(p.flags["--set"]); + } catch (err) { + throw new CliError(err instanceof Error ? err.message : String(err)); + } + } else return null; + if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new CliError("a patch is a JSON object"); + return patch; +} + +/** The output side: NDJSON on stdout under --progress ndjson, else lines. */ +function reporter(p, log, err) { + const ndjson = p.one("--progress") === "ndjson"; + if (p.has("--progress") && !ndjson) throw new CliError("--progress takes ndjson"); + return { + ndjson, + emit: (ev) => { + if (ndjson) return log(JSON.stringify(ev)); + if (ev.ev !== "take") return; + const tail = ev.phase === "failed" ? ` — ${ev.error}` : ev.phase === "done" && ev.seconds != null ? ` (${ev.seconds} s)` : ""; + log(`take ${ev.id}: ${ev.phase}${ev.n ? ` (${ev.i}/${ev.n})` : ""}${tail}`); + }, + // Under NDJSON the prose goes to stderr, so stdout is events only. + log: (line) => (ndjson ? err(line) : log(line)), + }; +} + +async function realDeps() { + const { probeSeconds } = await import("./takeRender.mjs"); + return { probe: probeSeconds, ensureOut: ensureWriteDir }; +} + +/** + * `umtool take …` + * @param {string[]} args everything after `take` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts] + * @returns {Promise<number>} + */ +export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) { + try { + const p = parse(args); + if (p.has("--help") || !p.positional.length) { + log(TAKE_USAGE); + return p.has("--help") ? 0 : 2; + } + const project = await pickProject(p.positional[0], reportsRoot); + const out = reporter(p, log, err); + const id = p.one("--id"); + if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)"); + let spec; + if (p.has("--rebuild")) { + const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); + if (!prev) throw new CliError(`${project.id} has no take ${id} to rebuild`); + spec = { + id, + label: prev.label, + group: prev.group, + order: prev.order, + kind: prev.kind === "similar" ? "similar" : undefined, + summary: prev.summary, + style: prev.style ?? null, + patch: prev.patch ?? null, + window: prev.window ?? undefined, + }; + } else { + spec = { + id, + label: p.one("--label") ?? "", + group: p.one("--group"), + kind: p.one("--kind"), + summary: p.one("--summary"), + style: p.one("--style") ?? null, + patch: await patchOf(p), + window: windowOf(p), + }; + } + const r = await makeTake(project.dir, spec, { + force: p.has("--force") || p.has("--rebuild"), + emit: out.emit, + log: out.log, + ...(deps ?? (await realDeps())), + }); + if (r.skipped) out.log(`take ${id} exists — pass --force to make it again`); + return 0; + } catch (e) { + if (e instanceof CliError) { + err(e.message); + return 2; + } + err(e instanceof Error ? e.message : String(e)); + return 1; + } +} + +/** + * `umtool takes …` + * @param {string[]} args everything after `takes` + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, deps?: Record<string, unknown> }} [opts] + * @returns {Promise<number>} + */ +export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, deps } = {}) { + try { + const p = parse(args); + const [sub, ...rest] = p.positional; + if (!sub || p.has("--help")) { + log(TAKES_USAGE); + return sub ? 0 : 2; + } + if (sub === "styles") { + const { styles, error, skipped } = await loadMontageStyles(); + if (p.has("--json")) { + log(JSON.stringify({ styles, error, skipped }, null, 2)); + return error ? 1 : 0; + } + const names = Object.keys(styles); + if (error) err(error); + if (!names.length) log("no montage styles are installed"); + for (const n of names) log(`${n.padEnd(16)} ${styles[n].label}${styles[n].summary ? ` — ${styles[n].summary}` : ""}`); + if (skipped.length) err(`not the shape { label, summary, patch }: ${skipped.join(", ")}`); + return error ? 1 : 0; + } + if (sub === "pick") { + const project = await pickProject(rest[0], reportsRoot); + const take = rest[1]; + if (!take) throw new CliError("which take? `umtool takes pick <project> <take>`"); + try { + const r = await pickTake(project, take, { anyway: p.has("--anyway") }); + if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); + else log(`${project.id}: now ${take}'s manifest${r.snapshot?.rel ? ` (the one before is ${r.snapshot.rel})` : ""}`); + return 0; + } catch (e) { + if (e instanceof TakeStale) { + err(`${e.message} — pass --anyway to use it all the same`); + return 1; + } + throw e; + } + } + if (sub === "make") { + const project = await pickProject(rest[0], reportsRoot); + const out = reporter(p, log, err); + let recipe; + if (p.has("--all-styles")) { + if (p.has("--recipe")) throw new CliError("--all-styles or --recipe, not both"); + const loaded = deps?.styles ? { styles: /** @type {any} */ (deps.styles), error: null } : await loadMontageStyles(); + if (loaded.error) throw new Error(loaded.error); + recipe = allStylesRecipe(loaded.styles, { group: p.one("--group") ?? undefined, window: windowOf(p) }); + const file = path.join(takesDirOf(project.dir), ALL_STYLES_RECIPE); + await mkdir(takesDirOf(project.dir), { recursive: true }); + await writeFile(file, JSON.stringify(recipe, null, 2) + "\n", "utf8"); + out.log(`wrote ${path.relative(project.dir, file)}: ${recipe.takes.length} take(s)`); + } else { + const file = path.resolve(project.dir, p.one("--recipe") ?? path.join("takes", RECIPE_FILE)); + try { + recipe = JSON.parse(await readFile(file, "utf8")); + } catch (e) { + throw new CliError(`the recipe ${file}: ${e instanceof Error ? e.message : e}`); + } + } + const only = p.one("--only")?.split(",").map((s) => s.trim()).filter(Boolean) ?? null; + const results = await makeTakes(project.dir, recipe, { + force: p.has("--force"), + only, + emit: out.emit, + log: out.log, + ...(deps ?? (await realDeps())), + }); + const failed = results.filter((r) => r.status === "failed"); + const made = results.filter((r) => r.status === "made").length; + const skipped = results.filter((r) => r.status === "skipped").length; + out.log(`${made} made, ${skipped} skipped, ${failed.length} failed${failed.length ? `: ${failed.map((f) => f.id).join(", ")}` : ""}`); + return failed.length ? 1 : 0; + } + throw new CliError(`unknown: takes ${sub}\n\n${TAKES_USAGE}`); + } catch (e) { + if (e instanceof CliError) { + err(e.message); + return 2; + } + err(e instanceof Error ? e.message : String(e)); + return 1; + } +} diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -0,0 +1,761 @@ +// THE TAKE MAKER (release 33): a take is the project's manifest with one +// change applied, rendered beside it, so two ways of cutting the same part can +// be watched side by side (takes.mjs is the contract it writes). +// +// makeTake(projectDir, spec) one take: copy the manifest, apply the +// style's patch then the take's own (RFC 7386 +// merge patches), render, write take.json +// makeTakes(projectDir, recipe) a recipe's takes, one after another +// pickTake(project, takeId) "Use this take": the take's manifest over +// the project's, through the manifest writer +// +// What a take is made of, on disk: +// +// takes/<id>/video.manifest.json the WHOLE patched manifest -- what a pick +// copies over the project's +// takes/<id>/preview.mp4 the render (the window, or the full cut) +// takes/<id>/out/ the take's own render scratch; its +// clips-raw/ and narration/ are LINKS to the +// project's out/ (the fetched media is +// reused, never copied, never fetched) +// takes/<id>/take.json written LAST, only when the preview +// exists: until then the directory is a +// work dir, which the listing ignores +// +// THE WINDOW. `{ at, dur }` renders the entries of the cut that the window +// [at, at + dur] touches -- timed by the project's last deck schedule when +// there is one, else by the manifest's own lengths -- as a cut of their own: +// a fast build of just those entries. Not build-video's `--chrome-preview` +// (it needs every segment already built in the take's out/, and the project's +// segments, linked in, would show the old cut for any change that re-cuts a +// clip) and not `--preview` (the rail's, over a cached concat). Every take of a +// group made with the same window covers the same entries, whatever its patch +// does to their lengths. `"full"` renders the whole cut, fast. +// +// THE RENDER is injected (tests pass a stub); the real one is takeRender.mjs: +// build-video.mjs through the heavy slot (scripts/queue-lock.mjs --heavy). +// +// Plain ESM: the CLI (`umtool take`) runs it with bare node, and the app's +// pages import the parts they show (the styles, the staleness check). +import { createHash } from "node:crypto"; +import { lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs"; +import { replaceManifest } from "./manifest.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { isTakeId, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; + +export const MANIFEST = "video.manifest.json"; +export const PREVIEW = "preview.mp4"; +/** The recipe `umtool takes make` reads when none is named. */ +export const RECIPE_FILE = "recipe.json"; +/** The recipe "Make all styles" writes (its own name: a hand-written recipe.json is never overwritten). */ +export const ALL_STYLES_RECIPE = "all-styles.recipe.json"; +export const DEFAULT_GROUP = "takes"; +export const DEFAULT_WINDOW = { at: 0, dur: 60 }; +/** The project's out/ entries a take's out/ links to: the fetched media and the synthesized voices. */ +export const SHARED_OUT = ["clips-raw", "narration"]; +/** Where a take's render manifest sits while it renders: beside the project's, so its relative paths hold. */ +export const renderManifestPath = (projectDir, id) => path.join(projectDir, `.take-${id}.render.json`); + +const serialise = (m) => JSON.stringify(m, null, 2) + "\n"; +export const hashText = (text) => createHash("sha256").update(text).digest("hex"); + +/** @param {unknown} v @returns {v is Record<string, any>} */ +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v))); + +// --------------------------------------------------------------------------- +// RFC 7386 JSON merge patch, and the words for what one changes. +// --------------------------------------------------------------------------- + +/** + * Apply a JSON merge patch (RFC 7386): an object patch merges key by key, a + * `null` member removes the key, anything else -- an array included -- + * replaces the value whole. Never mutates either argument. + * + * @param {unknown} target + * @param {unknown} patch + * @returns {unknown} + */ +export function mergePatch(target, patch) { + if (!isObj(patch)) return clone(patch); + const out = isObj(target) ? clone(target) : {}; + for (const [k, v] of Object.entries(patch)) { + if (v === null) delete out[k]; + else out[k] = mergePatch(out[k], v); + } + return out; +} + +/** + * Every leaf a merge patch sets, as a dotted path: a non-object value, a + * `null` (a removal) or an empty object. `{ render: { montage: { cut: "flash" } } }` + * → `[["render.montage.cut", "flash"]]`. + * + * @param {unknown} patch + * @param {string} [prefix] + * @returns {Array<[string, unknown]>} + */ +export function patchLeaves(patch, prefix = "") { + if (!isObj(patch)) return prefix ? [[prefix, patch]] : []; + const keys = Object.keys(patch); + if (!keys.length) return prefix ? [[prefix, {}]] : []; + return keys.flatMap((k) => patchLeaves(patch[k], prefix ? `${prefix}.${k}` : k)); +} + +/** The value at a dotted path, or undefined. */ +export function getPath(obj, dotted) { + let cur = obj; + for (const k of dotted.split(".")) { + if (!isObj(cur) && !Array.isArray(cur)) return undefined; + cur = /** @type {any} */ (cur)[k]; + } + return cur; +} + +/** A value in a change line: short and plain. */ +export function fmtValue(v) { + if (v === undefined || v === null) return "none"; + if (typeof v === "string") return v; + if (typeof v === "number" || typeof v === "boolean") return String(v); + const json = JSON.stringify(v); + if (json.length <= 60) return json; + return Array.isArray(v) ? `${v.length} items` : `${Object.keys(v).length} settings`; +} + +/** + * One plain line per leaf the patches change, in the order the patches name + * them (a later patch's line replaces an earlier one's for the same path): + * `render.montage.cut: flash`, `render.crf: 34 (was 30)`, + * `render.montage: removed`. A leaf whose value comes out the same as before + * is not a change and has no line. + * + * @param {unknown} before the manifest the patches were applied to + * @param {unknown} after the manifest they made + * @param {unknown[]} patches + * @returns {string[]} + */ +export function changeLines(before, after, patches) { + const lines = new Map(); + for (const p of patches) { + for (const [dotted] of patchLeaves(p)) { + const was = getPath(before, dotted); + const now = getPath(after, dotted); + lines.delete(dotted); + if (JSON.stringify(was) === JSON.stringify(now)) continue; + if (now === undefined) { + lines.set(dotted, `${dotted}: removed`); + continue; + } + const scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v); + const tail = was !== undefined && scalar(was) && scalar(now) ? ` (was ${fmtValue(was)})` : ""; + lines.set(dotted, `${dotted}: ${fmtValue(now)}${tail}`); + } + } + return [...lines.values()]; +} + +/** + * `--set render.montage.cut=flash` as a patch. The value is JSON when it + * parses (`3`, `true`, `null`, `{"mode":"snap"}`), else the string itself. + * + * @param {string[]} sets + * @returns {Record<string, unknown>} + */ +export function patchFromSets(sets) { + /** @type {Record<string, any>} */ + const out = {}; + for (const s of sets) { + const eq = s.indexOf("="); + if (eq <= 0) throw new Error(`--set takes path=value, not ${JSON.stringify(s)}`); + const keys = s.slice(0, eq).split("."); + if (keys.some((k) => !k)) throw new Error(`--set: ${JSON.stringify(s.slice(0, eq))} is not a dotted path`); + const raw = s.slice(eq + 1); + let value; + try { + value = JSON.parse(raw); + } catch { + value = raw; + } + let cur = out; + for (const k of keys.slice(0, -1)) { + if (!isObj(cur[k])) cur[k] = {}; + cur = cur[k]; + } + cur[keys[keys.length - 1]] = value; + } + return out; +} + +// --------------------------------------------------------------------------- +// The styles (lane M3's report-to-video/montage-styles.mjs). +// --------------------------------------------------------------------------- + +/** + * Where the styles are read from: report-to-video/montage-styles.mjs, unless + * E2E_UMTOOL_MONTAGE_STYLES names a module of the same shape (the e2e's stub). + */ +export function montageStylesFile(env = process.env) { + return env.E2E_UMTOOL_MONTAGE_STYLES || path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "montage-styles.mjs"); +} + +/** + * The named montage styles: `{ name: { label, summary, patch } }`, loaded at + * run time. A missing module is no styles, not an error (`error` says why); + * an entry that is not the shape is dropped and named in `skipped`. + * + * @param {{ file?: string }} [opts] + * @returns {Promise<{ styles: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, error: string | null, skipped: string[] }>} + */ +export async function loadMontageStyles({ file = montageStylesFile() } = {}) { + let mod; + try { + const href = pathToFileURL(file).href; + mod = await import(/* webpackIgnore: true */ /* turbopackIgnore: true */ href); + } catch (err) { + const code = /** @type {any} */ (err)?.code; + const missing = code === "ERR_MODULE_NOT_FOUND" && String(/** @type {any} */ (err)?.message ?? "").includes(path.basename(file)); + return { styles: {}, error: missing ? null : `the montage styles did not load: ${err instanceof Error ? err.message : err}`, skipped: [] }; + } + const raw = mod?.MONTAGE_STYLES; + /** @type {Record<string, { label: string, summary: string, patch: Record<string, unknown> }>} */ + const styles = {}; + const skipped = []; + if (isObj(raw)) { + for (const [name, s] of Object.entries(raw)) { + if (isObj(s) && typeof s.label === "string" && isObj(s.patch)) { + styles[name] = { label: s.label, summary: typeof s.summary === "string" ? s.summary : "", patch: clone(s.patch) }; + } else skipped.push(name); + } + } + return { styles, error: raw === undefined ? "montage-styles.mjs exports no MONTAGE_STYLES" : null, skipped }; +} + +// --------------------------------------------------------------------------- +// The window. +// --------------------------------------------------------------------------- + +/** An entry's length by the manifest's own numbers: a clip's cut, else `seconds`, else 4 s. */ +export function estimatedSeconds(e) { + if (e?.type === "clip") { + const a = Number(e.cutStart ?? e.start); + const b = Number(e.cutEnd ?? e.end); + if (Number.isFinite(a) && Number.isFinite(b) && b > a) return b - a; + } + const s = Number(e?.seconds); + return Number.isFinite(s) && s > 0 ? s : 4; +} + +/** The entries the default cut plays (build-video's selectVariant, sourced): untagged, or tagged sourced. */ +export const sourcedEntries = (timeline) => (Array.isArray(timeline) ? timeline : []).filter((e) => isObj(e) && (!e.variant || e.variant === "sourced")); + +/** + * The entries a window of the cut touches, in order. + * + * Timed by `schedule` (the deck's out/sourced/schedule.json: `segments[{ id, + * start, duration }]`) when it names every entry, else by estimatedSeconds + * laid end to end. At least one entry: a window past the end gets the last. + * + * @param {Array<Record<string, any>>} timeline + * @param {{ at: number, dur: number }} win + * @param {{ segments?: Array<{ id: string, start: number, duration: number }> } | null} [schedule] + * @returns {{ ids: string[], basis: "schedule" | "estimate", total: number }} + */ +export function windowEntries(timeline, win, schedule = null) { + const entries = sourcedEntries(timeline); + if (!entries.length) throw new Error("the manifest's timeline is empty"); + const segs = new Map((schedule?.segments ?? []).map((s) => [s.id, s])); + const useSchedule = entries.every((e) => { + const s = segs.get(e.id); + return s && Number.isFinite(Number(s.start)) && Number.isFinite(Number(s.duration)); + }); + let t = 0; + const spans = entries.map((e) => { + if (useSchedule) { + const s = /** @type {any} */ (segs.get(e.id)); + return { id: e.id, from: Number(s.start), to: Number(s.start) + Number(s.duration) }; + } + const span = { id: e.id, from: t, to: t + estimatedSeconds(e) }; + t = span.to; + return span; + }); + const total = Math.max(...spans.map((s) => s.to)); + const from = win.at; + const to = win.at + win.dur; + let ids = spans.filter((s) => s.from < to && s.to > from).map((s) => s.id); + if (!ids.length) ids = [spans[spans.length - 1].id]; + return { ids, basis: useSchedule ? "schedule" : "estimate", total }; +} + +/** + * The manifest a window renders: `manifest` with only `ids` in its timeline + * (the sourced ones), and the posts attached to a clip outside it dropped -- + * a post's `attachTo` must name a clip of the timeline. + */ +export function windowManifest(manifest, ids) { + const keep = new Set(ids); + const m = clone(manifest); + m.timeline = sourcedEntries(m.timeline).filter((e) => keep.has(e.id)); + if (Array.isArray(m.posts)) m.posts = m.posts.filter((p) => !p?.attachTo || keep.has(p.attachTo)); + return m; +} + +/** A window from the CLI's or a form's words: "full", or at/dur in seconds. */ +export function normalizeWindow(w) { + if (w === undefined || w === null || w === "") return { ...DEFAULT_WINDOW }; + const v = parseWindow(w); + if (!v) throw new Error('a window is "full" or { at ≥ 0, dur > 0 } in seconds'); + return v; +} + +// --------------------------------------------------------------------------- +// Making a take. +// --------------------------------------------------------------------------- + +/** + * @typedef {{ + * id: string, label: string, group?: string, kind?: string, summary?: string, + * style?: string | null, patch?: Record<string, unknown> | null, + * window?: "full" | { at: number, dur: number } | null, order?: number, + * }} TakeSpec + * + * @typedef {{ + * manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean, + * emit: (ev: Record<string, unknown>) => void, log: (line: string) => void, + * }} RenderJob + * @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn + */ + +/** A take spec, checked. Returns the spec with its defaults; throws what is wrong. */ +export function checkSpec(spec) { + if (!isObj(spec)) throw new Error("a take is an object"); + if (!isTakeId(spec.id)) throw new Error(`id must be lower-case letters, digits and dashes (${JSON.stringify(spec.id ?? null)})`); + const label = typeof spec.label === "string" ? spec.label.trim() : ""; + if (!label) throw new Error(`${spec.id}: a take needs a label`); + const group = typeof spec.group === "string" && spec.group.trim() ? spec.group.trim() : DEFAULT_GROUP; + if (spec.kind !== undefined && spec.kind !== null && !TAKE_KINDS.includes(spec.kind)) { + throw new Error(`${spec.id}: kind must be one of ${TAKE_KINDS.join(", ")}`); + } + if (spec.style !== undefined && spec.style !== null && (typeof spec.style !== "string" || !spec.style.trim())) { + throw new Error(`${spec.id}: style is a style's name`); + } + if (spec.patch !== undefined && spec.patch !== null && !isObj(spec.patch)) throw new Error(`${spec.id}: patch must be a JSON object`); + return { + id: spec.id, + label, + group, + kind: spec.kind ?? null, + summary: typeof spec.summary === "string" ? spec.summary.trim() : "", + style: typeof spec.style === "string" ? spec.style.trim() : null, + patch: isObj(spec.patch) ? spec.patch : null, + window: spec.window === "full" ? "full" : normalizeWindow(spec.window), + order: typeof spec.order === "number" && Number.isFinite(spec.order) ? spec.order : null, + }; +} + +async function readJson(file) { + try { + return JSON.parse(await readFile(file, "utf8")); + } catch { + return null; + } +} + +const exists = (p) => lstat(p).then(() => true, () => false); + +/** + * Link the project's shared out/ entries into the take's out/ (absolute links + * to the PROJECT's path, so a media root re-pointed under it keeps working). + * One that is already there -- a link or a real directory -- is left alone. + */ +export async function linkSharedOut(projectDir, takeOut) { + const linked = []; + for (const name of SHARED_OUT) { + const src = path.join(projectDir, "out", name); + const dst = path.join(takeOut, name); + if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue; + if (await exists(dst)) continue; + await symlink(src, dst); + linked.push(name); + } + return linked; +} + +/** + * Make one take (see the top of the file). Skipped -- `{ skipped: true }` -- + * when take.json exists and `force` is not set. + * + * @param {string} projectDir + * @param {TakeSpec} rawSpec + * @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise<number | null>, + * styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, + * emit?: (ev: Record<string, unknown>) => void, log?: (line: string) => void, + * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date }} [opts] + */ +export async function makeTake(projectDir, rawSpec, opts = {}) { + const spec = checkSpec(rawSpec); + const emit = opts.emit ?? (() => {}); + const log = opts.log ?? (() => {}); + const now = opts.now ?? (() => new Date()); + const takeDir = path.join(takesDirOf(projectDir), spec.id); + const takeFile = path.join(takeDir, TAKE_FILE); + const previous = await readJson(takeFile); + if (previous && !opts.force) { + emit({ ev: "take", id: spec.id, phase: "skipped" }); + return { id: spec.id, skipped: true }; + } + + const baseText = await readFile(path.join(projectDir, MANIFEST), "utf8"); + const base = JSON.parse(baseText); + const styles = opts.styles ?? (spec.style ? (await loadMontageStyles()).styles : {}); + let stylePatch = null; + if (spec.style) { + stylePatch = styles[spec.style]?.patch ?? null; + if (!stylePatch) { + const known = Object.keys(styles); + throw new Error(`unknown style "${spec.style}"${known.length ? ` — one of ${known.join(", ")}` : " (no montage styles are installed)"}`); + } + } + const patches = [stylePatch, spec.patch].filter(Boolean); + const manifest = /** @type {Record<string, any>} */ (patches.reduce((m, p) => mergePatch(m, p), base)); + if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error("the patched manifest has no timeline"); + const changes = changeLines(base, manifest, patches); + const kind = changes.length === 0 ? "reference" : (spec.kind ?? "different"); + + // The render: the window's entries (timed against the project's, so every + // take of a group covers the same ones), or the whole cut. + let renderDoc = manifest; + /** @type {null | { ids: string[], basis: string, total: number }} */ + let covered = null; + if (spec.window !== "full") { + const schedule = await readJson(path.join(projectDir, "out", "sourced", "schedule.json")); + covered = windowEntries(base.timeline, spec.window, schedule); + const present = new Set(sourcedEntries(manifest.timeline).map((e) => e.id)); + const ids = covered.ids.filter((id) => present.has(id)); + if (!ids.length) throw new Error(`${spec.id}: the patch removed every entry the window covers (${covered.ids.join(", ")})`); + renderDoc = windowManifest(manifest, ids); + } + + await mkdir(takeDir, { recursive: true }); + const takeOut = path.join(takeDir, "out"); + await (opts.ensureOut ?? ((d) => mkdir(d, { recursive: true })))(takeOut); + const linked = await linkSharedOut(projectDir, takeOut); + if (linked.length) log(`${spec.id}: reusing the project's ${linked.join(" and ")}`); + + // The take's manifest is written under a work name until the render is + // done: a failed REBUILD must not leave the old preview beside a new manifest. + const nextManifest = path.join(takeDir, `.next.${MANIFEST}`); + await writeFile(nextManifest, serialise(manifest), "utf8"); + const renderPath = renderManifestPath(projectDir, spec.id); + await writeFile(renderPath, serialise(renderDoc), "utf8"); + + const transition = Number(manifest.render?.transition ?? 0); + const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0; + emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null }); + let file; + try { + const render = opts.render ?? (await import("./takeRender.mjs")).renderTake; + ({ file } = await render({ + manifestPath: renderPath, + outDir: takeOut, + slug: String(manifest.slug ?? ""), + full: spec.window === "full", + xfade, + emit, + log, + })); + } finally { + await rm(renderPath, { force: true }); + } + + const preview = path.join(takeDir, PREVIEW); + await moveFile(file, preview); + await rename(nextManifest, path.join(takeDir, MANIFEST)); + const seconds = opts.probe ? await opts.probe(preview) : null; + + const listing = previous ? null : await listTakes(projectDir); + const order = + spec.order ?? + (typeof previous?.order === "number" ? previous.order : Math.max(0, ...(listing?.takes ?? []).map((t) => t.order)) + 1); + const styleLabel = spec.style ? styles[spec.style]?.label : null; + const summary = spec.summary || (spec.style ? styles[spec.style]?.summary ?? "" : ""); + const doc = { + id: spec.id, + group: spec.group, + order, + label: spec.label, + kind, + summary, + changes: [...(styleLabel ? [`style: ${styleLabel}`] : []), ...changes], + preview: PREVIEW, + seconds: seconds === null || seconds === undefined ? null : Math.round(seconds * 100) / 100, + builtAt: now().toISOString(), + style: spec.style, + patch: spec.patch, + window: spec.window, + ...(covered ? { entries: { ids: covered.ids, basis: covered.basis } } : {}), + baseHash: hashText(baseText), + }; + const tmp = `${takeFile}.tmp-${process.pid}`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, takeFile); + emit({ ev: "take", id: spec.id, phase: "done", seconds: doc.seconds }); + return { id: spec.id, skipped: false, take: doc }; +} + +/** Rename, or copy and remove across filesystems (a take's out/ may be on the media root). */ +async function moveFile(from, to) { + try { + await rename(from, to); + } catch (err) { + if (/** @type {any} */ (err)?.code !== "EXDEV") throw err; + const { copyFile, unlink } = await import("node:fs/promises"); + const tmp = `${to}.tmp-${process.pid}`; + await copyFile(from, tmp); + await rename(tmp, to); + await unlink(from).catch(() => {}); + } +} + +// --------------------------------------------------------------------------- +// Recipes. +// --------------------------------------------------------------------------- + +/** + * A recipe, checked: `{ group?, window?, takes: [{ id, label, style?, patch?, + * summary?, kind?, group?, window? }] }`. A take's own group and window win + * over the recipe's. Ids are unique. + * + * @param {unknown} raw + * @returns {{ group: string, window: "full" | { at: number, dur: number }, takes: ReturnType<typeof checkSpec>[] }} + */ +export function parseRecipe(raw) { + if (!isObj(raw)) throw new Error("a recipe is an object"); + const group = typeof raw.group === "string" && raw.group.trim() ? raw.group.trim() : DEFAULT_GROUP; + const window = raw.window === "full" ? "full" : normalizeWindow(raw.window); + if (!Array.isArray(raw.takes) || !raw.takes.length) throw new Error("a recipe needs takes: [...]"); + const seen = new Set(); + const takes = raw.takes.map((t, i) => { + if (!isObj(t)) throw new Error(`takes[${i}] is not an object`); + const spec = checkSpec({ group, window, ...t }); + if (seen.has(spec.id)) throw new Error(`take ${spec.id} is in the recipe twice`); + seen.add(spec.id); + return spec; + }); + return { group, window, takes }; +} + +/** + * A recipe's takes, one after another (one render at a time). A take that + * exists is skipped unless `force`; a take that fails is recorded and the next + * one is made. `only` limits the run to those ids. + * + * @param {string} projectDir + * @param {unknown} recipe + * @param {Parameters<typeof makeTake>[2] & { only?: string[] | null }} [opts] + */ +export async function makeTakes(projectDir, recipe, opts = {}) { + const r = parseRecipe(recipe); + const list = opts.only?.length ? r.takes.filter((t) => opts.only?.includes(t.id)) : r.takes; + if (opts.only?.length && list.length !== opts.only.length) { + const missing = opts.only.filter((id) => !r.takes.some((t) => t.id === id)); + throw new Error(`not in the recipe: ${missing.join(", ")}`); + } + const needStyles = list.some((t) => t.style); + const styles = opts.styles ?? (needStyles ? (await loadMontageStyles()).styles : {}); + const results = []; + for (const [i, spec] of list.entries()) { + opts.emit?.({ ev: "take", id: spec.id, phase: "start", i: i + 1, n: list.length }); + try { + const done = await makeTake(projectDir, spec, { ...opts, styles }); + results.push({ id: spec.id, status: done.skipped ? "skipped" : "made" }); + } catch (err) { + const error = err instanceof Error ? err.message : String(err); + opts.emit?.({ ev: "take", id: spec.id, phase: "failed", error }); + opts.log?.(`${spec.id}: failed — ${error}`); + results.push({ id: spec.id, status: "failed", error }); + } + } + return results; +} + +/** + * The recipe "Make all styles" runs: every style, one take each, with one + * group and window. The take id is the style's name made into a take id. + * + * @param {Record<string, { label: string, summary: string }>} styles + * @param {{ group?: string, window?: unknown }} [opts] + */ +export function allStylesRecipe(styles, { group = DEFAULT_GROUP, window = DEFAULT_WINDOW } = {}) { + const names = Object.keys(styles); + if (!names.length) throw new Error("no montage styles are installed"); + const used = new Set(); + return { + group, + window, + takes: names.map((name) => { + const id = uniqueTakeId(name, used); + used.add(id); + return { id, label: styles[name].label, style: name }; + }), + }; +} + +/** A take id from any words: lower case, dashes, unique against `taken`. */ +export function uniqueTakeId(words, taken = new Set()) { + const base = + String(words ?? "") + .toLowerCase() + .normalize("NFKD") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 56) || "take"; + const ok = /^[a-z0-9]/.test(base) ? base : `t-${base}`.slice(0, 56); + if (!taken.has(ok)) return ok; + for (let n = 2; ; n += 1) if (!taken.has(`${ok}-${n}`)) return `${ok}-${n}`; +} + +// --------------------------------------------------------------------------- +// Picking a take. +// --------------------------------------------------------------------------- + +export class TakeStale extends Error { + /** @param {string} message */ + constructor(message) { + super(message); + this.name = "TakeStale"; + } +} + +/** + * Has the project's manifest changed since the take was made? `null` when the + * take does not say what it was made from (made by hand, before release 33). + * + * @param {string} projectDir + * @param {{ baseHash?: string | null }} take + */ +export async function takeIsStale(projectDir, take) { + if (!take.baseHash) return null; + const text = await readFile(path.join(projectDir, MANIFEST), "utf8").catch(() => null); + return text === null ? true : hashText(text) !== take.baseHash; +} + +/** + * "Use this take": the take's video.manifest.json over the project's, through + * the manifest writer (replaceManifest: the auto snapshot `auto-before-pick-take`, + * so "Undo last edit" takes it back) inside withEditNotes, then the pick in + * verdicts.json (one per group). + * + * REFUSED (TakeStale) when the project's manifest is not the one the take was + * made from -- a pick would throw away whatever changed since -- unless + * `anyway`. A take that does not record its base is refused the same way. + * + * @param {{ id: string, dir: string, kind: string }} project + * @param {string} takeId + * @param {{ anyway?: boolean, token?: string | null, now?: Date }} [opts] + */ +export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date() } = {}) { + if (!isTakeId(takeId)) throw new Error("not a take id"); + const listing = await listTakes(project.dir); + const take = listing.takes.find((t) => t.id === takeId); + if (!take) throw new Error(`no take ${takeId}`); + const text = await readFile(path.join(takesDirOf(project.dir), takeId, MANIFEST), "utf8").catch(() => null); + if (text === null) throw new Error(`take ${takeId} has no ${MANIFEST} to use`); + const manifest = JSON.parse(text); + if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new Error(`take ${takeId}'s ${MANIFEST} is not a manifest`); + if (!anyway) { + const stale = await takeIsStale(project.dir, take); + if (stale === null) throw new TakeStale("This take does not record which manifest it was made from"); + if (stale) throw new TakeStale("The project changed since this take was made"); + } + const { result, editNotes } = await withEditNotes(project, () => replaceManifest(project.dir, manifest, { token, op: "pick-take" })); + const group = listing.takes.filter((t) => t.group === take.group).map((t) => t.id); + const { verdicts } = await setTakePicked(project.dir, takeId, group, { now }); + return { take: takeId, group: take.group, snapshot: result.snapshot, token: result.token, editNotes, verdicts }; +} + +// --------------------------------------------------------------------------- +// The app's jobs: the CLI above, as job steps (lib/jobs.ts runs them). +// --------------------------------------------------------------------------- + +/** A take render's timeout: a window is minutes; the whole cut is the fast build's own budget. */ +export const takeTimeoutMs = (full, clipCount) => (full ? Math.max(15 * 60_000, clipCount * 60_000) : 15 * 60_000); + +const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + +const windowArgs = (w) => (w === "full" ? ["--full"] : ["--at", String(w.at), "--dur", String(w.dur)]); + +/** + * What a Takes-page button asks for, as the steps of one job. Every argument + * is checked here first, so a bad request is a 400 and not a failed job. + * + * { take: { id?, label, group?, style?, patch?, window?, summary?, kind? }, force? } New take + * { allStyles: { group?, window? }, force? } Make all styles + * { rebuild: "<take id>" } Rebuild + * + * @param {{ id: string }} project + * @param {Record<string, any>} req + * @param {{ styles: Record<string, { label: string }>, existing: Array<{ id: string, window?: unknown }>, clipCount: number }} ctx + * @returns {{ kind: string, takes: string[], steps: Array<{ label: string, argv: string[], cwd: string, env: Record<string, string>, ndjson: true, timeoutMs: number }> }} + */ +export function takeSteps(project, req, { styles, existing, clipCount }) { + const ids = new Set(existing.map((t) => t.id)); + const base = { cwd: UMTOOL_DIR, env: {}, ndjson: /** @type {const} */ (true) }; + const cli = ["node", umtoolCli()]; + const force = req.force === true ? ["--force"] : []; + if (typeof req.rebuild === "string") { + const t = existing.find((x) => x.id === req.rebuild); + if (!t) throw new Error(`no take ${req.rebuild}`); + return { + kind: `take ${project.id} ${t.id} (rebuild)`, + takes: [t.id], + steps: [{ ...base, label: `rebuild take ${t.id}`, argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", "--progress", "ndjson"], timeoutMs: takeTimeoutMs(t.window === "full", clipCount) }], + }; + } + if (isObj(req.allStyles)) { + const recipe = allStylesRecipe(styles, { + group: typeof req.allStyles.group === "string" && req.allStyles.group.trim() ? req.allStyles.group.trim() : DEFAULT_GROUP, + window: req.allStyles.window === "full" ? "full" : normalizeWindow(req.allStyles.window), + }); + const group = ["--group", recipe.group]; + return { + kind: `takes ${project.id} (all styles)`, + takes: recipe.takes.map((t) => t.id), + steps: [{ + ...base, + label: `make ${recipe.takes.length} take(s), one per style`, + argv: [...cli, "takes", "make", project.id, "--all-styles", ...group, ...windowArgs(recipe.window), ...force, "--progress", "ndjson"], + timeoutMs: recipe.takes.length * takeTimeoutMs(recipe.window === "full", clipCount), + }], + }; + } + if (isObj(req.take)) { + const t = req.take; + const id = t.id === undefined || t.id === "" ? uniqueTakeId(t.label || t.style || "take", ids) : t.id; + const spec = checkSpec({ ...t, id }); + if (spec.style && !styles[spec.style]) throw new Error(`unknown style "${spec.style}"`); + if (ids.has(spec.id) && req.force !== true) throw new Error(`take ${spec.id} exists — rebuild it, or tick "make it again"`); + const argv = [ + ...cli, "take", project.id, "--id", spec.id, "--label", spec.label, "--group", spec.group, + ...(spec.kind ? ["--kind", spec.kind] : []), + ...(spec.summary ? ["--summary", spec.summary] : []), + ...(spec.style ? ["--style", spec.style] : []), + ...(spec.patch ? ["--patch-json", JSON.stringify(spec.patch)] : []), + ...windowArgs(spec.window), ...force, "--progress", "ndjson", + ]; + return { + kind: `take ${project.id} ${spec.id}`, + takes: [spec.id], + steps: [{ ...base, label: `make take ${spec.id}`, argv, timeoutMs: takeTimeoutMs(spec.window === "full", clipCount) }], + }; + } + throw new Error("say what to make: take, allStyles or rebuild"); +} + +/** The group a new take is offered: the newest take's, else the default. */ +export function lastGroup(takes) { + const newest = [...takes].sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")))[0]; + return newest?.group ?? DEFAULT_GROUP; +} diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -0,0 +1,418 @@ +// The take maker: the merge patch, the words for what a take changes, the +// window, a take made with a stub renderer, recipes, and the pick with its +// base-hash guard. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { lstat, mkdir, mkdtemp, readFile, readlink, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + TakeStale, + allStylesRecipe, + changeLines, + loadMontageStyles, + makeTake, + makeTakes, + mergePatch, + parseRecipe, + patchFromSets, + pickTake, + renderManifestPath, + lastGroup, + takeIsStale, + takeSteps, + uniqueTakeId, + windowEntries, +} from "./takeMaker.mjs"; +import { listTakes, readVerdicts, setTakeVerdict } from "./takes.mjs"; +import { takeCommand, takesCommand } from "./takeCli.mjs"; + +const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: `v-${id}`, start, end, cite: start, section: 0, ...extra }); + +const MANIFEST = { + schemaVersion: 1, + slug: "fixture", + title: "Fixture", + render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30 }, + timeline: [clip("s01", 0, 10), clip("s02", 20, 25), clip("s03", 40, 50), { type: "card", id: "k1", seconds: 3 }, clip("s04", 0, 5)], +}; + +const STYLES = { + flash: { label: "Flash count", summary: "Flash cuts and a big counter.", patch: { render: { montage: { cut: "flash", counter: { style: "big" } } } } }, + straight: { label: "Straight", summary: "Tight hard cuts.", patch: { render: { montage: { cut: "hard" } } } }, +}; + +async function project(manifest = MANIFEST) { + const root = await mkdtemp(path.join(tmpdir(), "takemaker-")); + const dir = path.join(root, "reports", "proj"); + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await writeFile(path.join(dir, "out", "clips-raw", "v-s01_0.00-13.00.mp4"), "media"); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n"); + return { root, dir, reportsRoot: path.join(root, "reports") }; +} + +/** A renderer that writes a file where build-video would, and remembers what it was given. */ +function stubRender({ fail = null } = {}) { + const calls = []; + const render = async (job) => { + const doc = JSON.parse(await readFile(job.manifestPath, "utf8")); + calls.push({ ...job, doc, linked: await readdir(job.outDir) }); + if (fail) throw new Error(fail); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, `render of ${doc.timeline.map((e) => e.id).join(",")}`); + return { file }; + }; + return { render, calls }; +} + +const opts = (r, extra = {}) => ({ render: r.render, styles: STYLES, probe: async () => 12.345, now: () => new Date("2026-10-17T12:00:00Z"), ...extra }); + +test("mergePatch is RFC 7386: objects merge, null removes, arrays and scalars replace, nothing is mutated", () => { + const target = { a: 1, b: { c: 2, d: [1, 2] }, e: "x" }; + const patch = { a: null, b: { c: 3, d: [9] }, f: { g: true } }; + const before = JSON.stringify(target); + assert.deepEqual(mergePatch(target, patch), { b: { c: 3, d: [9] }, e: "x", f: { g: true } }); + assert.equal(JSON.stringify(target), before); + assert.deepEqual(mergePatch({ a: { b: 1 } }, { a: "flat" }), { a: "flat" }); + assert.deepEqual(mergePatch("scalar", { a: 1 }), { a: 1 }); + assert.deepEqual(mergePatch({ a: 1 }, [1, 2]), [1, 2]); + assert.deepEqual(mergePatch({ a: 1 }, {}), { a: 1 }); +}); + +test("changeLines: one plain line per changed leaf, with the old value when there was one", () => { + const base = { render: { crf: 30, montage: { cut: "hard", ramp: { from: 3, to: 1 } } } }; + const p1 = { render: { crf: 34, montage: { cut: "flash", counter: { style: "big" } } } }; + const p2 = { render: { montage: { ramp: null, cut: "hard" } } }; + const after = mergePatch(mergePatch(base, p1), p2); + assert.deepEqual(changeLines(base, after, [p1, p2]), [ + "render.crf: 34 (was 30)", + "render.montage.counter.style: big", + "render.montage.ramp: removed", + ]); + // A value set to what it already was is not a change. + assert.deepEqual(changeLines(base, mergePatch(base, { render: { crf: 30 } }), [{ render: { crf: 30 } }]), []); + // An array is a value: replaced whole, shown short. + const pa = { render: { montage: { stutter: { clips: ["s01", "s02"] } } } }; + assert.deepEqual(changeLines(base, mergePatch(base, pa), [pa]), ['render.montage.stutter.clips: ["s01","s02"]']); +}); + +test("patchFromSets: dotted paths, JSON values when they parse, strings otherwise", () => { + assert.deepEqual(patchFromSets(["render.montage.cut=flash", "render.crf=34", "render.montage.counter={\"style\":\"big\"}", "render.x=null"]), { + render: { montage: { cut: "flash", counter: { style: "big" } }, crf: 34, x: null }, + }); + assert.throws(() => patchFromSets(["nothing"]), /path=value/); + assert.throws(() => patchFromSets(["a..b=1"]), /dotted path/); +}); + +test("windowEntries: by the manifest's own lengths, or by the deck's schedule when it names every entry", () => { + // s01 0–10, s02 10–15, s03 15–25, k1 25–28, s04 28–33 + assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 12, dur: 5 }), { ids: ["s02", "s03"], basis: "estimate", total: 33 }); + assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 0, dur: 60 }).ids, ["s01", "s02", "s03", "k1", "s04"]); + // Past the end: the last entry, never nothing. + assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 500, dur: 10 }).ids, ["s04"]); + // A clip's cut, not its extent, is what plays. + assert.deepEqual(windowEntries([clip("a", 0, 100, { cutStart: 10, cutEnd: 12 }), clip("b", 0, 3)], { at: 2.5, dur: 1 }).ids, ["b"]); + const schedule = { segments: ["s01", "s02", "s03", "k1", "s04"].map((id, i) => ({ id, start: i * 2, duration: 2 })) }; + assert.deepEqual(windowEntries(MANIFEST.timeline, { at: 3, dur: 2 }, schedule), { ids: ["s02", "s03"], basis: "schedule", total: 10 }); + // A schedule that misses an entry is not trusted. + assert.equal(windowEntries(MANIFEST.timeline, { at: 3, dur: 2 }, { segments: schedule.segments.slice(1) }).basis, "estimate"); + // Only the default cut's entries. + assert.deepEqual(windowEntries([clip("a", 0, 5), clip("f", 0, 5, { variant: "full" }), clip("b", 0, 5)], { at: 6, dur: 1 }).ids, ["b"]); +}); + +test("makeTake: the style's patch then the take's, rendered from beside the project's manifest, take.json last", async () => { + const { root, dir } = await project(); + const r = stubRender(); + try { + const done = await makeTake(dir, { id: "flash", label: "Flash", group: "montage", style: "flash", patch: { render: { crf: 34 } }, window: { at: 12, dur: 5 } }, opts(r)); + assert.equal(done.skipped, false); + const takeDir = path.join(dir, "takes", "flash"); + // The take's manifest is the WHOLE patched manifest -- what a pick copies. + const m = JSON.parse(await readFile(path.join(takeDir, "video.manifest.json"), "utf8")); + assert.equal(m.timeline.length, 5); + assert.deepEqual(m.render.montage, { cut: "flash", counter: { style: "big" } }); + assert.equal(m.render.crf, 34); + // The render saw only the window's entries, from a manifest in the PROJECT's directory. + assert.equal(r.calls.length, 1); + assert.equal(path.dirname(r.calls[0].manifestPath), dir); + assert.equal(r.calls[0].manifestPath, renderManifestPath(dir, "flash")); + assert.deepEqual(r.calls[0].doc.timeline.map((e) => e.id), ["s02", "s03"]); + assert.equal(r.calls[0].full, false); + assert.equal(r.calls[0].xfade, false, "hard cuts unless the take sets a transition"); + assert.equal(r.calls[0].outDir, path.join(takeDir, "out")); + assert.deepEqual(r.calls[0].linked, ["clips-raw"]); + // ...and it is gone once the render is done. + await assert.rejects(lstat(renderManifestPath(dir, "flash"))); + // The fetched media is LINKED from the project, never copied. + const link = path.join(takeDir, "out", "clips-raw"); + assert.ok((await lstat(link)).isSymbolicLink()); + assert.equal(await readlink(link), path.join(dir, "out", "clips-raw")); + // The preview was moved into the take; take.json says how it was made. + assert.match(await readFile(path.join(takeDir, "preview.mp4"), "utf8"), /render of s02,s03/); + const t = JSON.parse(await readFile(path.join(takeDir, "take.json"), "utf8")); + assert.equal(t.kind, "different"); + assert.equal(t.group, "montage"); + assert.equal(t.order, 1); + assert.equal(t.summary, "Flash cuts and a big counter."); + assert.deepEqual(t.changes, ["style: Flash count", "render.montage.cut: flash", "render.montage.counter.style: big", "render.crf: 34 (was 30)"]); + assert.equal(t.seconds, 12.35); + assert.equal(t.builtAt, "2026-10-17T12:00:00.000Z"); + assert.equal(t.style, "flash"); + assert.deepEqual(t.window, { at: 12, dur: 5 }); + assert.deepEqual(t.entries, { ids: ["s02", "s03"], basis: "estimate" }); + assert.match(t.baseHash, /^[0-9a-f]{64}$/); + assert.equal(await takeIsStale(dir, t), false); + // The listing reads it back. + const listing = await listTakes(dir); + assert.deepEqual(listing.takes.map((x) => [x.id, x.style, x.baseHash === t.baseHash]), [["flash", "flash", true]]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("makeTake: no change is the reference; a transition turns crossfades on; full renders the whole cut", async () => { + const { root, dir } = await project(); + const r = stubRender(); + try { + await makeTake(dir, { id: "as-is", label: "As built", window: "full" }, opts(r)); + const ref = JSON.parse(await readFile(path.join(dir, "takes", "as-is", "take.json"), "utf8")); + assert.equal(ref.kind, "reference"); + assert.deepEqual(ref.changes, []); + assert.equal(ref.window, "full"); + assert.equal(ref.entries, undefined); + assert.equal(r.calls[0].full, true); + assert.equal(r.calls[0].doc.timeline.length, 5); + await makeTake(dir, { id: "soft", label: "Soft", kind: "similar", patch: { render: { transition: 0.3 } } }, opts(r)); + assert.equal(r.calls[1].xfade, true); + const soft = JSON.parse(await readFile(path.join(dir, "takes", "soft", "take.json"), "utf8")); + assert.equal(soft.kind, "similar"); + assert.equal(soft.order, 2); + assert.deepEqual(soft.window, { at: 0, dur: 60 }, "the default window"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("makeTake: an existing take is skipped unless forced; a failed rebuild leaves the old take whole", async () => { + const { root, dir } = await project(); + const r = stubRender(); + try { + await makeTake(dir, { id: "t", label: "T", patch: { render: { crf: 31 } } }, opts(r)); + const takeDir = path.join(dir, "takes", "t"); + const before = await Promise.all(["take.json", "video.manifest.json", "preview.mp4"].map((f) => readFile(path.join(takeDir, f), "utf8"))); + assert.deepEqual(await makeTake(dir, { id: "t", label: "T", patch: { render: { crf: 99 } } }, opts(r)), { id: "t", skipped: true }); + assert.equal(r.calls.length, 1); + const bad = stubRender({ fail: "2 entries could not be cut: s02, s03" }); + await assert.rejects(makeTake(dir, { id: "t", label: "T", patch: { render: { crf: 99 } } }, opts(bad, { force: true })), /could not be cut/); + const after = await Promise.all(["take.json", "video.manifest.json", "preview.mp4"].map((f) => readFile(path.join(takeDir, f), "utf8"))); + assert.deepEqual(after, before); + await assert.rejects(lstat(renderManifestPath(dir, "t")), "the render manifest is removed on failure too"); + // A first make that fails writes no take.json: the listing shows nothing. + await assert.rejects(makeTake(dir, { id: "never", label: "Never" }, opts(bad))); + assert.deepEqual((await listTakes(dir)).takes.map((x) => x.id), ["t"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("makeTake refuses an unknown style, a bad id, and a window the patch emptied", async () => { + const { root, dir } = await project(); + const r = stubRender(); + try { + await assert.rejects(makeTake(dir, { id: "x", label: "X", style: "nope" }, opts(r)), /unknown style "nope" — one of flash, straight/); + await assert.rejects(makeTake(dir, { id: "x", label: "X", style: "nope" }, opts(r, { styles: {} })), /no montage styles are installed/); + await assert.rejects(makeTake(dir, { id: "Bad", label: "X" }, opts(r)), /id must be/); + await assert.rejects(makeTake(dir, { id: "x", label: "" }, opts(r)), /needs a label/); + await assert.rejects( + makeTake(dir, { id: "x", label: "X", window: { at: 0, dur: 5 }, patch: { timeline: [clip("s04", 0, 5)] } }, opts(r)), + /removed every entry the window covers/, + ); + assert.equal(r.calls.length, 0); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("recipes: checked, made one at a time, existing takes skipped unless forced, a failure does not stop the rest", async () => { + assert.throws(() => parseRecipe({ takes: [] }), /needs takes/); + assert.throws(() => parseRecipe({ takes: [{ id: "a", label: "A" }, { id: "a", label: "B" }] }), /twice/); + const parsed = parseRecipe({ group: "g", window: "full", takes: [{ id: "a", label: "A" }, { id: "b", label: "B", group: "own", window: { at: 1, dur: 2 } }] }); + assert.deepEqual(parsed.takes.map((t) => [t.id, t.group, t.window]), [["a", "g", "full"], ["b", "own", { at: 1, dur: 2 }]]); + + const { root, dir } = await project(); + const r = stubRender(); + try { + const recipe = { group: "montage", window: { at: 0, dur: 12 }, takes: [{ id: "flash", label: "Flash", style: "flash" }, { id: "nope", label: "Nope", style: "nope" }, { id: "straight", label: "Straight", style: "straight" }] }; + const events = []; + const first = await makeTakes(dir, recipe, opts(r, { emit: (e) => events.push(e) })); + assert.deepEqual(first.map((x) => x.status), ["made", "failed", "made"]); + assert.match(first[1].error, /unknown style/); + assert.deepEqual(events.filter((e) => e.phase === "start").map((e) => `${e.id} ${e.i}/${e.n}`), ["flash 1/3", "nope 2/3", "straight 3/3"]); + const again = await makeTakes(dir, recipe, opts(r)); + assert.deepEqual(again.map((x) => x.status), ["skipped", "failed", "skipped"]); + assert.equal(r.calls.length, 2); + const forced = await makeTakes(dir, recipe, opts(r, { force: true, only: ["straight"] })); + assert.deepEqual(forced, [{ id: "straight", status: "made" }]); + await assert.rejects(makeTakes(dir, recipe, opts(r, { only: ["ghost"] })), /not in the recipe: ghost/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("allStylesRecipe: one take per style, ids made from the names", () => { + assert.deepEqual(allStylesRecipe(STYLES, { group: "m", window: "full" }), { + group: "m", + window: "full", + takes: [ + { id: "flash", label: "Flash count", style: "flash" }, + { id: "straight", label: "Straight", style: "straight" }, + ], + }); + assert.throws(() => allStylesRecipe({}), /no montage styles/); + assert.equal(uniqueTakeId("Wall Finale!"), "wall-finale"); + assert.equal(uniqueTakeId("wall", new Set(["wall", "wall-2"])), "wall-3"); + assert.equal(uniqueTakeId("§§"), "take"); +}); + +test("pickTake: the take's manifest over the project's, an undo point first, one pick per group", async () => { + const { root, dir } = await project(); + const r = stubRender(); + const proj = { id: "proj", dir, kind: "report-video" }; + try { + await makeTake(dir, { id: "flash", label: "Flash", group: "m", style: "flash" }, opts(r)); + await makeTake(dir, { id: "straight", label: "Straight", group: "m", style: "straight" }, opts(r)); + await setTakeVerdict(dir, "flash", { verdict: "like" }); + const got = await pickTake(proj, "flash"); + const projectText = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + assert.equal(projectText, await readFile(path.join(dir, "takes", "flash", "video.manifest.json"), "utf8")); + assert.match(got.snapshot.rel, /^revisions\/.*-auto-before-pick-take\.manifest\.json$/); + const snap = JSON.parse(await readFile(path.join(dir, got.snapshot.rel), "utf8")); + assert.equal(snap.render.montage, undefined, "the snapshot is the manifest as it was"); + let v = await readVerdicts(dir); + assert.equal(v.flash.picked, true); + assert.equal(v.flash.verdict, "like"); + + // The other take was made from the manifest the pick replaced: refused, then used anyway. + await assert.rejects(pickTake(proj, "straight"), (e) => e instanceof TakeStale && /changed since this take was made/.test(e.message)); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), projectText, "a refused pick writes nothing"); + await pickTake(proj, "straight", { anyway: true }); + v = await readVerdicts(dir); + assert.equal(v.straight.picked, true); + assert.equal(v.flash.picked, undefined, "one pick per group"); + assert.equal(v.flash.verdict, "like"); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + assert.deepEqual(m.render.montage, { cut: "hard" }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("pickTake: a take that does not record its base needs anyway; an unknown take is an error", async () => { + const { root, dir } = await project(); + const proj = { id: "proj", dir, kind: "report-video" }; + try { + const takeDir = path.join(dir, "takes", "by-hand"); + await mkdir(takeDir, { recursive: true }); + await writeFile(path.join(takeDir, "take.json"), JSON.stringify({ id: "by-hand", group: "g", order: 1, label: "By hand", kind: "different", preview: "preview.mp4" })); + await writeFile(path.join(takeDir, "video.manifest.json"), JSON.stringify({ ...MANIFEST, title: "By hand" }, null, 2) + "\n"); + await assert.rejects(pickTake(proj, "by-hand"), /does not record which manifest/); + await pickTake(proj, "by-hand", { anyway: true }); + assert.equal(JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")).title, "By hand"); + await assert.rejects(pickTake(proj, "ghost"), /no take ghost/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("loadMontageStyles: a module of the shape, a missing module is none, a wrong entry is named", async () => { + const root = await mkdtemp(path.join(tmpdir(), "styles-")); + try { + const file = path.join(root, "montage-styles.mjs"); + await writeFile( + file, + `export const MONTAGE_STYLES = { a: { label: "A", summary: "s", patch: { render: { montage: { cut: "flash" } } } }, broken: { label: 3 } };\n`, + ); + const got = await loadMontageStyles({ file }); + assert.deepEqual(Object.keys(got.styles), ["a"]); + assert.deepEqual(got.skipped, ["broken"]); + assert.equal(got.error, null); + const none = await loadMontageStyles({ file: path.join(root, "montage-styles-absent.mjs") }); + assert.deepEqual(none, { styles: {}, error: null, skipped: [] }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("the CLI: umtool take with --set, umtool takes make with a recipe, umtool takes pick", async () => { + const { root, dir, reportsRoot } = await project(); + const r = stubRender(); + const out = []; + const err = []; + const io = { reportsRoot, log: (s) => out.push(s), err: (s) => err.push(s), deps: { render: r.render, styles: STYLES, probe: async () => 1 } }; + try { + assert.equal(await takeCommand(["proj", "--id", "crisp", "--label", "Crisp", "--set", "render.crf=33", "--at", "0", "--dur", "11"], io), 0, err.join("\n")); + const t = JSON.parse(await readFile(path.join(dir, "takes", "crisp", "take.json"), "utf8")); + assert.deepEqual(t.changes, ["render.crf: 33 (was 30)"]); + assert.deepEqual(t.window, { at: 0, dur: 11 }); + assert.deepEqual(r.calls[0].doc.timeline.map((e) => e.id), ["s01", "s02"]); + // NDJSON progress: events on stdout, nothing else. + out.length = 0; + assert.equal(await takeCommand(["proj", "--id", "crisp", "--rebuild", "--progress", "ndjson"], io), 0, err.join("\n")); + assert.ok(out.length > 0 && out.every((l) => JSON.parse(l))); + assert.deepEqual(r.calls[1].doc.render.crf, 33, "a rebuild reapplies the take's own patch"); + // Usage errors exit 2. + assert.equal(await takeCommand(["proj", "--id", "x", "--label", "X", "--full", "--at", "3"], io), 2); + assert.equal(await takeCommand(["proj", "--id", "x", "--label", "X", "--set", "a=1", "--patch-json", "{}"], io), 2); + assert.equal(await takeCommand(["nowhere", "--id", "x", "--label", "X"], io), 2); + + await writeFile(path.join(dir, "takes", "recipe.json"), JSON.stringify({ group: "m", window: "full", takes: [{ id: "flash", label: "Flash", style: "flash" }] })); + assert.equal(await takesCommand(["make", "proj"], io), 0, err.join("\n")); + assert.equal((await listTakes(dir)).takes.length, 2); + assert.equal(await takesCommand(["make", "proj", "--all-styles", "--full"], io), 0, err.join("\n")); + const all = JSON.parse(await readFile(path.join(dir, "takes", "all-styles.recipe.json"), "utf8")); + assert.deepEqual(all.takes.map((x) => x.id), ["flash", "straight"]); + assert.deepEqual((await listTakes(dir)).takes.map((x) => x.id).sort(), ["crisp", "flash", "straight"]); + + assert.equal(await takesCommand(["pick", "proj", "flash"], io), 0, err.join("\n")); + err.length = 0; + assert.equal(await takesCommand(["pick", "proj", "crisp"], io), 1); + assert.match(err.join("\n"), /changed since this take was made — pass --anyway/); + assert.equal(await takesCommand(["pick", "proj", "crisp", "--anyway"], io), 0); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("takeSteps: each button is one job running the CLI, checked before it starts", () => { + const proj = { id: "reports/proj" }; + const ctx = { styles: STYLES, existing: [{ id: "flash", window: "full" }], clipCount: 75 }; + const one = takeSteps(proj, { take: { label: "Crisp cut", group: "m", patch: { render: { crf: 33 } }, window: { at: 5, dur: 20 } } }, ctx); + assert.deepEqual(one.takes, ["crisp-cut"]); + assert.equal(one.steps.length, 1); + const argv = one.steps[0].argv; + assert.equal(argv[0], "node"); + assert.match(argv[1], /bin\/umtool\.mjs$/); + assert.deepEqual(argv.slice(2), [ + "take", "reports/proj", "--id", "crisp-cut", "--label", "Crisp cut", "--group", "m", + "--patch-json", '{"render":{"crf":33}}', "--at", "5", "--dur", "20", "--progress", "ndjson", + ]); + assert.equal(one.steps[0].ndjson, true); + assert.deepEqual(one.steps[0].env, {}, "nothing in env: jobView shows it to the browser"); + assert.throws(() => takeSteps(proj, { take: { label: "Flash", style: "flash", id: "flash" } }, ctx), /exists/); + assert.ok(takeSteps(proj, { take: { label: "Flash", style: "flash", id: "flash" }, force: true }, ctx).steps[0].argv.includes("--force")); + assert.throws(() => takeSteps(proj, { take: { label: "X", style: "nope" } }, ctx), /unknown style/); + assert.throws(() => takeSteps(proj, { take: { label: "" } }, ctx), /label/); + const all = takeSteps(proj, { allStyles: { group: "m", window: "full" } }, ctx); + assert.deepEqual(all.takes, ["flash", "straight"]); + assert.deepEqual(all.steps[0].argv.slice(2), ["takes", "make", "reports/proj", "--all-styles", "--group", "m", "--full", "--progress", "ndjson"]); + assert.equal(all.steps[0].timeoutMs, 2 * 75 * 60_000); + const rb = takeSteps(proj, { rebuild: "flash" }, ctx); + assert.deepEqual(rb.steps[0].argv.slice(2), ["take", "reports/proj", "--id", "flash", "--rebuild", "--progress", "ndjson"]); + assert.throws(() => takeSteps(proj, { rebuild: "ghost" }, ctx), /no take ghost/); + assert.throws(() => takeSteps(proj, {}, ctx), /say what to make/); + assert.equal(lastGroup([{ group: "a", builtAt: "2026-01-01" }, { group: "b", builtAt: "2026-02-01" }]), "b"); + assert.equal(lastGroup([]), "takes"); +}); diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs @@ -0,0 +1,126 @@ +// A take's render (release 33): build-video.mjs over the take's render +// manifest, into the take's own out/, through the machine's heavy slot. +// +// node scripts/queue-lock.mjs --heavy -- node build-video.mjs <render manifest> +// --out takes/<id>/out --progress ndjson --skip-fetch --continue-on-error +// [--no-xfade] [--no-chapters] +// +// --skip-fetch: a take never fetches. Its clips come from what the project +// already has (out/clips-raw, linked in; the editor's corpus windows; a saved +// source) -- a clip none of them covers fails the take, by name. +// --continue-on-error: every clip that cannot be cut is named in one run +// rather than one per run (the build then refuses to concatenate). +// --no-xfade unless the take sets a transition (the `fast` preset's hard cuts); +// --no-chapters for a window, which is not a deliverable. +// +// queue-lock admits the render by memory, one heavy job machine-wide, and runs +// it in a memory-capped scope unless the caller is already capped (the live +// umtool unit). Inside a slot already held (HEAVY_HELD: an e2e run) it passes +// straight through. A copy of umtool without the checkout's scripts/ runs +// build-video directly, which takes the slot itself (heavy-gate.mjs). +import { execFile, spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import path from "node:path"; +import { promisify } from "node:util"; +import { DEFAULT_VARIANT, variantPaths } from "umtool-report-to-video/build-video"; +import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs"; + +const execFileP = promisify(execFile); + +/** The checkout's heavy-slot CLI, when this umtool sits in the checkout. */ +export function queueLockScript() { + const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs"); + return existsSync(/* turbopackIgnore: true */ file) ? file : null; +} + +/** + * The argv of a take's render, pure. + * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, queueLock?: string | null }} job + */ +export function renderArgv({ manifestPath, outDir, full, xfade, queueLock = queueLockScript() }) { + const build = [ + process.execPath, + path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), + manifestPath, + "--out", + outDir, + "--progress", + "ndjson", + "--skip-fetch", + "--continue-on-error", + ...(xfade ? [] : ["--no-xfade"]), + ...(full ? [] : ["--no-chapters"]), + ]; + return queueLock ? [process.execPath, queueLock, "--heavy", "--", ...build] : build; +} + +/** + * Render one take. Resolves to the file build-video wrote (the default + * variant's deliverable path inside the take's out/); rejects with the + * entries that failed, or the exit code. + * + * @param {import("./takeMaker.mjs").RenderJob} job + * @returns {Promise<{ file: string }>} + */ +export function renderTake(job) { + const argv = renderArgv(job); + job.log(`$ ${argv.join(" ")}`); + return new Promise((resolve, reject) => { + const child = spawn(argv[0], argv.slice(1), { + // In the checkout, so queue-lock finds the checkout's lock. + cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), + stdio: ["ignore", "pipe", "pipe"], + }); + const failed = []; + let buf = ""; + child.stdout.on("data", (b) => { + buf += b.toString(); + const lines = buf.split("\n"); + buf = lines.pop() ?? ""; + for (const line of lines) { + if (!line.trim()) continue; + if (line.startsWith("{")) { + try { + const ev = JSON.parse(line); + if (ev?.ev === "entry-failed") failed.push(`${ev.id}: ${ev.error ?? ev.message ?? "failed"}`); + job.emit(ev); + continue; + } catch { + /* a line of prose after all */ + } + } + job.log(line); + } + }); + child.stderr.on("data", (b) => { + for (const line of b.toString().split("\n")) if (line.trim()) job.log(line); + }); + child.on("error", reject); + child.on("close", (code) => { + if (code === 0 && !failed.length) { + resolve({ file: variantPaths(job.outDir, job.slug, DEFAULT_VARIANT).final }); + return; + } + reject( + new Error( + failed.length + ? `${failed.length} entr${failed.length === 1 ? "y" : "ies"} could not be cut: ${failed.join("; ")}` + : `build-video exited ${code}`, + ), + ); + }); + }); +} + +/** A file's length in seconds (ffprobe), or null. */ +export async function probeSeconds(file) { + try { + const { stdout } = await execFileP(process.env.FFPROBE_BIN ?? "ffprobe", [ + "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file, + ]); + const n = Number(String(stdout).trim()); + return Number.isFinite(n) ? n : null; + } catch { + return null; + } +} diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -16,7 +16,7 @@ // Plain ESM for the same reason manifest.mjs is: `node --test` runs it with no // TypeScript, and the rules about which file a request may open live here, // tested, rather than in a route. -import { readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises"; +import { mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { inside } from "../paths.mjs"; @@ -85,6 +85,15 @@ export function parseTake(dirName, raw) { if (j.builtAt !== undefined && j.builtAt !== null && typeof j.builtAt !== "string") { return { error: "builtAt is not a string" }; } + // What the take maker (takeMaker.mjs) records about how it made the take: + // optional, and checked like the rest -- a Rebuild reads them back. + if (j.style !== undefined && j.style !== null && typeof j.style !== "string") return { error: "style is not a string" }; + if (j.patch !== undefined && j.patch !== null && !isPlainObject(j.patch)) return { error: "patch is not an object" }; + if (j.baseHash !== undefined && j.baseHash !== null && typeof j.baseHash !== "string") { + return { error: "baseHash is not a string" }; + } + const window = parseWindow(j.window); + if (window === undefined) return { error: 'window is not "full" or { at, dur }' }; return { take: { id: dirName, @@ -97,10 +106,37 @@ export function parseTake(dirName, raw) { preview, seconds: typeof j.seconds === "number" ? j.seconds : null, builtAt: typeof j.builtAt === "string" ? j.builtAt : null, + style: typeof j.style === "string" && j.style.trim() ? j.style.trim() : null, + patch: isPlainObject(j.patch) ? /** @type {Record<string, unknown>} */ (j.patch) : null, + window, + baseHash: typeof j.baseHash === "string" && j.baseHash ? j.baseHash : null, }, }; } +/** @param {unknown} v @returns {v is Record<string, unknown>} */ +function isPlainObject(v) { + return !!v && typeof v === "object" && !Array.isArray(v); +} + +/** + * A take's render window: `"full"` (the whole cut), `{ at, dur }` in seconds + * of the cut, or null when take.json does not say (a take made by hand). + * `undefined` is a window that is there and is neither -- an error. + * + * @param {unknown} v + * @returns {"full" | { at: number, dur: number } | null | undefined} + */ +export function parseWindow(v) { + if (v === undefined || v === null) return null; + if (v === "full") return "full"; + if (!isPlainObject(v)) return undefined; + const at = Number(v.at); + const dur = Number(v.dur); + if (!Number.isFinite(at) || at < 0 || !Number.isFinite(dur) || dur <= 0) return undefined; + return { at, dur }; +} + /** * Every take of a project, grouped, plus what was skipped and why. * @@ -188,11 +224,16 @@ export async function previewFile(projectDir, take) { // --------------------------------------------------------------------------- // Verdicts. // -// { "<takeId>": { "verdict": "like" | "maybe" | "no" | null, "note": string, "at": ISO } } +// { "<takeId>": { "verdict": "like" | "maybe" | "no" | null, "note": string, "at": ISO, +// "picked"?: true } } +// +// `picked` (release 33) is the take that "Use this take" copied over the +// project's manifest: at most one per group, present only when true, so a row +// that was never picked keeps exactly the three keys it always had. // // Read back by the agent that made the takes, so the shape is fixed and every -// row carries all three keys. A row whose verdict is null and note empty is -// REMOVED rather than stored -- it says nothing. +// row carries all three keys. A row whose verdict is null, note empty and that +// is not picked is REMOVED rather than stored -- it says nothing. // // Its own write queue, as manifest.mjs has its own: lib/state.ts is TypeScript // (and serialises the song state files, an unrelated set). Within a process the @@ -225,14 +266,43 @@ function cleanVerdicts(raw) { const verdict = TAKE_VERDICTS.includes(row.verdict) ? row.verdict : null; const note = typeof row.note === "string" ? row.note : ""; const at = typeof row.at === "string" ? row.at : ""; - out[id] = { verdict, note, at }; + out[id] = row.picked === true ? { verdict, note, at, picked: true } : { verdict, note, at }; } return out; } +/** A row that says nothing: no verdict, no note, not picked. */ +const emptyRow = (row) => row.verdict === null && !row.note && row.picked !== true; + +/** + * Read verdicts.json for a write: `{}` when absent, an ERROR when present and + * unparseable (writing over it would erase every judgement in it). + */ +async function readVerdictsForWrite(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 {}; + try { + return cleanVerdicts(JSON.parse(text)); + } catch { + throw new Error(`${VERDICTS_FILE} does not parse; not overwriting it`); + } +} + +async function writeVerdicts(file, map) { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + /** * @param {string} projectDir - * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string }>>} + * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true }>>} */ export async function readVerdicts(projectDir) { try { @@ -262,36 +332,52 @@ export async function setTakeVerdict(projectDir, takeId, patch) { if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string"); const file = verdictsFileOf(projectDir); return withTakesLock(async () => { - let text = null; - try { - text = await readFile(file, "utf8"); - } catch (err) { - if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw err; - } - let map = {}; - if (text !== null) { - try { - map = cleanVerdicts(JSON.parse(text)); - } catch { - throw new Error(`${VERDICTS_FILE} does not parse; not overwriting it`); - } - } + const map = await readVerdictsForWrite(file); const prev = map[takeId] ?? { verdict: null, note: "", at: "" }; + /** @type {{ verdict: any, note: string, at: string, picked?: true }} */ const row = { verdict: patch.verdict === undefined ? prev.verdict : patch.verdict, note: patch.note === undefined ? prev.note : patch.note.slice(0, TAKE_NOTE_LIMIT).replace(/\s+$/, ""), at: new Date().toISOString(), }; - if (row.verdict === null && !row.note) delete map[takeId]; + if (prev.picked === true) row.picked = true; + if (emptyRow(row)) delete map[takeId]; else map[takeId] = row; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; - await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); - await rename(tmp, file); + await writeVerdicts(file, map); return { entry: map[takeId] ?? null, verdicts: map }; }); } /** + * Record that `takeId` was picked ("Use this take"), and clear the pick of + * every other take of its group: one pick per group. `group` is the take ids + * of that group, the picked one included. A cleared row that then says + * nothing is removed. Returns the whole file. + * + * @param {string} projectDir + * @param {string} takeId + * @param {string[]} group + * @param {{ now?: Date }} [opts] + */ +export async function setTakePicked(projectDir, takeId, group, { now = new Date() } = {}) { + if (!isTakeId(takeId)) throw new Error("not a take id"); + const file = verdictsFileOf(projectDir); + return withTakesLock(async () => { + const map = await readVerdictsForWrite(file); + for (const id of group) { + if (id === takeId || !map[id]?.picked) continue; + const { picked: _gone, ...rest } = map[id]; + if (emptyRow(rest)) delete map[id]; + else map[id] = rest; + } + const prev = map[takeId] ?? { verdict: null, note: "", at: "" }; + map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true }; + await writeVerdicts(file, map); + return { entry: map[takeId], verdicts: map }; + }); +} + +/** * Every take with its verdict, for an agent reading the conversation back * (`umtool notes`, the notes digest): label, group, summary and changes from * take.json, and the operator's verdict and note from verdicts.json. A verdict @@ -299,7 +385,7 @@ export async function setTakeVerdict(projectDir, takeId, patch) { * dropped -- the agent may have deleted the take it was about. * * @param {string} projectDir - * @returns {Promise<Array<{ id: string, group: string | null, label: string | null, summary: string, changes: string[], verdict: "like" | "maybe" | "no" | null, note: string, at: string, missing?: true }>>} + * @returns {Promise<Array<{ id: string, group: string | null, label: string | null, summary: string, changes: string[], verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true, missing?: true }>>} */ export async function takesWithVerdicts(projectDir) { const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]); @@ -312,11 +398,12 @@ export async function takesWithVerdicts(projectDir) { verdict: verdicts[t.id]?.verdict ?? null, note: verdicts[t.id]?.note ?? "", at: verdicts[t.id]?.at ?? "", + ...(verdicts[t.id]?.picked ? { picked: /** @type {const} */ (true) } : {}), })); const known = new Set(out.map((t) => t.id)); for (const [id, v] of Object.entries(verdicts)) { if (known.has(id)) continue; - out.push({ id, group: null, label: null, summary: "", changes: [], verdict: v.verdict, note: v.note, at: v.at, missing: true }); + out.push({ id, group: null, label: null, summary: "", changes: [], verdict: v.verdict, note: v.note, at: v.at, ...(v.picked ? { picked: /** @type {const} */ (true) } : {}), missing: true }); } return out; } diff --git a/umtool/lib/report/takes.test.mjs b/umtool/lib/report/takes.test.mjs @@ -66,6 +66,10 @@ test("parseTake accepts the contract and fills the optional fields", () => { preview: "preview.mp4", seconds: 38.2, builtAt: "2026-10-06T23:10:00Z", + style: null, + patch: null, + window: null, + baseHash: null, }); const min = parseTake("x", { id: "x", group: "g", order: 0, label: "X", kind: "reference", preview: "p.mp4" }); assert.ok("take" in min); @@ -94,6 +98,11 @@ test("parseTake refuses a take it cannot show truthfully", () => { ["slow-burn", good({ summary: 4 }), "summary"], ["slow-burn", good({ seconds: "38" }), "seconds"], ["slow-burn", good({ builtAt: 1 }), "builtAt"], + ["slow-burn", good({ style: 3 }), "style"], + ["slow-burn", good({ patch: [] }), "patch"], + ["slow-burn", good({ window: { at: -1, dur: 5 } }), "window"], + ["slow-burn", good({ window: "half" }), "window"], + ["slow-burn", good({ baseHash: 7 }), "baseHash"], ]; for (const [dir, doc, want] of cases) { const r = parseTake(dir, doc); @@ -260,3 +269,45 @@ test("takesWithVerdicts joins take.json and verdicts.json, keeping a verdict on await rm(dir, { recursive: true }); } }); + +test("parseTake reads back what the take maker records", () => { + const r = parseTake("slow-burn", good({ style: "flash-count", patch: { render: { crf: 30 } }, window: { at: 5, dur: 20 }, baseHash: "ab" })); + assert.ok("take" in r); + assert.equal(r.take.style, "flash-count"); + assert.deepEqual(r.take.patch, { render: { crf: 30 } }); + assert.deepEqual(r.take.window, { at: 5, dur: 20 }); + assert.equal(r.take.baseHash, "ab"); + const full = parseTake("slow-burn", good({ window: "full" })); + assert.ok("take" in full); + assert.equal(full.take.window, "full"); +}); + +test("a pick is one per group, keeps the row's verdict and note, and survives a verdict change", async () => { + const { setTakePicked } = await import("./takes.mjs"); + const dir = await project(); + try { + await writeTake(dir, "a", good({ id: "a", group: "g" })); + await writeTake(dir, "b", good({ id: "b", group: "g" })); + await setTakeVerdict(dir, "a", { verdict: "like", note: "good" }); + let r = await setTakePicked(dir, "a", ["a", "b"]); + assert.equal(r.verdicts.a.picked, true); + assert.equal(r.verdicts.a.verdict, "like"); + assert.equal(r.verdicts.a.note, "good"); + // A verdict change keeps the pick. + await setTakeVerdict(dir, "a", { verdict: "maybe" }); + assert.equal((await readVerdicts(dir)).a.picked, true); + // Picking b clears a's pick; a keeps its verdict row, b gets one of its own. + r = await setTakePicked(dir, "b", ["a", "b"]); + assert.equal(r.verdicts.b.picked, true); + assert.equal(r.verdicts.a.picked, undefined); + assert.deepEqual(Object.keys(r.verdicts.a).sort(), ["at", "note", "verdict"]); + assert.equal(r.verdicts.a.verdict, "maybe"); + // A picked row with no verdict and no note is still a row; once unpicked it is removed. + await setTakePicked(dir, "a", ["a", "b"]); + const onDisk = JSON.parse(await readFile(verdictsFileOf(dir), "utf8")); + assert.equal(onDisk.b, undefined, "b's row said nothing once its pick was cleared"); + assert.equal(onDisk.a.picked, true); + } finally { + await rm(dir, { recursive: true, force: true }); + } +});