commit 68417175f6dadf15713dd23189a7014d576d8fa2
parent ca0b02408b0e976e939c21b511ebf483d0720d91
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 28 Oct 2026 22:44:43 -0400
Merge lane/walk-take: walk a take on the clip bench -- drafts, the take's own edits with undo, promote to the cut
- manifest.mjs: patchClipEntry and applyStructural (with moveIn/removeIn),
updateClip's and the structural writers' rules over a manifest in memory.
- umtool take --draft (recorded, not rendered) and --promote [--anyway]
(the take's patch over the manifest through replaceManifest, one snapshot);
takeEdit.mjs writes walk edits into the take's patch.timeline with an undo
point per write; umtool walk, window --take, timeline --take.
- App: /projects/<p>/takes/<take>/walk and .../clip/<id>; every bench route
takes `take`; the bench's take strip; Takes page Walk / Render / Make this
the cut; GET /api/report/walk.
- Docs (clip-bench.md, report-video.md, cli.md, knobs.md), CHANGELOG, and
take-walk.spec.ts on its own fixture.
Conflicts, both sides' behaviour kept:
- umtool/app/api/report/fetch/route.ts: bench-prep's benchPrepAfterWrite
import and this lane's writePlayManifest import (the bodies auto-merged:
a take's fetch points the job at the take's play manifest, and the landed
window is queued for bench prep).
- umtool/lib/report/manifest.mjs: main's prepAfter/clipIdOf (bench prep after
a structural write) kept beside this lane's applyStructural/moveIn/removeIn;
updateClip now calls patchClipEntry and still queues bench prep on a moved
extent; structural() calls applyStructural.
- umtool/components/projects/TakesBench.tsx: imports fmtBytes (take-prune)
and takeWalkHref (this lane).
- umtool/docs/report-video.md: both new sections kept (a take's work files;
walking a take).
- editor/CHANGELOG.md: both sides' Unreleased bullets kept.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
43 files changed, 2684 insertions(+), 462 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A report-video take can be walked clip by clip before it is rendered, and made the cut.** Until now the clip bench walked only a project's own cut, and a take's clips could only be watched as a render. Now a take — a tight version's 27 sub-windows, say — opens on the bench at `/projects/<project>/takes/<take>/walk` (**Walk this take** on its card, or **walk a take** on the Cut tab): its clips in walk order with their verdicts, each played from the windows already fetched, with nothing fetched again for a clip inside one. Everything the walk changes — a verdict, a trim, a note, a clip removed or moved (**← earlier**, **later →**, **Remove from take**) — goes into the take's own patch in `takes/<take>/take.json`, never the project's manifest, and **Undo take edit** takes back the newest one. **walk every clip** keeps the clips that already carry a verdict on the walk. `umtool take <project> --id <take> --patch F --draft` records a take without rendering it (the Takes page shows it as **draft — walk / render**), and `umtool take <project> --id <take> --full` or **Render full** renders it later from its walked patch. **Make this the cut** (`umtool take <project> --id <take> --promote`) puts the take over the project's manifest with one undo point, so the Cut tab's **Undo last edit** takes it back; it waits for **Make it the cut anyway** when the take's timeline would replace a cut that changed since the take was made. From a terminal: `umtool walk <project> --take <take>`, `umtool window <project> <clip> --take <take> …` and `umtool timeline <project> --take <take> move|remove|undo`. A windowed render of a take whose timeline has none of the project's clips is now timed over the take's own clips instead of being refused. Needs a restart of umtool for the pages; the CLI has it at once.
- **A live stream can be transcribed and clipped while it is still recording.** Until now a recording was transcribed only once the stream ended and the file landed, so on a long stream nothing could be found or shared until hours later. `pnpm ops record-live` takes `"preclip": true` (or `{"everyMinutes": 10, "maxChunkMinutes": 20, "overlapSeconds": 15, "scan": true, "mine": true, "project": "<slug>"}`, defaults in `settings.livePreclip`). `pnpm ops live-preclip {"slug", "id"}` starts the same thing on a recording already running, and the video page's **Live pre-clip** panel has a Start button. Every few minutes a tick transcribes only what was recorded since the last one. It reads the growing file in place and never copies it or touches the recorder, whatever the recording is: one MPEG-TS, YouTube's separate video and audio, or Kick's polled VOD. The new span is transcribed on the transcription worker, with word timings, and added to `data/<id>/live-transcript.json`, marked provisional, on the clock the landed video will have. The clip finder then grows a umtool project for the stream (`<id>-live`), so its windows can be walked in the clip editor while the stream goes on. A busy worker never piles ticks up: the next tick takes everything since, and a tick that is far behind is followed by the next one at once. A tick is skipped, and the log says why, when there is under 30 s new, when the machine is under the 6 GB memory floor (checked again every minute), or when the store's disk has under 2 GB free. A recorder that restarts or falls back (Rumble) is followed. If its audio matches, the transcript goes on; if not, it starts again on the new recording and the project's windows are flagged. When the stream lands, the landed video is checked against what was transcribed live, and the windows stay where they are when it matches (flagged when it does not). Once the final transcript is there it replaces the live one, and the project reads the corpus from then on. `"action": "stop"`, `"status"` and `"finalize"` stop it (the recording goes on), print its state, and finish that hand-over by hand. **A clip of a stream still live can be shared at once:** `pnpm ops live-clip {"slug", "id", "start", "end"}`, the panel's **Share this clip**, or the clip editor's **Share now (live)** cuts the window from what is recorded so far and makes the clip's short with the live captions. A share is at most 2:20 and 512 MiB, for X, and nothing is fetched from the network. Needs a restart of the editor and umtool.
- **A reply can be captured with the post it answers above it.** `capture-posts` with `"thread": true` (X; or a channel's new `postCaptureThread`, or the Thread shot box under Capture posts on an X channel's page) also writes `shot-thread.png` beside the post's `shot.png`: the post it replies to over the reply, in the same page load — only the immediate parent, a longer chain cut to it. The parent is the post the archive says it answers; with no archive word, the post directly above it on the page; a post the archive says is no reply is not opened for it, and a post shot before gets only its thread shot. **The replied-to author is blurred** — avatar, name and handle, and any link to them in the reply — unless they carry an organisation's gold or a government's grey check, or are the reply's own author. X Premium's blue check is bought, so a blue-checked person is blurred like anyone else (the first live proof's parent was one). `"threadRedact": false` (or `{"<id>": false}`) takes it unblurred; a parent whose name cannot be found to blur gets no thread shot. capture.json records the parent, its badge and every blurred box. Proved on TheQuartering's reply 2114214000653414579. Needs a restart of the editor.
- **A report video can draw a reply with the post it answers.** A manifest post's `thread: true` draws its capture's `shot-thread.png` in place of its shot (its own shot while there is none) — set with `umtool posts set <project> <post> thread=on`, `umtool posts add … --thread`, or the **thread** box in the On-screen Posts table. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut. A cut with no thread shot renders byte for byte as before.
diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts
@@ -1,5 +1,6 @@
import path from "node:path";
-import { ensureWindowFile, resolveClip, segmentFor, windowsFor } from "@/lib/report/serve.mjs";
+import { ensureWindowFile, projectCache, resolveClip, segmentFor, windowsFor } from "@/lib/report/serve.mjs";
+import { takeToken } from "@/lib/report/takeEdit.mjs";
import { manifestToken } from "@/lib/report/manifest.mjs";
import { cuesInWindow, readClipDetail, siblingsOf } from "@/lib/projects/report.mjs";
@@ -15,15 +16,18 @@ export async function GET(request: Request) {
const url = new URL(request.url);
const projectId = url.searchParams.get("project") ?? "";
const clipId = url.searchParams.get("clip") ?? "";
+ // `take` (walk a take): the take's clip, and the TAKE's token -- its saves go into take.json.
+ const take = url.searchParams.get("take") || null;
- const r = await resolveClip(projectId, clipId);
+ const r = await resolveClip(projectId, clipId, { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const { project, manifest, clip } = r;
- const windows = await windowsFor(project, clip);
+ const windows = await windowsFor(project, clip, take ? await projectCache(project, manifest) : null);
// Re-read after a re-render: the segment lands on the SAME path, so its mtime
- // is what tells the player it is looking at a different file.
- const seg = await segmentFor(project, clipId);
+ // is what tells the player it is looking at a different file. A take's clip
+ // has none (the project's segments are the project's cut).
+ const seg = take ? null : await segmentFor(project, clipId);
const detail = await readClipDetail(project.dir, { manifest });
const entry = detail?.entries.find((e: { id: string }) => e.id === clipId) ?? null;
@@ -37,7 +41,7 @@ export async function GET(request: Request) {
? { from: widest.from, to: widest.to }
: { from: Math.max(0, clip.start - 20), to: clip.end + 20 };
- const cues = await cuesInWindow(project.dir, clipId, view.from, view.to);
+ const cues = await cuesInWindow(project.dir, clipId, view.from, view.to, { manifest });
return Response.json(
{
@@ -79,7 +83,7 @@ export async function GET(request: Request) {
// A record captured live has no length in its cues (`duration: 0`): unknown,
// not zero -- a zero here capped every drag at second 0.
sourceDuration: entry?.duration && entry.duration > 0 ? entry.duration : null,
- segment: seg?.rel ?? entry?.segment ?? null,
+ segment: take ? null : (seg?.rel ?? entry?.segment ?? null),
segmentMtime: seg?.mtimeMs ?? null,
sourceTitle: entry?.sourceTitleClean ?? null,
uploadDate: entry?.uploadDate ?? null,
@@ -92,7 +96,7 @@ export async function GET(request: Request) {
// is missing already in the cut, or is it a hole?
siblings: siblingsOf(manifest, clipId),
punctuationRate: cues?.punctuationRate ?? null,
- token: await manifestToken(project.dir),
+ token: take ? await takeToken(project.dir, take) : await manifestToken(project.dir),
fetchPad: manifest.render?.fetchPad ?? 3,
outLabel: path.posix.join(project.id, "out"),
},
diff --git a/umtool/app/api/report/cues/route.ts b/umtool/app/api/report/cues/route.ts
@@ -30,10 +30,12 @@ export async function GET(request: Request) {
return Response.json(got, { headers: { "cache-control": "no-store" } });
}
- const r = await resolveClip(projectId, clipId);
+ // `take` (walk a take): the take's clip.
+ const take = url.searchParams.get("take") || null;
+ const r = await resolveClip(projectId, clipId, { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
- const cues = await cuesInWindow(r.project.dir, clipId, from, to);
+ const cues = await cuesInWindow(r.project.dir, clipId, from, to, { manifest: r.manifest });
if (!cues) return Response.json({ error: "no cue file for this source" }, { status: 404 });
return Response.json(cues, { headers: { "cache-control": "no-store" } });
}
diff --git a/umtool/app/api/report/cut/route.ts b/umtool/app/api/report/cut/route.ts
@@ -1,5 +1,6 @@
import { withEditNotes } from "@/lib/report/guard";
import { StaleToken, updateClip } from "@/lib/report/manifest.mjs";
+import { updateTakeClip } from "@/lib/report/takeEdit.mjs";
import { cleanRespellings } from "yt-dlp-transcript-common/lib/citations/respell.mjs";
import { cuesInWindow } from "@/lib/projects/report.mjs";
import { resolveClip } from "@/lib/report/serve.mjs";
@@ -28,8 +29,10 @@ export async function POST(request: Request) {
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
const projectId = String(body.project ?? "");
const clipId = String(body.clip ?? "");
+ // `take` (walk a take): the take's clip, and the cut written into the take's patch.
+ const take = typeof body.take === "string" && body.take ? body.take : null;
- const r = await resolveClip(projectId, clipId);
+ const r = await resolveClip(projectId, clipId, { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const { project, clip, manifest } = r;
@@ -40,7 +43,7 @@ export async function POST(request: Request) {
);
}
- const doc = await cuesInWindow(project.dir, clipId, clip.start - LOOK, clip.end + LOOK);
+ const doc = await cuesInWindow(project.dir, clipId, clip.start - LOOK, clip.end + LOOK, { manifest });
if (!doc?.cues?.length) {
return Response.json(
{ error: "no cue file for this source, so there is nothing to match against", ok: false },
@@ -71,6 +74,15 @@ export async function POST(request: Request) {
}
try {
+ if (take) {
+ const res = await updateTakeClip(project.dir, take, clipId, { cutStart: hit.cutStart, cutEnd: hit.cutEnd }, {
+ token: body.token === undefined ? null : String(body.token),
+ });
+ return Response.json(
+ { ok: true, take, entry: res.entry, token: res.token, score: hit.score, matched: hit.matched },
+ { headers: { "cache-control": "no-store" } },
+ );
+ }
const { result: res, editNotes } = await withEditNotes(project, () =>
updateClip(
project.dir,
diff --git a/umtool/app/api/report/fetch/route.ts b/umtool/app/api/report/fetch/route.ts
@@ -8,6 +8,7 @@ import {
} from "@/lib/report/driver.mjs";
import { projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs";
import { benchPrepAfterWrite } from "@/lib/report/benchPrepTrigger.mjs";
+import { writePlayManifest } from "@/lib/report/takeManifest.mjs";
export const dynamic = "force-dynamic";
@@ -68,7 +69,12 @@ export async function POST(request: Request) {
);
}
- const r = await resolveClip(projectId, clipId);
+ // `take` (walk a take): the clip is the take's. The fetch scripts read a
+ // manifest by path, so the take's is written beside the project's (its play
+ // manifest, takeManifest.mjs) and the job is pointed at it. The bytes land
+ // where every fetch's do: they are the recording's, not the take's.
+ const take = typeof body.take === "string" && body.take ? body.take : null;
+ const r = await resolveClip(projectId, clipId, { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
// ASK THE CACHE FIRST.
@@ -138,11 +144,12 @@ export async function POST(request: Request) {
// corpus where the next report reuses them instead of paying again. Running
// yt-dlp from here has none of that, which is why it is now the opt-out
// (UMTOOL_LOCAL_FETCH=1) rather than the default.
+ const manifestPath = take ? await writePlayManifest(r.project.dir, take, r.manifest) : null;
const steps = wantFull
- ? editorFullSourceSteps(r.project, clipId, { manifest: r.manifest })
+ ? editorFullSourceSteps(r.project, clipId, { manifest: r.manifest, manifestPath })
: localFetch()
- ? fetchSteps(r.project, clipId, { padBefore, padAfter })
- : editorFetchSteps(r.project, clipId, { padBefore, padAfter, storedUrl });
+ ? fetchSteps(r.project, clipId, { padBefore, padAfter }, { manifestPath })
+ : editorFetchSteps(r.project, clipId, { padBefore, padAfter, storedUrl }, { manifestPath });
const job = startJob(
wantFull
? `fetch whole source ${projectId}/${clipId}`
diff --git a/umtool/app/api/report/peaks/route.ts b/umtool/app/api/report/peaks/route.ts
@@ -1,4 +1,4 @@
-import { absOf, ensureWindowFile, pickWindow, resolveClip, windowsFor } from "@/lib/report/serve.mjs";
+import { absOf, ensureWindowFile, pickWindow, projectCache, resolveClip, windowsFor } from "@/lib/report/serve.mjs";
import { ENV_RATE, analyseMedia } from "@/lib/media";
export const dynamic = "force-dynamic";
@@ -15,10 +15,12 @@ export const dynamic = "force-dynamic";
export async function GET(request: Request) {
const url = new URL(request.url);
- const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "");
+ // `take` (walk a take): the take's clip, its window as the take has it -- as /raw.
+ const take = url.searchParams.get("take") || null;
+ const r = await resolveClip(url.searchParams.get("project") ?? "", url.searchParams.get("clip") ?? "", { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
- const windows = await windowsFor(r.project, r.clip);
+ const windows = await windowsFor(r.project, r.clip, take ? await projectCache(r.project, r.manifest) : null);
const win = pickWindow(windows, url.searchParams.get("file"));
if (!win) return Response.json({ error: "no cached window for this clip" }, { status: 404 });
// A recording's excerpt is cut on first read (serve.mjs, "A RECORDING IS NOT A WINDOW").
diff --git a/umtool/app/api/report/takes/promote/route.ts b/umtool/app/api/report/takes/promote/route.ts
@@ -0,0 +1,44 @@
+import { invalidateProjects, projectRef } from "@/lib/projects";
+import { pieceHrefOfProject } from "@/lib/pieces/article";
+import { refuseCaller } from "@/lib/report/caller";
+import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
+import { PromoteStale, promoteTake } from "@/lib/report/takeEdit.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+
+export const dynamic = "force-dynamic";
+
+// "MAKE THIS THE CUT" (walk a take). POST { project, take, anyway? }
+//
+// The take's manifest -- the project's as it is now with the take's patch
+// applied, walked edits and all -- over the project's, through the manifest
+// writer (replaceManifest: ONE auto snapshot `auto-before-promote-take`, so
+// the Cut tab's "Undo last edit" takes the whole promotion back) inside the
+// edit-notes guard; then the take's group's pick in takes/verdicts.json.
+// The CLI twin is `umtool take <p> --id <take> --promote [--anyway]`.
+//
+// Not "Use this take" (/api/report/takes/pick), which copies the manifest a
+// take was RENDERED from: this applies its patch now, so a draft promotes.
+//
+// 409 `{ stale: true }` when the take replaces the timeline and the project's
+// manifest changed since the take was made, until `anyway`.
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/takes/promote");
+ if (refused) return refused;
+ 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 promoteTake(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 PromoteStale) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ 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/app/api/report/takes/timeline/route.ts b/umtool/app/api/report/takes/timeline/route.ts
@@ -0,0 +1,52 @@
+import { projectRef } from "@/lib/projects";
+import { refuseCaller } from "@/lib/report/caller";
+import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
+import { moveTakeEntry, removeTakeEntry, undoTakeEdit } from "@/lib/report/takeEdit.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A TAKE'S TIMELINE, walked (lib/report/takeEdit.mjs; the CLI twin is
+// `umtool timeline <p> --take <id> move|remove|undo`). The writes go into the
+// take's patch (takes/<id>/take.json), each with an undo point of the take's
+// own; the project's manifest is never written here.
+//
+// POST { project, take, token?, op, ... }
+// move { id, toIndex, at? } toIndex is the index AFTER the move
+// remove { id, at? }
+// undo {} the take's newest edit taken back
+//
+// A stale token is a 409; a structure the build would refuse is a 400 with its sentences.
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/takes/timeline");
+ if (refused) return refused;
+ 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 });
+ 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 });
+ const take = body.take;
+ const token = body.token === undefined || body.token === null ? null : String(body.token);
+ const at = body.at === undefined || body.at === null ? null : Number(body.at);
+ const id = typeof body.id === "string" ? body.id : "";
+ try {
+ let r: Record<string, unknown>;
+ if (body.op === "move") {
+ if (!id) return Response.json({ error: "move needs an id" }, { status: 400 });
+ r = await moveTakeEntry(project.dir, take, id, Number(body.toIndex), { token, at });
+ } else if (body.op === "remove") {
+ if (!id) return Response.json({ error: "remove needs an id" }, { status: 400 });
+ r = await removeTakeEntry(project.dir, take, id, { token, at });
+ } else if (body.op === "undo") {
+ r = await undoTakeEdit(project.dir, take, { token });
+ } else {
+ return Response.json({ error: "op must be move, remove or undo" }, { status: 400 });
+ }
+ return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ 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/app/api/report/walk/route.ts b/umtool/app/api/report/walk/route.ts
@@ -0,0 +1,28 @@
+import { projectRef } from "@/lib/projects";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { walkJson, walkOf } from "@/lib/report/walkData.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE WALK, as data (lib/report/walkData.mjs -- what the bench page and
+// `umtool walk` read): every clip in walk order with its verdict, whether a
+// fetched file holds it, and which ones the walk visits.
+//
+// GET ?project=<id>[&take=<take>][&all=1]
+// take: walk a take -- the project's manifest with the take's patch applied
+// (a draft too); `token` is then the take's (its saves go into take.json)
+// all: the walk visits every fetched clip, judged or not
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(url.searchParams.get("project") ?? "");
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ const take = url.searchParams.get("take") || null;
+ if (take !== null && !isTakeId(take)) return Response.json({ error: "take must be a take id" }, { status: 400 });
+ try {
+ const w = await walkOf(project, { take, all: url.searchParams.get("all") === "1" });
+ return Response.json(walkJson(w), { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e);
+ return Response.json({ error: message }, { status: /^no take |no video\.manifest/.test(message) ? 404 : 400 });
+ }
+}
diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts
@@ -1,5 +1,6 @@
import { withEditNotes } from "@/lib/report/guard";
import { StaleToken, updateClip } from "@/lib/report/manifest.mjs";
+import { updateTakeClip } from "@/lib/report/takeEdit.mjs";
import { resolveClip } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
@@ -27,7 +28,10 @@ export async function PUT(request: Request) {
const projectId = String(body.project ?? "");
const clipId = String(body.clip ?? "");
- const r = await resolveClip(projectId, clipId);
+ // `take` (walk a take): the clip is the TAKE's, and the save goes into the
+ // take's patch (lib/report/takeEdit.mjs) -- never the project's manifest.
+ const take = typeof body.take === "string" && body.take ? body.take : null;
+ const r = await resolveClip(projectId, clipId, { take });
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
// The whitelist, mirrored from lib/report/manifest.mjs so a field nobody
@@ -67,6 +71,15 @@ export async function PUT(request: Request) {
if (!Object.keys(patch).length) return Response.json({ error: "nothing to change" }, { status: 400 });
try {
+ if (take) {
+ const res = await updateTakeClip(r.project.dir, take, clipId, patch, {
+ token: body.token === undefined ? null : String(body.token),
+ });
+ return Response.json(
+ { ok: true, take, entry: res.entry, before: res.before, token: res.token, revision: res.revision.rel },
+ { headers: { "cache-control": "no-store" } },
+ );
+ }
const { result: res, editNotes } = await withEditNotes(r.project, () =>
updateClip(r.project.dir, clipId, patch, {
token: body.token === undefined ? null : String(body.token),
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -23,6 +23,8 @@
// [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q]
// [--correction TEXT] [--verdict confirmed|incorrect|'']
// [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent
+// [--take <id>] a take's clip: the edit goes into the take's patch (walk a take)
+// umtool walk <project> [--take <id>] [--all] [--json] the walk: clips in walk order, verdicts, fetched
// umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label,
// marks=<json> mark.add=<verdict>[@<sec>] mark.remove=<id> mark.verdict=<v> [--mark <id>],
// audio.offset|gain|fadeIn|fadeOut (`key=` clears) (docs/knobs.md)
@@ -56,6 +58,7 @@
// 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] [--from TAKE] [--keep-frames] | --id <id> --rebuild make one take
+// [--draft] record it without rendering (walk it first) · --id <id> --promote [--anyway] make it the cut
// umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]
// umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3]
// [--out NAME] [--dry-run] [--json] a trailer cut from the take's finished master
@@ -77,6 +80,7 @@
// umtool timeline <project> [ls | insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--title …]
// [--date …] [--quote …] [--cite S] | move <id> --to <index> | remove <id> | duplicate <id> |
// post <json|@file> | post-remove <id> | teaser <id> <patch-json> | undo] the cut's structure
+// [--take <id>] ls | move | remove | undo on a take's timeline (its patch, not the manifest)
// umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--json] cuts + black spans, source seconds
// umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag …] [--thread] a post from the archive
// set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] the Posts table's writer
@@ -727,6 +731,10 @@ function usage() {
" --verdict confirmed|incorrect what the walk said; incorrect needs --correction",
" --cut-start S --cut-end E --lock-cut the cut the video renders",
" an empty value (--title '') deletes the field",
+ " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's",
+ " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched",
+ " umtool walk <project> [--take <id>] [--all] [--json] the clip bench's walk: every clip in walk order,",
+ " its verdict, fetched or not, and (→) the ones the walk visits; --take walks a take (a draft too)",
" umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):",
" claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp",
" claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]",
@@ -777,6 +785,10 @@ function usage() {
" 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;",
" --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)",
+ " --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later",
+ " (`umtool take <p> --id <id> --full` renders a draft from its stored patch)",
+ " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
+ " manifest, one undo point (revisions/…-auto-before-promote-take)",
" umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
" umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
" a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
@@ -817,6 +829,8 @@ function usage() {
" umtool timeline <project> post <json|@file> | post-remove <id> | teaser <id> <patch-json|@file> | undo",
" the Cut tab's structure (POST /api/report/timeline's writers): each write snapshots the",
" manifest first (revisions/…-auto-before-<op>), is checked by the build, notes a generated cut",
+ " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:",
+ " the writes go into its patch (takes/<id>/take.json), each with an undo point of its own",
" umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 | --from S --to S] [--json]",
" scene cuts (scdet) and black spans (blackdetect) in the clip's fetched window, in SOURCE",
" seconds — for blur.from/blur.to and trims; nothing fetched (`umtool fetch` first)",
@@ -847,6 +861,8 @@ async function settled(code) {
const COMMANDS = {
ls: cmdLs,
window: cmdWindow,
+ // The clip bench's walk, of the cut or of a take (walk a take): lib/report/walkCli.mjs.
+ walk: async () => process.exit(await (await import("../lib/report/walkCli.mjs")).walkCommand(argv.slice(argv.indexOf("walk") + 1))),
link: cmdLink,
// The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs.
set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))),
@@ -985,6 +1001,26 @@ async function cmdWindow() {
}
if (!Object.keys(patch).length) die("nothing to change");
+ // --take <id>: the clip is the TAKE's (walk a take), and the edit goes into
+ // the take's patch (takes/<id>/take.json) through the walk's writer -- the
+ // same rules, an undo point first -- never into the project's manifest.
+ const take = val("--take");
+ if (take !== undefined) {
+ try {
+ const { updateTakeClip } = await import("../lib/report/takeEdit.mjs");
+ const res = await updateTakeClip(p.dir, take, clipId, patch);
+ if (json) return out({ ok: true, take, ...res });
+ console.log(`${clipId} (take ${take}): ${res.before.start}–${res.before.end} -> ${res.entry.start}–${res.entry.end}`);
+ if (res.entry.cutStart != null) console.log(` cut: ${res.entry.cutStart}–${res.entry.cutEnd}`);
+ if (patch.verdict !== undefined || patch.correction !== undefined) console.log(` review: ${clipVerdict(res.entry)}`);
+ if (res.entry.correction) console.log(` correction: ${res.entry.correction}`);
+ console.log(` undo point: takes/${take}/${res.revision.rel} (umtool timeline ${p.id} --take ${take} undo)`);
+ return;
+ } catch (e) {
+ die(e?.message ?? String(e));
+ }
+ }
+
try {
// Through the SAME writer the bench uses: 2 dp, the CLI's own formatting,
// tmp+rename, one .bak. A second implementation here is how the two would
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -19,6 +19,7 @@ import { BenchBody, VerdictBar } from "./bench/BenchShell";
import CopyCitation from "./bench/CopyCitation";
import EdgeStrip from "./bench/EdgeStrip";
import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts";
+import TakeWalkStrip from "./bench/TakeWalkStrip";
// The renderer's own line, imported rather than re-written. A preview that
// disagrees with the header by a character is worth less than no preview: you
// would only find out twenty minutes into a build.
@@ -284,6 +285,31 @@ export type ClipBenchData = {
* if one was (its render does not change when this manifest does).
*/
fromPlay?: { href: string; take: string | null } | null;
+ /**
+ * WALKING A TAKE (/projects/<p>/takes/<take>/clip/<id>): the clip is the
+ * take's -- the project's manifest with the take's patch applied -- and
+ * every save goes into the take's patch (takes/<id>/take.json), never the
+ * project's manifest. Every route this bench calls is asked with `take`.
+ * `all`: the walk visits every fetched clip, judged or not.
+ */
+ take?: {
+ id: string;
+ label: string;
+ draft: boolean;
+ /** take.json exists, so there is somewhere for an edit to land (a recipe-only take is read only). */
+ editable: boolean;
+ all: boolean;
+ /** The Takes page, and this walk's own start (with `all` as it is). */
+ takesHref: string;
+ walkHref: string;
+ /** The same clip on the walk of every clip / of the unjudged ones. */
+ toggleAllHref: string;
+ /** Clip id -> its bench address on this take's walk (siblings link through it). */
+ clipHref: Record<string, string>;
+ /** This clip's index in the take's timeline, and the timeline's length (the strip's moves). */
+ at: number;
+ entries: number;
+ } | null;
};
const hms = (t: number) => {
@@ -332,6 +358,8 @@ type UndoRec = {
before: Record<string, unknown>;
/** The Confirm carried a moved window, so Undo puts the edges back too. */
moved: boolean;
+ /** Walking a take: the take the Confirm was written into. */
+ take?: string | null;
};
const readUndo = (): UndoRec | null => {
try {
@@ -460,6 +488,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// The project's notes: this clip's row notes, and the edit notes a save on a
// generated manifest leaves (the save says so, and they are re-read).
const notes = useSharedNotes({ project: data.project });
+ // Walking a take: every route is asked about the TAKE's clip, and every
+ // save lands in the take's patch (see ClipBenchData.take).
+ const takeId = data.take?.id ?? null;
+ const tq = takeId ? `&take=${encodeURIComponent(takeId)}` : "";
+ const takeBody = takeId ? { take: takeId } : {};
const [clip, setClip] = useState<Clip>(data.clip);
const [windows, setWindows] = useState<Win[]>(data.windows);
const [cues, setCues] = useState<Cue[]>(data.cues);
@@ -468,7 +501,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const [sel, setSel] = useState({ from: data.clip.start, to: data.clip.end });
// Where the render will actually cut the drafted selection (bench/RenderGhosts.tsx): the
// desk's waveform and the phone's edge strip both draw it.
- const renderEdges = useRenderEdges(data.project, clip, sel);
+ const renderEdges = useRenderEdges(data.project, clip, sel, takeId);
// The mute mark as drafted. Like the edges it is unsaved until `save window`
// or `y`, and it is what the bench's own playback mutes at -- so a mark is
// heard before it is written.
@@ -613,10 +646,10 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
} catch {
/* nothing to clear */
}
- if (u.project !== data.project || (u.next !== data.clip.id && u.clip !== data.clip.id)) return;
+ if (u.project !== data.project || (u.take ?? null) !== takeId || (u.next !== data.clip.id && u.clip !== data.clip.id)) return;
if (Date.now() - u.at >= UNDO_MS) return;
setUndo(u);
- }, [data.project, data.clip.id]);
+ }, [data.project, data.clip.id, takeId]);
useEffect(() => {
if (!undo) return;
const id = window.setTimeout(() => setUndo(null), Math.max(0, undo.at + UNDO_MS - Date.now()));
@@ -648,7 +681,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
let live = true;
void (async () => {
const r = await fetch(
- `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}`,
+ `/api/report/peaks?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}`,
{ cache: "no-store" },
);
if (!r.ok || !live) return;
@@ -657,7 +690,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
return () => {
live = false;
};
- }, [cached, data.project, clip.id]);
+ }, [cached, data.project, clip.id, tq]);
// Follow the playhead in the reading pane, and ONLY while something is
// playing: scrolling the words out from under somebody who is reading ahead
@@ -685,7 +718,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
void (async () => {
const r = await fetch(
`/api/report/cues?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` +
- `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}`,
+ `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}${tq}`,
{ cache: "no-store" },
);
if (!r.ok || !live) return;
@@ -695,7 +728,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
return () => {
live = false;
};
- }, [data.project, clip.id, view.from, view.to, peekPad]);
+ }, [data.project, clip.id, view.from, view.to, peekPad, tq]);
// ---- playback preferences ------------------------------------------------
useEffect(() => setPlayback(readPlayback()), []);
@@ -868,7 +901,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
setAudio({ state: "loading" });
const r = await fetch(
`/api/report/audio?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` +
- `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}`,
+ `&file=${encodeURIComponent(cached.name)}&from=${span.from}&to=${span.to}${tq}`,
);
if (!r.ok) {
const j = (await r.json().catch(() => null)) as { error?: string } | null;
@@ -1345,7 +1378,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const r = await fetch("/api/report/window", {
method: "PUT",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current, ...patch }),
+ body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current, ...patch }),
});
const j = (await r.json()) as Record<string, unknown>;
lastSaved.current = j;
@@ -1522,7 +1555,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// A verdict is a state change, and a thumb lands where it did not mean to.
const before = (lastSaved.current?.before ?? null) as Record<string, unknown> | null;
if (before) {
- const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win };
+ const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win, take: takeId };
try {
sessionStorage.setItem(UNDO_KEY, JSON.stringify(rec));
} catch {
@@ -1543,7 +1576,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
async (u: UndoRec) => {
setUndo(null);
const b = u.before;
- const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}`, {
+ const uq = u.take ? `&take=${encodeURIComponent(u.take)}` : "";
+ const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}${uq}`, {
cache: "no-store",
});
if (!r.ok) {
@@ -1562,11 +1596,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const w = await fetch("/api/report/window", {
method: "PUT",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project: u.project, clip: u.clip, token: tok, ...patch }),
+ body: JSON.stringify({ project: u.project, clip: u.clip, ...(u.take ? { take: u.take } : {}), token: tok, ...patch }),
});
const j = (await w.json()) as Record<string, unknown>;
if (!w.ok) {
- setNote(j.stale ? "could not undo: the manifest changed since — reload" : `could not undo: ${String(j.error ?? w.status)}`);
+ setNote(j.stale ? `could not undo: the ${u.take ? "take" : "manifest"} changed since — reload` : `could not undo: ${String(j.error ?? w.status)}`);
return;
}
if (wroteNotes(j)) void notes.reload();
@@ -1586,7 +1620,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const q = new URLSearchParams(window.location.search);
q.delete("at");
const qs = q.toString();
- router.push(`/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`);
+ router.push(
+ u.take
+ ? `/projects/${u.project}/takes/${encodeURIComponent(u.take)}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`
+ : `/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`,
+ );
},
// `notes.reload` is the stable part of `notes`.
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1832,7 +1870,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const refresh = useCallback(async (): Promise<ClipBenchData | null> => {
const r = await fetch(
- `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}`,
+ `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`,
{ cache: "no-store" },
);
if (!r.ok) return null;
@@ -1875,6 +1913,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
body: JSON.stringify({
project: data.project,
clip: clip.id,
+ ...takeBody,
padBefore: round2(pads.padBefore),
padAfter: round2(pads.padAfter),
...storedAsk,
@@ -1945,7 +1984,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const r = await fetch("/api/report/fetch", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project: data.project, clip: clip.id, full: true }),
+ body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, full: true }),
});
if (!r.ok) {
const j = (await r.json()) as { error?: string };
@@ -2032,7 +2071,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const r = await fetch("/api/report/cut", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current }),
+ body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current }),
});
const j = (await r.json()) as {
ok?: boolean;
@@ -2176,7 +2215,8 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const padLabelForCue = (c: Cue) =>
c.end > view.to ? `+${padsForCue(c).padAfter} s` : `−${padsForCue(c).padBefore} s`;
- const segSrc = segment
+ // A take's clip has no segment of the project's (ClipBenchPage passes none).
+ const segSrc = segment && !takeId
? `/api/report/segment?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&v=${segmentMtime ?? 0}`
: null;
@@ -2822,11 +2862,24 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
{/* On a phone the banner is one muted line under Notes (phoneNotesHead).
The wrapper only when there is a banner: an empty one would be a
flex item, and a gap, on the desk. */}
- {data.generatedBy && (
+ {data.generatedBy && !data.take && (
<div className="max-md:hidden">
<GeneratedBanner generatedBy={data.generatedBy} />
</div>
)}
+ {/* Walking a take: what is being walked, where the edits go, and the take's own structure. */}
+ {data.take && (
+ <TakeWalkStrip
+ className="max-md:order-[22]"
+ project={data.project}
+ take={data.take}
+ clipId={clip.id}
+ index={data.take.at}
+ total={data.take.entries}
+ nextHref={hrefOf("next")}
+ getToken={() => token.current}
+ />
+ )}
{/* ---- where you are, where you can go, and what will be burned in ---- */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents">
{/* On a phone both counts are the place bar's `50/51` and its hairline. */}
@@ -2890,7 +2943,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
<video
ref={video}
data-testid="clip-video"
- src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}`}
+ src={`/api/report/raw?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&file=${encodeURIComponent(cached.name)}${tq}`}
// object-contain, because the height is now whatever is left
// rather than whatever 16:9 asks for.
// The picture and the words SHARE what is left, 3:2, rather
@@ -3555,20 +3608,33 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
nothing rendered for this clip yet
</div>
)}
- <button
- type="button"
- data-rerender=""
- className={buttonVariants({ variant: "outline", size: "sm" })}
- disabled={!!busy}
- onClick={() => void rerender()}
- >
- Re-render this clip
- </button>
- <p className="text-[11px] leading-snug text-[var(--color-dim)]">
- One clip, no crossfade, no chapters — it overwrites this clip’s segment and
- nothing else. The header is drawn by ffmpeg from a text file, so this is the only
- place the line above can be checked rather than believed.
- </p>
+ {data.take ? (
+ // The one-clip render builds the PROJECT's segment; a take is rendered whole.
+ <p data-take-no-rerender="" className="text-[11px] leading-snug text-[var(--color-dim)]">
+ A take is rendered as a whole, from its own patch:{" "}
+ <Link href={data.take.takesHref} className="ink-link">
+ Render on the Takes page
+ </Link>{" "}
+ or <code className="font-mono">umtool take {data.project} --id {data.take.id} --full</code>.
+ </p>
+ ) : (
+ <>
+ <button
+ type="button"
+ data-rerender=""
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ disabled={!!busy}
+ onClick={() => void rerender()}
+ >
+ Re-render this clip
+ </button>
+ <p className="text-[11px] leading-snug text-[var(--color-dim)]">
+ One clip, no crossfade, no chapters — it overwrites this clip’s segment and
+ nothing else. The header is drawn by ffmpeg from a text file, so this is the only
+ place the line above can be checked rather than believed.
+ </p>
+ </>
+ )}
</div>
{/* ---- lock, explained rather than labelled ---- */}
@@ -3662,7 +3728,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
{siblings.map((sb) => (
<li key={sb.id} data-sibling={sb.id} className="leading-snug">
<Link
- href={`/projects/${data.project}/clip/${sb.id}`}
+ href={data.take?.clipHref[sb.id] ?? `/projects/${data.project}/clip/${sb.id}`}
className="font-mono ink-link"
>
{sb.id}
diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx
@@ -1,17 +1,15 @@
import { notFound } from "next/navigation";
-import { projectsHref, clipBenchHref, playHref } from "@/lib/hrefs";
+import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs";
import { BenchFrame, BenchTop } from "./bench/BenchShell";
import ClipBench, { type ClipBenchData } from "./ClipBench";
-import { manifestToken } from "@/lib/report/manifest.mjs";
import {
clipVerdict,
cuesInWindow,
- readClipDetail,
- readManifest,
siblingsOf,
walkOrder,
walkReadiness,
} from "@/lib/projects/report.mjs";
+import { walkNeighbours, walkOf } from "@/lib/report/walkData.mjs";
import { projectCache, segmentFor, windowsFor } from "@/lib/report/serve.mjs";
import { FETCH_MAX_PAD } from "@/lib/report/driver.mjs";
import { deckOn } from "umtool-report-to-video/deck";
@@ -26,16 +24,28 @@ export default async function ClipBenchPage({
project,
clipId,
search = {},
+ take = null,
}: {
project: ProjectRef;
clipId: string;
search?: Record<string, string | undefined>;
+ /**
+ * WALKING A TAKE (`/projects/<p>/takes/<take>/clip/<id>`): the clip is the
+ * take's -- the project's manifest with the take's patch applied
+ * (lib/report/walkData.mjs) -- and the bench's saves go into the take.
+ */
+ take?: string | null;
}) {
- const manifest = await readManifest(project.dir);
- if (!manifest) notFound();
-
- const detail = await readClipDetail(project.dir, { manifest });
- if (!detail) notFound();
+ // `?all=1`: the walk visits every fetched clip, judged or not.
+ const all = search.all === "1";
+ let walk: Awaited<ReturnType<typeof walkOf>>;
+ try {
+ walk = await walkOf(project, { take, all });
+ } catch {
+ notFound();
+ }
+ const manifest = walk.manifest;
+ const detail = walk.detail;
const entry = detail.entries.find(
(e: { id: string; kind: string }) => e.id === clipId && e.kind === "clip",
);
@@ -53,26 +63,24 @@ export default async function ClipBenchPage({
// judge and the only move is to press `n` again -- and one already answered is
// the round trip a walk exists to remove. A URL still opens ANY clip: this
// page renders it, says what it has (or has not) got, and points its links at
- // the fetched, unjudged neighbours on either side.
+ // the fetched, unjudged neighbours on either side. (walkData.mjs, the
+ // reading `umtool walk` prints; `all` keeps the judged ones on it too.)
const readiness = walkReadiness(clips);
- const inWalk = new Set<string>(readiness.readyIds as string[]);
- const onWalk = (e: { id: string }) => e.id !== clipId && inWalk.has(e.id);
- const prev =
- [...clips.slice(0, Math.max(0, i))].reverse().find(onWalk)?.id ?? null;
- const next = clips.slice(i + 1).find(onWalk)?.id ?? null;
+ const { prev, next } = walkNeighbours(walk.order, walk.onWalk, clipId);
// One listing of clips-raw for the page: readClipDetail already built one to
// answer `fetched` for every clip, and this is the same question for this one.
- const windows = await windowsFor(project, entry, await projectCache(project));
+ const windows = await windowsFor(project, entry, await projectCache(project, manifest));
// The mtime rides along so a re-render busts the browser's cache: the segment
// is written back to the SAME path, and without it the player would keep
- // showing the cut from before the edit.
- const seg = await segmentFor(project, clipId);
+ // showing the cut from before the edit. A take's clip has none: the
+ // project's segments are the project's cut.
+ const seg = take ? null : await segmentFor(project, clipId);
const widest = windows[0] ?? null;
const view = widest
? { from: widest.from, to: widest.to }
: { from: Math.max(0, entry.start - 20), to: entry.end + 20 };
- const cues = await cuesInWindow(project.dir, clipId, view.from, view.to);
+ const cues = await cuesInWindow(project.dir, clipId, view.from, view.to, { manifest });
const data: ClipBenchData = {
project: project.id,
@@ -123,7 +131,7 @@ export default async function ClipBenchPage({
endsSentence: entry.endsSentence ?? null,
noPunctuation: !!entry.noPunctuation,
sourceDuration: entry.duration ?? null,
- segment: seg?.rel ?? entry.segment ?? null,
+ segment: take ? null : (seg?.rel ?? entry.segment ?? null),
segmentMtime: seg?.mtimeMs ?? null,
// What the header would say with no overrides. Shown beside the fields that
// replace it, because "the archive says 2019" is the whole reason `date`
@@ -147,7 +155,8 @@ export default async function ClipBenchPage({
).length,
cues: cues?.cues ?? [],
siblings: siblingsOf(manifest, clipId),
- token: await manifestToken(project.dir),
+ // The project's manifest token, or -- walking a take -- the take's.
+ token: walk.token,
fetchPad: manifest.render?.fetchPad ?? 3,
// The widest the fetch route will go. The BUTTON has to know it: it names
// the pad it will ask for, and "that is as wide as it goes" is a different
@@ -171,7 +180,8 @@ export default async function ClipBenchPage({
};
// The piece this view belongs to: the article's when an article claims the project (P4a-2).
- const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+ // Walking a take, Back is the take's walk (its overview), on the Takes page's side.
+ const back = take ? takeWalkHref(project.id, take, { all }) : await pieceHrefOfProject(project.id, { tab: "cut" });
// ---- opened from Play the cut ("Edit this clip") --------------------------
//
// `?from=play` rides every walk link from here (p / n / Confirm's advance),
@@ -181,17 +191,34 @@ export default async function ClipBenchPage({
// everything after this clip. A take's render does not change when the
// project's manifest does, so a take's Back is the project's cut too, and
// the bench says so (`take`).
- const fromPlay = search.from === "play";
+ const fromPlay = !take && search.from === "play";
const playTake = fromPlay && search.take ? search.take : null;
const atRaw = Number(search.at);
const at = fromPlay && Number.isFinite(atRaw) && atRaw > 0 ? atRaw : 0;
- const href = (id: string) => clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {});
+ const href = (id: string) =>
+ take ? takeClipHref(project.id, take, id, { all }) : clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {});
data.walkHrefs = {
prev: prev ? href(prev) : null,
next: next ? href(next) : null,
back,
- backLabel: project.name,
+ backLabel: take ? `take ${take}` : project.name,
};
+ if (take && walk.take) {
+ const timeline = (manifest.timeline ?? []) as { id: string }[];
+ data.take = {
+ id: take,
+ label: walk.take.label,
+ draft: walk.take.draft,
+ editable: walk.take.editable,
+ all,
+ takesHref: takesHref(project.id),
+ walkHref: takeWalkHref(project.id, take, { all }),
+ toggleAllHref: takeClipHref(project.id, take, clipId, { all: !all }),
+ clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all })])),
+ at: timeline.findIndex((e) => e.id === clipId),
+ entries: timeline.length,
+ };
+ }
data.fromPlay = fromPlay ? { href: playHref(project.id, { clip: clipId, at }), take: playTake } : null;
return (
// The bench shell (P4b): its top bar here, the body -- the work, the
@@ -200,9 +227,13 @@ export default async function ClipBenchPage({
kind="clip"
top={
<BenchTop
- trail={[{ href: projectsHref(), label: "Projects" }]}
- back={{ href: back, label: project.name }}
- kind="Clip bench"
+ trail={
+ take
+ ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }]
+ : [{ href: projectsHref(), label: "Projects" }]
+ }
+ back={{ href: back, label: take ? `take ${take}` : project.name }}
+ kind={take ? "Take walk" : "Clip bench"}
here={clipId}
// The walk on a phone draws its own place bar (ClipBench).
phone="hidden"
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -11,6 +11,8 @@ import NarrationPage from "./NarrationPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
import PlayCutPage from "./PlayCutPage";
+import TakeWalkPage from "./TakeWalkPage";
+import { isTakeId } from "@/lib/report/takes.mjs";
// ---------------------------------------------------------------------------
// The one place a kind id is matched against a component.
@@ -58,6 +60,14 @@ export default async function ProjectView({
// `/browse/<project>/takes` -- alternative renders of one part of the
// cut, side by side, each judged like / maybe / no.
if (rest.length === 1 && rest[0] === "takes") return <TakesPage project={project} />;
+ // `/projects/<project>/takes/<take>/walk` -- walk a take: its clips, and
+ // where the walk starts; `…/takes/<take>/clip/<id>` -- the bench on one
+ // of them, its saves going into the take's patch, never the manifest.
+ if (rest.length === 3 && rest[0] === "takes" && rest[2] === "walk") return <TakeWalkPage project={project} take={rest[1]} search={search} />;
+ if (rest.length === 4 && rest[0] === "takes" && rest[2] === "clip") {
+ if (!isTakeId(rest[1])) return notFound();
+ return <ClipBenchPage project={project} clipId={rest[3]} take={rest[1]} search={search} />;
+ }
// `/browse/<project>/narration` -- the narration script, card by card,
// approved / edited / rejected before synthesis.
if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />;
diff --git a/umtool/components/projects/TakeActions.tsx b/umtool/components/projects/TakeActions.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { buttonVariants } from "@/components/ui/button";
+import { startTakeJob } from "./NewTakePanel";
+
+// What a take offers once it can be walked (walk a take): walk it, render it
+// (a draft's first render, or a walked take's again), and make it the cut.
+// The Takes page's cards and the take's walk page both draw this; each button
+// is the CLI's own command run the app's way:
+//
+// Render full / Render 60 s POST /api/report/takes/make { rebuild, window }
+// = umtool take <p> --id <t> --rebuild [--full | --at 0 --dur 60]
+// Make this the cut POST /api/report/takes/promote
+// = umtool take <p> --id <t> --promote [--anyway]
+
+export default function TakeActions({
+ project,
+ take,
+ draft,
+ walkHref,
+ edited,
+ compact = false,
+}: {
+ project: string;
+ take: string;
+ draft: boolean;
+ walkHref: string | null;
+ /** Edited by the walk since its render (or never rendered). */
+ edited: boolean;
+ compact?: boolean;
+}) {
+ const router = useRouter();
+ const [ready, setReady] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<string | null>(null);
+ const [stale, setStale] = useState<string | null>(null);
+ const [done, setDone] = useState<string | null>(null);
+ useEffect(() => setReady(true), []);
+
+ const render = async (window: "full" | { at: number; dur: number }) => {
+ setBusy(true);
+ setSaid(null);
+ const r = await startTakeJob({ project, rebuild: take, window });
+ setBusy(false);
+ setSaid(r.error ?? "rendering — the job is on the jobs bar");
+ };
+ const promote = async (anyway: boolean) => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const r = await fetch("/api/report/takes/promote", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, take, anyway }),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean; historyHref?: string; clips?: number };
+ if (r.status === 409 && j.stale) setStale(j.error ?? "the project changed since this take was made");
+ else if (!r.ok) setSaid(j.errors?.join("; ") ?? j.error ?? `HTTP ${r.status}`);
+ else {
+ setStale(null);
+ setDone(j.historyHref ?? "");
+ router.refresh();
+ }
+ } finally {
+ setBusy(false);
+ }
+ };
+ const off = !ready || busy;
+ const size = compact ? "sm" : "md";
+ return (
+ <div data-take-actions={take} className="flex flex-wrap items-center gap-1.5 text-[11.5px]">
+ {walkHref && (
+ <Link href={walkHref} data-take-walk-link={take} className={buttonVariants({ variant: draft ? "go" : "outline", size })}>
+ Walk this take
+ </Link>
+ )}
+ <button
+ type="button"
+ data-take-render="full"
+ disabled={off}
+ className={buttonVariants({ variant: "outline", size })}
+ title={`umtool take ${project} --id ${take} --rebuild --full`}
+ onClick={() => void render("full")}
+ >
+ {draft ? "Render full" : edited ? "Render again (full)" : "Render full"}
+ </button>
+ <button
+ type="button"
+ data-take-render="window"
+ disabled={off}
+ className={buttonVariants({ variant: "quiet", size })}
+ title={`umtool take ${project} --id ${take} --rebuild --at 0 --dur 60`}
+ onClick={() => void render({ at: 0, dur: 60 })}
+ >
+ Render the first 60 s
+ </button>
+ <button
+ type="button"
+ data-take-promote=""
+ disabled={off}
+ className={buttonVariants({ size })}
+ title={`the take's patch over the project's manifest, one undo point — umtool take ${project} --id ${take} --promote`}
+ onClick={() => void promote(false)}
+ >
+ Make this the cut
+ </button>
+ {stale && (
+ <span data-take-promote-stale="" className="flex basis-full flex-wrap items-center gap-1.5 text-doubt-text">
+ <span>{stale}.</span>
+ <button type="button" data-take-promote-anyway="" disabled={off} className={buttonVariants({ size: "sm" })} onClick={() => void promote(true)}>
+ Make it the cut anyway
+ </button>
+ </span>
+ )}
+ {done !== null && (
+ <span data-take-promoted="" className="basis-full text-text-2">
+ This take is the cut now — the Cut tab's Undo last edit takes it back.{" "}
+ {done && (
+ <a href={done} className="ink-link">
+ Revisions
+ </a>
+ )}
+ </span>
+ )}
+ {said && (
+ <span data-take-said="" className="basis-full text-[var(--color-dim)]">
+ {said}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/TakeWalkPage.tsx b/umtool/components/projects/TakeWalkPage.tsx
@@ -0,0 +1,124 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { hms } from "umtool-report-to-video/attribution";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { projectsHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs";
+import { isTakeId } from "@/lib/report/takes.mjs";
+import { walkOf } from "@/lib/report/walkData.mjs";
+import type { ProjectRef } from "@/lib/project-types";
+import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
+import TakeActions from "./TakeActions";
+
+// `/projects/<project>/takes/<take>/walk` -- WALK A TAKE: the take's clips
+// (the project's manifest with the take's patch applied, a draft too) in walk
+// order, each with its verdict and whether a fetched file holds it, and where
+// the walk starts. Each clip opens the clip bench on the TAKE
+// (`…/takes/<take>/clip/<id>`), whose saves go into the take's patch.
+// `umtool walk <project> --take <take>` prints the same reading.
+
+const VERDICT_TONE = { confirmed: "on", incorrect: "meter", unreviewed: "state" } as const;
+
+export default async function TakeWalkPage({
+ project,
+ take,
+ search = {},
+}: {
+ project: ProjectRef;
+ take: string;
+ search?: Record<string, string | undefined>;
+}) {
+ if (!isTakeId(take)) notFound();
+ const all = search.all === "1";
+ let w: Awaited<ReturnType<typeof walkOf>>;
+ try {
+ w = await walkOf(project, { take, all });
+ } catch {
+ notFound();
+ }
+ const start = w.first ? takeClipHref(project.id, take, w.first, { all }) : null;
+ const unfetched = w.clips.filter((c) => !c.fetched).length;
+ return (
+ <BenchFrame
+ kind="take-walk"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: takesHref(project.id), label: `${project.name} · takes` }}
+ kind="Take walk"
+ here={take}
+ next={start ? { href: start, label: w.first ?? "", attrs: { "data-take-walk-start": w.first ?? "" } } : null}
+ note={`${w.total} clips · ${hms(w.seconds)} · ${w.reviewed} reviewed`}
+ />
+ }
+ >
+ <BenchBody workClassName="space-y-3 overflow-y-auto">
+ <section data-take-walk-head={take} className="space-y-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <h1 className="text-[15px] text-text">{w.take?.label ?? take}</h1>
+ {w.take?.draft && <span className={badgeVariants({ variant: "state", size: "sm" })}>draft — not rendered</span>}
+ {!w.take?.editable && <span className={badgeVariants({ variant: "meter", size: "sm" })}>read only — a recipe's take, not made</span>}
+ </div>
+ <p className="text-[12px] text-text-2">
+ Edits made while walking go into this take's patch (<code className="font-mono">takes/{take}/take.json</code>), never the
+ project's manifest. {w.needing} need a verdict, {w.ready} of them fetched
+ {unfetched ? ` · ${unfetched} not fetched` : ""}.
+ </p>
+ {w.note && <p className="text-[12px] text-doubt-text">{w.note}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ {start ? (
+ <Link href={start} data-take-walk-go="" className={buttonVariants({ variant: "go", size: "md" })}>
+ Walk → start at {w.first}
+ </Link>
+ ) : (
+ <span className="text-[12px] text-[var(--color-dim)]">
+ {all ? "Nothing fetched to walk." : "Every fetched clip has a verdict."}
+ </span>
+ )}
+ <Link href={takeWalkHref(project.id, take, { all: !all })} data-take-walk-all={all ? "1" : "0"} className="text-[12px] ink-link">
+ {all ? "walk only the clips needing a verdict" : "walk every clip (judged ones too)"}
+ </Link>
+ </div>
+ {w.take?.editable && (
+ <TakeActions project={project.id} take={take} draft={!!w.take?.draft} walkHref={null} edited compact />
+ )}
+ </section>
+ <table data-take-walk-clips="" className="w-full border-collapse text-[12px]">
+ <thead>
+ <tr className="micro text-left">
+ <th className="py-1 pr-2">#</th>
+ <th className="py-1 pr-2">clip</th>
+ <th className="py-1 pr-2">window</th>
+ <th className="py-1 pr-2 text-right">s</th>
+ <th className="py-1 pr-2">verdict</th>
+ <th className="py-1 pr-2">quote</th>
+ </tr>
+ </thead>
+ <tbody>
+ {w.clips.map((c) => (
+ <tr key={c.id} data-take-walk-clip={c.id} data-on-walk={c.onWalk ? "1" : "0"} className="border-t border-seam align-top">
+ <td className="num py-1 pr-2 text-[var(--color-dim)]">{c.cut}</td>
+ <td className="py-1 pr-2">
+ <Link href={takeClipHref(project.id, take, c.id, { all })} className="font-mono ink-link">
+ {c.id}
+ </Link>
+ {c.onWalk && <span className="ml-1 text-meter" title="on the walk">→</span>}
+ </td>
+ <td className="num py-1 pr-2 whitespace-nowrap">
+ {hms(c.start)}–{hms(c.end)}
+ {!c.fetched && <span className={`ml-1 ${badgeVariants({ variant: "state", size: "sm" })}`}>not fetched</span>}
+ </td>
+ <td className="num py-1 pr-2 text-right">{c.seconds.toFixed(1)}</td>
+ <td className="py-1 pr-2">
+ <span className={badgeVariants({ variant: VERDICT_TONE[c.verdict as keyof typeof VERDICT_TONE] ?? "state", size: "sm" })}>{c.verdict}</span>
+ {c.correction && <span className="block text-[11px] text-doubt-text">{c.correction}</span>}
+ </td>
+ <td className="py-1 pr-2 text-text-2">{c.quote}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </BenchBody>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -10,9 +10,10 @@ import TimedNotes from "@/components/notes/TimedNotes";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { fmtAgo, fmtBytes } from "@/lib/format";
-import { playHref } from "@/lib/hrefs";
+import { playHref, takeWalkHref } from "@/lib/hrefs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
+import TakeActions from "./TakeActions";
// The takes of one project, a group at a time, every preview on screen at once.
//
@@ -47,6 +48,10 @@ export type Take = {
quick?: boolean;
/** The project's manifest is not the one it was made from (null: it does not say). */
stale?: boolean | null;
+ /** Recorded, not rendered (`umtool take … --draft`): walk it, then render it. */
+ draft?: boolean;
+ /** The walk's last edit to its patch (later than builtAt: the render is older than the take). */
+ editedAt?: string | null;
};
/** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */
@@ -556,6 +561,10 @@ function TakeCard({
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;
+ // Walk a take: a draft is walked before it is rendered; a rendered take
+ // walked since says its render is older than it (editedAt after builtAt).
+ const editedSinceRender = !!t.editedAt && (!t.builtAt || t.editedAt > t.builtAt);
+ const walkable = !!t.draft || !!t.baseHash;
return (
<article
@@ -578,6 +587,16 @@ function TakeCard({
}}
className="aspect-video w-full bg-black"
/>
+ ) : t.draft ? (
+ <div
+ data-take-draft={t.id}
+ className="flex aspect-video w-full flex-col items-center justify-center gap-1 bg-black px-3 text-center text-[12px] text-[var(--color-dim)]"
+ >
+ <span className="text-text-2">draft — walk / render</span>
+ <span className="text-[11px]">
+ nothing rendered yet: walk its clips on the bench (edits go into this take), then render it
+ </span>
+ </div>
) : (
<div data-no-preview="" className="flex aspect-video w-full items-center justify-center bg-black text-[11px] text-[var(--color-dim)]">
no preview yet
@@ -598,6 +617,16 @@ function TakeCard({
picked
</span>
)}
+ {t.draft && (
+ <span data-take-is-draft="" className={badgeVariants({ variant: "state", size: "sm" })}>
+ draft
+ </span>
+ )}
+ {!t.draft && editedSinceRender && (
+ <span data-take-edited="" className={badgeVariants({ variant: "meter", size: "sm" })} title="walked since its render: Render again to watch the edits">
+ edited since render
+ </span>
+ )}
<Link
href={playHref(project, { take: t.id })}
data-play-take={t.id}
@@ -660,17 +689,30 @@ 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" />
+ {walkable && (
+ <TakeActions
+ project={project}
+ take={t.id}
+ draft={!!t.draft}
+ walkHref={takeWalkHref(project, t.id)}
+ edited={!!t.draft || editedSinceRender}
+ compact
+ />
+ )}
<div className="flex flex-wrap items-center gap-1.5">
+ {!t.draft && (
<button
type="button"
data-action="pick"
disabled={!ready || busy}
className={buttonVariants({ size: "sm" })}
+ title="the manifest this take was RENDERED from, over the project's"
onClick={() => void pick(false)}
>
Use this take
</button>
- {t.baseHash && (
+ )}
+ {t.baseHash && !t.draft && (
<button
type="button"
data-action="rebuild"
diff --git a/umtool/components/projects/bench/RenderGhosts.tsx b/umtool/components/projects/bench/RenderGhosts.tsx
@@ -52,13 +52,15 @@ export function useRenderEdges(
project: string,
clip: { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null },
sel: { from: number; to: number },
+ /** Walking a take: the clip is the take's (the cut-points route reads its manifest). */
+ take: string | null = null,
): RenderEdges {
const [got, setGot] = useState<{ key: string; row: Row | null; knobs: Got["knobs"]; leadIn: number } | null>(null);
// Measured again when what was SAVED moves (the extent picks the file and the span).
- const key = `${project}|${clip.id}|${clip.start}|${clip.end}|${clip.cutStart}|${clip.cutEnd}`;
+ const key = `${project}|${take ?? ""}|${clip.id}|${clip.start}|${clip.end}|${clip.cutStart}|${clip.cutEnd}`;
useEffect(() => {
let live = true;
- const q = new URLSearchParams({ project, clip: clip.id });
+ const q = new URLSearchParams({ project, clip: clip.id, ...(take ? { take } : {}) });
fetch(`/api/report/cut-points?${q}`, { cache: "no-store" })
.then((r) => (r.ok ? (r.json() as Promise<Got>) : null))
.then((j) => {
@@ -68,7 +70,7 @@ export function useRenderEdges(
return () => {
live = false;
};
- }, [key, project, clip.id]);
+ }, [key, project, clip.id, take]);
const row = got?.row;
if (!got || !row || !row.silences || row.fetchStart == null || row.montage) return null;
const pw = playWindowOf(sel, clip, got.leadIn);
diff --git a/umtool/components/projects/bench/TakeWalkStrip.tsx b/umtool/components/projects/bench/TakeWalkStrip.tsx
@@ -0,0 +1,140 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import Link from "next/link";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// WALKING A TAKE: the line that says so, on the clip bench, and the take's
+// own structure -- this clip out of the take, earlier or later in it, and the
+// take's last edit taken back. Every one is POST /api/report/takes/timeline
+// (lib/report/takeEdit.mjs), the writer `umtool timeline <p> --take <id>`
+// runs; the project's manifest is never written from here.
+//
+// After a structural edit the page is LOADED again rather than refreshed: the
+// bench holds its token and its drafts in state, and a remount is the honest
+// way to show the take as it now is.
+
+export default function TakeWalkStrip({
+ project,
+ take,
+ clipId,
+ index,
+ total,
+ nextHref,
+ getToken,
+ className,
+}: {
+ project: string;
+ take: { id: string; label: string; draft: boolean; editable: boolean; all: boolean; takesHref: string; walkHref: string; toggleAllHref: string };
+ clipId: string;
+ /** This clip's place in the take's timeline, 0-based, and the timeline's length. */
+ index: number;
+ total: number;
+ /** Where the walk goes after this clip is removed. */
+ nextHref: string | null;
+ getToken: () => string | null;
+ className?: string;
+}) {
+ const [ready, setReady] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<string | null>(null);
+ useEffect(() => setReady(true), []);
+
+ const run = async (op: "move" | "remove" | "undo", extra: Record<string, unknown> = {}, then: string | null = null) => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const r = await fetch("/api/report/takes/timeline", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, take: take.id, op, token: getToken(), ...extra }),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean };
+ if (!r.ok) {
+ setSaid(j.stale ? "the take changed since this page was read — reload" : (j.errors?.join("; ") ?? j.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ window.location.assign(then ?? window.location.href);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const off = !ready || busy || !take.editable;
+ return (
+ <div
+ data-take-walk={take.id}
+ className={cn(
+ "flex flex-wrap items-center gap-x-2 gap-y-1 rounded border border-[var(--color-sel)] bg-[var(--color-panel)] px-2 py-1 text-[11.5px]",
+ className,
+ )}
+ >
+ <span className="micro">walking take</span>
+ <span className="font-mono text-[var(--color-text)]">{take.id}</span>
+ <span className="truncate text-text-2">{take.label}</span>
+ {take.draft && <span className={badgeVariants({ variant: "state", size: "sm" })}>draft</span>}
+ <span className="text-[var(--color-dim)]">
+ {take.editable ? "edits go to the take, not the cut" : "a recipe's take, not made yet: read only"}
+ </span>
+ <span className="ml-auto flex flex-wrap items-center gap-1.5">
+ <span className="num text-[var(--color-dim)]">
+ {index + 1}/{total} in the take
+ </span>
+ <button
+ type="button"
+ data-take-move="earlier"
+ disabled={off || index <= 0}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ title="one place earlier in the take"
+ onClick={() => void run("move", { id: clipId, toIndex: index - 1 })}
+ >
+ ← earlier
+ </button>
+ <button
+ type="button"
+ data-take-move="later"
+ disabled={off || index >= total - 1}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ title="one place later in the take"
+ onClick={() => void run("move", { id: clipId, toIndex: index + 1 })}
+ >
+ later →
+ </button>
+ <button
+ type="button"
+ data-take-remove={clipId}
+ disabled={off}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ title="take this clip out of the take (Undo puts it back)"
+ onClick={() => void run("remove", { id: clipId }, nextHref ?? take.takesHref)}
+ >
+ Remove from take
+ </button>
+ <button
+ type="button"
+ data-take-undo=""
+ disabled={off}
+ className={buttonVariants({ size: "sm" })}
+ title="take back the take's last edit -- a verdict, a trim, a move or a removal"
+ onClick={() => void run("undo")}
+ >
+ Undo take edit
+ </button>
+ <Link href={take.toggleAllHref} data-take-walk-all={take.all ? "1" : "0"} className="ink-link">
+ {take.all ? "walk the unjudged only" : "walk every clip"}
+ </Link>
+ <Link href={take.takesHref} className="ink-link">
+ Takes
+ </Link>
+ </span>
+ {said && (
+ <span data-take-said="" className="basis-full text-[var(--color-bad)]">
+ {said}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -8,7 +8,7 @@ import {
} from "@/lib/projects/report.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { buttonVariants } from "@/components/ui/button";
-import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takesHref } from "@/lib/hrefs";
+import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref } from "@/lib/hrefs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
@@ -203,6 +203,22 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
Make takes
</Link>
)}
+ {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */}
+ {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && (
+ <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]">
+ <span className="micro">walk a take</span>
+ {[...takes.takes]
+ .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash)
+ .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft))
+ .slice(0, 6)
+ .map((t: { id: string; label: string; draft?: boolean }) => (
+ <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}>
+ {t.id}
+ {t.draft ? " (draft)" : ""}
+ </Link>
+ ))}
+ </span>
+ )}
{clips.length > 0 && (
<VoiceMatchPanel
project={project.id}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -23,6 +23,8 @@ Inbox cannot disagree about what is wrong with one.
| `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx |
| `folders [--json]` · `kinds [--json]` | the tree, the registry |
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window |
+| `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) |
+| `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at |
| `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) |
| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)); `key=` clears one ([knobs.md](knobs.md#marks)) |
| `look <project> key=value …` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) |
@@ -45,6 +47,7 @@ Inbox cannot disagree about what is wrong with one.
| `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 …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), 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)) |
+| `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) |
| `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 effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) |
@@ -57,6 +60,7 @@ Inbox cannot disagree about what is wrong with one.
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
+| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it |
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) |
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -317,6 +317,39 @@ reviewed. See
[report-video.md](report-video.md#verdict--what-the-walk-said) for what is
stored and what the writer refuses.
+## Walking a take
+
+`/projects/<project>/takes/<take>/walk` — from **Walk this take** on the take's card, or **walk a
+take** on the Cut tab — lists the take's clips in walk order: each clip's window, length, verdict,
+whether a fetched file holds it, and (→) the ones the walk visits, with **Walk → start at
+`<clip>`**. A take is the project's manifest with its patch applied (a draft too:
+[report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)),
+so its clips may be windows the project's cut does not have — a tight version's sub-windows. Each
+plays from the cached windows of its recording: a sub-window inside a fetched window plays without
+a new fetch.
+
+`/projects/<project>/takes/<take>/clip/<id>` is this bench on the take's clip. Everything works as
+on the project's cut, and **every save goes into the take's patch** (`takes/<take>/take.json`),
+never the project's manifest: the verdict (`y`, `x`), the edges, the attribution, the mute mark,
+cut to quote, a wider fetch (the job is pointed at the take's manifest, written beside the
+project's; the bytes land where every fetch's do). A strip at the top says **walking take
+`<take>` — edits go to the take, not the cut**, with **← earlier**, **later →**, **Remove from
+take** and **Undo take edit** (the take's newest edit taken back, whichever it was). The one-clip
+re-render is not offered: a take is rendered whole (**Render full** on the Takes page, or `umtool
+take <p> --id <take> --full`).
+
+**`?all=1` walks every clip.** A take's clips often carry the verdict of the clip they were cut
+from, so the default walk — fetched and still needing a verdict — would skip them. **walk every
+clip** keeps the judged ones on the walk too.
+
+The terminal reads the same walk (`lib/report/walkData.mjs`, also `GET /api/report/walk`):
+
+```
+umtool walk <project> --take <take> [--all] [--json]
+umtool window <project> <clip> --take <take> --verdict confirmed # or --start/--end/--correction …
+umtool timeline <project> --take <take> [ls | move <id> --to <i> | remove <id> | undo]
+```
+
## The extent you reviewed, and the cut that plays
The window you drag is the clip's **extent** — how much of this recording is
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -229,6 +229,13 @@ own patch (a take's own `timeline` included), from `takes/<id>/take.json` or —
names it; its pages are composed under `takes/<id>/out/`, never over the project's. `render.blur: "off"` on the
take plays its blurred clips as recorded.
+**To judge a take clip by clip, walk it** (`/projects/<p>/takes/<id>/walk`, **Walk this take** on its card):
+the clip bench on the take's own clips, whose verdicts, trims and removals go into the take's patch, never the
+project's manifest; `umtool walk <p> --take <id>`, `umtool window <p> <clip> --take <id> …` and `umtool timeline
+<p> --take <id> move|remove|undo` are the terminal's. **Make this the cut** (`umtool take <p> --id <id> --promote`)
+puts the walked take over the project's manifest with one undo
+([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)).
+
| | In umtool | Keys |
|---|---|---|
| play / pause, back (tap again: further), pause, play (tap again: 1.5×, 2×, …; the voice keeps its pitch), ±5 s, previous / next clip | the transport under the picture, the speed menu | Space, J K L, ← →, P N |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1044,6 +1044,63 @@ go into its `chrome/pruned.json` first, so `verify-build` still checks the cut;
appended to `takes/<id>/pruned-work.json`. The project's own `out/` is not a take and is not
touched. A pruned take rebuilt, or used as a `--from` base, renders its work again.
+### Walking a take: drafts, edits into the take, and making it the cut
+
+A take can be **walked** on the clip bench like the project's own cut — its clips, played from the
+cached windows (a sub-window inside a fetched window plays without a new fetch), each confirmed,
+noted, trimmed, removed or moved — and every one of those edits goes into the **take's patch**,
+never the project's manifest ([clip-bench.md](clip-bench.md#walking-a-take)).
+
+```
+umtool take <project> --id tight --label "Tight — walk" --patch tight.json --draft # recorded, nothing rendered
+umtool walk <project> --take tight [--all] # the clips, verdicts, where the walk starts
+umtool window <project> t06a --take tight --verdict confirmed --end 6201.2 # a clip of the take
+umtool timeline <project> --take tight move t07b --to 3 | remove t09c | undo # its structure, its undo
+umtool take <project> --id tight --full # render the draft, edits and all
+umtool take <project> --id tight --promote [--anyway] # make it the cut (one undo)
+```
+
+**A draft** (`--draft`, or `--no-render`) is the take recorded with nothing rendered:
+`takes/<id>/take.json` with `draft: true`, its `patch`, label, group and `baseHash`, `preview`
+naming where the render will go, `seconds` and `builtAt` null, and `window` null unless one was
+given. The patch is applied once to check it makes a manifest with a timeline (refused now, not at
+the render) and to write `changes[]`. No take.json is written over a rendered take; over a draft
+only with `--force`. The Takes page shows it as **draft — walk / render**. `umtool take <p> --id
+<id> --full` (or **Render full** on its card) renders a draft from what it stores — the patch as
+the walk left it — and it is an ordinary made take from then on; `--rebuild` takes a window flag
+too (`--rebuild --full`, `--rebuild --at 0 --dur 60`).
+
+**The walk's edits** (`lib/report/takeEdit.mjs`) resolve the take's manifest as it is now (the
+merge the build makes: `takeManifest.mjs resolveTakeManifest`), apply the edit with the project
+writer's own functions — `patchClipEntry` (updateClip's rules: 2 dp, the verdict needing its
+note, the cut inside the extent, …) or `applyStructural` (the build's structure checks) — and
+write the WHOLE edited timeline back as `patch.timeline` (an RFC 7386 array replaces whole). A
+take whose patch had no timeline (a style take) gets one on its first edit, and from then on its
+timeline is its own. Each write first copies take.json into
+`takes/<id>/revisions/<stamp>-<ms>-auto-before-<op>.take.json` — every write, not one per two
+minutes, because a walk is many small edits and Undo means the last of them — and stamps
+`editedAt`. **Undo take edit** (`umtool timeline <p> --take <id> undo`) restores the newest one
+byte for byte, keeping the take.json it replaces as `…-undo-saved…` and renaming the restored one
+`…-undone-<op>…`, so the next undo goes one further. The token is take.json's mtime: a stale one
+is a 409, never an overwrite. A rendered take walked since says **edited since render** on its
+card.
+
+**Make this the cut** (`umtool take <p> --id <id> --promote`, `POST /api/report/takes/promote`)
+writes the take's manifest — the project's as it is now with the take's patches applied — over the
+project's through `replaceManifest`: one auto snapshot `auto-before-promote-take`, so the Cut
+tab's **Undo last edit** (`umtool timeline <p> undo`) takes the whole promotion back; the
+generated-manifest guard; the build's structure checks (refused only for what the promotion
+breaks); then the take is its group's pick in verdicts.json. It is not **Use this take**, which
+copies the manifest a take was *rendered* from: a draft, or a take walked since its render,
+promotes exactly what was walked. When the take's patch replaces the timeline and the project's
+manifest changed since the take was made (`baseHash`), it is refused until `--anyway` (**Make it
+the cut anyway**) — the take's timeline would replace what the cut gained since.
+
+**A window of a take that replaces the timeline.** A windowed render times its window over the
+project's timeline so every take of a group covers the same entries; a take whose timeline holds
+none of those entries (a tight version's sub-windows) is timed over its own timeline instead, and
+its log says so, rather than refused as emptied.
+
### Trailer from the master
`umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) [--intro] [--finale S]
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -33,6 +33,7 @@ import { makeClipDeckFixture } from "./clip-deck-fixture.mjs";
import { makeMontageOpsFixture } from "./montage-ops-fixture.mjs";
import { makeClipEditorFixture } from "./clip-editor-fixture.mjs";
import { makeBenchShellFixture } from "./bench-shell-fixture.mjs";
+import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
@@ -1845,6 +1846,8 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1, name: "clip-look-fixture", title: "The Clip Look Fixture" });
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// Walk a take: a draft take of sub-windows, walked on the bench (take-walk.spec.ts).
+makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
diff --git a/umtool/e2e/fixtures/take-walk-fixture.mjs b/umtool/e2e/fixtures/take-walk-fixture.mjs
@@ -0,0 +1,73 @@
+// What take-walk.spec.ts acts on (walk a take): its own project, written by
+// that spec alone.
+//
+// reports/take-walk-fixture/
+// video.manifest.json ONE clip, w01 1.00-8.00 (confirmed) -- the master
+// out/clips-raw/ vid1 0.00-9.00, which holds every take clip below
+// takes/tight/take.json a DRAFT take (recorded, nothing rendered) whose
+// patch replaces the timeline with three
+// sub-windows of w01, as `umtool take … --draft`
+// writes one:
+// t01a 1.00-3.00 confirmed (carried from w01)
+// t01b 3.50-6.00 no verdict -- where the walk starts
+// t01c 6.20-8.50 no verdict
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import path from "node:path";
+
+const write = (dir, name, text) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), text);
+};
+const json = (doc) => JSON.stringify(doc, null, 2) + "\n";
+
+/**
+ * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ * `manifest` is make-fixture's manifest(slug, title, provenance, timeline);
+ * `cachedWindow` the vid1 0-9 s window the build fixtures share.
+ */
+export function makeTakeWalkFixture({ reports, manifest, cachedWindow }) {
+ const dir = path.join(reports, "take-walk-fixture");
+ const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid1", start, end, cite: start, section: 0, lock: true, ...extra });
+ write(
+ dir,
+ "video.manifest.json",
+ json(manifest("take-walk-fixture", "The Take Walk Fixture", { siteOrigin: "https://archive.example" }, [
+ clip("w01", 1.0, 8.0, { verdict: "confirmed", quote: "the whole of it" }),
+ ])),
+ );
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow)));
+ const baseHash = createHash("sha256").update(readFileSync(path.join(dir, "video.manifest.json"), "utf8")).digest("hex");
+ write(
+ path.join(dir, "takes", "tight"),
+ "take.json",
+ json({
+ id: "tight",
+ group: "takes",
+ order: 1,
+ label: "Tight — walk",
+ kind: "different",
+ summary: "",
+ changes: ["timeline: 3 items"],
+ preview: "preview.mp4",
+ seconds: null,
+ builtAt: null,
+ style: null,
+ patch: {
+ timeline: [
+ clip("t01a", 1.0, 3.0, { verdict: "confirmed", quote: "the first of it" }),
+ clip("t01b", 3.5, 6.0, { quote: "the middle of it" }),
+ clip("t01c", 6.2, 8.5, { quote: "the end of it" }),
+ ],
+ },
+ window: null,
+ draft: true,
+ draftedAt: "2026-10-27T12:00:00.000Z",
+ baseHash,
+ }),
+ );
+ return dir;
+}
diff --git a/umtool/e2e/take-walk.spec.ts b/umtool/e2e/take-walk.spec.ts
@@ -0,0 +1,106 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// WALK A TAKE (umtool/docs/clip-bench.md, "Walking a take"): a draft take --
+// recorded, not rendered -- walked on the clip bench, every edit landing in
+// the take's patch and none in the project's manifest; then made the cut.
+//
+// Fixture (fixtures/take-walk-fixture.mjs), written by this file alone:
+// take-walk-fixture's master is one clip, w01; its draft take `tight` replaces
+// the timeline with t01a (confirmed), t01b and t01c, all inside the cached
+// vid1 0-9 s window. The tests run in order, each leaving what the next reads.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const PROJECT = "reports/take-walk-fixture";
+const TAKE = "tight";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "take-walk-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const takeDoc = () => JSON.parse(readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8"));
+const takeClip = (id: string) => (takeDoc().patch.timeline as { id: string; verdict?: string }[]).find((e) => e.id === id);
+
+/** The bench's keys answer once it has hydrated (`x` focuses the note box). */
+const keyboardLive = async (page: import("@playwright/test").Page) => {
+ const box = page.locator("[data-attrib-field=correction]");
+ await expect(async () => {
+ await page.locator("body").press("x");
+ await expect(box).toBeFocused({ timeout: 500 });
+ }).toPass({ timeout: 10_000 });
+ await box.blur();
+};
+
+let masterBefore = "";
+test.beforeAll(() => {
+ masterBefore = manifestText();
+});
+
+test("the Takes page shows the draft as `draft — walk / render`, with Walk this take", async ({ page }) => {
+ await page.goto(urls.takesHref(PROJECT));
+ const card = page.locator(`[data-take="${TAKE}"]`);
+ await expect(card.locator(`[data-take-draft="${TAKE}"]`)).toContainText("draft — walk / render");
+ await expect(card.locator("[data-take-is-draft]")).toBeVisible();
+ await expect(card.locator(`[data-take-walk-link="${TAKE}"]`)).toHaveAttribute("href", urls.takeWalkHref(PROJECT, TAKE));
+ // Nothing rendered to use: the draft is made the cut, not "used".
+ await expect(card.locator("[data-action=pick]")).toHaveCount(0);
+ await expect(card.locator("[data-take-promote]")).toBeVisible();
+});
+
+test("the take's walk: its clips in walk order, the walk starting at the first one needing a verdict", async ({ page, request }) => {
+ await page.goto(urls.takeWalkHref(PROJECT, TAKE));
+ await expect(page.locator("[data-take-walk-clip]")).toHaveCount(3);
+ await expect(page.locator("[data-take-walk-go]")).toHaveAttribute("href", urls.takeClipHref(PROJECT, TAKE, "t01b"));
+ await page.locator("[data-take-walk-all]").click();
+ await expect(page.locator("[data-take-walk-go]")).toHaveAttribute("href", urls.takeClipHref(PROJECT, TAKE, "t01a", { all: true }));
+ // The data route: the same reading.
+ const j = (await (await request.get(`/api/report/walk?project=${encodeURIComponent(PROJECT)}&take=${TAKE}`)).json()) as {
+ first: string;
+ take: { draft: boolean };
+ clips: { id: string; onWalk: boolean; fetched: boolean }[];
+ };
+ expect(j.first).toBe("t01b");
+ expect(j.take.draft).toBe(true);
+ expect(j.clips.map((c) => [c.id, c.fetched, c.onWalk])).toEqual([
+ ["t01a", true, false],
+ ["t01b", true, true],
+ ["t01c", true, true],
+ ]);
+});
+
+test("confirming on the bench writes the take's patch, never the manifest, and walks on", async ({ page }) => {
+ await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01b"));
+ await expect(page.locator(`[data-take-walk="${TAKE}"]`)).toContainText("edits go to the take, not the cut");
+ await expect(page.locator("[data-bench-kind]")).toHaveText("Take walk");
+ // A take renders whole: no one-clip re-render of the project's segment here.
+ await expect(page.locator("[data-rerender]")).toHaveCount(0);
+ await keyboardLive(page);
+ await page.locator("body").press("y");
+ await expect(page.locator("[data-bench=t01c]")).toBeVisible();
+ await expect.poll(() => takeClip("t01b")?.verdict).toBe("confirmed");
+ expect(manifestText()).toBe(masterBefore);
+ expect(takeDoc().draft).toBe(true);
+});
+
+test("remove from the take, then undo the take's edit", async ({ page }) => {
+ await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01c"));
+ await expect(page.locator(`[data-take-walk="${TAKE}"]`)).toBeVisible();
+ await page.locator("[data-take-remove=t01c]").click();
+ await expect.poll(() => (takeDoc().patch.timeline as { id: string }[]).map((e) => e.id)).toEqual(["t01a", "t01b"]);
+ await page.goto(urls.takeClipHref(PROJECT, TAKE, "t01b"));
+ await page.locator("[data-take-undo]").click();
+ await expect.poll(() => (takeDoc().patch.timeline as { id: string }[]).map((e) => e.id)).toEqual(["t01a", "t01b", "t01c"]);
+ expect(manifestText()).toBe(masterBefore);
+});
+
+test("Make this the cut: the take's walked timeline becomes the project's", async ({ page }) => {
+ await page.goto(urls.takeWalkHref(PROJECT, TAKE));
+ await page.locator(`[data-take-actions="${TAKE}"] [data-take-promote]`).click();
+ await expect(page.locator("[data-take-promoted]")).toBeVisible();
+ const m = JSON.parse(manifestText()) as { timeline: { id: string; verdict?: string }[] };
+ expect(m.timeline.map((e) => e.id)).toEqual(["t01a", "t01b", "t01c"]);
+ expect(m.timeline[1].verdict).toBe("confirmed");
+});
diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs
@@ -23,6 +23,13 @@ test("note is always the last parameter", () => {
}
});
+test("walk a take: /projects/<p>/takes/<take>/walk and …/clip/<id>, `all` as 1, note last", () => {
+ assert.equal(H.takeWalkHref("a/b", "tight-1"), "/projects/a/b/takes/tight-1/walk");
+ assert.equal(H.takeWalkHref("a/b", "tight-1", { all: true }), "/projects/a/b/takes/tight-1/walk?all=1");
+ assert.equal(H.takeClipHref("a/b", "tight-1", "t01a"), "/projects/a/b/takes/tight-1/clip/t01a");
+ assert.equal(H.takeClipHref("a/b", "tight-1", "t01a", { all: true, note: "n" }), "/projects/a/b/takes/tight-1/clip/t01a?all=1¬e=n");
+});
+
test("the clip deck: /projects/<p>/clips, its filter in `show`", () => {
assert.equal(H.clipDeckHref("a/b"), "/projects/a/b/clips");
assert.equal(H.clipDeckHref("a/b", { show: "unruled" }), "/projects/a/b/clips?show=unruled");
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -296,6 +296,24 @@ export function takesHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note);
}
+/**
+ * Walk a take: the take's clips, the walk's start (an overview of every clip,
+ * and where the walk begins). `all`: the walk visits every fetched clip, judged
+ * or not, rather than only the ones still needing a verdict.
+ */
+export function takeWalkHref(project: string, take: string, q: NoteOpt & { all?: boolean } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/takes/${encodeURIComponent(take)}/walk`, { all: q.all }, q.note);
+}
+
+/** The clip bench on one of a take's clips: its saves go into the take's patch, never the project's manifest. */
+export function takeClipHref(project: string, take: string, clip: string, q: NoteOpt & { all?: boolean } = {}): string {
+ return withQuery(
+ `/projects/${encodePath(project)}/takes/${encodeURIComponent(take)}/clip/${encodeURIComponent(clip)}`,
+ { all: q.all },
+ q.note,
+ );
+}
+
/** What the clip deck (release 34) walks: every instance, the unruled, the doubtful first, the ruled. */
export const CLIP_DECK_SHOWS = ["all", "unruled", "doubtful", "ruled"] as const;
export type ClipDeckShow = (typeof CLIP_DECK_SHOWS)[number];
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -1541,9 +1541,19 @@ export async function readClipDetail(dir, { manifest = null } = {}) {
return { manifest: m, build, channelsDir, shadowExists, entries };
}
-/** The cues a clip bench draws, trimmed to a window. Absolute source seconds. */
-export async function cuesInWindow(dir, clipId, from, to) {
- const m = await readManifest(dir);
+/**
+ * The cues a clip bench draws, trimmed to a window. Absolute source seconds.
+ * `manifest`: the one the clip is in, when it is not the project's own (a
+ * take's, walking a take).
+ *
+ * @param {string} dir
+ * @param {string} clipId
+ * @param {number} from
+ * @param {number} to
+ * @param {{ manifest?: Record<string, any> | null }} [opts]
+ */
+export async function cuesInWindow(dir, clipId, from, to, { manifest = null } = {}) {
+ const m = manifest ?? (await readManifest(dir));
const e = clipsOf(m).find((x) => x.id === clipId);
if (!e) return null;
return cuesOfSource(dir, m, e, from, to);
diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs
@@ -298,9 +298,11 @@ export const FETCH_MAX_PAD = 120;
* @param {{ dir: string }} project
* @param {string} clipId
* @param {number | { padBefore: number, padAfter: number }} pad
+ * @param {{ manifestPath?: string | null }} [opts] the manifest the clip is in, when it
+ * is not the project's (a take's, written beside it: takeManifest.mjs writePlayManifest)
* @returns {import("../trim").Step[]}
*/
-export function fetchSteps(project, clipId, pad) {
+export function fetchSteps(project, clipId, pad, { manifestPath = null } = {}) {
// A number is the symmetric shorthand; {padBefore, padAfter} is one edge at
// a time, which is what extending a window actually is.
const before = typeof pad === "object" && pad ? Number(pad.padBefore) : Number(pad);
@@ -313,7 +315,7 @@ export function fetchSteps(project, clipId, pad) {
argv: [
"node",
script("build-video.mjs"),
- path.join(project.dir, "video.manifest.json"),
+ manifestPath ?? path.join(project.dir, "video.manifest.json"),
"--out",
path.join(project.dir, "out"),
"--fetch-only",
@@ -348,9 +350,10 @@ export function fetchSteps(project, clipId, pad) {
* @param {{ dir: string }} project
* @param {string} clipId
* @param {number | { padBefore: number, padAfter: number, storedUrl?: "fallback" | "only" | null }} pad
+ * @param {{ manifestPath?: string | null }} [opts] as fetchSteps
* @returns {import("../trim").Step[]}
*/
-export function editorFetchSteps(project, clipId, pad) {
+export function editorFetchSteps(project, clipId, pad, { manifestPath = null } = {}) {
const before = typeof pad === "object" && pad ? Number(pad.padBefore) : Number(pad);
const after = typeof pad === "object" && pad ? Number(pad.padAfter) : Number(pad);
// Cut from the stored media URL (release 32 R6): `--stored-url <mode>`.
@@ -370,7 +373,7 @@ export function editorFetchSteps(project, clipId, pad) {
argv: [
"node",
script("fetch-via-editor.mjs"),
- path.join(project.dir, "video.manifest.json"),
+ manifestPath ?? path.join(project.dir, "video.manifest.json"),
"--fetch-only",
clipId,
"--pad-before",
@@ -414,7 +417,7 @@ export function editorFetchSteps(project, clipId, pad) {
*
* @param {{ dir: string }} project
* @param {string} clipId
- * @param {{ maxHeight?: unknown, manifest?: { render?: { maxHeightSource?: unknown } } | null }} [opts]
+ * @param {{ maxHeight?: unknown, manifest?: { render?: { maxHeightSource?: unknown } } | null, manifestPath?: string | null }} [opts]
* @returns {import("../trim").Step[]}
*/
export function editorFullSourceSteps(project, clipId, opts = {}) {
@@ -429,7 +432,7 @@ export function editorFullSourceSteps(project, clipId, opts = {}) {
argv: [
"node",
script("fetch-via-editor.mjs"),
- path.join(project.dir, "video.manifest.json"),
+ opts.manifestPath ?? path.join(project.dir, "video.manifest.json"),
"--fetch-only",
clipId,
"--full",
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -187,363 +187,384 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri
// Re-read INSIDE the lock, every time. Nothing is held across requests.
const raw = await readFile(manifestFile(dir), "utf8");
const manifest = JSON.parse(raw);
- const entry = (manifest.timeline ?? []).find((e) => e.id === clipId);
- if (!entry) throw new Error(`no timeline entry with id ${clipId}`);
- // `!== "clip"`, not `=== "card"`. The timeline's vocabulary is open -- one
- // real manifest carries `scroll` and `chart` entries -- and the card-only
- // check would have let a window be written onto one of those.
- if (entry.type !== "clip") throw new Error(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`);
- // Restore (release 35 C2): the assistant's own edges, read inside the lock.
- if (patch === RESTORE_PATCH) {
- patch = restorePatchOf(entry);
- edit = "restore";
- }
+ const { entry, before } = patchClipEntry(manifest, clipId, patch, { edit, now, raw });
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ // A moved extent may need a new bench excerpt: queued, never waited for.
+ if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]);
+ return { entry, before, token: nextToken };
+ });
+}
- const before = { start: entry.start, end: entry.end };
- const cutBefore = cutOf(entry);
- for (const k of WINDOW_FIELDS) {
- if (patch[k] === undefined) continue;
- const v = Number(patch[k]);
- if (!Number.isFinite(v) || v < 0) throw new Error(`${k} must be a number ≥ 0`);
- entry[k] = round2(v);
- }
- if (entry.end - entry.start < 0.5) {
- throw new Error(`a clip must be at least half a second (${entry.start}–${entry.end})`);
- }
- for (const k of FLAG_FIELDS) {
- if (patch[k] === undefined) continue;
- // `false` REMOVES the key rather than writing it. The manifests are read
- // by humans, and `"lockEnd": false` is noise that reads like a decision.
- if (patch[k]) entry[k] = true;
- else delete entry[k];
- }
- if (patch.note !== undefined) {
- if (patch.note) entry.note = String(patch.note);
- else delete entry.note;
- }
+/**
+ * updateClip's rules over a manifest held in memory: the ONE place a clip
+ * patch is checked and applied. updateClip runs it on the project's file
+ * inside its lock; a take's walk (takeEdit.mjs) runs it on the take's
+ * timeline, so a trim, a verdict or an attribution edit is checked by the
+ * same sentences whichever file it lands in. Mutates `manifest`.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {string} clipId
+ * @param {Record<string, unknown>} patch
+ * @param {{ edit?: string, now?: string | null, raw?: string | null }} [opts]
+ * `raw`: the manifest's text before the patch, when the caller has it (the
+ * finale check compares against it); else it is taken here.
+ * @returns {{ entry: Record<string, any>, before: { start: number, end: number } }}
+ */
+export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = null, raw = null } = {}) {
+ const original = patch.layout !== undefined ? (raw ?? JSON.stringify(manifest)) : null;
+ const entry = (manifest.timeline ?? []).find((e) => e.id === clipId);
+ if (!entry) throw new Error(`no timeline entry with id ${clipId}`);
+ // `!== "clip"`, not `=== "card"`. The timeline's vocabulary is open -- one
+ // real manifest carries `scroll` and `chart` entries -- and the card-only
+ // check would have let a window be written onto one of those.
+ if (entry.type !== "clip") throw new Error(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`);
+ // Restore (release 35 C2): the assistant's own edges, read inside the lock.
+ if (patch === RESTORE_PATCH) {
+ patch = restorePatchOf(entry);
+ edit = "restore";
+ }
- // ---- what the header will say -------------------------------------------
- //
- // `correction` is the odd one out and belongs here anyway: it is written in
- // the same sitting, by the same person, looking at the same clip. It says
- // what the REPORT got wrong -- wrong speaker, wrong addressee, wrong date --
- // and nothing renders it. It is a message to the next report pass.
- for (const k of ["title", "quote", "correction"]) {
- if (patch[k] === undefined) continue;
- const v = String(patch[k] ?? "").trim();
- if (v) entry[k] = v;
- else delete entry[k];
- }
+ const before = { start: entry.start, end: entry.end };
+ const cutBefore = cutOf(entry);
+ for (const k of WINDOW_FIELDS) {
+ if (patch[k] === undefined) continue;
+ const v = Number(patch[k]);
+ if (!Number.isFinite(v) || v < 0) throw new Error(`${k} must be a number ≥ 0`);
+ entry[k] = round2(v);
+ }
+ if (entry.end - entry.start < 0.5) {
+ throw new Error(`a clip must be at least half a second (${entry.start}–${entry.end})`);
+ }
+ for (const k of FLAG_FIELDS) {
+ if (patch[k] === undefined) continue;
+ // `false` REMOVES the key rather than writing it. The manifests are read
+ // by humans, and `"lockEnd": false` is noise that reads like a decision.
+ if (patch[k]) entry[k] = true;
+ else delete entry[k];
+ }
+ if (patch.note !== undefined) {
+ if (patch.note) entry.note = String(patch.note);
+ else delete entry.note;
+ }
- if (patch.date !== undefined) {
- const v = String(patch.date ?? "").trim();
- if (!v) delete entry.date;
- else if (!isCalendarDate(v)) {
- throw new Error(
- `date must be a real calendar date written YYYY-MM-DD (got \`${v}\`)`,
- );
- } else entry.date = v;
- }
+ // ---- what the header will say -------------------------------------------
+ //
+ // `correction` is the odd one out and belongs here anyway: it is written in
+ // the same sitting, by the same person, looking at the same clip. It says
+ // what the REPORT got wrong -- wrong speaker, wrong addressee, wrong date --
+ // and nothing renders it. It is a message to the next report pass.
+ for (const k of ["title", "quote", "correction"]) {
+ if (patch[k] === undefined) continue;
+ const v = String(patch[k] ?? "").trim();
+ if (v) entry[k] = v;
+ else delete entry[k];
+ }
- if (patch.cite !== undefined) {
- // null or empty means "no cite", and the header then falls back to the
- // clip's own start -- which is what `entry.cite ?? entry.start` has always
- // done. Rounded like a window, for the same reason.
- if (patch.cite === null || patch.cite === "") delete entry.cite;
- else {
- const v = Number(patch.cite);
- if (!Number.isFinite(v) || v < 0) {
- throw new Error("cite must be a number of seconds ≥ 0, or empty to use the clip's start");
- }
- entry.cite = round2(v);
- }
- }
+ if (patch.date !== undefined) {
+ const v = String(patch.date ?? "").trim();
+ if (!v) delete entry.date;
+ else if (!isCalendarDate(v)) {
+ throw new Error(
+ `date must be a real calendar date written YYYY-MM-DD (got \`${v}\`)`,
+ );
+ } else entry.date = v;
+ }
- if (patch.citeUrl !== undefined) {
- const v = String(patch.citeUrl ?? "").trim();
- if (!v) delete entry.citeUrl;
- else {
- // The QR target. A value that is not an http(s) URL encodes to something
- // a phone camera opens and nothing answers -- the same class of defect
- // as the 19 codes that shipped reading `undefined/?v=…`.
- let u = null;
- try {
- u = new URL(v);
- } catch {
- /* handled below */
- }
- if (!u || (u.protocol !== "http:" && u.protocol !== "https:")) {
- throw new Error(`citeUrl must be an http:// or https:// URL (got \`${v}\`)`);
- }
- entry.citeUrl = v;
+ if (patch.cite !== undefined) {
+ // null or empty means "no cite", and the header then falls back to the
+ // clip's own start -- which is what `entry.cite ?? entry.start` has always
+ // done. Rounded like a window, for the same reason.
+ if (patch.cite === null || patch.cite === "") delete entry.cite;
+ else {
+ const v = Number(patch.cite);
+ if (!Number.isFinite(v) || v < 0) {
+ throw new Error("cite must be a number of seconds ≥ 0, or empty to use the clip's start");
}
+ entry.cite = round2(v);
}
+ }
- // ---- the CUT, inside the extent ------------------------------------------
- //
- // `start`/`end` is the reviewed EXTENT -- how much of this recording is
- // worth having -- and `cutStart`/`cutEnd` is the tight cut the video
- // renders, derived from where the quote actually is. Two numbers, one
- // rule: a cut that is not inside its extent is not a cut, it is a second
- // window nobody reviewed.
- //
- // Both or neither. A lone `cutStart` reads like a decision and builds like
- // nothing, because the build only honours the pair.
- for (const k of ["cutStart", "cutEnd"]) {
- if (patch[k] === undefined) continue;
- const raw = patch[k];
- if (raw === null || raw === "") {
- delete entry[k];
- continue;
- }
- const v = Number(raw);
- if (!Number.isFinite(v) || v < 0) throw new Error(`${k} must be a number ≥ 0, or empty`);
- entry[k] = round2(v);
- }
- if (patch.cutStart !== undefined || patch.cutEnd !== undefined || patch.start !== undefined || patch.end !== undefined) {
- const hasStart = entry.cutStart != null;
- const hasEnd = entry.cutEnd != null;
- if (hasStart !== hasEnd) {
- throw new Error("a cut needs both cutStart and cutEnd, or neither");
+ if (patch.citeUrl !== undefined) {
+ const v = String(patch.citeUrl ?? "").trim();
+ if (!v) delete entry.citeUrl;
+ else {
+ // The QR target. A value that is not an http(s) URL encodes to something
+ // a phone camera opens and nothing answers -- the same class of defect
+ // as the 19 codes that shipped reading `undefined/?v=…`.
+ let u = null;
+ try {
+ u = new URL(v);
+ } catch {
+ /* handled below */
}
- if (hasStart) {
- if (entry.cutEnd - entry.cutStart < 0.5) {
- throw new Error(`a cut must be at least half a second (${entry.cutStart}–${entry.cutEnd})`);
- }
- if (
- entry.cutStart < entry.start - WIN_EPS ||
- entry.cutEnd > entry.end + WIN_EPS
- ) {
- throw new Error(
- `the cut ${entry.cutStart}–${entry.cutEnd} must lie inside the window ` +
- `${entry.start}–${entry.end} — widen the window, or clear the cut`,
- );
- }
+ if (!u || (u.protocol !== "http:" && u.protocol !== "https:")) {
+ throw new Error(`citeUrl must be an http:// or https:// URL (got \`${v}\`)`);
}
+ entry.citeUrl = v;
}
+ }
- // ---- the mute mark ------------------------------------------------------
- //
- // `muteFrom`: from this source second to the end of the clip the sound
- // fades out and the picture plays on -- set by ear, in the bench, at the
- // last silence before a finale's ending sound. Inside the EXTENT, like the
- // cut, and checked against the entry AFTER the patch: a window save that
- // leaves the mark outside is refused rather than keeping a mark that no
- // longer says anything about the clip. Empty or null deletes it.
- if (patch.muteFrom !== undefined) {
- const v = parseMuteFrom(patch.muteFrom, entry.start, entry.end);
- if (v == null) delete entry.muteFrom;
- else entry.muteFrom = v;
- } else if ((patch.start !== undefined || patch.end !== undefined) && entry.muteFrom != null) {
- // Clamped and STORED, as a patched mark is: a mark within the writer's
- // 0.02 s of the moved edge lands on it (past the new start it still
- // mutes the whole clip), and the build (validateMuteFrom, strict)
- // accepts every manifest saved here. Left as it was, a start moved from 10.00 to 10.01 under a mark at
- // 10.00 saved, and the next build refused the whole manifest.
- try {
- entry.muteFrom = parseMuteFrom(entry.muteFrom, entry.start, entry.end);
- } catch {
+ // ---- the CUT, inside the extent ------------------------------------------
+ //
+ // `start`/`end` is the reviewed EXTENT -- how much of this recording is
+ // worth having -- and `cutStart`/`cutEnd` is the tight cut the video
+ // renders, derived from where the quote actually is. Two numbers, one
+ // rule: a cut that is not inside its extent is not a cut, it is a second
+ // window nobody reviewed.
+ //
+ // Both or neither. A lone `cutStart` reads like a decision and builds like
+ // nothing, because the build only honours the pair.
+ for (const k of ["cutStart", "cutEnd"]) {
+ if (patch[k] === undefined) continue;
+ const raw = patch[k];
+ if (raw === null || raw === "") {
+ delete entry[k];
+ continue;
+ }
+ const v = Number(raw);
+ if (!Number.isFinite(v) || v < 0) throw new Error(`${k} must be a number ≥ 0, or empty`);
+ entry[k] = round2(v);
+ }
+ if (patch.cutStart !== undefined || patch.cutEnd !== undefined || patch.start !== undefined || patch.end !== undefined) {
+ const hasStart = entry.cutStart != null;
+ const hasEnd = entry.cutEnd != null;
+ if (hasStart !== hasEnd) {
+ throw new Error("a cut needs both cutStart and cutEnd, or neither");
+ }
+ if (hasStart) {
+ if (entry.cutEnd - entry.cutStart < 0.5) {
+ throw new Error(`a cut must be at least half a second (${entry.cutStart}–${entry.cutEnd})`);
+ }
+ if (
+ entry.cutStart < entry.start - WIN_EPS ||
+ entry.cutEnd > entry.end + WIN_EPS
+ ) {
throw new Error(
- `the mute mark ${entry.muteFrom} must lie inside the window ` +
- `${entry.start}–${entry.end} — widen the window, or clear the mark`,
+ `the cut ${entry.cutStart}–${entry.cutEnd} must lie inside the window ` +
+ `${entry.start}–${entry.end} — widen the window, or clear the cut`,
);
}
}
+ }
- // ---- a claim's `at` stays inside the window (video knobs) ---------------
- //
- // The source second its stamp lands, on the entry's clock: a window save
- // that leaves it outside is refused, as the mute mark's is, rather than
- // keeping a mark that no longer says anything about the clip.
- if (patch.start !== undefined || patch.end !== undefined) {
- const many = Array.isArray(entry.claims);
- rawMarksOf(entry).forEach((m, k) => {
- if (!isObj(m) || typeof m.at !== "number" || (m.at >= entry.start && m.at <= entry.end)) return;
- const name = many ? `the mark ${m.id}'s second (claims[${k}].at ${m.at})` : `the stamp's second (claim.at ${m.at})`;
- throw new Error(
- `${name} must lie inside the window ` +
- `${entry.start}–${entry.end} — widen the window, or clear ${many ? "that mark's at" : "claim.at"}`,
- );
- });
+ // ---- the mute mark ------------------------------------------------------
+ //
+ // `muteFrom`: from this source second to the end of the clip the sound
+ // fades out and the picture plays on -- set by ear, in the bench, at the
+ // last silence before a finale's ending sound. Inside the EXTENT, like the
+ // cut, and checked against the entry AFTER the patch: a window save that
+ // leaves the mark outside is refused rather than keeping a mark that no
+ // longer says anything about the clip. Empty or null deletes it.
+ if (patch.muteFrom !== undefined) {
+ const v = parseMuteFrom(patch.muteFrom, entry.start, entry.end);
+ if (v == null) delete entry.muteFrom;
+ else entry.muteFrom = v;
+ } else if ((patch.start !== undefined || patch.end !== undefined) && entry.muteFrom != null) {
+ // Clamped and STORED, as a patched mark is: a mark within the writer's
+ // 0.02 s of the moved edge lands on it (past the new start it still
+ // mutes the whole clip), and the build (validateMuteFrom, strict)
+ // accepts every manifest saved here. Left as it was, a start moved from 10.00 to 10.01 under a mark at
+ // 10.00 saved, and the next build refused the whole manifest.
+ try {
+ entry.muteFrom = parseMuteFrom(entry.muteFrom, entry.start, entry.end);
+ } catch {
+ throw new Error(
+ `the mute mark ${entry.muteFrom} must lie inside the window ` +
+ `${entry.start}–${entry.end} — widen the window, or clear the mark`,
+ );
}
+ }
- // ---- the clip's sound (video knobs) -------------------------------------
- //
- // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment
- // encode (report-to-video clip-audio.mjs, whose validateClipAudio is the
- // check). Each key is merged into what the clip has; a key set to null
- // removes it, and `audio: null` (or "") removes them all. A key at 0 is
- // removed (0 is what absent says), and nothing left removes `audio`:
- // absent is the build as it always was.
- if (patch.audio !== undefined) {
- const v = patch.audio;
- if (v === null || v === "") delete entry.audio;
- else {
- if (!isObj(v)) throw new Error("audio must be { offset?, gain?, fadeIn?, fadeOut? }, or null to clear it");
- const next = { ...(isObj(entry.audio) ? entry.audio : {}) };
- for (const [k, x] of Object.entries(v)) {
- if (x === null || x === "") delete next[k];
- else next[k] = typeof x === "string" ? Number(x) : x;
- }
- const errors = validateClipAudio(next);
- if (errors.length) throw new Error(errors.join("; "));
- if (typeof next.offset === "number") next.offset = Math.round(next.offset);
- if (typeof next.gain === "number") next.gain = Number(next.gain.toFixed(1));
- for (const k of ["fadeIn", "fadeOut"]) if (typeof next[k] === "number") next[k] = round2(next[k]);
- for (const k of Object.keys(next)) if (next[k] === 0) delete next[k];
- if (Object.keys(next).length) entry.audio = next;
- else delete entry.audio;
+ // ---- a claim's `at` stays inside the window (video knobs) ---------------
+ //
+ // The source second its stamp lands, on the entry's clock: a window save
+ // that leaves it outside is refused, as the mute mark's is, rather than
+ // keeping a mark that no longer says anything about the clip.
+ if (patch.start !== undefined || patch.end !== undefined) {
+ const many = Array.isArray(entry.claims);
+ rawMarksOf(entry).forEach((m, k) => {
+ if (!isObj(m) || typeof m.at !== "number" || (m.at >= entry.start && m.at <= entry.end)) return;
+ const name = many ? `the mark ${m.id}'s second (claims[${k}].at ${m.at})` : `the stamp's second (claim.at ${m.at})`;
+ throw new Error(
+ `${name} must lie inside the window ` +
+ `${entry.start}–${entry.end} — widen the window, or clear ${many ? "that mark's at" : "claim.at"}`,
+ );
+ });
+ }
+
+ // ---- the clip's sound (video knobs) -------------------------------------
+ //
+ // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment
+ // encode (report-to-video clip-audio.mjs, whose validateClipAudio is the
+ // check). Each key is merged into what the clip has; a key set to null
+ // removes it, and `audio: null` (or "") removes them all. A key at 0 is
+ // removed (0 is what absent says), and nothing left removes `audio`:
+ // absent is the build as it always was.
+ if (patch.audio !== undefined) {
+ const v = patch.audio;
+ if (v === null || v === "") delete entry.audio;
+ else {
+ if (!isObj(v)) throw new Error("audio must be { offset?, gain?, fadeIn?, fadeOut? }, or null to clear it");
+ const next = { ...(isObj(entry.audio) ? entry.audio : {}) };
+ for (const [k, x] of Object.entries(v)) {
+ if (x === null || x === "") delete next[k];
+ else next[k] = typeof x === "string" ? Number(x) : x;
}
+ const errors = validateClipAudio(next);
+ if (errors.length) throw new Error(errors.join("; "));
+ if (typeof next.offset === "number") next.offset = Math.round(next.offset);
+ if (typeof next.gain === "number") next.gain = Number(next.gain.toFixed(1));
+ for (const k of ["fadeIn", "fadeOut"]) if (typeof next[k] === "number") next[k] = round2(next[k]);
+ for (const k of Object.keys(next)) if (next[k] === 0) delete next[k];
+ if (Object.keys(next).length) entry.audio = next;
+ else delete entry.audio;
}
+ }
- // ---- the clip's picture, blurred (video knobs) ---------------------------
- //
- // `blur: { on: true, caption?, strength?, from?, to? }` -- applied at the
- // segment encode (report-to-video clip-blur.mjs, whose validateClipBlur is
- // the check, against the window as patched). Merged into what the clip
- // has, as `audio` is: a key set to null removes it; `blur: null` (or "",
- // or `on` null/false) removes it all. A caption or strength at its default
- // is removed (absent says it), and so are a caption's outer spaces.
- if (patch.blur !== undefined) {
- const v = patch.blur;
- if (v === null || v === "" || (isObj(v) && (v.on === null || v.on === false || v.on === ""))) delete entry.blur;
- else {
- if (!isObj(v)) throw new Error("blur must be { on: true, caption?, strength?, from?, to? }, or null to clear it");
- const next = { ...(isObj(entry.blur) ? entry.blur : {}) };
- for (const [k, x] of Object.entries(v)) {
- if (x === null || x === "") delete next[k];
- else if (k === "on" && x === "true") next.on = true;
- else if (["strength", "from", "to"].includes(k) && typeof x === "string") next[k] = Number(x);
- else next[k] = x;
- }
- if (typeof next.caption === "string") next.caption = next.caption.trim();
- if (next.caption === BLUR_CAPTION_DEFAULT || next.caption === "") delete next.caption;
- if (typeof next.strength === "number") next.strength = Number(next.strength.toFixed(1));
- if (next.strength === BLUR_STRENGTH.default) delete next.strength;
- for (const k of ["from", "to"]) if (typeof next[k] === "number" && Number.isFinite(next[k])) next[k] = round2(next[k]);
- const errors = validateClipBlur(next, "blur", entry);
- if (errors.length) throw new Error(errors.join("; "));
- // `on` first: the manifests are read by humans.
- const { on, ...rest } = next;
- entry.blur = { on, ...rest };
+ // ---- the clip's picture, blurred (video knobs) ---------------------------
+ //
+ // `blur: { on: true, caption?, strength?, from?, to? }` -- applied at the
+ // segment encode (report-to-video clip-blur.mjs, whose validateClipBlur is
+ // the check, against the window as patched). Merged into what the clip
+ // has, as `audio` is: a key set to null removes it; `blur: null` (or "",
+ // or `on` null/false) removes it all. A caption or strength at its default
+ // is removed (absent says it), and so are a caption's outer spaces.
+ if (patch.blur !== undefined) {
+ const v = patch.blur;
+ if (v === null || v === "" || (isObj(v) && (v.on === null || v.on === false || v.on === ""))) delete entry.blur;
+ else {
+ if (!isObj(v)) throw new Error("blur must be { on: true, caption?, strength?, from?, to? }, or null to clear it");
+ const next = { ...(isObj(entry.blur) ? entry.blur : {}) };
+ for (const [k, x] of Object.entries(v)) {
+ if (x === null || x === "") delete next[k];
+ else if (k === "on" && x === "true") next.on = true;
+ else if (["strength", "from", "to"].includes(k) && typeof x === "string") next[k] = Number(x);
+ else next[k] = x;
}
- } else if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.blur)) {
- // A window save that leaves a partial blur's span outside is refused, as
- // a claim's `at` is: the span no longer says anything about the clip.
- const errors = validateClipBlur(entry.blur, "blur", entry);
+ if (typeof next.caption === "string") next.caption = next.caption.trim();
+ if (next.caption === BLUR_CAPTION_DEFAULT || next.caption === "") delete next.caption;
+ if (typeof next.strength === "number") next.strength = Number(next.strength.toFixed(1));
+ if (next.strength === BLUR_STRENGTH.default) delete next.strength;
+ for (const k of ["from", "to"]) if (typeof next[k] === "number" && Number.isFinite(next[k])) next[k] = round2(next[k]);
+ const errors = validateClipBlur(next, "blur", entry);
if (errors.length) throw new Error(errors.join("; "));
+ // `on` first: the manifests are read by humans.
+ const { on, ...rest } = next;
+ entry.blur = { on, ...rest };
}
+ } else if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.blur)) {
+ // A window save that leaves a partial blur's span outside is refused, as
+ // a claim's `at` is: the span no longer says anything about the clip.
+ const errors = validateClipBlur(entry.blur, "blur", entry);
+ if (errors.length) throw new Error(errors.join("; "));
+ }
- // ---- how the deck lays this entry out -----------------------------------
- //
- // `layout: "finale"` (the deck's finale layout, render.chrome.deck.finale);
- // "clip" -- the default -- or null/"" removes the key. Only these two: a
- // layout the deck does not draw is refused here, not at the build.
- if (patch.layout !== undefined) {
- const v = patch.layout;
- if (v === null || v === "" || v === "clip") delete entry.layout;
- else if (v === "finale") entry.layout = "finale";
- else throw new Error(`layout must be "finale" or "clip" (the default), not ${JSON.stringify(v)}`);
- // The finale's run (finale.mjs): a write may not break it -- refused
- // when it adds a problem the file did not have. Mark from the last
- // clip back, unmark from the first on.
- const was = new Set(validateFinaleEntries(JSON.parse(raw)));
- const bad = validateFinaleEntries(manifest).filter((e) => !was.has(e));
- if (bad.length) throw new Error(`layout: ${bad.join("; ")}`);
- }
+ // ---- how the deck lays this entry out -----------------------------------
+ //
+ // `layout: "finale"` (the deck's finale layout, render.chrome.deck.finale);
+ // "clip" -- the default -- or null/"" removes the key. Only these two: a
+ // layout the deck does not draw is refused here, not at the build.
+ if (patch.layout !== undefined) {
+ const v = patch.layout;
+ if (v === null || v === "" || v === "clip") delete entry.layout;
+ else if (v === "finale") entry.layout = "finale";
+ else throw new Error(`layout must be "finale" or "clip" (the default), not ${JSON.stringify(v)}`);
+ // The finale's run (finale.mjs): a write may not break it -- refused
+ // when it adds a problem the file did not have. Mark from the last
+ // clip back, unmark from the first on.
+ const was = new Set(validateFinaleEntries(JSON.parse(/** @type {string} */ (original))));
+ const bad = validateFinaleEntries(manifest).filter((e) => !was.has(e));
+ if (bad.length) throw new Error(`layout: ${bad.join("; ")}`);
+ }
- // ---- the walk's verdict -------------------------------------------------
- //
- // Whether somebody has LOOKED at this clip and said the description is what
- // the clip actually is. Three states, and an absent key is the honest way
- // to say "nobody has been here":
- //
- // verdict: "confirmed" -> the description is accurate
- // verdict: "incorrect" -> it is not, and `correction` says how
- // neither -> not yet reviewed
- //
- // `correction` is OPTIONAL under a confirmed verdict and REQUIRED under an
- // incorrect one. The two are not the same sentence: a note on a good clip
- // is why its window moved or a caveat for the writers, while an incorrect
- // clip with no note is a complaint nobody can act on. So the rule is a
- // property of the ENTRY AFTER the patch, which makes both halves of it one
- // check -- setting `incorrect` with no note, and clearing the note off a
- // clip that is already `incorrect`, are the same error.
- //
- // LEGACY, and deliberately not migrated: a clip carrying a `correction` and
- // no `verdict` predates `incorrect` and READS as incorrect (clipVerdict()).
- // The requirement above is keyed on the explicit value, so those entries can
- // still be cleared -- a rule that refused to let somebody undo a note they
- // wrote before the rule existed would be a trap.
- if (patch.verdict !== undefined) {
- const v = String(patch.verdict ?? "").trim();
- if (!v) delete entry.verdict;
- else if (v !== "confirmed" && v !== "incorrect") {
- throw new Error(
- `verdict must be "confirmed" or "incorrect", or empty to clear it (got \`${v}\`)`,
- );
- } else entry.verdict = v;
- }
+ // ---- the walk's verdict -------------------------------------------------
+ //
+ // Whether somebody has LOOKED at this clip and said the description is what
+ // the clip actually is. Three states, and an absent key is the honest way
+ // to say "nobody has been here":
+ //
+ // verdict: "confirmed" -> the description is accurate
+ // verdict: "incorrect" -> it is not, and `correction` says how
+ // neither -> not yet reviewed
+ //
+ // `correction` is OPTIONAL under a confirmed verdict and REQUIRED under an
+ // incorrect one. The two are not the same sentence: a note on a good clip
+ // is why its window moved or a caveat for the writers, while an incorrect
+ // clip with no note is a complaint nobody can act on. So the rule is a
+ // property of the ENTRY AFTER the patch, which makes both halves of it one
+ // check -- setting `incorrect` with no note, and clearing the note off a
+ // clip that is already `incorrect`, are the same error.
+ //
+ // LEGACY, and deliberately not migrated: a clip carrying a `correction` and
+ // no `verdict` predates `incorrect` and READS as incorrect (clipVerdict()).
+ // The requirement above is keyed on the explicit value, so those entries can
+ // still be cleared -- a rule that refused to let somebody undo a note they
+ // wrote before the rule existed would be a trap.
+ if (patch.verdict !== undefined) {
+ const v = String(patch.verdict ?? "").trim();
+ if (!v) delete entry.verdict;
+ else if (v !== "confirmed" && v !== "incorrect") {
+ throw new Error(
+ `verdict must be "confirmed" or "incorrect", or empty to clear it (got \`${v}\`)`,
+ );
+ } else entry.verdict = v;
+ }
- if (entry.verdict === "incorrect" && !String(entry.correction ?? "").trim()) {
- throw new Error("an incorrect verdict needs its note: say what the report got wrong");
- }
+ if (entry.verdict === "incorrect" && !String(entry.correction ?? "").trim()) {
+ throw new Error("an incorrect verdict needs its note: say what the report got wrong");
+ }
- // ---- what the deck will say ---------------------------------------------
- //
- // The bench's On-screen fields, written in the same sitting as the header
- // fields above. setOnscreen is updateOnscreen's rule, so a clip edited here
- // and a row saved from the On-screen table cannot store different shapes.
- if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen);
-
- // ---- the vertical short's framing (release 36 lane C) --------------------
- //
- // `vertical: {crop: [x, y, w, h], aspect?}` -- fractions of the source
- // picture, 9:16 on it (look.mjs verticalErrors, the build's own check).
- // null or "" removes it: the short is cut from the centre again.
- if (patch.vertical !== undefined) {
- const v = patch.vertical;
- if (v === null || v === "") delete entry.vertical;
- else {
- const errors = verticalErrors(v, "vertical");
- if (errors.length) throw new Error(errors.join("; "));
- const r4 = (n) => Number(Number(n).toFixed(4));
- const vv = /** @type {{ crop: number[], aspect?: number }} */ (v);
- entry.vertical = { crop: vv.crop.map(r4), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}) };
- }
+ // ---- what the deck will say ---------------------------------------------
+ //
+ // The bench's On-screen fields, written in the same sitting as the header
+ // fields above. setOnscreen is updateOnscreen's rule, so a clip edited here
+ // and a row saved from the On-screen table cannot store different shapes.
+ if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen);
+
+ // ---- the vertical short's framing (release 36 lane C) --------------------
+ //
+ // `vertical: {crop: [x, y, w, h], aspect?}` -- fractions of the source
+ // picture, 9:16 on it (look.mjs verticalErrors, the build's own check).
+ // null or "" removes it: the short is cut from the centre again.
+ if (patch.vertical !== undefined) {
+ const v = patch.vertical;
+ if (v === null || v === "") delete entry.vertical;
+ else {
+ const errors = verticalErrors(v, "vertical");
+ if (errors.length) throw new Error(errors.join("; "));
+ const r4 = (n) => Number(Number(n).toFixed(4));
+ const vv = /** @type {{ crop: number[], aspect?: number }} */ (v);
+ entry.vertical = { crop: vv.crop.map(r4), ...(vv.aspect !== undefined ? { aspect: r4(vv.aspect) } : {}) };
}
+ }
- // ---- room at the clip's edges (release 36 lane E) ------------------------
- //
- // `room: false` (none for this clip) or `{tail?, head?}` (that edge, whatever
- // the cut's render.room says) -- room.mjs validateRoom, the build's own
- // check. null or "" removes it: the cut's room again.
- if (patch.room !== undefined) {
- const v = patch.room;
- if (v === null || v === "") delete entry.room;
- else {
- const errors = validateRoom({ timeline: [{ ...entry, room: v }] });
- if (errors.length) throw new Error(errors.join("; "));
- const vv = /** @type {false | { tail?: boolean, head?: boolean }} */ (v);
- entry.room = vv === false ? false : { ...(typeof vv.tail === "boolean" ? { tail: vv.tail } : {}), ...(typeof vv.head === "boolean" ? { head: vv.head } : {}) };
- }
+ // ---- room at the clip's edges (release 36 lane E) ------------------------
+ //
+ // `room: false` (none for this clip) or `{tail?, head?}` (that edge, whatever
+ // the cut's render.room says) -- room.mjs validateRoom, the build's own
+ // check. null or "" removes it: the cut's room again.
+ if (patch.room !== undefined) {
+ const v = patch.room;
+ if (v === null || v === "") delete entry.room;
+ else {
+ const errors = validateRoom({ timeline: [{ ...entry, room: v }] });
+ if (errors.length) throw new Error(errors.join("; "));
+ const vv = /** @type {false | { tail?: boolean, head?: boolean }} */ (v);
+ entry.room = vv === false ? false : { ...(typeof vv.tail === "boolean" ? { tail: vv.tail } : {}), ...(typeof vv.head === "boolean" ? { head: vv.head } : {}) };
}
+ }
- // ---- an assistant's clip, edited by a person (release 35 C2) -------------
- //
- // A clip the clip finder proposed carries `assist`. The first human edit
- // of its cut flips `assist.by` to "operator" (a re-propose never touches
- // it again) and every edit is appended to `assist.edits`. Restore puts the
- // assistant's `original` back, and the clip is the assistant's again.
- const at = now ?? new Date().toISOString();
- noteAssistEdit(entry, edit, cutBefore, at);
- if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant";
-
- const nextToken = await writeManifestAtomic(dir, manifest);
- // A moved extent may need a new bench excerpt: queued, never waited for.
- if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]);
- return { entry, before, token: nextToken };
- });
+ // ---- an assistant's clip, edited by a person (release 35 C2) -------------
+ //
+ // A clip the clip finder proposed carries `assist`. The first human edit
+ // of its cut flips `assist.by` to "operator" (a re-propose never touches
+ // it again) and every edit is appended to `assist.edits`. Restore puts the
+ // assistant's `original` back, and the clip is the assistant's again.
+ const at = now ?? new Date().toISOString();
+ noteAssistEdit(entry, edit, cutBefore, at);
+ if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant";
+
+ return { entry, before };
}
// ---------------------------------------------------------------------------
@@ -1474,6 +1495,51 @@ async function prepAfter(dir, ids, write) {
const clipIdOf = (r) => [r?.entry?.type === "clip" ? r.id : null];
/**
+ * A structural edit over a manifest held in memory: `mutate` (which throws to
+ * refuse), then the build's checks -- refused only for what THIS edit breaks --
+ * then `sectionEnter` recomputed. Mutates `manifest`; returns mutate's result.
+ * The project's writers run it inside the lock (structural, below); a take's
+ * walk runs it on the take's timeline (takeEdit.mjs).
+ *
+ * @template T
+ * @param {Record<string, any>} manifest
+ * @param {(m: Record<string, any>) => T} mutate
+ * @returns {T}
+ */
+export function applyStructural(manifest, mutate) {
+ if (!Array.isArray(manifest.timeline)) manifest.timeline = [];
+ // Only what THIS edit breaks refuses it: a manifest that already carries a
+ // problem the build would name (somebody's hand edit) can still be
+ // re-ordered, and the problem is still the build's to report.
+ const already = new Set(structureErrors(manifest));
+ const result = mutate(manifest);
+ const errors = structureErrors(manifest).filter((e) => !already.has(e));
+ if (errors.length) throw new StructureRefused(errors);
+ applySectionEnter(manifest.timeline);
+ return result;
+}
+
+/** Move entry `id` to `toIndex` in `m.timeline` (moveEntry's rule, in memory). */
+export function moveIn(m, id, toIndex, at = null) {
+ const from = entryIndex(m.timeline, id, at);
+ const to = Number(toIndex);
+ if (!Number.isInteger(to) || to < 0 || to >= m.timeline.length) {
+ throw new Error(`toIndex must be 0–${m.timeline.length - 1}`);
+ }
+ if (to === from) throw new Error(`${id} is already at ${to}`);
+ const [e] = m.timeline.splice(from, 1);
+ m.timeline.splice(to, 0, e);
+ return { id, from, to };
+}
+
+/** Remove entry `id` from `m.timeline` (removeEntry's rule, in memory). */
+export function removeIn(m, id, at = null) {
+ const i = entryIndex(m.timeline, id, at);
+ const [removed] = m.timeline.splice(i, 1);
+ return { id, at: i, removed };
+}
+
+/**
* One structural write: token, read, `mutate` (which throws to refuse), the
* build's checks, the auto snapshot of the file as it still is, then the write.
*/
@@ -1482,15 +1548,7 @@ async function structural(dir, op, token, mutate) {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
- if (!Array.isArray(manifest.timeline)) manifest.timeline = [];
- // Only what THIS edit breaks refuses it: a manifest that already carries a
- // problem the build would name (somebody's hand edit) can still be
- // re-ordered, and the problem is still the build's to report.
- const already = new Set(structureErrors(manifest));
- const result = mutate(manifest);
- const errors = structureErrors(manifest).filter((e) => !already.has(e));
- if (errors.length) throw new StructureRefused(errors);
- applySectionEnter(manifest.timeline);
+ const result = applyStructural(manifest, mutate);
const snapshot = await autoSnapshot(dir, op);
const nextToken = await writeManifestAtomic(dir, manifest);
return { ...result, snapshot, token: nextToken };
@@ -1508,17 +1566,7 @@ async function structural(dir, op, token, mutate) {
* @param {{ token?: string | null, at?: number | null }} [opts]
*/
export async function moveEntry(dir, id, toIndex, { token = null, at = null } = {}) {
- return structural(dir, "move", token, (m) => {
- const from = entryIndex(m.timeline, id, at);
- const to = Number(toIndex);
- if (!Number.isInteger(to) || to < 0 || to >= m.timeline.length) {
- throw new Error(`toIndex must be 0–${m.timeline.length - 1}`);
- }
- if (to === from) throw new Error(`${id} is already at ${to}`);
- const [e] = m.timeline.splice(from, 1);
- m.timeline.splice(to, 0, e);
- return { id, from, to };
- });
+ return structural(dir, "move", token, (m) => moveIn(m, id, toIndex, at));
}
/**
@@ -1530,11 +1578,7 @@ export async function moveEntry(dir, id, toIndex, { token = null, at = null } =
* @param {{ token?: string | null, at?: number | null }} [opts]
*/
export async function removeEntry(dir, id, { token = null, at = null } = {}) {
- return structural(dir, "remove", token, (m) => {
- const i = entryIndex(m.timeline, id, at);
- const [removed] = m.timeline.splice(i, 1);
- return { id, at: i, removed };
- });
+ return structural(dir, "remove", token, (m) => removeIn(m, id, at));
}
/** Copy one entry to just after itself, under a fresh id. A copied claim is dropped (one claim, one entry). *
diff --git a/umtool/lib/report/serve.mjs b/umtool/lib/report/serve.mjs
@@ -85,6 +85,9 @@ export { rawCacheOf } from "./raw-cache.mjs";
* are the question. A bare rawCacheOf sees only out/clips-raw, so a window the
* editor fetched reads as "nothing fetched for this clip yet" and the bench
* offers to download bytes that are already on the disk.
+ *
+ * @param {any} project
+ * @param {Record<string, any> | null} [manifest] the manifest whose clips name the dirs (a take's, walking one); else the project's
*/
export async function projectCache(project, manifest = null) {
const m = manifest ?? (await readManifest(project.dir));
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -23,6 +23,7 @@ import {
RECIPE_FILE,
TakeStale,
allStylesRecipe,
+ draftTake,
loadMontageStyles,
makeTake,
makeTakes,
@@ -38,7 +39,15 @@ export const TAKE_USAGE = [
" [--summary S] [--style NAME] [--patch FILE | --patch-json JSON | --set path=value …]",
" [--effect NAME] [--at S --dur S | --full] [--quick] [--force] [--progress ndjson]",
" [--from TAKE] [--keep-frames]",
- " umtool take <project> --id <id> --rebuild [--from TAKE] [--keep-frames] made again from its own take.json",
+ " umtool take <project> --id <id> --rebuild [--at S --dur S | --full] [--from TAKE] [--keep-frames]",
+ " made again from its own take.json (its stored patch, walked edits included); a window",
+ " flag renders it over that window instead of its own",
+ " umtool take <project> --id <id> --label L [--patch F | …] --draft (or --no-render) the take RECORDED,",
+ " nothing rendered: it can be walked (/projects/<p>/takes/<id>/walk, `umtool walk <p> --take <id>`)",
+ " and its clips edited into its patch; `umtool take <p> --id <id> --full` renders it later",
+ " umtool take <project> --id <id> --promote [--anyway] [--json] make this the cut: the take's manifest",
+ " (its patch applied to the project's manifest now) over the project's -- one undo point",
+ " (revisions/…-auto-before-promote-take; `umtool timeline <p> undo` takes it back)",
"",
"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",
@@ -194,21 +203,28 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
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)");
+ if (p.has("--promote")) return await promote(project, id, p, log, err);
+ const draft = p.has("--draft") || p.has("--no-render");
+ const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null);
+ // A DRAFT named with no patch of its own is rendered from what it stores --
+ // its patch as the walk left it -- as --rebuild is: `umtool take <p> --id X --full`.
+ const patchGiven = ["--patch", "--patch-json", "--set", "--style", "--effect"].some((n) => p.has(n));
+ const fromStored = p.has("--rebuild") || (!draft && prev?.draft === true && !patchGiven);
+ if (draft && p.has("--rebuild")) throw new CliError("--draft or --rebuild, not both");
let spec;
- if (p.has("--rebuild")) {
- const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null);
+ if (fromStored) {
if (!prev) throw new CliError(`${project.id} has no take ${id} to rebuild`);
spec = {
id,
- label: prev.label,
+ label: p.one("--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,
+ window: windowOf(p) ?? prev.window ?? undefined,
+ quick: p.has("--quick") || prev.quick === true,
};
} else {
spec = {
@@ -223,8 +239,20 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
quick: p.has("--quick"),
};
}
+ if (draft) {
+ const d = await draftTake(project.dir, spec, { force: p.has("--force"), ...(deps?.styles ? { styles: /** @type {any} */ (deps.styles) } : {}) });
+ if (p.has("--json")) {
+ log(JSON.stringify({ ok: true, draft: true, ...d }, null, 2));
+ return 0;
+ }
+ out.log(`take ${id}: a draft, nothing rendered — ${d.clips} clip(s), ${d.entries} entr${d.entries === 1 ? "y" : "ies"}`);
+ for (const c of d.take.changes.slice(0, 8)) out.log(` ${c}`);
+ out.log(`walk it: umtool walk ${project.id} --take ${id} (the bench: /projects/${project.id}/takes/${id}/walk)`);
+ out.log(`render it: umtool take ${project.id} --id ${id} --full`);
+ return 0;
+ }
const r = await makeTake(project.dir, spec, {
- force: p.has("--force") || p.has("--rebuild"),
+ force: p.has("--force") || fromStored,
from: p.one("--from") ?? null,
keepFrames: p.has("--keep-frames"),
emit: out.emit,
@@ -243,6 +271,28 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons
}
}
+/** `umtool take <p> --id X --promote [--anyway]`: make the take the cut (takeEdit.mjs promoteTake). */
+async function promote(project, id, p, log, err) {
+ const { PromoteStale, promoteTake } = await import("./takeEdit.mjs");
+ try {
+ const r = await promoteTake(project, id, { anyway: p.has("--anyway") });
+ if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2));
+ else {
+ log(`${project.id}: take ${id} is the cut now — ${r.clips} clip(s), ${r.entries} entr${r.entries === 1 ? "y" : "ies"}`);
+ if (r.note) log(` ${r.note}`);
+ if (r.snapshot?.rel && !r.snapshot.skipped) log(` undo point: ${r.snapshot.rel} (umtool timeline ${project.id} undo)`);
+ else if (r.snapshot?.error) log(` NO undo point: ${r.snapshot.error}`);
+ }
+ return 0;
+ } catch (e) {
+ if (e instanceof PromoteStale) {
+ err(`${e.message} — pass --anyway to make it the cut all the same`);
+ return 1;
+ }
+ throw e;
+ }
+}
+
/**
* `umtool takes …`
* @param {string[]} args everything after `takes`
diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs
@@ -0,0 +1,319 @@
+// WALK A TAKE: the take's own edits, and making it the cut.
+//
+// A take is the project's manifest with a style's patch, then its own, merged
+// (takeManifest.mjs resolveTakeManifest -- the merge the take build uses). The
+// clip bench can walk one (`/projects/<p>/takes/<take>/walk`); everything the
+// walk writes -- a verdict, a trim, an attribution fix, a clip removed or
+// moved -- goes into the TAKE's patch, in takes/<id>/take.json, and the
+// project's manifest is never touched:
+//
+// updateTakeClip(dir, take, clip, patch) the bench's window/verdict save (updateClip's rules)
+// moveTakeEntry / removeTakeEntry the structure (applyStructural, the build's checks)
+// undoTakeEdit(dir, take) the newest edit taken back, byte for byte
+// promoteTake(project, take) "Make this the cut": the take over the project's
+// manifest through replaceManifest (one undo)
+//
+// THE TIMELINE IS THE PATCH'S. A merge patch replaces an array whole, so a
+// take's timeline is `patch.timeline` when it has one, else the project's.
+// Every edit here resolves the take's manifest as it is now, applies the edit
+// to its timeline with the project writer's own functions (patchClipEntry,
+// applyStructural -- manifest.mjs), and writes the WHOLE edited timeline back
+// as `patch.timeline`. A take whose patch had no timeline (a style take) gets
+// one on its first edit: from then on its timeline is its own, and an edit to
+// the project's timeline no longer reaches it.
+//
+// UNDO. Every write first copies take.json, as it still is, into
+// takes/<id>/revisions/<stamp>-<ms>-auto-before-<op>.take.json -- every write,
+// not one per two minutes as the project's structural snapshots are: a walk is
+// many small edits and Undo means the last of them. undoTakeEdit restores the
+// newest such copy, keeps the take.json it replaces as `…-undo-saved…`, and
+// renames the restored one `…-undone-<op>…` so the next undo goes one further.
+//
+// THE TOKEN is take.json's mtime, as the project's is its manifest's: a write
+// carrying a stale one is a StaleToken (a 409), never a silent overwrite.
+//
+// Plain ESM: `umtool window --take`, `umtool timeline --take` and
+// `umtool take --promote` run it under bare node.
+import { createHash } from "node:crypto";
+import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ StaleToken,
+ applyStructural,
+ moveIn,
+ patchClipEntry,
+ removeIn,
+ replaceManifest,
+} from "./manifest.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs";
+import { stampOf } from "./snapshots.mjs";
+
+export const TAKE_REVISIONS_DIR = "revisions";
+const AUTO = "auto-before-";
+const REV_RE = /^(\d{8}-\d{6}-\d{3}(?:-\d+)?)-(.+)\.take\.json$/;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const serialise = (v) => JSON.stringify(v, null, 2) + "\n";
+const clone = (v) => JSON.parse(JSON.stringify(v));
+
+export const takeFileOf = (projectDir, id) => path.join(takesDirOf(projectDir), id, TAKE_FILE);
+export const takeRevisionsDirOf = (projectDir, id) => path.join(takesDirOf(projectDir), id, TAKE_REVISIONS_DIR);
+
+/** The mtime a client hands back to be allowed to write the take; null when there is no take.json. */
+export async function takeToken(projectDir, id) {
+ if (!isTakeId(id)) return null;
+ const st = await stat(takeFileOf(projectDir, id)).catch(() => null);
+ return st ? String(Math.round(st.mtimeMs)) : null;
+}
+
+// One queue per process, as manifest.mjs and takes.mjs keep their own: within
+// a process it serialises read-modify-write; across processes the tmp + rename
+// and the token are the guard.
+/** @type {Promise<unknown>} */
+let queue = Promise.resolve();
+/**
+ * @template T
+ * @param {() => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+function withTakeEditLock(fn) {
+ const run = queue.then(fn, fn);
+ queue = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+}
+
+/** take.json as text and as an object; throws a sentence when there is none. */
+async function readTakeDoc(projectDir, id) {
+ if (!isTakeId(id)) throw new Error(`"${id}" is not a take id`);
+ const text = await readFile(takeFileOf(projectDir, id), "utf8").catch(() => null);
+ if (text === null) throw new Error(`no take ${id} (no takes/${id}/${TAKE_FILE}) — record one with \`umtool take <project> --id ${id} --patch F --draft\``);
+ let doc;
+ try {
+ doc = JSON.parse(text);
+ } catch (e) {
+ throw new Error(`takes/${id}/${TAKE_FILE} does not parse; not writing over it (${e instanceof Error ? e.message : e})`);
+ }
+ if (!isObj(doc)) throw new Error(`takes/${id}/${TAKE_FILE} is not an object`);
+ return { text, doc };
+}
+
+/** A revision name no other one has: the stamp, the milliseconds, and a counter if need be. */
+async function freshRevisionName(revDir, label, now) {
+ const base = `${stampOf(now)}-${String(now.getMilliseconds()).padStart(3, "0")}`;
+ const taken = new Set(await readdir(revDir).catch(() => []));
+ for (let n = 0; ; n += 1) {
+ const name = `${base}${n ? `-${n}` : ""}-${label}.take.json`;
+ if (!taken.has(name)) return name;
+ }
+}
+
+/** Copy take.json's text into the take's revisions/ as `<stamp>-<label>.take.json`. */
+async function keepRevision(projectDir, id, text, label, now) {
+ const dir = takeRevisionsDirOf(projectDir, id);
+ await mkdir(dir, { recursive: true });
+ const name = await freshRevisionName(dir, label, now);
+ await writeFile(path.join(dir, name), text, "utf8");
+ return { rel: path.posix.join(TAKE_REVISIONS_DIR, name), name };
+}
+
+async function writeTakeAtomic(projectDir, id, doc) {
+ const file = takeFileOf(projectDir, id);
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, serialise(doc), "utf8");
+ await rename(tmp, file);
+ return takeToken(projectDir, id);
+}
+
+/**
+ * The take's revisions, newest first: `{ rel, name, stamp, label, auto }`.
+ * `auto` is an undo point (`auto-before-<op>`).
+ */
+export async function listTakeRevisions(projectDir, id) {
+ if (!isTakeId(id)) return [];
+ const names = await readdir(takeRevisionsDirOf(projectDir, id)).catch(() => []);
+ return names
+ .map((name) => {
+ const m = REV_RE.exec(name);
+ return m ? { rel: path.posix.join(TAKE_REVISIONS_DIR, name), name, stamp: m[1], label: m[2], auto: m[2].startsWith(AUTO) } : null;
+ })
+ .filter((r) => r !== null)
+ .sort((a, b) => b.stamp.localeCompare(a.stamp, "en", { numeric: true }) || b.name.localeCompare(a.name));
+}
+
+/**
+ * One write to the take's timeline: the token, the take's manifest resolved
+ * as it is now, `mutate` over it (which throws to refuse), the undo point,
+ * then `patch.timeline` and `editedAt` written into take.json.
+ *
+ * @template T
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {string} op
+ * @param {string | null} token
+ * @param {(manifest: Record<string, any>) => T} mutate
+ * @param {{ now?: Date }} [opts]
+ * @returns {Promise<T & { token: string | null, revision: { rel: string, name: string } }>}
+ */
+async function editTakeTimeline(projectDir, id, op, token, mutate, { now = new Date() } = {}) {
+ return withTakeEditLock(async () => {
+ const current = await takeToken(projectDir, id);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const { text, doc } = await readTakeDoc(projectDir, id);
+ const resolved = await resolveTakeManifest(projectDir, id);
+ const manifest = clone(resolved.manifest);
+ const result = mutate(manifest);
+ const revision = await keepRevision(projectDir, id, text, `${AUTO}${op}`, now);
+ doc.patch = { ...(isObj(doc.patch) ? doc.patch : {}), timeline: manifest.timeline };
+ doc.editedAt = now.toISOString();
+ const nextToken = await writeTakeAtomic(projectDir, id, doc);
+ return { ...result, token: nextToken, revision };
+ });
+}
+
+/**
+ * The bench's save, on a take: one clip's window, locks, attribution,
+ * verdict and the rest -- updateClip's whitelist and its rules
+ * (patchClipEntry), written into the take's patch.
+ *
+ * @param {string} projectDir
+ * @param {string} id the take
+ * @param {string} clipId
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null, edit?: string, now?: Date }} [opts]
+ */
+export async function updateTakeClip(projectDir, id, clipId, patch, { token = null, edit = "trim", now = new Date() } = {}) {
+ if (!isObj(patch)) throw new Error("a clip patch is an object");
+ return editTakeTimeline(
+ projectDir,
+ id,
+ edit === "trim" ? "clip" : edit,
+ token,
+ (m) => patchClipEntry(m, clipId, patch, { edit, now: now.toISOString() }),
+ { now },
+ );
+}
+
+/**
+ * Move one of the take's entries to `toIndex` (its index after the move).
+ * @param {string} projectDir
+ * @param {string} id the take
+ * @param {string} entryId
+ * @param {number} toIndex
+ * @param {{ token?: string | null, at?: number | null, now?: Date }} [opts]
+ */
+export async function moveTakeEntry(projectDir, id, entryId, toIndex, { token = null, at = null, now = new Date() } = {}) {
+ return editTakeTimeline(projectDir, id, "move", token, (m) => applyStructural(m, (x) => moveIn(x, entryId, toIndex, at)), { now });
+}
+
+/**
+ * Remove one of the take's entries (refused when something the take keeps still names it).
+ * @param {string} projectDir
+ * @param {string} id the take
+ * @param {string} entryId
+ * @param {{ token?: string | null, at?: number | null, now?: Date }} [opts]
+ */
+export async function removeTakeEntry(projectDir, id, entryId, { token = null, at = null, now = new Date() } = {}) {
+ return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at)), { now });
+}
+
+/**
+ * Take back the take's newest edit: its newest `auto-before-<op>` revision
+ * restored over take.json, byte for byte (see the top of the file).
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {{ token?: string | null, now?: Date }} [opts]
+ */
+export async function undoTakeEdit(projectDir, id, { token = null, now = new Date() } = {}) {
+ return withTakeEditLock(async () => {
+ const current = await takeToken(projectDir, id);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const { text } = await readTakeDoc(projectDir, id);
+ const target = (await listTakeRevisions(projectDir, id)).find((r) => r.auto);
+ if (!target) throw new Error(`nothing to undo: take ${id} has no edit to take back`);
+ const op = target.label.slice(AUTO.length);
+ const dir = takeRevisionsDirOf(projectDir, id);
+ const restored = await readFile(path.join(dir, target.name), "utf8");
+ JSON.parse(restored); // a revision that does not parse is not restored over a take.json that does
+ const saved = await keepRevision(projectDir, id, text, "undo-saved", now);
+ const file = takeFileOf(projectDir, id);
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, restored, "utf8");
+ await rename(tmp, file);
+ const undone = target.name.replace(`-${target.label}.take.json`, `-undone-${op}.take.json`);
+ await rename(path.join(dir, target.name), path.join(dir, undone)).catch(() => {});
+ return { restored: target.rel, op, saved: saved.rel, token: await takeToken(projectDir, id) };
+ });
+}
+
+/** Did the take's walk write anything? (editedAt, and the undo points it left.) */
+export async function takeEditState(projectDir, id) {
+ const revisions = await listTakeRevisions(projectDir, id);
+ return { undoable: revisions.filter((r) => r.auto).length, revisions };
+}
+
+export class PromoteStale extends Error {
+ /** @param {string} message */
+ constructor(message) {
+ super(message);
+ this.name = "PromoteStale";
+ }
+}
+
+const hashText = (text) => createHash("sha256").update(text).digest("hex");
+
+/**
+ * "Make this the cut": the take's manifest -- the project's as it is now, with
+ * the take's style patch and its own (walked) patch applied, the same merge a
+ * render makes -- written over the project's through replaceManifest (the lock,
+ * the token, ONE auto snapshot `auto-before-promote-take`, so the Cut tab's
+ * "Undo last edit" takes the whole promotion back), inside the generated-
+ * manifest guard, then recorded as the take's group's pick in verdicts.json.
+ *
+ * Not "Use this take" (pickTake): that copies the manifest the take was
+ * RENDERED from; this applies the take's patch now, so a draft, and a take
+ * walked since its render, promote exactly what was walked.
+ *
+ * Checked by the build's structure rules (refused only for what the
+ * promotion breaks). REFUSED (PromoteStale) when the take's patch replaces the
+ * timeline and the project's manifest changed since the take was made -- the
+ * promotion would throw away whatever the cut's timeline gained since --
+ * unless `anyway`.
+ *
+ * @param {{ id: string, dir: string, kind: string }} project
+ * @param {string} id
+ * @param {{ anyway?: boolean, token?: string | null, now?: Date }} [opts]
+ */
+export async function promoteTake(project, id, { anyway = false, token = null, now = new Date() } = {}) {
+ const { doc } = await readTakeDoc(project.dir, id);
+ const masterText = await readFile(path.join(project.dir, "video.manifest.json"), "utf8");
+ const master = JSON.parse(masterText);
+ const { manifest: merged, note } = await resolveTakeManifest(project.dir, id, { base: master });
+ const replacesTimeline = isObj(doc.patch) && Array.isArray(doc.patch.timeline);
+ if (!anyway && replacesTimeline) {
+ if (typeof doc.baseHash !== "string" || !doc.baseHash) {
+ throw new PromoteStale(`take ${id} does not record which manifest it was made from, and its timeline replaces the cut's`);
+ }
+ if (hashText(masterText) !== doc.baseHash) {
+ throw new PromoteStale(`the project's manifest changed since take ${id} was made: its timeline would replace the cut's, and what the cut gained since would go`);
+ }
+ }
+ // The build's structure rules, over the project's manifest becoming the take's.
+ const next = clone(master);
+ applyStructural(next, (m) => {
+ for (const k of Object.keys(m)) delete m[k];
+ Object.assign(m, clone(merged));
+ });
+ const { result, editNotes } = await withEditNotes(project, () => replaceManifest(project.dir, next, { token, op: "promote-take" }));
+ const listing = await listTakes(project.dir);
+ const take = listing.takes.find((t) => t.id === id);
+ const group = take ? listing.takes.filter((t) => t.group === take.group).map((t) => t.id) : [id];
+ const { verdicts } = await setTakePicked(project.dir, id, group, { now });
+ const clips = (next.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").length;
+ return { take: id, snapshot: result.snapshot, token: result.token, editNotes, verdicts, note, clips, entries: (next.timeline ?? []).length };
+}
diff --git a/umtool/lib/report/takeEdit.test.mjs b/umtool/lib/report/takeEdit.test.mjs
@@ -0,0 +1,322 @@
+// Walk a take: a draft recorded without rendering, the walk's edits written
+// into the take's patch (never the project's manifest) with an undo point
+// each, undone byte for byte, a draft rendered from its edited patch, the
+// walk's reading (walkData, what GET /api/report/walk and `umtool walk`
+// answer), and "Make this the cut" (promoteTake) with its one undo.
+//
+// Run with: node --test lib/report/takeEdit.test.mjs
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { StaleToken, StructureRefused, undoStructural } from "./manifest.mjs";
+import { draftTake } from "./takeMaker.mjs";
+import {
+ PromoteStale,
+ listTakeRevisions,
+ moveTakeEntry,
+ promoteTake,
+ removeTakeEntry,
+ takeToken,
+ undoTakeEdit,
+ updateTakeClip,
+} from "./takeEdit.mjs";
+import { listTakes, readVerdicts } from "./takes.mjs";
+import { resolveTakeManifest } from "./takeManifest.mjs";
+import { takeCommand } from "./takeCli.mjs";
+import { timelineCommand } from "./timelineCli.mjs";
+import { walkCommand } from "./walkCli.mjs";
+import { walkJson, walkNeighbours, walkOf } from "./walkData.mjs";
+import { PROJECT_KINDS } from "../projects/kinds.mjs";
+
+const TAKES_KIND = PROJECT_KINDS.find((k) => k.makesTakes).id;
+const clip = (id, start, end, extra = {}) => ({ type: "clip", id, channel: "chan", video: "vid", start, end, cite: start, ...extra });
+
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "fixture",
+ title: "Fixture",
+ render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30 },
+ timeline: [clip("c01", 100, 160, { verdict: "confirmed" }), clip("c02", 200, 260, { verdict: "confirmed" }), clip("c03", 300, 360)],
+};
+
+/** The tight version: sub-windows of the master's clips, a whole `timeline` merge patch. */
+const TIGHT = {
+ timeline: [
+ clip("t01a", 105, 115, { verdict: "confirmed" }),
+ clip("t01b", 130, 150, { verdict: "confirmed" }),
+ clip("t02a", 210, 230),
+ clip("t03a", 310, 320),
+ ],
+};
+
+async function project(manifest = MANIFEST) {
+ const root = await mkdtemp(path.join(tmpdir(), "takeedit-"));
+ const reportsRoot = path.join(root, "reports");
+ const dir = path.join(reportsRoot, "proj");
+ // One fetched window holding c01..c02's span (and so t01a, t01b, t02a); nothing for c03 / t03a.
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await writeFile(path.join(dir, "out", "clips-raw", "vid_90.00-270.00.mp4"), "media");
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
+ const ref = { id: "proj", dir, kind: TAKES_KIND };
+ return { root, dir, reportsRoot, ref };
+}
+
+const masterText = (dir) => readFile(path.join(dir, "video.manifest.json"), "utf8");
+const takeJson = async (dir, id) => JSON.parse(await readFile(path.join(dir, "takes", id, "take.json"), "utf8"));
+
+function stubRender() {
+ const calls = [];
+ const render = async (job) => {
+ const doc = JSON.parse(await readFile(job.manifestPath, "utf8"));
+ calls.push({ ...job, doc });
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, "render");
+ return { file };
+ };
+ return { render, calls };
+}
+
+test("a draft take is recorded, not rendered: listed as a draft, its manifest is the project's with its patch", async () => {
+ const { root, dir } = await project();
+ try {
+ const d = await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ assert.equal(d.clips, 4);
+ const t = await takeJson(dir, "tight");
+ assert.equal(t.draft, true);
+ assert.equal(t.builtAt, null);
+ assert.equal(t.window, null, "a draft says its window when it is rendered");
+ assert.ok(t.baseHash);
+ assert.deepEqual(await readdir(path.join(dir, "takes", "tight")), ["take.json"], "nothing rendered, no manifest copied");
+ const listed = (await listTakes(dir)).takes;
+ assert.equal(listed.length, 1);
+ assert.equal(listed[0].draft, true);
+ assert.equal(listed[0].previewSize, null);
+ const { manifest } = await resolveTakeManifest(dir, "tight");
+ assert.deepEqual(manifest.timeline.map((e) => e.id), ["t01a", "t01b", "t02a", "t03a"]);
+ // Again: refused, then --force records it again; a RENDERED take is never drafted over.
+ await assert.rejects(draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT }), /exists \(a draft\)/);
+ await draftTake(dir, { id: "tight", label: "Tight 2", patch: TIGHT }, { force: true });
+ assert.equal((await takeJson(dir, "tight")).label, "Tight 2");
+ await assert.rejects(draftTake(dir, { id: "x", label: "X", patch: { timeline: "no" } }), /no timeline/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the walk's edits go into the take's patch with an undo point each; the project's manifest is untouched", async () => {
+ const { root, dir } = await project();
+ try {
+ await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ const before = await masterText(dir);
+ const token = await takeToken(dir, "tight");
+ const r = await updateTakeClip(dir, "tight", "t02a", { end: 233.456, verdict: "confirmed" }, { token });
+ assert.equal(r.entry.end, 233.46, "2 dp, the project writer's rule");
+ assert.equal(r.before.end, 230);
+ assert.notEqual(r.token, token);
+ let t = await takeJson(dir, "tight");
+ const e = t.patch.timeline.find((x) => x.id === "t02a");
+ assert.equal(e.end, 233.46);
+ assert.equal(e.verdict, "confirmed");
+ assert.ok(t.editedAt);
+ assert.equal(t.draft, true, "still a draft");
+ assert.equal(await masterText(dir), before, "the project's manifest is never written");
+ // The project writer's own refusals.
+ await assert.rejects(updateTakeClip(dir, "tight", "t03a", { verdict: "incorrect" }), /needs its note/);
+ await assert.rejects(updateTakeClip(dir, "tight", "t03a", { start: 319.9 }), /at least half a second/);
+ await assert.rejects(updateTakeClip(dir, "tight", "c01", { end: 150 }), /no timeline entry with id c01/, "the master's clip is not the take's");
+ // A stale token is refused, not written over.
+ await assert.rejects(updateTakeClip(dir, "tight", "t03a", { verdict: "confirmed" }, { token }), StaleToken);
+ // Structure: move and remove, checked by the build's rules.
+ await moveTakeEntry(dir, "tight", "t03a", 0);
+ await removeTakeEntry(dir, "tight", "t01b");
+ t = await takeJson(dir, "tight");
+ assert.deepEqual(t.patch.timeline.map((x) => x.id), ["t03a", "t01a", "t02a"]);
+ const revs = await listTakeRevisions(dir, "tight");
+ assert.deepEqual(revs.map((x) => x.label), ["auto-before-remove", "auto-before-move", "auto-before-clip"]);
+ // Undo: newest first, byte for byte, one step further each time.
+ let u = await undoTakeEdit(dir, "tight");
+ assert.equal(u.op, "remove");
+ assert.deepEqual((await takeJson(dir, "tight")).patch.timeline.map((x) => x.id), ["t03a", "t01a", "t01b", "t02a"]);
+ u = await undoTakeEdit(dir, "tight");
+ assert.equal(u.op, "move");
+ u = await undoTakeEdit(dir, "tight");
+ assert.equal(u.op, "clip");
+ assert.deepEqual((await takeJson(dir, "tight")).patch, TIGHT, "back to the patch as drafted");
+ await assert.rejects(undoTakeEdit(dir, "tight"), /nothing to undo/);
+ assert.equal(await masterText(dir), before);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a take whose patch has no timeline (a style take) gets the cut's timeline on its first edit", async () => {
+ const { root, dir } = await project();
+ try {
+ await draftTake(dir, { id: "crisp", label: "Crisp", patch: { render: { crf: 33 } } });
+ await updateTakeClip(dir, "crisp", "c03", { verdict: "confirmed" });
+ const t = await takeJson(dir, "crisp");
+ assert.equal(t.patch.render.crf, 33, "the rest of the patch is kept");
+ assert.deepEqual(t.patch.timeline.map((x) => x.id), ["c01", "c02", "c03"]);
+ assert.equal(t.patch.timeline[2].verdict, "confirmed");
+ assert.equal(JSON.parse(await masterText(dir)).timeline[2].verdict, undefined);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a refused structure edit writes nothing; removing a clip a post is attached to is the build's sentence", async () => {
+ const { root, dir } = await project({ ...MANIFEST, posts: [{ id: "p1", platform: "x", date: "2026-01-01", text: "hi", url: "https://x.com/a/status/1", attachTo: "t01a" }] });
+ try {
+ await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ const t0 = await readFile(path.join(dir, "takes", "tight", "take.json"), "utf8");
+ await assert.rejects(removeTakeEntry(dir, "tight", "t01a"), StructureRefused);
+ assert.equal(await readFile(path.join(dir, "takes", "tight", "take.json"), "utf8"), t0);
+ assert.deepEqual(await listTakeRevisions(dir, "tight"), []);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("draft, walk, then render: the render reads the edited patch, and the take is made", 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, probe: async () => 42 } };
+ try {
+ await writeFile(path.join(root, "patch.json"), JSON.stringify(TIGHT));
+ assert.equal(await takeCommand(["proj", "--id", "tight", "--patch", path.join(root, "patch.json"), "--draft", "--label", "Tight — walk"], io), 0, err.join("\n"));
+ assert.match(out.join("\n"), /a draft, nothing rendered — 4 clip\(s\)/);
+ assert.equal(r.calls.length, 0, "a draft renders nothing");
+ await updateTakeClip(dir, "tight", "t01a", { start: 104 });
+ await removeTakeEntry(dir, "tight", "t03a");
+ // `umtool take <p> --id X --full`: the draft, from what it stores.
+ assert.equal(await takeCommand(["proj", "--id", "tight", "--full"], io), 0, err.join("\n"));
+ assert.equal(r.calls.length, 1);
+ assert.equal(r.calls[0].full, true);
+ assert.deepEqual(r.calls[0].doc.timeline.map((e) => [e.id, e.start]), [["t01a", 104], ["t01b", 130], ["t02a", 210]]);
+ const t = await takeJson(dir, "tight");
+ assert.equal(t.draft, undefined, "made now");
+ assert.equal(t.label, "Tight — walk");
+ assert.equal(t.window, "full");
+ assert.equal(t.seconds, 42);
+ const listed = (await listTakes(dir)).takes[0];
+ assert.equal(listed.draft, false);
+ assert.ok(listed.previewSize > 0);
+ // --rebuild takes a window flag now.
+ assert.equal(await takeCommand(["proj", "--id", "tight", "--rebuild", "--at", "0", "--dur", "5"], io), 0, err.join("\n"));
+ assert.deepEqual((await takeJson(dir, "tight")).window, { at: 0, dur: 5 });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("walkOf: the take's clips in walk order, the walk visiting the fetched unjudged ones (all: every fetched one)", async () => {
+ const { root, dir, ref } = await project();
+ try {
+ await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ const w = await walkOf(ref, { take: "tight" });
+ assert.equal(w.take.id, "tight");
+ assert.equal(w.take.draft, true);
+ assert.equal(w.take.editable, true);
+ assert.deepEqual(w.order, ["t01a", "t01b", "t02a", "t03a"]);
+ assert.deepEqual(w.clips.map((c) => [c.id, c.verdict, c.fetched, c.onWalk]), [
+ ["t01a", "confirmed", true, false],
+ ["t01b", "confirmed", true, false],
+ ["t02a", "unreviewed", true, true],
+ ["t03a", "unreviewed", false, false],
+ ]);
+ assert.equal(w.first, "t02a");
+ assert.equal(w.needing, 2);
+ assert.equal(w.ready, 1);
+ assert.equal(w.token, await takeToken(dir, "tight"));
+ assert.equal(w.seconds, 60);
+ const all = await walkOf(ref, { take: "tight", all: true });
+ assert.equal(all.first, "t01a");
+ assert.deepEqual(walkNeighbours(all.order, all.onWalk, "t01b"), { prev: "t01a", next: "t02a" });
+ assert.deepEqual(walkNeighbours(all.order, all.onWalk, "t03a"), { prev: "t02a", next: null });
+ // The route's JSON: no manifest, no Set.
+ const j = walkJson(all);
+ assert.equal(j.manifest, undefined);
+ assert.equal(j.onWalk, undefined);
+ assert.ok(JSON.stringify(j));
+ // The project's own walk is unchanged by the take.
+ const master = await walkOf(ref);
+ assert.equal(master.take, null);
+ assert.deepEqual(master.order, ["c01", "c02", "c03"]);
+ await assert.rejects(walkOf(ref, { take: "nope" }), /no take nope/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("promoteTake: the take's patch over the project's manifest, one undo point; refused when the cut moved on, unless anyway", async () => {
+ const { root, dir, ref } = await project();
+ try {
+ await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ await updateTakeClip(dir, "tight", "t03a", { verdict: "incorrect", correction: "not her" });
+ const before = await masterText(dir);
+ const r = await promoteTake(ref, "tight");
+ assert.equal(r.clips, 4);
+ assert.match(r.snapshot.rel, /auto-before-promote-take/);
+ const m = JSON.parse(await masterText(dir));
+ assert.deepEqual(m.timeline.map((e) => e.id), ["t01a", "t01b", "t02a", "t03a"]);
+ assert.equal(m.timeline[3].correction, "not her", "the walk's edits are what is promoted");
+ assert.equal(m.render.crf, 30, "the rest of the manifest is the project's");
+ assert.equal((await readVerdicts(dir)).tight.picked, true);
+ // One undo takes the whole promotion back, byte for byte.
+ await undoStructural(dir);
+ assert.equal(await masterText(dir), before);
+
+ // The cut changed since the take was made: refused, then made all the same with anyway.
+ const changed = JSON.parse(before);
+ changed.timeline[2].verdict = "confirmed";
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(changed, null, 2) + "\n");
+ await assert.rejects(promoteTake(ref, "tight"), PromoteStale);
+ await promoteTake(ref, "tight", { anyway: true });
+ assert.equal(JSON.parse(await masterText(dir)).timeline[0].id, "t01a");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --promote", async () => {
+ const { root, dir, reportsRoot } = await project();
+ const out = [];
+ const err = [];
+ const io = { root: reportsRoot, out: (s) => out.push(s), err: (s) => err.push(s) };
+ try {
+ await draftTake(dir, { id: "tight", label: "Tight", patch: TIGHT });
+ assert.equal(await walkCommand(["proj", "--take", "tight"], io), 0, err.join("\n"));
+ const text = out.join("\n");
+ assert.match(text, /take tight "Tight" \(draft\) · 4 clip\(s\)/);
+ assert.match(text, /→ +3 +t02a/);
+ assert.match(text, /NOT FETCHED/);
+ assert.match(text, /\/projects\/proj\/takes\/tight\/walk/);
+ out.length = 0;
+ assert.equal(await walkCommand(["proj", "--take", "tight", "--all", "--json"], io), 0, err.join("\n"));
+ assert.equal(JSON.parse(out.join("\n")).first, "t01a");
+
+ out.length = 0;
+ assert.equal(await timelineCommand(["proj", "--take", "tight", "move", "t03a", "--to", "0"], io), 0, err.join("\n"));
+ assert.match(out.join("\n"), /take tight: moved t03a: 3 -> 0/);
+ assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n"));
+ assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "--after", "-", "chan/vid@1-5"], io), 2, "only ls, move, remove, undo on a take");
+ out.length = 0;
+ assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n"));
+ assert.match(out.join("\n"), /4 entries in take tight of proj$/, "the move was undone: nothing left to undo");
+
+ const log = [];
+ const before = await masterText(dir);
+ assert.equal(await takeCommand(["proj", "--id", "tight", "--promote"], { reportsRoot, log: (s) => log.push(s), err: (s) => err.push(s) }), 0, err.join("\n"));
+ assert.match(log.join("\n"), /take tight is the cut now — 4 clip\(s\)/);
+ assert.notEqual(await masterText(dir), before);
+ const st = await stat(path.join(dir, "revisions"));
+ assert.ok(st.isDirectory());
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -563,7 +563,19 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
const [schedSt, manSt] = await Promise.all([stat(scheduleFile).catch(() => null), stat(path.join(projectDir, MANIFEST)).catch(() => null)]);
log(`${spec.id}: ${windowBasisLine(covered, { schedule: !!schedule, scheduleOlder: !!(schedSt && manSt && schedSt.mtimeMs < manSt.mtimeMs) })}`);
const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id));
- const ids = withPatchEntries(ruled.manifest.timeline, base.timeline, covered.ids).filter((id) => present.has(id));
+ let ids = withPatchEntries(ruled.manifest.timeline, base.timeline, covered.ids).filter((id) => present.has(id));
+ // A take whose patch REPLACES the timeline with entries of its own (a
+ // tight version, walked) holds none of the project's entries to cover:
+ // its window is timed over its OWN timeline instead (by the estimates --
+ // the deck's schedule names the project's entries).
+ if (!ids.length && isObj(spec.patch) && Array.isArray(spec.patch.timeline) && !covered.ids.some((id) => present.has(id))) {
+ covered = windowEntries(ruled.manifest.timeline, spec.window, null);
+ log(
+ `${spec.id}: none of those is in the take's own timeline — the window covers ${covered.ids.length} of ITS entries ` +
+ `(${covered.ids.join(", ")}), timed by their own lengths`,
+ );
+ ids = covered.ids.filter((id) => present.has(id));
+ }
if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`);
renderDoc = windowManifest(ruled.manifest, ids);
}
@@ -664,6 +676,84 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
return { id: spec.id, skipped: false, take: doc };
}
+/**
+ * A DRAFT take (walk a take): the take recorded -- its label, group, style,
+ * patch and window -- with NOTHING rendered, so it can be walked (the bench
+ * on the take's own timeline, takeEdit.mjs) before anybody pays for a build.
+ * `umtool take <p> --id X --draft`; a later `umtool take <p> --id X --full`
+ * renders it from its stored patch, edits and all (makeTake over it).
+ *
+ * takes/<id>/take.json `draft: true`, `preview` naming where the render
+ * will go, `seconds`/`builtAt` null, and the
+ * baseHash of the manifest it was drafted against
+ *
+ * The patch is applied here once, to check it makes a manifest with a
+ * timeline (a patch that does not is refused now, not at the render), and to
+ * write the take's `changes` lines. No take.json is written over a RENDERED
+ * take (its preview would then sit beside a take that says it has none);
+ * over a draft only with `force`.
+ *
+ * @param {string} projectDir
+ * @param {TakeSpec} rawSpec `window` absent: the render's window is said when it is rendered
+ * @param {{ force?: boolean, styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, now?: () => Date }} [opts]
+ */
+export async function draftTake(projectDir, rawSpec, opts = {}) {
+ const spec = checkSpec(rawSpec);
+ const window = rawSpec?.window === undefined || rawSpec?.window === null ? null : spec.window;
+ 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 && previous.draft !== true) throw new Error(`take ${spec.id} is rendered — a draft needs an id of its own`);
+ if (previous && !opts.force) throw new Error(`take ${spec.id} exists (a draft) — pass --force to record it again`);
+
+ 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 = 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 styleLabel = spec.style ? styles[spec.style]?.label : null;
+ const listing = await listTakes(projectDir);
+ const order =
+ spec.order ??
+ (typeof previous?.order === "number" ? previous.order : Math.max(0, ...listing.takes.filter((t) => t.id !== spec.id).map((t) => t.order)) + 1);
+ const doc = {
+ id: spec.id,
+ group: spec.group,
+ order,
+ label: spec.label,
+ kind: changes.length === 0 ? "reference" : (spec.kind ?? "different"),
+ summary: spec.summary || (spec.style ? styles[spec.style]?.summary ?? "" : ""),
+ changes: [...(styleLabel ? [`style: ${styleLabel}`] : []), ...changes],
+ preview: PREVIEW,
+ seconds: null,
+ builtAt: null,
+ style: spec.style,
+ patch: spec.patch,
+ window,
+ ...(spec.quick ? { quick: true } : {}),
+ draft: true,
+ draftedAt: now().toISOString(),
+ baseHash: hashText(baseText),
+ };
+ await mkdir(takeDir, { recursive: true });
+ const tmp = `${takeFile}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, takeFile);
+ const clips = manifest.timeline.filter((e) => isObj(e) && e.type === "clip").length;
+ return { id: spec.id, take: doc, clips, entries: manifest.timeline.length };
+}
+
/** Remove `file` when it is a hard link of `of` (the same inode); anything else is left. */
async function unlinkIfSameFile(file, of) {
const [a, b] = await Promise.all([lstat(file).catch(() => null), lstat(of).catch(() => null)]);
@@ -841,6 +931,8 @@ export async function pickTake(project, takeId, { anyway = false, token = null,
const listing = await listTakes(project.dir);
const take = listing.takes.find((t) => t.id === takeId);
if (!take) throw new Error(`no take ${takeId}`);
+ // A draft has no rendered manifest to use: "Make this the cut" (takeEdit.mjs promoteTake) applies its patch.
+ if (take.draft) throw new Error(`take ${takeId} is a draft — nothing rendered to use; make it the cut (umtool take ${project.id} --id ${takeId} --promote)`);
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);
@@ -898,10 +990,19 @@ export function takeSteps(project, req, { styles, existing, clipCount, seconds =
if (typeof req.rebuild === "string") {
const t = existing.find((x) => x.id === req.rebuild);
if (!t) throw new Error(`no take ${req.rebuild}`);
+ // `window`: render it over this window rather than its own (a draft's
+ // Render full / Render a window: a draft may not say one yet).
+ const win = req.window === undefined || req.window === null ? null : req.window === "full" ? "full" : normalizeWindow(req.window);
+ const full = (win ?? t.window) === "full";
return {
- kind: `take ${project.id} ${t.id} (rebuild)`,
+ kind: `take ${project.id} ${t.id} (${/** @type {any} */ (t).draft ? "render" : "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, seconds) }],
+ steps: [{
+ ...base,
+ label: `${/** @type {any} */ (t).draft ? "render" : "rebuild"} take ${t.id}`,
+ argv: [...cli, "take", project.id, "--id", t.id, "--rebuild", ...(win ? windowArgs(win) : []), "--progress", "ndjson"],
+ timeoutMs: takeTimeoutMs(full, clipCount, seconds),
+ }],
};
}
if (isObj(req.allStyles)) {
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -289,11 +289,14 @@ test("makeTake refuses an unknown style, a bad id, and a window the patch emptie
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);
+ // A patch whose timeline holds none of the entries the window covers is
+ // timed over its OWN timeline (walk a take: a tight version's sub-windows),
+ // rather than refused as emptied.
+ const own = await makeTake(dir, { id: "x", label: "X", window: { at: 0, dur: 5 }, patch: { timeline: [clip("s04", 0, 5), clip("s05", 7, 9)] } }, opts(r));
+ assert.equal(own.skipped, false);
+ assert.deepEqual(r.calls[0].doc.timeline.map((e) => e.id), ["s04"]);
+ assert.ok(r.logs.some((l) => /none of those is in the take's own timeline — the window covers 1 of ITS entries \(s04\)/.test(l)), r.logs.join("\n"));
} finally {
await rm(root, { recursive: true, force: true });
}
diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs
@@ -94,6 +94,13 @@ export function parseTake(dirName, raw) {
}
const window = parseWindow(j.window);
if (window === undefined) return { error: 'window is not "full" or { at, dur }' };
+ // A DRAFT (walk a take): recorded, not rendered -- `umtool take … --draft`.
+ // Its `preview` names where the render will go; the file is not there yet,
+ // which the listing already says (previewSize null). `editedAt` is the
+ // walk's last write to its patch (takeEdit.mjs): later than `builtAt`, the
+ // render is older than the take.
+ if (j.draft !== undefined && typeof j.draft !== "boolean") return { error: "draft is not true or false" };
+ if (j.editedAt !== undefined && j.editedAt !== null && typeof j.editedAt !== "string") return { error: "editedAt is not a string" };
return {
take: {
id: dirName,
@@ -111,6 +118,8 @@ export function parseTake(dirName, raw) {
window,
baseHash: typeof j.baseHash === "string" && j.baseHash ? j.baseHash : null,
quick: j.quick === true,
+ draft: j.draft === true,
+ editedAt: typeof j.editedAt === "string" && j.editedAt ? j.editedAt : null,
},
};
}
diff --git a/umtool/lib/report/takes.test.mjs b/umtool/lib/report/takes.test.mjs
@@ -71,6 +71,8 @@ test("parseTake accepts the contract and fills the optional fields", () => {
window: null,
baseHash: null,
quick: false,
+ draft: false,
+ editedAt: null,
});
const min = parseTake("x", { id: "x", group: "g", order: 0, label: "X", kind: "reference", preview: "p.mp4" });
assert.ok("take" in min);
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -72,13 +72,18 @@ export const TIMELINE_USAGE = [
" umtool timeline <project> post-remove <id>",
" umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)",
" umtool timeline <project> undo restore the newest automatic snapshot",
+ " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]",
+ " a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),",
+ " each write with an undo point of the take's own; the project's manifest is untouched",
"",
"Every write snapshots the manifest first (revisions/…-auto-before-<op>), is checked by the build's own",
"validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.",
].join("\n");
const VERBS = ["ls", "insert", "move", "remove", "duplicate", "post", "post-remove", "teaser", "undo"];
-const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url"]);
+const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take"]);
+/** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */
+const TAKE_VERBS = ["ls", "move", "remove", "undo"];
class CliError extends Error {}
@@ -310,6 +315,7 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
}
if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`);
const project = await projectOf(projectArg, root);
+ if (flags.has("--take")) return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json });
const manifest = await readManifest(project.dir);
if (!manifest) throw new CliError(`${project.id} has no manifest`);
@@ -447,6 +453,56 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
}
}
+/**
+ * `umtool timeline <p> --take <id> ls|move|remove|undo`: a take's timeline
+ * (walk a take). The writes go into the take's patch through takeEdit.mjs --
+ * the same structure rules, an undo point of the take's own first -- and the
+ * project's manifest is never written. Errors are thrown to the caller's catch.
+ */
+async function takeTimeline(project, take, verb, rest, flags, { out, json }) {
+ if (!TAKE_VERBS.includes(verb)) throw new CliError(`on a take: timeline --take ${take} ${TAKE_VERBS.join(" | ")} (not ${verb})`);
+ const edit = await import("./takeEdit.mjs");
+ const at = intFlag(flags, "--at");
+ if (verb === "ls") {
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ const { manifest } = await resolveTakeManifest(project.dir, take);
+ const rows = timelineRows(manifest);
+ if (json) {
+ out(JSON.stringify({ project: project.id, take, token: await edit.takeToken(project.dir, take), timeline: rows }, null, 2));
+ return 0;
+ }
+ for (const line of timelineLines(rows)) out(line);
+ const { undoable } = await edit.takeEditState(project.dir, take);
+ out(`${rows.length} entr${rows.length === 1 ? "y" : "ies"} in take ${take} of ${project.id}${undoable ? ` · ${undoable} edit(s) to undo` : ""}`);
+ return 0;
+ }
+ const token = await edit.takeToken(project.dir, take);
+ let result;
+ if (verb === "move") {
+ const id = rest[0];
+ if (!id) throw new CliError("move needs an entry id");
+ const to = intFlag(flags, "--to");
+ if (to === null) throw new CliError(`move needs --to <index> (\`umtool timeline ${project.id} --take ${take}\` lists them)`);
+ result = await edit.moveTakeEntry(project.dir, take, id, to, { token, at });
+ } else if (verb === "remove") {
+ const id = rest[0];
+ if (!id) throw new CliError("remove needs an entry id");
+ result = await edit.removeTakeEntry(project.dir, take, id, { token, at });
+ } else {
+ result = await edit.undoTakeEdit(project.dir, take, { token });
+ }
+ if (json) {
+ out(JSON.stringify({ ok: true, op: verb, take, ...result }, null, 2));
+ return 0;
+ }
+ if (verb === "undo") out(`take ${take}: undid ${result.op}: restored ${result.restored} (the state before the undo kept as ${result.saved})`);
+ else {
+ out(`take ${take}: ${summaryOf(verb, result, null)}`);
+ out(` undo point: takes/${take}/${result.revision.rel} (umtool timeline ${project.id} --take ${take} undo)`);
+ }
+ return 0;
+}
+
function summaryOf(verb, r, attribution) {
switch (verb) {
case "insert": {
diff --git a/umtool/lib/report/walkCli.mjs b/umtool/lib/report/walkCli.mjs
@@ -0,0 +1,78 @@
+// `umtool walk <project> [--take <id>] [--all] [--json]`: the walk from a
+// terminal -- every clip in walk order with its verdict, whether it is fetched,
+// and which ones the walk visits -- read by walkData.mjs, the reading the bench
+// page and GET /api/report/walk make. The edits are `umtool window <p> <clip>
+// [--take <id>] --verdict …` and `umtool timeline <p> [--take <id>] move|remove|undo`.
+//
+// Plain ESM: the CLI runs under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { hms } from "umtool-report-to-video/attribution";
+import { walkJson, walkOf } from "./walkData.mjs";
+
+export const WALK_USAGE = [
+ "usage: umtool walk <project> [--take <id>] [--all] [--json]",
+ "",
+ "The clip bench's walk: every clip in walk order (by source), its window, its verdict, whether a",
+ "fetched file holds it, and (→) the ones the walk visits -- the fetched clips still needing a verdict;",
+ "--all: every fetched clip. --take walks a take: the project's manifest with the take's patch applied",
+ "(a draft too); its edits go to the take (`umtool window <p> <clip> --take <id> …`,",
+ "`umtool timeline <p> --take <id> move|remove|undo`), never the project's manifest.",
+].join("\n");
+
+class CliError extends Error {}
+
+/**
+ * @param {string[]} args the words after `walk`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function walkCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--take") {
+ if (i + 1 >= args.length) throw new CliError("--take needs a take id");
+ flags.set(a, args[++i]);
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ if (!words[0] || flags.has("--help")) {
+ (flags.has("--help") ? out : err)(WALK_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ const take = flags.has("--take") ? String(flags.get("--take")) : null;
+ const w = await walkOf(project, { take, all: flags.has("--all") });
+ if (flags.has("--json")) {
+ out(JSON.stringify(walkJson(w), null, 2));
+ return 0;
+ }
+ const what = w.take
+ ? `take ${w.take.id} "${w.take.label}"${w.take.draft ? " (draft)" : w.take.made ? "" : " (in a recipe, not made — read only)"}`
+ : "the cut";
+ out(`${project.id} · ${what} · ${w.total} clip(s) · ${hms(w.seconds)} · ${w.reviewed} reviewed · ${w.needing} need a verdict, ${w.ready} of them fetched`);
+ if (w.note) out(` ${w.note}`);
+ const idW = Math.max(2, ...w.clips.map((c) => c.id.length));
+ for (const c of w.clips) {
+ const win = `${hms(c.start)}–${hms(c.end)}`;
+ const cut = c.cutStart != null ? ` cut ${hms(c.cutStart)}–${hms(c.cutEnd)}` : "";
+ out(
+ `${c.onWalk ? "→" : " "} ${String(c.cut ?? "").padStart(3)} ${c.id.padEnd(idW)} ${win.padEnd(22)}${cut} ${c.seconds.toFixed(1).padStart(6)}s ` +
+ `${c.verdict.padEnd(10)} ${c.fetched ? "fetched" : "NOT FETCHED"}${c.correction ? ` note: ${c.correction}` : ""}`,
+ );
+ }
+ const enc = project.id.split("/").map(encodeURIComponent).join("/");
+ const base = w.take ? `/projects/${enc}/takes/${encodeURIComponent(w.take.id)}/walk` : `/projects/${enc}/clip/${encodeURIComponent(w.first ?? "")}`;
+ if (w.first) out(`\nthe walk starts at ${w.first}: ${w.take ? `${base}${w.all ? "?all=1" : ""}` : base}`);
+ else out(`\nnothing on the walk${w.all ? "" : " (every fetched clip has a verdict; --all walks them all)"}`);
+ return 0;
+ } catch (e) {
+ err(`umtool walk: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/walkData.mjs b/umtool/lib/report/walkData.mjs
@@ -0,0 +1,146 @@
+// THE WALK, as data: which clips a walk visits, in what order, and where `p`
+// and `n` go -- for the project's own cut, or for a TAKE (walk a take): the
+// project's manifest with the take's patches applied, resolveTakeManifest's
+// merge (takeManifest.mjs), the one the take build makes.
+//
+// One reading for the bench page (ClipBenchPage), the walk's data route
+// (GET /api/report/walk) and `umtool walk`, so a terminal and the page cannot
+// disagree about what is left to judge.
+//
+// WHAT THE WALK VISITS (umtool/docs/clip-bench.md, "What the walk skips"):
+// the clips that still NEED JUDGEMENT (no verdict) and are FETCHED (a cached
+// file holds the clip's own window end to end), in walk order (by source --
+// lib/projects/report.mjs walkOrder). `all` widens it to every FETCHED clip,
+// judged or not: a take's clips are new windows, often carrying the verdict
+// of the clip they were cut from, and "watch the tight version through" is a
+// walk of all of them.
+//
+// Plain ESM: `umtool walk` runs it under bare node.
+import { clipVerdict, readClipDetail, readManifest, walkOrder, walkReadiness } from "../projects/report.mjs";
+import { manifestToken } from "./manifest.mjs";
+
+/**
+ * The manifest a walk reads: the project's, or the take's.
+ *
+ * @param {{ dir: string }} project
+ * @param {string | null} take
+ * @returns {Promise<{ manifest: Record<string, any>, token: string | null, take: null | { id: string, label: string, draft: boolean, made: boolean, editable: boolean }, note: string | null }>}
+ */
+export async function walkManifest(project, take = null) {
+ if (!take) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new Error("the project has no video.manifest.json");
+ return { manifest, token: await manifestToken(project.dir), take: null, note: null };
+ }
+ const [{ resolveTakeManifest }, { takeToken }, { listTakes }] = await Promise.all([
+ import("./takeManifest.mjs"),
+ import("./takeEdit.mjs"),
+ import("./takes.mjs"),
+ ]);
+ const r = await resolveTakeManifest(project.dir, take);
+ const token = await takeToken(project.dir, take);
+ const listed = (await listTakes(project.dir)).takes.find((t) => t.id === take);
+ return {
+ manifest: r.manifest,
+ token,
+ take: {
+ id: take,
+ label: r.take.label,
+ draft: !!listed?.draft,
+ made: !!listed && !listed.draft,
+ // Edits land in takes/<id>/take.json: a take a recipe only names has none to land in.
+ editable: token !== null,
+ },
+ note: r.note,
+ };
+}
+
+/**
+ * Where `p` and `n` go from `clipId`: the nearest clip on the walk either side
+ * in walk order (never the clip itself). `order` is walk order; `onWalk` the
+ * ids the walk visits.
+ *
+ * @param {string[]} order
+ * @param {Set<string>} onWalk
+ * @param {string} clipId
+ */
+export function walkNeighbours(order, onWalk, clipId) {
+ const i = order.indexOf(clipId);
+ const ok = (id) => id !== clipId && onWalk.has(id);
+ const prev = [...order.slice(0, Math.max(0, i))].reverse().find(ok) ?? null;
+ const next = (i < 0 ? order : order.slice(i + 1)).find(ok) ?? null;
+ return { prev, next };
+}
+
+/**
+ * @typedef {{
+ * id: string, cut: number | null, channel: string | null, video: string, start: number, end: number,
+ * seconds: number, cutStart: number | null, cutEnd: number | null,
+ * verdict: "confirmed" | "incorrect" | "unreviewed", correction: string | null, quote: string | null,
+ * fetched: boolean, onWalk: boolean,
+ * }} WalkClip
+ */
+
+/**
+ * The walk of a project's cut or of a take.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take?: string | null, all?: boolean }} [opts]
+ */
+export async function walkOf(project, { take = null, all = false } = {}) {
+ const base = await walkManifest(project, take);
+ const detail = await readClipDetail(project.dir, { manifest: base.manifest });
+ if (!detail) throw new Error("the project has no video.manifest.json");
+ const ordered = walkOrder(detail.entries);
+ const readiness = walkReadiness(ordered);
+ const onWalk = new Set(all ? ordered.filter((e) => !!e.fetched).map((e) => e.id) : readiness.readyIds);
+ const cutIndex = new Map(
+ (detail.entries ?? []).filter((e) => e.kind === "clip").map((e, i) => [e.id, i + 1]),
+ );
+ /** @type {WalkClip[]} */
+ const clips = ordered.map((/** @type {any} */ e) => ({
+ id: e.id,
+ /** 1-based place among the cut's clips (the timeline's order). */
+ cut: cutIndex.get(e.id) ?? null,
+ channel: e.channel ?? null,
+ video: e.video,
+ start: e.start,
+ end: e.end,
+ seconds: Number((Number(e.cutEnd ?? e.end) - Number(e.cutStart ?? e.start)).toFixed(2)),
+ cutStart: e.cutStart ?? null,
+ cutEnd: e.cutEnd ?? null,
+ verdict: clipVerdict(e),
+ correction: typeof e.correction === "string" && e.correction.trim() ? e.correction.trim() : null,
+ quote: typeof e.quote === "string" ? e.quote : null,
+ fetched: !!e.fetched,
+ onWalk: onWalk.has(e.id),
+ }));
+ const order = clips.map((c) => c.id);
+ const first = order.find((id) => onWalk.has(id)) ?? null;
+ const reviewed = clips.filter((c) => c.verdict !== "unreviewed").length;
+ return {
+ project: project.id,
+ take: base.take,
+ note: base.note,
+ all,
+ token: base.token,
+ manifest: base.manifest,
+ detail,
+ clips,
+ order,
+ onWalk,
+ first,
+ /** Clips that need an answer, and how many of them can be judged today (fetched). */
+ needing: readiness.needing,
+ ready: readiness.ready,
+ reviewed,
+ total: clips.length,
+ seconds: Number(clips.reduce((s, c) => s + c.seconds, 0).toFixed(2)),
+ };
+}
+
+/** walkOf's answer as JSON for the route and `umtool walk --json`: no manifest, no detail, no Set. */
+export function walkJson(w) {
+ const { manifest: _m, detail: _d, onWalk: _o, ...rest } = w;
+ return rest;
+}