Archilyzer · Source

archilyzer

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

commit 16662aad15661ded6e916cbb3fb5595c537cf9af
parent 8dd2f12ad57664254265dca07dbbb1e60c1f17da
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 17:30:55 -0400

Merge r33/takes: variant auditions — umtool take / takes make|styles|pick, New take + Make all styles + Use this take on the Takes page, recipes, replaceManifest with undo

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 41+++++++++++++++++++++++++++++++++++++++++
Aplans/release-33/takes.md | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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 | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/TakesBench.tsx | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/components/projects/TakesPage.tsx | 35++++++++++++++++++++++++++++++-----
Mumtool/components/projects/report/CutTab.tsx | 10+++++++---
Mumtool/docs/cli.md | 7++++++-
Mumtool/docs/report-video.md | 67++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/e2e/fixtures/make-fixture.mjs | 18++++++++++++++++++
Aumtool/e2e/fixtures/montage-styles.e2e.mjs | 16++++++++++++++++
Mumtool/e2e/takes.spec.ts | 95++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/annotations/digest.mjs | 2+-
Mumtool/lib/report/manifest.mjs | 25+++++++++++++++++++++++++
Aumtool/lib/report/takeCli.mjs | 302++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeMaker.mjs | 766+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeMaker.test.mjs | 435+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeRender.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takes.mjs | 140++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/takes.test.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 6++++++
Mumtool/report-to-video/package.json | 1+
25 files changed, 2751 insertions(+), 41 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Variant auditions: make takes on umtool's Takes page, and use one.** A report video's Takes page (the Cut tab's **Takes — N**, or **Make takes** when there are none yet) has **New take**: a montage style or none, a label, a group, the window (from S seconds for D seconds, or the full cut), an optional patch (JSON, checked before it is sent) and **quick render**. **Make all styles** makes one take per montage style with the same window. A take is rendered beside the project from the media the project already has — nothing is fetched — and appears when it is built, its changes listed in plain lines (`render.montage.cut: flash`, `render.crf: 34 (was 30)`); **Rebuild** makes it again against the cut as it is now. **Use this take** makes the take's manifest the project's and marks it **picked**, one per group; the Cut tab's **Undo last edit** takes it back. When the cut changed since the take was made, the card says so and waits for **Use anyway**. The same from a terminal: `umtool take`, `umtool takes make` (a recipe, or `--all-styles`), `umtool takes styles`, `umtool takes pick`. Nothing calls a model. Needs a restart of umtool. - **A montage from a phrase.** umtool's new project can be seeded from a phrase said across channels: `umtool new <slug> --seed phrase --phrase '<regex>' --channels a,b --prefer <channel>`, or the new-project form's seed "a phrase across channels" when no source is given. Every place the transcripts say it becomes a clip, in date order, found even where a caption line split the phrase in two; a stream that the preferred channel also holds (a Rumble copy, say) is cut from that copy; a stream and its clip upload are one clip; `--exclude` leaves out lines that match (a chat line read out), and a caption speaker change is noted for a voice check. The scan is kept beside the manifest as `phrase-scan.json`. - **Report videos can be montages.** A cut of one phrase said many times can now be edited as one: each clip cut tight to the phrase as said (found in its captions, or in whisper's word timings when the corpus keeps them) and snapped to the pauses around it; a white flash, a whip or a dip to black on every cut; a running count on the picture (a small "#12 · 2 May 2019 · YouTube", a big number that slams in, or tally marks), the year large in a corner when it changes; a punch-in as the phrase starts or a slow zoom; the end of the phrase repeated on chosen clips ("…news day-day-day"); clips that get shorter toward the end; and a closing wall of 9, 16 or 25 clips filling in and then all saying it together. All of it is set under `render.montage` in the video manifest, and none of it is a card. Six named styles to audition — Straight, Flash and count, Accelerate, Stutter, Wall finale, Whip and years — are listed by `node umtool/report-to-video/montage-styles.mjs list`, and `apply <style> <manifest> --out <file>` writes a manifest with one applied. A manifest without `render.montage` renders exactly as before. - **`pnpm heavy` caps what it runs.** A command admitted to the heavy slot through `pnpm heavy -- <cmd>` (or `scripts/queue-lock.mjs --heavy`) now runs in a memory-capped systemd user scope of its own — 8 GB, 2 GB of swap — so a runaway render or build is stopped in its scope instead of taking the desktop session down. A command that sets its own `MemoryMax=`, or one started from inside a capped unit or scope (the live editor and umtool, a publish stage's build), is run as before. `HEAVY_CAP=0` turns it off; `HEAVY_CAP_MB` and `HEAVY_CAP_SWAP_MB` size it. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -10388,6 +10388,47 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri (headers + part of the body, then the socket destroyed) or, on a request's first byte, before any response; a cut request is `dropped: true` with the bytes it sent. `cdn.lock()` takes an unlock back. +## Release 33 lane M1: the take maker (verified 2026-10-17, branch `r33/takes`) + +- **A take on disk** (`umtool/lib/report/takeMaker.mjs`; the contract `takes.mjs`): `takes/<id>/video.manifest.json` + is the WHOLE patched manifest (what a pick copies); `preview.mp4` the render; `out/` the take's own render scratch + (made by `ensureWriteDir`, so it follows `UMTOOL_MEDIA_DIR`) with `clips-raw` and `narration` as absolute links to + `<project>/out/<name>` (only when the project has them); `take.json` written LAST, only once the preview exists (a + dir without it is a work dir the listing ignores). The new manifest is `.next.video.manifest.json` until the render + is done, so a failed rebuild leaves the old take whole. take.json adds (optional, checked by `parseTake`): `style`, + `patch`, `window` (`"full"` | `{at, dur}`), `quick`, `entries {ids, basis: "schedule"|"estimate"}`, `baseHash` + (sha256 of the project's manifest TEXT the take was made from). `changes[]`: `style: <label>` then one line per leaf + the patches change (`changeLines`; a leaf whose value is unchanged has none). No change at all = kind `reference`. +- **The patch** is RFC 7386 (`mergePatch`, M3's from `montage-styles.mjs`, re-exported by takeMaker.mjs; the + package exports `umtool-report-to-video/montage-styles`: objects merge, `null` removes, arrays/scalars replace): the style's + (`MONTAGE_STYLES[name].patch` from `report-to-video/montage-styles.mjs`, loaded at run time by an assembled + `pathToFileURL` + `webpackIgnore`; `E2E_UMTOOL_MONTAGE_STYLES` overrides the file; a missing module = no styles, + `error: null`), then the take's own. +- **The window is a sub-cut**, not `--chrome-preview`/`--preview`: the sourced entries [at, at+dur] touches, timed by + `<project>/out/sourced/schedule.json` when it names every entry, else each entry's own length (clip `cutEnd−cutStart` + else `end−start`, else `seconds`, else 4 s), computed on the BASE manifest so a group's takes cover the same entries; + posts attached outside are dropped. Montage features numbered by position (`planMontage`'s `k`, `n`) count within + the sub-cut. +- **The render** (`takeRender.mjs`): `node scripts/queue-lock.mjs --heavy -- node build-video.mjs + <project>/.take-<id>.render.json --out takes/<id>/out --progress ndjson --skip-fetch --continue-on-error + [--no-xfade] [--no-chapters]` from the checkout root. The render manifest sits BESIDE the project's (its relative + paths, drafts review and shadow channels hold) and is removed after. `--no-xfade` unless a patch sets + `render.transition` > 0; `--no-chapters` for a window. Quick (`--quick`) merges `QUICK_RENDER` (`render.preset: + veryfast`) into the render manifest only. The final (`variantPaths(out, slug, "sourced").final`) is renamed (EXDEV: + copied) to `preview.mp4`; seconds by ffprobe. +- **The pick** (`pickTake`): refused (`TakeStale`) when the project's manifest hash ≠ `baseHash` or the take has none, + unless `anyway`; a project whose manifest text already IS the take's is a no-op write. Writes through + `replaceManifest` (manifest.mjs: lock, token, `autoSnapshot(dir, "pick-take")`, `writeManifestAtomic`) inside + edit-guard's `withEditNotes`; `undoStructural` (the Cut tab's Undo) restores it. Then `setTakePicked`: verdicts.json + rows gain `picked: true` (present only when true), one per group; an unpicked row that then says nothing is removed; + `setTakeVerdict` keeps a pick. +- **The app's jobs**: `/api/report/takes/make` POST `{project, take | allStyles | rebuild, force?}` → `takeSteps` → + ONE job on lib/jobs.ts whose step runs the CLI (`umtool take …` / `umtool takes make … --all-styles`, NDJSON); + GET `?job=` the job, GET `?project=` the styles and a running take job. `/api/report/takes/pick` POST `{project, + take, anyway?}` → 409 `{stale: true}`. Recipes: `{group, window, quick?, takes: [{id, label, style?, patch?, summary?, + kind?, group?, window?, quick?}]}`; `takes/recipe.json` is the CLI's default, Make all styles writes + `takes/all-styles.recipe.json`; a recipe carries on past a failed take and exits 1. + ## Release 33 lane M3: montage editing in report-to-video (verified 2026-10-17, branch `r33/montage`) - `render.montage` (object; absent or `null` = off) is read only by `umtool/report-to-video/montage.mjs` (pure) and diff --git a/plans/release-33/takes.md b/plans/release-33/takes.md @@ -0,0 +1,116 @@ +# Release 33 lane M1 — `r33/takes`: variant auditions in umtool (as shipped) + +Operator request (2026-10-17): variant auditions for a montage project, in umtool. Operator rule (2026-10-16): +everything a model can do is doable in the UI with no model. Before this lane takes were only ever made by a one-off +script, and the winner was copied by hand. Now umtool makes them, from the Takes page or a terminal, and **Use this +take** puts one in the project's place. Nothing here calls a model. + +## What + +1. **The take maker** (`umtool/lib/report/takeMaker.mjs`). `makeTake(projectDir, spec)` reads the project's + manifest, applies a montage style's patch (lane M3's `report-to-video/montage-styles.mjs`, loaded at run time; + none installed = no styles), then the take's own patch. Both are RFC 7386 merge patches (`mergePatch`: lane M3's, from + `montage-styles.mjs`, which `report-to-video/package.json` now exports; arrays replace). It writes `takes/<id>/video.manifest.json` (the whole patched manifest) and + `changes[]` (`style: <label>`, then one plain line per changed leaf, e.g. `render.crf: 34 (was 30)`), then renders. + take.json is written only once the preview exists. It carries `builtAt`, `seconds` (ffprobe), `style`, `patch`, + `window`, `quick`, `entries` and `baseHash`. An empty change is kind `reference`; otherwise `different`, or the + given `kind`. +2. **The render** (`takeRender.mjs`): build-video through `scripts/queue-lock.mjs --heavy` (capped by default since + r33/heavy-cap; passes through under HEAVY_HELD), `--skip-fetch --continue-on-error`. It writes into the take's own + `out/`, whose `clips-raw` and `narration` are links to the project's; nothing is copied or fetched. `--no-xfade` + unless a patch sets `render.transition` > 0 (the `fast` preset). `--no-chapters` for a window. + **Quick render** (`--quick`, on by default in the form) encodes the render with x264 veryfast and never touches the + take's manifest. +3. **The window is a sub-cut.** `{at, dur}` renders the entries that window touches, as a cut of their own. The + entries are timed by the project's deck schedule when it names every entry, otherwise by the manifest's own + lengths, on the base manifest. `"full"` renders the whole cut. +4. **Recipes**: `makeTakes(projectDir, recipe)` makes one take at a time. It skips a take that exists unless forced, + carries on past a failure, and exits 1 at the end. `allStylesRecipe` gives one take per style. +5. **The CLI** (`lib/report/takeCli.mjs`, two dispatch lines in `bin/umtool.mjs`): `umtool take`, `umtool take --id X + --rebuild`, `umtool takes make [--recipe F | --all-styles]`, `umtool takes styles`, `umtool takes pick [--anyway]`. +6. **The pick** (`pickTake`) goes through a new manifest writer, `replaceManifest` (manifest.mjs). That takes the + lock and the token, takes the auto snapshot `auto-before-pick-take` (so the Cut tab's **Undo last edit** restores + it), keeps the drafted-mark rule and writes atomically, all inside `withEditNotes`. The pick is then recorded in + verdicts.json (`setTakePicked`, takes.mjs): `picked: true`, one per group. The pick is refused when the project's + manifest hash ≠ the take's `baseHash`, or when the take records none, until `anyway`. A take whose manifest + already is the project's re-picks as a no-op write. +7. **UI** (`/projects/<p>/takes`): + - **New take** (`NewTakePanel.tsx`): style select, label (taken from the style), group (the newest take's), + window (from/for, or Full cut; 0/60 by default), patch JSON (checked before submit), quick render, and "make it + again if it exists". + - **Make all styles**. The job is watched with JobProgress (per-take steps, log, Stop), and the page refreshes + when it ends. + - Per card: **Use this take**; on a stale base, "The project changed since this take was made." and **Use + anyway**. Once used, "The project's manifest is this take's now." with a link to **Revisions** (the History + tab). + - Per card: a **picked** badge, and **Rebuild** (takes the maker made). + - The Cut tab links **Make takes** when the project has no `takes/`. The notes digest marks the picked take. + - Works at 390 px. + +## Files + +umtool: `lib/report/{takeMaker,takeRender,takeCli}.mjs` (new), `lib/report/takeMaker.test.mjs` (new), +`lib/report/takes.mjs` (+ `parseWindow`, `setTakePicked`, parseTake's maker fields, `picked` rows), `takes.test.mjs`, +`lib/report/manifest.mjs` (`replaceManifest`), `lib/annotations/digest.mjs`, `bin/umtool.mjs` (dispatch + usage), +`app/api/report/takes/{make,pick}/route.ts` (new), `components/projects/{NewTakePanel,TakesBench,TakesPage}.tsx`, +`components/projects/report/CutTab.tsx`, `e2e/takes.spec.ts`, `e2e/fixtures/make-fixture.mjs` (takes-make-fixture), +`e2e/fixtures/montage-styles.e2e.mjs` (new), `playwright.config.ts` (E2E_UMTOOL_MONTAGE_STYLES), `docs/cli.md`, +`docs/report-video.md` ("Making takes"). plans/FACTS.md, editor/CHANGELOG.md. + +## Interfaces + +- `makeTake(projectDir, {id, label, group?, kind?, summary?, style?, patch?, window?, order?, quick?}, {force, + render, probe, styles, emit, log, ensureOut, now})` → `{id, skipped, take?}`; `RenderFn(job: {manifestPath, + outDir, slug, full, xfade, emit, log}) → {file}`. +- `makeTakes(projectDir, recipe, {...makeTake opts, only})` → `[{id, status: made|skipped|failed, error?}]`; + `parseRecipe`, `allStylesRecipe(styles, {group, window, quick})`. +- `pickTake({id, dir, kind}, takeId, {anyway, token, now})` → `{take, group, snapshot, token, editNotes, verdicts}`; + `TakeStale`; `takeIsStale(projectDir, take)`. +- `mergePatch`, `changeLines(before, after, patches)`, `patchLeaves`, `patchFromSets`, `windowEntries(timeline, + {at, dur}, schedule?)`, `windowManifest`, `loadMontageStyles({file?})`, `montageStylesFile`, `takeSteps(project, req, + ctx)`, `lastGroup`, `uniqueTakeId`, `hashText`, `QUICK_RENDER`, `renderManifestPath`. +- takes.mjs: `setTakePicked(projectDir, takeId, groupIds)`, `parseWindow`. +- manifest.mjs: `replaceManifest(dir, manifest, {token, op})`. +- Reads M3's `MONTAGE_STYLES: Record<name, {label, summary, patch}>`. `montageStyle()` is not needed. + +## Decisions / rulings followed + +- One merge patch: the take maker imports M3's `mergePatch` (the module exported as + `umtool-report-to-video/montage-styles`) and re-exports it, rather than a second implementation. The styles + themselves are still loaded at run time, so `E2E_UMTOOL_MONTAGE_STYLES` can stand in for them. + +- The window is a sub-cut, not `--chrome-preview`/`--preview`. Those need every segment already built in the take's + `out/`; linking the project's segments would show the old cut for any patch that re-cuts a clip; and `--preview` is + the rail's. +- The render manifest is `<project>/.take-<id>.render.json`, beside the project's (relative paths, drafts review, + shadow channels hold), and is removed after. +- A rebuild writes the new manifest under a work name until the render succeeds. +- The UI's Make all styles writes `takes/all-styles.recipe.json`, never a hand-written `takes/recipe.json`. +- The window is prefilled 0/60: the Cut tab's preview window is component state and is not kept. +- Quick render is on by default in the form (an audition compares cuts); the CLI's default is off. +- A pick of a take with no `baseHash` (made by hand) needs Use anyway. + +## Gates (all through the shared lock) + +- tsc (all packages) clean before every commit. +- test:scripts 1073 (1069 pass, 4 skipped, 0 fail) before main's merges; 1113 (1109 pass, 4 skipped) after them. Baseline 1056 (1052 pass, 4 skipped) on `643434f7`, so +17: + takeMaker 15, takes 2. +- umtool `test` 45/45 (no take tests in it). +- e2e umtool `takes.spec.ts` 7/7 (17.9 s; again 7/7 in 16.6 s after main's merges; +2 tests, one assertion more in test 1). +- e2e umtool `bench-shell.spec.ts` + `visual-audit.spec.ts` 71/71 (1.4 min). +- Smoke on a COPY of the montage project's manifest under `$T/r33m1-smoke/` (the real corpus read-only), with `--quick`: + - window 0/20 s gives 7 clips and a 26.1 s 1080p preview in 14 s. + - The first run failed by design, naming all 7 clips: the manifest's `render.fetchPad: 3` asks for wider windows than + the editor fetched. It passed with `--set render.fetchPad=0`. + - After main's merge (M3 on main, the project at `fetchPad: 0`), on a fresh copy: + - `flash-count` over 0/20 s: kind `different`, 17.95 s, 7 clips, tightened to the phrase. + - `as-built`: `reference`, 26.12 s. + - Both takes together took 19 s. + +## Found and left + +- **The montage project's manifest:** at `render.fetchPad: 3`, every `--skip-fetch` build of it refused, because the + editor's windows are the clip extents exactly. The orchestrator set it to 0 (2026-10-17). +- **Window takes and position-counted montage features:** M3's `planMontage` numbers by position. A window take's + counter starts at #1 and its ramp runs over the window. For `accelerate` and `wall-finale` audition the full cut, + or have the counter read `montage.n`. 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, @@ -712,6 +715,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)", @@ -745,6 +751,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,303 @@ +"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); + // On by default: an audition compares cuts, and a quick encode is minutes sooner. + const [quick, setQuick] = useState(true); + 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(), quick } }); + }} + > + <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(), quick } })} + > + Make all styles{styles.length ? ` (${styles.length})` : ""} + </button> + <label className="flex items-center gap-1 text-[12px] text-text-2" title="x264 veryfast for the preview; the take's manifest keeps its own encode"> + <input type="checkbox" checked={quick} onChange={(e) => setQuick(e.target.checked)} data-take-quick="" disabled={!ready} /> + quick render + </label> + <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,18 @@ 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; + /** Rendered with a quick encode (the render only). */ + quick?: boolean; + /** 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 +96,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 +226,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 +286,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 +312,7 @@ function TakeCard({ onPlay, onUnmute, save, + onPicked, }: { project: string; take: Take; @@ -310,6 +325,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 +362,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 +429,14 @@ 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}`} + {t.quick && " · quick"} </span> + {verdict?.picked && ( + <span data-take-picked="" className={badgeVariants({ variant: "on", size: "sm" })}> + picked + </span> + )} <button type="button" data-action="listen" @@ -434,6 +491,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/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -122,9 +122,9 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </span> </div> )} - {/* Alternative renders of part of the cut, made elsewhere and judged - on their own page. Only when there is a takes/ to look at. */} - {takes.exists && ( + {/* Alternative renders of part of the cut, judged on their own page -- + where the first one is made, too (release 33's take maker). */} + {takes.exists ? ( <Link href={takesHref(project.id)} data-takes-link={takes.takes.length} @@ -132,6 +132,10 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor > Takes — {takes.takes.length} </Link> + ) : ( + <Link href={takesHref(project.id)} data-takes-make-link="" className={buttonVariants({ variant: "quiet", size: "sm" })}> + Make takes + </Link> )} </div> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -39,6 +39,9 @@ Inbox cannot disagree about what is wrong with one. | `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) | | `schedule list \| show <id> [--json]` | the recurring reports, read-only ([recurring.md](recurring.md)) | | `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) | +| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) | +| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed | +| `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | A project argument is an exact id, a directory, or a **unique** basename. Two projects answering to one name is reported, never resolved by picking one. @@ -47,7 +50,9 @@ projects answering to one name is reported, never resolved by picking one. `REPORTS_DIR`, `SONG_REPORTS_DIR`, `SONG_DIR`, `CHANNELS_DIR`, `UMTOOL_INDEX_DIR`, `UMTOOL_CACHE_DIR`, `UMTOOL_MEDIA_DIR` -— which is how it is tested against the e2e fixture. The path defaults +— which is how it is tested against the e2e fixture (which also sets +`E2E_UMTOOL_MONTAGE_STYLES`, the montage styles module `take`/`takes` read in place of +`report-to-video/montage-styles.mjs`). The path defaults (`lib/paths.mjs`, `song/paths.mjs`): | Variable | Default | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -695,17 +695,22 @@ there too. No field is moved or rewritten. ## Takes: alternative renders, judged side by side `/projects/<project>/takes` (a bench: [piece.md](piece.md#the-benches)), linked from the Cut tab as **Takes — N** -when `takes/` exists. -Something else renders the takes; umtool reads them and records the verdicts. +when `takes/` exists, and as **Make takes** when it does not. +umtool's take maker makes them (below), or something else does in the same shape; umtool reads +them and records the verdicts. ``` takes/<id>/take.json id (== dir, [a-z0-9-]), group, order, label, kind reference|similar|different, preview; optional summary, changes[], seconds, builtAt takes/<id>/preview.mp4 whatever `preview` names, inside the take dir -takes/verdicts.json { "<id>": { verdict: like|maybe|no|null, note, at } } +takes/verdicts.json { "<id>": { verdict: like|maybe|no|null, note, at, picked?: true } } ``` +The take maker also records, in take.json, `style`, `patch`, `window` (`"full"` or +`{ at, dur }`), `quick`, `entries` (`{ ids, basis }`: what the window covered) and `baseHash` (sha256 of +the project's `video.manifest.json` the take was made from); all optional, checked when present. + A take.json that fails validation is listed under **skipped** with the reason; a directory with no take.json is not a take. A row whose verdict is null and note empty is removed. A `verdicts.json` that does not parse is never @@ -724,6 +729,62 @@ anyway**; a umtool job working in the project refuses. Its verdict row and the notes on it are kept: the agent reads them back, and a verdict on a take that is gone shows as missing. +### Making takes + +On the Takes page, **New take**: a montage style (or none), a label (the style's, until typed +over), a group (the newest take's), the window — from *S* s for *D* s (0 / 60 by default) or +**Full cut** — an optional patch (a JSON object, checked before it is sent) and **quick render** +(on by default: the render is encoded with x264 `veryfast`; the take's own manifest, which a pick +uses, keeps its encode settings). **Make all +styles** makes one take per style with that group and window. Each is one job on the app's +runner, shown under the form with its log and **Stop**; the take appears when it is built. +Nothing on the page calls a model. The same, from a terminal ([cli.md](cli.md)): + +``` +umtool take <project> --id flash --label "Flash" --style flash-count --at 0 --dur 60 +umtool take <project> --id crisp --label "Crisp" --set render.crf=34 --full +umtool takes make <project> --recipe takes/recipe.json # or --all-styles +umtool takes styles +umtool takes pick <project> flash [--anyway] +``` + +A take (`lib/report/takeMaker.mjs`): + +1. reads the project's `video.manifest.json`, applies the style's patch + (`report-to-video/montage-styles.mjs`: `MONTAGE_STYLES[name].patch`) and then the take's own — + RFC 7386 JSON merge patches: objects merge, `null` removes a key, an array replaces whole; +2. writes `takes/<id>/video.manifest.json`, the whole patched manifest, and `changes[]`: one plain + line per leaf the patches change (`render.montage.cut: flash`, `render.crf: 34 (was 30)`, + `render.montage.ramp: removed`) after `style: <label>`. No change at all is the `reference` + kind; otherwise `different` (or `--kind similar`); +3. renders: build-video through the heavy slot (`queue-lock.mjs --heavy`), `--skip-fetch` + (nothing is fetched: the take's `out/clips-raw` and `out/narration` are links to the + project's, and the editor's corpus windows are found as for any build), `--no-xfade` unless + the take sets `render.transition`, `--no-chapters` for a window. The manifest it renders sits + beside the project's (`.take-<id>.render.json`, removed after) so its relative paths hold. + A **window** renders the entries [at, at + dur] touches — timed by the project's + `out/sourced/schedule.json` when it names every entry, else by each entry's own length (a + clip's cut, else `seconds`, else 4 s) — as a cut of its own, so every take of a group made with + one window covers the same entries; +4. moves the render to `takes/<id>/preview.mp4` and writes take.json — only then; a take that + fails leaves no take.json (a work dir the listing ignores), and a failed **Rebuild** leaves the + old take whole. + +`--quick` (a recipe's or a take's `quick: true`) is that quick render. A take that exists is skipped unless forced (**make it again if it exists**, `--force`). +**Rebuild** on a card (`--rebuild`) makes it again from its own take.json against the project's +manifest as it is now. A recipe is `{ group, window, quick?, takes: [{ id, label, style?, patch?, +summary?, kind?, quick? }] }` (a take's own `group`/`window`/`quick` win), run one take at a time, carrying on +past a failure; Make all styles writes `takes/all-styles.recipe.json`. + +**Use this take** (`POST /api/report/takes/pick`, `umtool takes pick`) copies the take's +`video.manifest.json` over the project's through the manifest writer (`replaceManifest`: the +automatic snapshot `auto-before-pick-take` first, the generated-manifest guard, the drafted-mark +rule), marks it **picked** in verdicts.json (one pick per group) and links the History tab's +revisions; **Undo last edit** on the Cut tab takes it back. When the project's manifest is not +the one the take was made from (its `baseHash`), the card says **The project changed since this +take was made** and the pick waits for **Use anyway**. A take that does not record its base asks +the same. + ## Montages (`render.montage`) A cut of one phrase said many times — every "slow news day" — is a montage, and diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1960,6 +1960,23 @@ take("intro-a", { group: "opening", order: 5, label: "Cold open", kind: "similar take("bad-kind", { group: "finale", order: 4, label: "Bad", kind: "maybe" }); mkdirSync(path.join(TAKES, "takes", "current", "out"), { recursive: true }); +// takes-make-fixture: a project the take MAKER makes takes of (takes.spec.ts: +// New take -> the take appears -> Use this take). One clip, its window cached +// in out/clips-raw (the take links it, never fetches), no takes/ yet. Its own +// project, because the spec writes its manifest. The styles the form offers +// are e2e/fixtures/montage-styles.e2e.mjs (E2E_UMTOOL_MONTAGE_STYLES). +const TAKES_MAKE = writeProject( + "takes-make-fixture", + manifest("takes-make-fixture", "The Take Maker Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "clip", id: "m01", video: "vid1", start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" }, + ]), +); +mkdirSync(path.join(TAKES_MAKE, "out", "clips-raw"), { recursive: true }); +copyFileSync( + path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + path.join(TAKES_MAKE, "out", "clips-raw", "vid1_0.00-9.00.mp4"), +); + // -- THE VIDEO-NOTES AND TIMELINE FIXTURES ------------------------------------ // // video-notes-fixture is a GENERATED manifest (`generatedBy`) with a built cut @@ -2083,6 +2100,7 @@ console.log(` onscreen-posts-fixture (writable, deck on, three posts, console.log(` onscreen-feed-fixture (writable, posts feed, built by the spec)`); console.log(` deliver-stop-fixture (writable: six confirmed clips to cut, for Stop and resume)`); console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`); +console.log(` takes-make-fixture (writable: one clip, its window cached, no takes/ -- the take maker's)`); console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`); console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`); console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`); diff --git a/umtool/e2e/fixtures/montage-styles.e2e.mjs b/umtool/e2e/fixtures/montage-styles.e2e.mjs @@ -0,0 +1,16 @@ +// The montage styles the e2e's Takes page offers (E2E_UMTOOL_MONTAGE_STYLES, +// set in playwright.config.ts): the shape of report-to-video/montage-styles.mjs, +// with patches any manifest renders -- the suite tests the take maker, not a +// style's look. +export const MONTAGE_STYLES = { + "e2e-crisp": { + label: "Crisp", + summary: "A lower quality setting.", + patch: { render: { crf: 34 } }, + }, + "e2e-soft": { + label: "Soft", + summary: "A higher quality setting.", + patch: { render: { crf: 26 } }, + }, +}; diff --git a/umtool/e2e/takes.spec.ts b/umtool/e2e/takes.spec.ts @@ -1,5 +1,5 @@ import { test, expect } from "@playwright/test"; -import { readFileSync } from "node:fs"; +import { readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; @@ -25,6 +25,8 @@ test("a project with no takes/ says so, and its page has no takes link", async ( await page.goto(urls.section("reports/report-fixture", "takes")); await expect(page.locator("[data-takes-link]")).toHaveCount(0); + // ...but a way to make the first one. + await expect(page.locator("[data-takes-make-link]")).toHaveAttribute("href", urls.takesHref("reports/report-fixture")); }); test("takes are grouped and ordered; the skipped one says why; a work dir is not a take", async ({ page }) => { @@ -142,3 +144,94 @@ test("listen picks the one audio source; play all starts the group from zero", a expect(await muted("ref")).toBe(false); expect(await muted("slow")).toBe(true); }); + +// --------------------------------------------------------------------------- +// The take maker (release 33), on takes-make-fixture: one clip, its window +// cached, no takes/. The styles are e2e/fixtures/montage-styles.e2e.mjs. A +// take is a real (tiny) render -- build-video over the cached window, nothing +// fetched -- and a pick writes the project's manifest. +// --------------------------------------------------------------------------- + +const MAKE_DIR = path.join(HERE, "..", ".e2e-song", "reports", "takes-make-fixture"); +const MAKE_PAGE = urls.takesHref("reports/takes-make-fixture"); +const readText = (rel: string) => readFileSync(path.join(MAKE_DIR, rel), "utf8"); + +test("the take maker: New take with a style, the take appears, Use this take makes it the project's manifest", async ({ page, request }) => { + test.setTimeout(240_000); + await page.goto(MAKE_PAGE); + await expect(page.locator("[data-takes-empty]")).toContainText("No takes yet"); + + await page.locator("[data-action='new-take-open']").click(); + const style = page.locator("[data-take-style]"); + await expect(style).toBeEnabled(); + await style.selectOption("e2e-crisp"); + await expect(page.locator("[data-take-label]")).toHaveValue("Crisp"); + await page.locator("[data-take-window='full']").check(); + // A patch that is not a JSON object is refused before anything is sent. + await page.locator("[data-take-patch]").fill("[1, 2]"); + await expect(page.locator("[data-action='make-take']")).toBeDisabled(); + await page.locator("[data-take-patch]").fill(""); + await page.locator("[data-action='make-take']").click(); + + await expect(page.locator("[data-take-job]")).toBeVisible(); + const card = page.locator("[data-take='crisp']"); + await expect(card).toBeVisible({ timeout: 180_000 }); + await expect(card).toContainText("style: Crisp"); + await expect(card).toContainText("render.crf: 34 (was 30)"); + await expect(card).toHaveAttribute("data-kind", "different"); + await expect(card.locator("video")).toHaveCount(1); + const made = JSON.parse(readText("takes/crisp/take.json")); + expect(made.style).toBe("e2e-crisp"); + expect(made.window).toBe("full"); + // Quick render is on by default: the render's encode, never the take's manifest. + expect(made.quick).toBe(true); + expect(JSON.parse(readText("takes/crisp/video.manifest.json")).render.preset).toBe("ultrafast"); + expect(made.baseHash).toMatch(/^[0-9a-f]{64}$/); + expect(JSON.parse(readText("takes/crisp/video.manifest.json")).render.crf).toBe(34); + + // Use this take: the project's manifest is the take's, the badge shows. + await card.locator("[data-action='pick']").click(); + await expect(card.locator("[data-take-used]")).toBeVisible(); + await expect(card.locator("[data-take-picked]")).toBeVisible(); + expect(readText("video.manifest.json")).toBe(readText("takes/crisp/video.manifest.json")); + expect(JSON.parse(readText("takes/verdicts.json")).crisp.picked).toBe(true); + + // A second take, by the route the form uses. It is made from the picked manifest. + const r = await request.post("/api/report/takes/make", { + data: { project: "reports/takes-make-fixture", take: { label: "Soft", style: "e2e-soft", window: "full" } }, + }); + expect(r.status()).toBe(200); + const { job } = (await r.json()) as { job: { id: string } }; + await expect + .poll(async () => ((await (await request.get(`/api/report/takes/make?job=${job.id}`)).json()) as { state: string }).state, { timeout: 180_000 }) + .toBe("done"); + + // The project moves on after the take was made: Use this take is refused until Use anyway. + const m = JSON.parse(readText("video.manifest.json")); + writeFileSync(path.join(MAKE_DIR, "video.manifest.json"), JSON.stringify({ ...m, title: "Moved on" }, null, 2) + "\n"); + await page.reload(); + const soft = page.locator("[data-take='soft']"); + await soft.locator("[data-action='pick']").click(); + await expect(soft.locator("[data-take-stale]")).toContainText("The project changed since this take was made"); + expect(JSON.parse(readText("video.manifest.json")).title).toBe("Moved on"); + await soft.locator("[data-action='pick-anyway']").click(); + await expect(soft.locator("[data-take-picked]")).toBeVisible(); + expect(readText("video.manifest.json")).toBe(readText("takes/soft/video.manifest.json")); + // One pick per group. + await page.reload(); + await expect(page.locator("[data-take='crisp'] [data-take-picked]")).toHaveCount(0); + await expect(page.locator("[data-take='soft'] [data-take-picked]")).toBeVisible(); +}); + +test("the Takes page with the New take form open fits a phone", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(MAKE_PAGE); + await page.locator("[data-action='new-take-open']").click(); + await expect(page.locator("[data-take-style]")).toBeVisible(); + const { scroll, client } = await page.evaluate(() => ({ + scroll: document.documentElement.scrollWidth, + client: document.documentElement.clientWidth, + })); + expect(scroll).toBeLessThanOrEqual(client); + await expect(page.locator("[data-action='pick']").first()).toBeVisible(); +}); diff --git a/umtool/lib/annotations/digest.mjs b/umtool/lib/annotations/digest.mjs @@ -196,7 +196,7 @@ export async function digest(entry, { status = "open", reportsRoot = REPORTS_ROO lines.push("", "## Takes (takes/verdicts.json)"); for (const t of ctx.takes) { const v = ctx.verdicts?.[t.id]; - lines.push(`- \`${t.id}\` “${t.label}” (${t.group}, ${t.kind}): ${v?.verdict ?? "no verdict"}${v?.note ? ` — ${clip(v.note, 400)}` : ""}`); + lines.push(`- \`${t.id}\` “${t.label}” (${t.group}, ${t.kind}): ${v?.verdict ?? "no verdict"}${v?.picked ? " · picked" : ""}${v?.note ? ` — ${clip(v.note, 400)}` : ""}`); } } if (shown.length) { 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,302 @@ +// `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] [--quick] [--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] [--quick] [--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. --quick encodes`, + "the render with x264 veryfast (the render only: the take's manifest, what a pick uses, keeps its own).", +].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] [--quick] [--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, + quick: prev.quick === true, + }; + } 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), + quick: p.has("--quick"), + }; + } + 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), quick: p.has("--quick") }); + 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,766 @@ +// 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 { mergePatch } from "umtool-report-to-video/montage-styles"; +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 }; +/** + * A QUICK render: what the render manifest gets on top of the take, never the + * take's own manifest -- so a pick never carries an audition's encode setting + * into the deliverable. Every take of a group made quick is encoded alike. + */ +export const QUICK_RENDER = Object.freeze({ render: Object.freeze({ preset: "veryfast" }) }); +/** 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))); + +// --------------------------------------------------------------------------- +// The words for what a merge patch changes. +// --------------------------------------------------------------------------- + +// mergePatch is lane M3's (report-to-video/montage-styles.mjs): the same +// RFC 7386 the styles are written for -- objects merge, `null` removes a key, +// anything else (an array included) replaces the value whole -- one +// implementation, re-exported here for the take maker's callers. +export { mergePatch }; + +/** + * 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, quick?: boolean, + * }} 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, + quick: spec.quick === true, + }; +} + +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); + } + if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER)); + + 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, + ...(spec.quick ? { quick: true } : {}), + ...(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?, quick?, takes: [{ id, label, style?, + * patch?, summary?, kind?, group?, window?, quick? }] }`. A take's own group, + * window and quick win over the recipe's. Ids are unique. + * + * @param {unknown} raw + * @returns {{ group: string, window: "full" | { at: number, dur: number }, quick: boolean, 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); + const quick = raw.quick === true; + 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, quick, ...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, quick, 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, quick?: boolean }} [opts] + */ +export function allStylesRecipe(styles, { group = DEFAULT_GROUP, window = DEFAULT_WINDOW, quick = false } = {}) { + const names = Object.keys(styles); + if (!names.length) throw new Error("no montage styles are installed"); + const used = new Set(); + return { + group, + window, + ...(quick ? { quick: true } : {}), + 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`); + // Already the project's manifest (picked before): nothing to write, nothing to refuse. + const current = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null); + const same = current === text; + if (!anyway && !same) { + 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 } = same + ? { result: { snapshot: null, token: null }, editNotes: null } + : 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?, quick? }, force? } New take + * { allStyles: { group?, window?, quick? }, 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), + quick: req.allStyles.quick === true, + }); + 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), ...(recipe.quick ? ["--quick"] : []), ...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), ...(spec.quick ? ["--quick"] : []), ...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,435 @@ +// 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); + assert.equal(t.quick, undefined); + assert.equal(r.calls[0].doc.render.preset, undefined); + // 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"); + // Quick: the RENDER is encoded veryfast; the take's manifest -- what a pick uses -- is not touched. + await makeTake(dir, { id: "quick", label: "Quick", patch: { render: { crf: 33 } }, quick: true }, opts(r)); + assert.equal(r.calls[2].doc.render.preset, "veryfast"); + assert.equal(r.calls[2].doc.render.crf, 33); + const qm = JSON.parse(await readFile(path.join(dir, "takes", "quick", "video.manifest.json"), "utf8")); + assert.equal(qm.render.preset, undefined); + const qt = JSON.parse(await readFile(path.join(dir, "takes", "quick", "take.json"), "utf8")); + assert.equal(qt.quick, true); + assert.deepEqual(qt.changes, ["render.crf: 33 (was 30)"]); + } 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 }]]); + assert.deepEqual(parseRecipe({ quick: true, takes: [{ id: "a", label: "A" }, { id: "b", label: "B", quick: false }] }).takes.map((t) => t.quick), [true, false]); + + 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"); + // Picking it again is no write and no refusal: it already is the project's manifest. + const again = await pickTake(proj, "flash"); + assert.equal(again.snapshot, null); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), projectText); + + // 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/); + assert.ok(takeSteps(proj, { take: { label: "Q", quick: true } }, ctx).steps[0].argv.includes("--quick")); + 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,38 @@ 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, + quick: j.quick === true, }, }; } +/** @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 +225,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 +267,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 +333,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 +386,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 +399,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,11 @@ 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, + quick: false, }); const min = parseTake("x", { id: "x", group: "g", order: 0, label: "X", kind: "reference", preview: "p.mp4" }); assert.ok("take" in min); @@ -94,6 +99,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 +270,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 }); + } +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -22,6 +22,8 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // `next dev` in .next-e2e, no rebuild per edit // E2E_BUILD_CHECKED set below once the stamp was checked, so a // worker's load of this config does not check again +// E2E_UMTOOL_MONTAGE_STYLES set below on the app server: the montage styles +// module the take maker reads (release 33) // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); @@ -158,6 +160,10 @@ export default defineConfig({ // takes a second (onscreen.spec.ts). Its review stills use the system // chromium (CHROME, default /usr/bin/chromium), which is not stubbed. `HYPERFRAMES_BIN=${FIXTURE}/bin/hyperframes ` + + // The montage styles the Takes page offers (release 33): a stub module of + // report-to-video/montage-styles.mjs's shape, so takes.spec makes a take + // with a style whatever the real styles do. Read by lib/report/takeMaker.mjs. + `E2E_UMTOOL_MONTAGE_STYLES=${path.join(path.dirname(fileURLToPath(import.meta.url)), "e2e", "fixtures", "montage-styles.e2e.mjs")} ` + // Where a clip window is fetched FROM, and the shared secret it is asked // with. Set here rather than in a step's env: jobView() echoes a step's // env back to the browser, and this is a token. diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -28,6 +28,7 @@ "./factcheck": "./factcheck.mjs", "./frames-cut": "./frames-cut.mjs", "./ledger-totals": "./ledger-totals.mjs", + "./montage-styles": "./montage-styles.mjs", "./lint": "./lint.mjs", "./local-media": "./local-media.mjs", "./mute": "./mute.mjs",