Archilyzer · Source

archilyzer

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

commit 842aed3ba4e7108d1d3e969f376bb6df4b3d3e73
parent 60f91f06a0b5db1023323c57fa17dc013c83861f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 11:20:39 -0500

umtool: the working cut is the latest take -- Play plays it by default and names it ("Latest: draft-22 · 28:03 · +N edits since"), Re-render remakes it, and a new whole-cut take is its group's pick (auto-pick, unless a pick is pinned)

The operator (1 Nov): "Most of the time I'll only really be working on the
latest cut/draft rather than the picked one, I only picked a cut because I
needed to in order to start working on anything."

- lib/report/workingCut.mjs: the newest WORKING take (takes.mjs
  isWorkingTake: window full, rendered, not quick, made from the manifest,
  no style, no timeline of its own) and the edits since it -- 0 when the
  manifest's hash is its baseHash, else cutDiff of what it rendered against
  the manifest now with its patch (added / removed / moved / trimmed, in words).
- Play: /play with no take plays the latest take (?cut=1 the manifest alone);
  WhatPlays names it first, the other takes behind "N more", the pick small
  and only when it is not the latest. Edits from Play (Reject) go to the
  project's manifest on any take without a timeline of its own; notes taken on
  the default are the cut's.
- The take link clicked while playing is no longer cancelled: Play writes no
  URL of its own while a navigation is in flight.
- clipDeck.ts: Re-render the take = the latest take, else the pick, else the
  newest whole-cut take. With two whole-cut takes and none picked it used to
  have no target ("Choose a take to render") -- the gate that made a pick
  necessary.
- Auto-pick (takes.mjs autoPickTake, called when a take is built): a working
  take becomes its group's pick, mark only; `pinned` on a pick (umtool takes
  pick <p> <t> --pin / --unpin, the pick route's `pin`) keeps it there.
- umtool takes ls prints the working cut's line first and marks `latest`; the
  Takes page shows the line and a latest badge (picked de-emphasised).

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

Diffstat:
Mumtool/app/api/report/takes/pick/route.ts | 9++++++---
Mumtool/components/projects/PlayCutPage.tsx | 7+++++--
Mumtool/components/projects/ProjectView.tsx | 2+-
Mumtool/components/projects/TakesBench.tsx | 13++++++++++---
Mumtool/components/projects/TakesPage.tsx | 16++++++++++++++--
Mumtool/components/projects/review/ClipDeck.tsx | 2+-
Mumtool/components/projects/review/PlayCut.tsx | 75+++++++++++++++++++++++++++++++++++++++++++++------------------------------
Aumtool/components/projects/review/WhatPlays.tsx | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 4+++-
Mumtool/lib/report/clipDeck.ts | 21++++++++++++++++-----
Mumtool/lib/report/clipEditorTypes.ts | 2+-
Mumtool/lib/report/playView.mjs | 32+++++++++++++++++++++++++++-----
Mumtool/lib/report/takeCli.mjs | 25++++++++++++++++++-------
Mumtool/lib/report/takeHousekeeping.mjs | 4+++-
Mumtool/lib/report/takeMaker.mjs | 14++++++++++----
Mumtool/lib/report/takes.mjs | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aumtool/lib/report/workingCut.mjs | 172+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/workingCut.test.mjs | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18 files changed, 661 insertions(+), 71 deletions(-)

diff --git a/umtool/app/api/report/takes/pick/route.ts b/umtool/app/api/report/takes/pick/route.ts @@ -5,7 +5,10 @@ import { isTakeId } from "@/lib/report/takes.mjs"; export const dynamic = "force-dynamic"; -// "USE THIS TAKE" (release 33). POST { project, take, anyway? } +// "USE THIS TAKE" (release 33). POST { project, take, anyway?, pin? } +// +// `pin` (1 Nov 2026): true pins the pick (a newer whole-cut take is not +// auto-picked over it), false unpins; absent keeps a re-picked take's pin. // // The take's video.manifest.json over the project's, through the manifest // writer (lib/report/manifest.mjs replaceManifest: the auto snapshot @@ -17,13 +20,13 @@ export const dynamic = "force-dynamic"; // was made from -- the pick would throw away what changed since -- until the // operator says `anyway` (a second, explicit click). export async function POST(request: Request) { - const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown } | null; + const body = (await request.json().catch(() => null)) as { project?: unknown; take?: unknown; anyway?: unknown; pin?: unknown } | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 }); const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); try { - const r = await pickTake(project, body.take, { anyway: body.anyway === true }); + const r = await pickTake(project, body.take, { anyway: body.anyway === true, pinned: body.pin === true ? true : body.pin === false ? false : undefined }); invalidateProjects(); const historyHref = await pieceHrefOfProject(project.id, { tab: "history" }); return Response.json({ ok: true, ...r, historyHref }, { headers: { "cache-control": "no-store" } }); diff --git a/umtool/components/projects/PlayCutPage.tsx b/umtool/components/projects/PlayCutPage.tsx @@ -19,24 +19,27 @@ import PlayCut, { type PlayViewData } from "./review/PlayCut"; export default async function PlayCutPage({ project, take, + bare = false, note, clip, at, }: { project: ProjectRef; take?: string; + /** `?cut=1`: the project's manifest alone, no take's patch (the default is the latest take). */ + bare?: boolean; note?: string; /** `?clip=<id>&at=<s>`: start on that clip, that far into it (the clip bench's "Back to the cut"). */ clip?: string; at?: string; }) { - const [view, back] = await Promise.all([playView(project, { take: take || null }), pieceHrefOfProject(project.id, { tab: "cut" })]); + const [view, back] = await Promise.all([playView(project, { take: take || null, bare }), pieceHrefOfProject(project.id, { tab: "cut" })]); const top = ( <BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Play the cut" - here={"error" in view || !view.take ? "the cut" : `take ${view.take.id}`} + here={"error" in view || !view.take ? "the manifest" : view.take.defaulted ? `latest · ${view.take.id}` : `take ${view.take.id}`} /> ); if ("error" in view) { diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -83,7 +83,7 @@ export default async function ProjectView({ // the browser in its final look, no render, with notes taken as it plays. // `/projects/<project>/trailer` -- the trailer's beats (promo/trailer-beats.json). if (rest.length === 1 && rest[0] === "trailer") return <TrailerPage project={project} />; - if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} note={search.note} clip={search.clip} at={search.at} />; + if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} bare={search.cut === "1"} note={search.note} clip={search.clip} at={search.at} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -54,6 +54,8 @@ export type Take = { editedAt?: string | null; /** What a running render names (takeHousekeeping.mjs renderHolds): it is rendering, or a render is made from it. */ holds?: string[]; + /** The newest whole-cut take of the manifest: the working cut's name (lib/report/workingCut.mjs). */ + latest?: boolean; }; /** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */ @@ -78,7 +80,7 @@ type WorkPlan = { }; export type Verdict = "like" | "maybe" | "no"; -export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true; superseded?: { by: string | null; at: string } }; +export type TakeVerdict = { verdict: Verdict | null; note: string; at: string; picked?: true; pinned?: true; superseded?: { by: string | null; at: string } }; const KIND_TONE: Record<Take["kind"], BadgeVariants["variant"]> = { reference: "on", @@ -690,9 +692,14 @@ function TakeCard({ {windowWords && ` · ${windowWords}`} {t.quick && " · quick"} </span> + {t.latest && ( + <span data-take-latest="" title="the newest whole-cut take of the manifest: what Play plays, and Re-render remakes" className={badgeVariants({ variant: "on", size: "sm" })}> + latest + </span> + )} {verdict?.picked && ( - <span data-take-picked="" className={badgeVariants({ variant: "on", size: "sm" })}> - picked + <span data-take-picked="" title={`“Use this take” (or a new whole-cut take) made it its group's pick${verdict.pinned ? "; pinned" : ""}`} className={badgeVariants({ variant: "info", size: "sm" })}> + picked{verdict.pinned ? " · pinned" : ""} </span> )} {(t.holds ?? []).length > 0 && ( diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx @@ -11,6 +11,9 @@ import { renderHolds } from "@/lib/report/takeHousekeeping.mjs"; import { fxPresetsFor } from "umtool-report-to-video/fx"; import NewTakePanel from "./NewTakePanel"; import TakesBench, { type Take, type TakeVerdict } from "./TakesBench"; +import { LatestLine } from "./review/WhatPlays"; +import { readWorkingCut } from "@/lib/report/workingCut.mjs"; +import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; // `/browse/<project>/takes` -- alternative renders of one part of the cut, // watched side by side and judged like / maybe / no. @@ -38,7 +41,9 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { } // What a running render names (take housekeeping): the card says so, and relabel/delete refuse. const holds = new Map(await Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await renderHolds(project.dir, t.id)] as const))); - const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [] })); + // The working cut's name: the latest whole-cut take and the edits since it (lib/report/workingCut.mjs). + const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null); + const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id })); const byId = new Map(takes.map((t) => [t.id, t])); const panel = project.kind === "report-video" ? ( @@ -98,7 +103,14 @@ export default async function TakesPage({ project }: { project: ProjectRef }) { project={project.id} groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes.map((t: { id: string }) => byId.get(t.id) as Take) }))} initial={verdicts as Record<string, TakeVerdict>} - head={panel} + head={ + <> + <p className="m-0 text-[12.5px]" data-takes-working=""> + <LatestLine project={project.id} working={working} /> + </p> + {panel} + </> + } > {skipped} </TakesBench> diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx @@ -930,7 +930,7 @@ function EndCard({ </div> {rerender && ( <p className="m-0 text-[11.5px] text-muted" data-rerender-why={rerender.why}> - {rerender.why === "picked" ? "The picked take" : "The whole-cut take"} + {rerender.why === "latest" ? `The latest take, ${rerender.take}` : rerender.why === "picked" ? "The picked take" : "The newest whole-cut take"} {since !== null ? ` · ${since} ruling${since === 1 ? "" : "s"} since it was made` : ""} </p> )} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -1,13 +1,12 @@ "use client"; -import Link from "next/link"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { useSharedNotes } from "@/components/notes/NotesProvider"; import { NoteThread } from "@/components/notes/NoteThread"; import type { Anchor, CutAsk, Note } from "@/lib/annotations/types"; -import { clipBenchHref, playHref } from "@/lib/hrefs"; +import { clipBenchHref } from "@/lib/hrefs"; import { cn } from "@/lib/utils"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; @@ -22,6 +21,7 @@ import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; import type { EngineInfo, MediaRef } from "./playEngine/engine"; import ReelStrip, { type StripCounter } from "./ReelStrip"; import RejectClip from "./RejectClip"; +import WhatPlays, { type WorkingCut } from "./WhatPlays"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; // --------------------------------------------------------------------------- @@ -113,9 +113,11 @@ export type PlayEntry = { export type PlayViewData = { project: string; title: string; - take: { id: string; label: string; summary: string; made: boolean; from: string } | null; + take: { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; note: string | null; takes: { id: string; label: string; made: boolean }[]; + /** The working cut's name: the latest whole-cut take, the edits since, the pick (lib/report/workingCut.mjs). */ + working?: WorkingCut; counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] }; markers: { after: string; label: string }[]; leadIn: number; @@ -222,6 +224,13 @@ export default function PlayCut({ const router = useRouter(); const project = view.project; const take = view.take?.id ?? null; + // Edits made here (Reject, a reorder, the bench) write the PROJECT'S manifest, which a take + // without a timeline of its own plays as it is now -- the latest take follows them. A take + // with its own timeline does not: nothing structural is offered on it (its walk edits it). + const editable = !view.take?.ownTimeline; + // A note taken on the latest take (the default) is a note on the cut: the manifest is the + // file to edit. On a take chosen by name it is that take's, as it always was. + const noteTake = view.take && !view.take.defaulted ? take : null; // Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/. const clipExport = useClipExport(project, take); @@ -392,8 +401,11 @@ export default function PlayCut({ // ---- the notes ------------------------------------------------------------------- const notes = useSharedNotes({ project }); const mine = useMemo( - () => notes.notes.filter((n) => n.anchor.kind === "cut" && (n.anchor.take ?? null) === take).sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t), - [notes.notes, take], + () => + notes.notes + .filter((n) => n.anchor.kind === "cut" && ((n.anchor.take ?? null) === noteTake || (view.take?.defaulted && (n.anchor.take ?? null) === take))) + .sort((a, b) => (a.anchor as CutAnchor).t - (b.anchor as CutAnchor).t), + [notes.notes, take, noteTake, view.take?.defaulted], ); // A note's second on this clock: by its clip and source second when it has them (the // render's edges re-time the cut; a note stays on the word it was taken on), else its t. @@ -421,8 +433,8 @@ export default function PlayCut({ setPlaying(false); } const src = item.clip ? sourceAt(item, e.t) : null; - setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(take ? { take } : {}) }); - }, [pauseWhileWriting, setPlaying, take, now]); + setDrafting({ kind: "cut", t: Math.round(e.t * 100) / 100, entry: item.id, ...(src !== null ? { sourceT: src } : {}), ...(noteTake ? { take: noteTake } : {}) }); + }, [pauseWhileWriting, setPlaying, noteTake, now]); const closeDraft = useCallback(() => { setDrafting(null); if (resumeAfter.current) { @@ -455,8 +467,8 @@ export default function PlayCut({ const e = now(); const it = planRef.current.items[e.cur]; if (!it?.clip) return null; - return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take } }); - }, [project, take, now]); + return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take: view.take?.defaulted ? null : take } }); + }, [project, take, now, view.take?.defaulted]); /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ const placeHref = useCallback(() => { const e = now(); @@ -481,10 +493,22 @@ export default function PlayCut({ router.push(h); }, [editHref, router, setPlaying, placeHref]); const lastPlace = useRef(0); + // A navigation in flight (a take link, Play the latest): Play's own URL write would land on + // top of it and cancel it (the audit's "a take link clicked while playing is cancelled"), so + // nothing is written until the new view arrives. + const navigating = useRef(false); + const onNavigate = useCallback(() => { + navigating.current = true; + setPlaying(false); + }, [setPlaying]); + useEffect(() => { + navigating.current = false; + }, [view]); useEffect(() => { // Not while a place is still being restored: the URL holds it until it lands. if (anchor.current) return; const due = () => { + if (navigating.current) return; lastPlace.current = performance.now(); const h = placeHref(); if (h !== `${window.location.pathname}${window.location.search}${window.location.hash}`) window.history.replaceState(null, "", h); @@ -664,23 +688,7 @@ export default function PlayCut({ {/* ---- the head: the cut's title, what plays, the running time ---- */} <header className="flex flex-wrap items-center gap-x-4 gap-y-1.5 border-b border-seam px-4 py-2 max-md:-mx-4"> <h1 className="m-0 min-w-0 truncate font-display text-[17px] font-semibold tracking-[-0.01em] text-text">{view.title}</h1> - <nav aria-label="What plays" className="flex flex-wrap items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-play-takes=""> - {[{ id: null as string | null, label: "The cut", made: true }, ...view.takes].map((tk) => { - const on = (tk.id ?? null) === take; - return ( - <Link - key={tk.id ?? "cut"} - href={playHref(project, { take: tk.id })} - aria-current={on ? "page" : undefined} - data-play-take-link={tk.id ?? ""} - title={tk.id ? `${tk.label}${tk.made ? "" : " (not rendered yet)"}` : "the project's cut"} - className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !tk.made && "italic")} - > - {tk.id ?? "The cut"} - </Link> - ); - })} - </nav> + <WhatPlays project={project} take={view.take} takes={view.takes} working={view.working ?? null} onNavigate={onNavigate} /> <span className="ml-auto font-mono text-[15px] tabular-nums text-text" data-play-clock=""> {runningTime(t)} <span className="text-muted">/ {runningTime(plan.total)}</span> </span> @@ -688,10 +696,17 @@ export default function PlayCut({ ? </button> </header> - {view.take && ( - <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id}> - take “{view.take.label}”: the project&rsquo;s cut with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} + {view.take ? ( + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take={view.take.id} data-play-take-defaulted={view.take.defaulted ? "" : undefined}> + {view.take.defaulted ? "the latest take, " : ""}take “{view.take.label}”: the project&rsquo;s cut as it is now with its patch ({view.take.from}){view.take.made ? "" : " — not rendered yet"} {view.take.summary ? ` · ${view.take.summary}` : ""} + {view.take.ownTimeline + ? " — it has its own timeline: edits to the cut do not show in it, and nothing here edits it (walk the take)" + : " · edits here go to the cut, and show at once"} + </p> + ) : ( + <p className="m-0 border-b border-seam px-4 py-1 text-[11.5px] text-text-2 max-md:-mx-4 max-md:-mt-3" data-play-take=""> + the project&rsquo;s manifest alone — no take&rsquo;s look (title, deck and effects patches are not applied) </p> )} @@ -832,7 +847,7 @@ export default function PlayCut({ <ClipExportStatus exp={clipExport} /> </div> {/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */} - {!take && ( + {editable && ( <RejectClip project={project} hotkey diff --git a/umtool/components/projects/review/WhatPlays.tsx b/umtool/components/projects/review/WhatPlays.tsx @@ -0,0 +1,159 @@ +"use client"; + +import Link from "next/link"; +import { playHref, takesHref } from "@/lib/hrefs"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// WHAT PLAYS (operator, 1 Nov 2026): the working cut's NAME, as prominent as a +// take's -- "Latest: draft-22 · 28:03 · +3 edits since" -- and the switch to an +// older take or to the manifest alone. The latest take is the newest +// whole-cut take made from the project (lib/report/workingCut.mjs); the edits +// since it are the project's manifest against what that take rendered. The +// pick (verdicts.json) is secondary: named small, only when it is not the +// latest. Every switch is a link (`?take=`, `?cut=1`, nothing for the latest); +// `onNavigate` lets Play stop writing its own URL while one is in flight. +// --------------------------------------------------------------------------- + +export type WorkingCut = { + latest: { id: string; label: string; builtAt: string | null; seconds: number | null } | null; + edits: { count: number; words: string[]; same: boolean } | null; + picked: { id: string; at: string | null; pinned: boolean; label: string } | null; +} | null; + +export type WhatPlaysTake = { id: string; label: string; summary: string; made: boolean; from: string; ownTimeline?: boolean; defaulted?: boolean } | null; + +const mmss = (s: number | null) => (typeof s === "number" ? `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : null); +const day = (iso: string | null) => { + if (!iso) return null; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString(undefined, { day: "numeric", month: "short" }); +}; + +/** "+3 edits since" / "no edits since" / "edits since: unknown". */ +export function editsLine(w: WorkingCut) { + if (!w?.latest) return ""; + if (!w.edits) return "edits since: unknown"; + return w.edits.count === 0 ? "no edits since" : `+${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; +} + +/** The working cut's line, alone (the bench's head, the Takes page). */ +export function LatestLine({ project, working, className }: { project: string; working: WorkingCut; className?: string }) { + if (!working) return null; + const l = working.latest; + return ( + <span data-working-cut={l?.id ?? ""} data-working-edits={working.edits?.count ?? ""} className={cn("inline-flex flex-wrap items-baseline gap-x-1.5", className)}> + {l ? ( + <> + <span className="micro">Latest</span> + <Link href={playHref(project)} className="font-mono font-medium text-text hover:underline" title={l.label}> + {l.id} + </Link> + {mmss(l.seconds) && <span className="font-mono text-muted">{mmss(l.seconds)}</span>} + <span className="text-muted" title={working.edits?.words.join("\n") || undefined} data-working-edit-words={working.edits?.words.join("; ") ?? ""}> + · {editsLine(working)} + </span> + </> + ) : ( + <span className="text-muted">no whole-cut take yet — the manifest is the cut</span> + )} + </span> + ); +} + +export default function WhatPlays({ + project, + take, + takes, + working, + onNavigate, +}: { + project: string; + take: WhatPlaysTake; + takes: { id: string; label: string; made: boolean }[]; + working: WorkingCut; + onNavigate?: () => void; +}) { + const latest = working?.latest ?? null; + const current = take?.id ?? null; + const isLatest = !!latest && current === latest.id; + // A few takes are pills; many are a list (the latest and the one playing stay pills). + const many = takes.length > 4; + const pills = many ? takes.filter((t) => t.id === current || t.id === latest?.id) : takes; + const rest = many ? takes.filter((t) => !pills.includes(t)) : []; + const link = (t: { id: string | null; label: string; made: boolean }, label: string) => { + const on = t.id === null ? take === null : t.id === current; + const href = t.id === null ? playHref(project, { bare: true }) : t.id === latest?.id ? playHref(project) : playHref(project, { take: t.id }); + return ( + <Link + key={t.id ?? "cut"} + href={href} + onClick={onNavigate} + aria-current={on ? "page" : undefined} + data-play-take-link={t.id ?? ""} + title={t.id ? `${t.label}${t.made ? "" : " (not rendered yet)"}` : "the project's manifest alone: no take's look"} + className={cn("rounded-[2px] px-2 py-0.5", on ? "bg-panel-2 font-medium text-text" : "text-muted-2 hover:text-text", !t.made && "italic")} + > + {label} + </Link> + ); + }; + return ( + <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1"> + {/* The working cut's name, first and largest. */} + <span + data-play-working={latest?.id ?? ""} + data-play-working-edits={working?.edits?.count ?? ""} + className="inline-flex flex-wrap items-baseline gap-x-1.5 text-[13px]" + > + {latest ? ( + <> + <span className="micro">{isLatest ? "Latest" : "Latest is"}</span> + {isLatest ? ( + <span className="font-mono font-semibold text-text" title={latest.label}> + {latest.id} + </span> + ) : ( + <Link href={playHref(project)} onClick={onNavigate} className="font-mono font-semibold text-text underline decoration-dotted" title={`${latest.label} — play it`} data-play-latest-link=""> + {latest.id} + </Link> + )} + {mmss(latest.seconds) && <span className="font-mono text-[12px] text-muted">{mmss(latest.seconds)}</span>} + <span className="text-[12px] text-muted" title={working?.edits?.words.join("\n") || undefined} data-play-edit-words={working?.edits?.words.join("; ") ?? ""}> + · {editsLine(working)} + </span> + </> + ) : ( + <span className="text-[12px] text-muted">no whole-cut take yet — the manifest is the cut</span> + )} + </span> + <nav aria-label="What plays" className="flex flex-wrap items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-play-takes=""> + {pills.map((t) => link(t, t.id))} + {link({ id: null, label: "the manifest alone", made: true }, "manifest only")} + {rest.length > 0 && ( + <details className="relative" data-play-more-takes=""> + <summary className="cursor-pointer list-none rounded-[2px] px-2 py-0.5 text-muted-2 hover:text-text">{rest.length} more ▾</summary> + <div className="absolute left-0 top-full z-40 mt-1 flex max-h-[50vh] min-w-[260px] flex-col overflow-auto rounded-[3px] border border-seam-2 bg-panel p-1 shadow-lg"> + {rest + .slice() + .reverse() + .map((t) => ( + <span key={t.id} className="flex items-baseline gap-2 whitespace-nowrap"> + {link(t, t.id)} + <span className="truncate text-[11px] text-muted">{t.label}</span> + </span> + ))} + </div> + </details> + )} + </nav> + {working?.picked && working.picked.id !== latest?.id && ( + <Link href={takesHref(project)} className="text-[11px] text-muted-2 hover:text-text" data-play-picked={working.picked.id} title={`“Use this take” last copied ${working.picked.id} over the manifest${working.picked.pinned ? " (pinned)" : ""}`}> + picked: {working.picked.id} + {day(working.picked.at) ? ` (${day(working.picked.at)})` : ""} + {working.picked.pinned ? ", pinned" : ""} + </Link> + )} + </div> + ); +} diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -346,6 +346,8 @@ export function playHref( project: string, q: NoteOpt & { take?: string | null; + /** The project's manifest alone, no take's patch (`?cut=1`); without it and a take, the latest take plays. */ + bare?: boolean; /** Start on this clip, `at` seconds into what the page shows of it (the bench's Back to the cut). */ clip?: string | null; at?: number | null; @@ -353,7 +355,7 @@ export function playHref( ): string { return withQuery( `/projects/${encodePath(project)}/play`, - { take: q.take, clip: q.clip, at: q.clip && q.at != null && q.at > 0 ? q.at.toFixed(2) : null }, + { take: q.take, cut: !q.take && q.bare ? "1" : null, clip: q.clip, at: q.clip && q.at != null && q.at > 0 ? q.at.toFixed(2) : null }, q.note, ); } diff --git a/umtool/lib/report/clipDeck.ts b/umtool/lib/report/clipDeck.ts @@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { channelFor, readManifest } from "@/lib/projects/report.mjs"; import { listTakes, readVerdicts } from "@/lib/report/takes.mjs"; +import { latestWorkingTake } from "@/lib/report/workingCut.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { earlierRulingsOffer, montageClipsOf, readRulingsState } from "@/lib/report/montageRulings.mjs"; import type { CitedTarget } from "@/lib/clips/types"; @@ -42,7 +43,7 @@ export type ClipCard = { extent: CitedTarget | null; }; -export type RerenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" }; +export type RerenderTarget = { take: string; label: string; builtAt: string | null; why: "latest" | "picked" | "whole cut" }; export type ClipDeckView = { cards: ClipCard[]; @@ -142,13 +143,23 @@ export async function clipDeckView(project: { id: string; dir: string }): Promis }); } - // The take "Re-render the take" makes again: the one picked, else the one - // whole-cut take; anything else is a choice the Takes page makes. - type T = { id: string; label: string; builtAt: string | null; window?: unknown; baseHash?: string | null }; + // The take "Re-render the take" makes again: the LATEST whole-cut take of the + // manifest (operator, 1 Nov 2026 -- the working cut's name, workingCut.mjs), + // else the one picked, else the one whole-cut take. It used to be the pick + // first, and with two whole-cut takes and none picked there was no target at + // all: "Choose a take to render", which only a pick unblocked. + type T = { id: string; label: string; builtAt: string | null; window?: unknown; baseHash?: string | null; order: number }; const made = (listing.takes as T[]).filter((t) => t.baseHash); + const latest = latestWorkingTake(listing.takes as Parameters<typeof latestWorkingTake>[0]) as T | null; const picked = made.filter((t) => (verdicts as Record<string, { picked?: true }>)[t.id]?.picked); const whole = made.filter((t) => t.window === "full"); - const target = picked.length === 1 ? { t: picked[0], why: "picked" as const } : picked.length === 0 && whole.length === 1 ? { t: whole[0], why: "whole cut" as const } : null; + const target = latest + ? { t: latest, why: "latest" as const } + : picked.length === 1 + ? { t: picked[0], why: "picked" as const } + : whole.length >= 1 + ? { t: [...whole].sort((a, b) => String(b.builtAt ?? "").localeCompare(String(a.builtAt ?? "")))[0], why: "whole cut" as const } + : null; const left = offer.rulings.filter((r: { ruling: { verdict: string } }) => r.ruling.verdict !== "keep").length; return { diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -121,4 +121,4 @@ export type Neighbourhood = { }; /** The take "Render a take" makes again (the clip deck's rule), or null: the Takes page chooses. */ -export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" } | null; +export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "latest" | "picked" | "whole cut" } | null; diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -16,6 +16,7 @@ import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; +import { readWorkingCut } from "./workingCut.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -27,21 +28,41 @@ export function headingOf(e) { } /** + * WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no + * `take`, the newest working take (workingCut.mjs) -- the project's manifest + * as it is now with that take's patch, so the look is the next draft's and + * every edit since shows. `bare` plays the manifest alone (`?cut=1`). The + * working cut's name rides along (`working`) for the label. + * * @param {{ id: string, dir: string }} project - * @param {{ take?: string | null }} [opts] + * @param {{ take?: string | null, bare?: boolean }} [opts] */ -export async function playView(project, { take = null } = {}) { +export async function playView(project, { take = null, bare = false } = {}) { const base = await readManifest(project.dir); if (!base) return { error: "this project has no video.manifest.json" }; + const working = await readWorkingCut(project.dir, { + resolveNow: async (id) => (await resolveTakeManifest(project.dir, id, { base })).manifest, + }).catch(() => null); + const defaulted = !take && !bare && !!working?.latest; + if (defaulted) take = working.latest.id; let manifest = base; - /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string }} */ + /** @type {null | { id: string, label: string, summary: string, made: boolean, from: string, ownTimeline: boolean, defaulted: boolean }} */ let takeInfo = null; let note = null; if (take) { try { - const r = await resolveTakeManifest(project.dir, take); + const r = await resolveTakeManifest(project.dir, take, { base }); manifest = r.manifest; - takeInfo = { id: r.take.id, label: r.take.label, summary: r.take.summary, made: r.take.made, from: r.take.from }; + takeInfo = { + id: r.take.id, + label: r.take.label, + summary: r.take.summary, + made: r.take.made, + from: r.take.from, + // A patch that brings its own timeline: edits to the project's cut do not show in it (its walk edits it). + ownTimeline: Array.isArray(/** @type {any} */ (r.take.patch)?.timeline), + defaulted, + }; note = r.note; } catch (e) { return { error: e instanceof Error ? e.message : String(e) }; @@ -127,6 +148,7 @@ export async function playView(project, { take = null } = {}) { take: takeInfo, note, takes: await playableTakes(project.dir), + working, leadIn: fin(render.leadIn) ? render.leadIn : 0.4, transition: D, blurRendered: render.blur !== "off", diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -81,9 +81,12 @@ export const TAKES_USAGE = [ " [--priority] (either form: render mode for the whole batch, as `umtool take --priority`)", ` one take per montage style (writes takes/${ALL_STYLES_RECIPE})`, " umtool takes styles [--json] the montage styles: name, label, summary", - " umtool takes pick <project> <take> [--anyway] use this take: its manifest over the project's", + " umtool takes pick <project> <take> [--anyway] [--pin | --unpin] use this take: its manifest over the", + " project's (to go back to an older take); --pin keeps the pick there when newer takes are", + " made (each whole-cut take of the manifest is otherwise its group's pick once built)", " umtool takes effects <project> [--json] the overlay effects this cut offers, for --effect", - " umtool takes ls <project> [--json] each take: label, length, picked / superseded / rendering", + " umtool takes ls <project> [--json] the working cut (Latest: <take> · +N edits since), then", + " each take: label, length, latest / picked / superseded / rendering", " umtool takes relabel <project> <take> <label…> take.json's label (an undo point of the take's own;", " refused while it renders)", " umtool takes supersede <project> <take> [--by <take>] | --clear folded away in the takes list (verdicts.json)", @@ -354,10 +357,16 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con if (sub === "ls") { const project = await pickProject(rest[0], reportsRoot); const { takesOverview, takeLine } = await import("./takeHousekeeping.mjs"); - const o = await takesOverview(project.dir); - if (p.has("--json")) log(JSON.stringify({ project: project.id, ...o }, null, 2)); + const { readWorkingCut, workingCutLine } = await import("./workingCut.mjs"); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + const [o, working] = await Promise.all([ + takesOverview(project.dir), + readWorkingCut(project.dir, { resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }), + ]); + if (p.has("--json")) log(JSON.stringify({ project: project.id, working, ...o }, null, 2)); else { - for (const r of o.rows) log(takeLine(r)); + log(workingCutLine(working) + (working.edits?.words?.length ? ` (${working.edits.words.slice(0, 8).join("; ")}${working.edits.words.length > 8 ? "; …" : ""})` : "")); + for (const r of o.rows) log(takeLine({ ...r, latest: r.id === working.latest?.id })); for (const sk of o.skipped) err(`skipped takes/${sk.dir}: ${sk.why}`); } return 0; @@ -424,9 +433,11 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con const take = rest[1]; if (!take) throw new CliError("which take? `umtool takes pick <project> <take>`"); try { - const r = await pickTake(project, take, { anyway: p.has("--anyway") }); + if (p.has("--pin") && p.has("--unpin")) throw new CliError("--pin or --unpin, not both"); + const pinned = p.has("--pin") ? true : p.has("--unpin") ? false : undefined; + const r = await pickTake(project, take, { anyway: p.has("--anyway"), pinned }); if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2)); - else log(`${project.id}: now ${take}'s manifest${r.snapshot?.rel ? ` (the one before is ${r.snapshot.rel})` : ""}`); + else log(`${project.id}: now ${take}'s manifest${r.snapshot?.rel ? ` (the one before is ${r.snapshot.rel})` : ""}${r.verdicts?.[take]?.pinned ? " — pinned: newer takes do not move the pick" : ""}`); return 0; } catch (e) { if (e instanceof TakeStale) { diff --git a/umtool/lib/report/takeHousekeeping.mjs b/umtool/lib/report/takeHousekeeping.mjs @@ -65,6 +65,7 @@ export async function takesOverview(projectDir) { draft: t.draft, verdict: v?.verdict ?? null, picked: v?.picked === true, + pinned: v?.pinned === true, superseded: v?.superseded ?? null, rendering: holds.some((h) => h.startsWith("it is rendering")), base: holds.some((h) => !h.startsWith("it is rendering")), @@ -77,7 +78,8 @@ export async function takesOverview(projectDir) { /** One line of `umtool takes ls`. */ export function takeLine(r) { const marks = [ - r.picked ? "picked" : null, + r.latest ? "latest" : null, + r.picked ? (r.pinned ? "picked, pinned" : "picked") : null, r.superseded ? `superseded${r.superseded.by ? ` by ${r.superseded.by}` : ""}` : null, r.draft ? "draft" : null, r.rendering ? "RENDERING" : null, diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -54,7 +54,7 @@ import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; -import { isTakeId, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; +import { autoPickTake, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; @@ -690,6 +690,11 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { const tmp = `${takeFile}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); + // A whole-cut take of the manifest is its group's pick now (takes.mjs autoPickTake): mark only. + const group = ((listing ?? (await listTakes(projectDir))).takes ?? []).filter((t) => t.group === doc.group).map((t) => t.id); + const pick = await autoPickTake(projectDir, { ...doc, id: spec.id }, group).catch((e) => ({ picked: false, why: e instanceof Error ? e.message : String(e) })); + if (pick.picked) log(`${spec.id}: the working cut's take now (picked: ${pick.why})`); + else if (isWorkingTake(doc)) log(`${spec.id}: not picked — ${pick.why}`); emit({ ev: "take", id: spec.id, phase: "done", seconds: doc.seconds }); return { id: spec.id, skipped: false, take: doc }; } @@ -942,9 +947,10 @@ export async function takeIsStale(projectDir, take) { * * @param {{ id: string, dir: string, kind: string }} project * @param {string} takeId - * @param {{ anyway?: boolean, token?: string | null, now?: Date }} [opts] + * @param {{ anyway?: boolean, token?: string | null, now?: Date, pinned?: boolean }} [opts] + * `pinned`: true pins the pick (no auto-pick over it), false unpins (takes.mjs setTakePicked) */ -export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date() } = {}) { +export async function pickTake(project, takeId, { anyway = false, token = null, now = new Date(), pinned = undefined } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === takeId); @@ -967,7 +973,7 @@ export async function pickTake(project, takeId, { anyway = false, token = null, ? { result: { snapshot: null, token: null }, editNotes: null } : await withEditNotes(project, () => replaceManifest(project.dir, manifest, { token, op: "pick-take" })); const group = listing.takes.filter((t) => t.group === take.group).map((t) => t.id); - const { verdicts } = await setTakePicked(project.dir, takeId, group, { now }); + const { verdicts } = await setTakePicked(project.dir, takeId, group, { now, pinned }); return { take: takeId, group: take.group, snapshot: result.snapshot, token: result.token, editNotes, verdicts }; } diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -276,7 +276,7 @@ function cleanVerdicts(raw) { const verdict = TAKE_VERDICTS.includes(row.verdict) ? row.verdict : null; const note = typeof row.note === "string" ? row.note : ""; const at = typeof row.at === "string" ? row.at : ""; - out[id] = row.picked === true ? { verdict, note, at, picked: true } : { verdict, note, at }; + out[id] = row.picked === true ? { verdict, note, at, picked: true, ...(row.pinned === true ? { pinned: true } : {}) } : { verdict, note, at }; const sup = supersededOf(row.superseded); if (sup) out[id].superseded = sup; } @@ -359,6 +359,7 @@ export async function setTakeVerdict(projectDir, takeId, patch) { at: new Date().toISOString(), }; if (prev.picked === true) row.picked = true; + if (prev.pinned === true) row.pinned = true; if (prev.superseded) row.superseded = prev.superseded; if (emptyRow(row)) delete map[takeId]; else map[takeId] = row; @@ -373,31 +374,79 @@ export async function setTakeVerdict(projectDir, takeId, patch) { * of that group, the picked one included. A cleared row that then says * nothing is removed. Returns the whole file. * + * `pinned` (1 Nov 2026): `true` pins the pick -- a new full take made from the + * manifest is NOT auto-picked over it (autoPickTake); `false` unpins it; + * absent, a re-pick of the pinned take keeps its pin and any other pick is + * unpinned. + * * @param {string} projectDir * @param {string} takeId * @param {string[]} group - * @param {{ now?: Date }} [opts] + * @param {{ now?: Date, pinned?: boolean }} [opts] */ -export async function setTakePicked(projectDir, takeId, group, { now = new Date() } = {}) { +export async function setTakePicked(projectDir, takeId, group, { now = new Date(), pinned = undefined } = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const file = verdictsFileOf(projectDir); return withTakesLock(async () => { const map = await readVerdictsForWrite(file); for (const id of group) { if (id === takeId || !map[id]?.picked) continue; - const { picked: _gone, ...rest } = map[id]; + const { picked: _gone, pinned: _pin, ...rest } = map[id]; if (emptyRow(rest)) delete map[id]; else map[id] = rest; } const prev = map[takeId] ?? { verdict: null, note: "", at: "" }; + const pin = pinned === undefined ? prev.picked === true && prev.pinned === true : pinned === true; // A take picked is not superseded any more. - map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true }; + map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true, ...(pin ? { pinned: true } : {}) }; await writeVerdicts(file, map); return { entry: map[takeId], verdicts: map }; }); } /** + * A WORKING take (operator, 1 Nov 2026: "most of the time I'll only really be + * working on the latest cut/draft"): a whole-cut render of the project's + * manifest -- window `full`, rendered (not a draft), not a quick draft-quality + * render, made from the manifest (it records `baseHash`), and the manifest's + * own content: no montage style and no patch that brings a `timeline` of its + * own. The newest of them is the working cut's name (workingCut.mjs), and a + * new one is its group's pick (autoPickTake). A partial window, a style take + * or a take with its own timeline is a variant, never the cut. + * + * @param {{ window?: unknown, draft?: boolean, quick?: boolean, baseHash?: string | null, style?: string | null, patch?: Record<string, unknown> | null } | null | undefined} t + */ +export function isWorkingTake(t) { + if (!t || t.window !== "full" || t.draft === true || t.quick === true || !t.baseHash || t.style) return false; + return !(t.patch && typeof t.patch === "object" && Array.isArray(/** @type {any} */ (t.patch).timeline)); +} + +/** + * AUTO-PICK (1 Nov 2026): a working take just built becomes its group's pick + * -- a mark in verdicts.json, nothing copied: the project's manifest IS what it + * was made from -- so whatever still reads `picked` (the pruner's keep list, + * the Takes page) follows the latest draft, an agent's take as much as the + * operator's. Not when another take of the group holds a PINNED pick + * (`umtool takes pick <p> <take> --pin`). Never throws for a take that does not + * qualify: it says why. + * + * @param {string} projectDir + * @param {Parameters<typeof isWorkingTake>[0] & { id: string }} take + * @param {string[]} group the take ids of its group (it included) + * @param {{ now?: Date }} [opts] + * @returns {Promise<{ picked: boolean, why: string }>} + */ +export async function autoPickTake(projectDir, take, group, { now = new Date() } = {}) { + if (!isWorkingTake(take)) return { picked: false, why: "not a whole-cut take of the manifest (a window, a draft, a quick render, a style or its own timeline)" }; + const verdicts = await readVerdicts(projectDir); + const pinned = group.find((id) => id !== take.id && verdicts[id]?.picked && verdicts[id]?.pinned); + if (pinned) return { picked: false, why: `the pick is pinned to ${pinned} (umtool takes pick … ${pinned} --unpin)` }; + if (verdicts[take.id]?.picked) return { picked: true, why: "already the pick" }; + await setTakePicked(projectDir, take.id, group.includes(take.id) ? group : [...group, take.id], { now }); + return { picked: true, why: "the newest whole-cut take of the manifest" }; +} + +/** * Mark take `takeId` SUPERSEDED (UI notes 2026-10-30, item 19) -- by take * `by` when one is named -- or clear the mark (`clear: true`). The operator's * judgement, so it lives in verdicts.json beside the verdict and the pick (a diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs @@ -0,0 +1,172 @@ +// THE WORKING CUT'S NAME (operator, 1 Nov 2026): "Most of the time I'll only +// really be working on the latest cut/draft rather than the picked one". +// +// The project's video.manifest.json IS the working cut: the bench, Play, the +// Cut tab and every agent write it, and every take is MADE FROM it (take.json +// `baseHash`, the hash of the manifest it was made from). So the cut has a +// name -- the newest WORKING take (takes.mjs isWorkingTake: a whole-cut render +// of the manifest's own content) -- and a distance from it: the edits made to +// the manifest since that take was made. +// +// latest the newest working take, by builtAt (then order) +// edits 0 when the manifest's hash is the take's baseHash; else the +// entries added, removed, moved and changed between the manifest +// the take RENDERED (takes/<id>/video.manifest.json, its patch +// applied) and the manifest now with the same patch -- in words +// ("aw3 removed", "mc1 moved"); null when the take's rendered +// manifest is gone (pruned) and the hashes differ +// picked the group pick in verdicts.json (secondary: "Use this take", +// auto-picked for each new working take unless pinned) +// +// Plain ESM: the CLI (`umtool takes ls`) reads it under bare node. +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { isWorkingTake, listTakes, readVerdicts, takesDirOf } from "./takes.mjs"; + +const MANIFEST = "video.manifest.json"; +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const hashText = (text) => createHash("sha256").update(text).digest("hex"); + +/** + * The newest working take of a listing (listTakes's `takes`), or null. + * + * @template {{ id: string, builtAt?: string | null, order?: number }} T + * @param {T[]} takes + * @returns {T | null} + */ +export function latestWorkingTake(takes) { + const ok = (takes ?? []).filter((t) => isWorkingTake(/** @type {any} */ (t)) && t.builtAt); + ok.sort((a, b) => String(b.builtAt).localeCompare(String(a.builtAt)) || (b.order ?? 0) - (a.order ?? 0) || b.id.localeCompare(a.id)); + return ok[0] ?? null; +} + +/** What changed on an entry, as a word: a trim, gaps, the verdict, or an edit. */ +function changeWord(a, b) { + const differs = (k) => JSON.stringify(a?.[k] ?? null) !== JSON.stringify(b?.[k] ?? null); + if (["start", "end", "cutStart", "cutEnd"].some(differs)) return "trimmed"; + if (differs("gaps")) return "gaps"; + if (["verdict", "reason", "correction"].some(differs)) return "verdict"; + return "edited"; +} + +/** + * The edits from timeline `before` to `after`, by entry id: added, removed, + * moved (not on the longest run kept in order) and changed (same id, other + * fields), plus whether anything outside the timeline changed. `count` is the + * number of entries touched (+1 for the rest of the manifest); `words` one + * phrase per entry, in the order of `after`. + * + * @param {Record<string, any>} before + * @param {Record<string, any>} after + */ +export function cutDiff(before, after) { + const A = (Array.isArray(before?.timeline) ? before.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); + const B = (Array.isArray(after?.timeline) ? after.timeline : []).filter((e) => isObj(e) && typeof e.id === "string"); + const inA = new Map(A.map((e) => [e.id, e])); + const inB = new Map(B.map((e) => [e.id, e])); + const removed = A.filter((e) => !inB.has(e.id)).map((e) => e.id); + const added = B.filter((e) => !inA.has(e.id)).map((e) => e.id); + // The longest run of common ids kept in order: everything off it moved. + const a = A.map((e) => e.id).filter((id) => inB.has(id)); + const b = B.map((e) => e.id).filter((id) => inA.has(id)); + const posA = new Map(a.map((id, i) => [id, i])); + const seq = b.map((id) => posA.get(id)); + // Patience LIS over positions. + const tails = []; + const prevIdx = new Array(seq.length).fill(-1); + const tailIdx = []; + seq.forEach((v, i) => { + let lo = 0; + let hi = tails.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (tails[mid] < v) lo = mid + 1; + else hi = mid; + } + tails[lo] = v; + tailIdx[lo] = i; + prevIdx[i] = lo > 0 ? tailIdx[lo - 1] : -1; + }); + const kept = new Set(); + for (let i = tailIdx[tails.length - 1] ?? -1; i >= 0; i = prevIdx[i]) kept.add(b[i]); + const moved = b.filter((id) => !kept.has(id)); + const changed = b.filter((id) => JSON.stringify(inA.get(id)) !== JSON.stringify(inB.get(id))).map((id) => ({ id, what: changeWord(inA.get(id), inB.get(id)) })); + const { timeline: _a, ...restA } = isObj(before) ? before : {}; + const { timeline: _b, ...restB } = isObj(after) ? after : {}; + const rest = JSON.stringify(restA) !== JSON.stringify(restB); + const words = []; + const movedSet = new Set(moved); + const changedOf = new Map(changed.map((c) => [c.id, c.what])); + for (const e of B) { + const parts = []; + if (!inA.has(e.id)) parts.push("added"); + else { + if (movedSet.has(e.id)) parts.push("moved"); + if (changedOf.has(e.id)) parts.push(changedOf.get(e.id)); + } + if (parts.length) words.push(`${e.id} ${parts.join(", ")}`); + } + for (const id of removed) words.push(`${id} removed`); + if (rest) words.push("the look or the deck changed"); + const touched = new Set([...added, ...removed, ...moved, ...changed.map((c) => c.id)]); + return { added, removed, moved, changed, rest, count: touched.size + (rest ? 1 : 0), words }; +} + +async function readJson(file) { + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch { + return null; + } +} + +/** + * The working cut: the newest working take, the edits since it, the pick. + * + * @param {string} projectDir + * @param {{ manifestText?: string | null, resolveNow?: ((takeId: string) => Promise<Record<string, any> | null>) | null }} [opts] + * `resolveNow`: the manifest as it is now with that take's patch (takeManifest.mjs resolveTakeManifest) -- + * compared with what the take rendered; without it the bare manifest is compared + */ +export async function readWorkingCut(projectDir, { manifestText = null, resolveNow = null } = {}) { + const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]); + const takes = listing.takes; + const latest = latestWorkingTake(takes); + const pickedId = Object.keys(verdicts).find((id) => verdicts[id]?.picked && takes.some((t) => t.id === id)) ?? null; + const picked = pickedId + ? { id: pickedId, at: verdicts[pickedId].at || null, pinned: verdicts[pickedId].pinned === true, label: takes.find((t) => t.id === pickedId)?.label ?? pickedId } + : null; + if (!latest) return { latest: null, edits: null, picked, takes: takes.length }; + const text = manifestText ?? (await readFile(/* turbopackIgnore: true */ path.join(projectDir, MANIFEST), "utf8").catch(() => null)); + let edits = null; + if (text !== null && hashText(text) === latest.baseHash) edits = { count: 0, words: [], same: true }; + else { + const rendered = await readJson(path.join(takesDirOf(projectDir), latest.id, MANIFEST)); + let now = null; + try { + now = resolveNow ? await resolveNow(latest.id) : text !== null ? JSON.parse(text) : null; + } catch { + now = null; + } + if (isObj(rendered) && isObj(now)) { + const d = cutDiff(rendered, now); + edits = { count: d.count, words: d.words, same: false }; + } + } + return { + latest: { id: latest.id, label: latest.label, builtAt: latest.builtAt ?? null, seconds: latest.seconds ?? null, group: latest.group }, + edits, + picked, + takes: takes.length, + }; +} + +/** "Latest: draft-22 · 28:04 · +3 edits since" -- the line `umtool takes ls` prints first, and the pages show. */ +export function workingCutLine(w) { + if (!w?.latest) return "Latest: no whole-cut take yet — the manifest is the cut"; + const s = w.latest.seconds; + const len = typeof s === "number" ? ` · ${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}` : ""; + const ed = !w.edits ? " · edits since: unknown (its rendered manifest is gone)" : w.edits.count === 0 ? " · no edits since" : ` · +${w.edits.count} edit${w.edits.count === 1 ? "" : "s"} since`; + return `Latest: ${w.latest.id}${len}${ed}`; +} diff --git a/umtool/lib/report/workingCut.test.mjs b/umtool/lib/report/workingCut.test.mjs @@ -0,0 +1,116 @@ +// The working cut's name (workingCut.mjs) and the auto-pick (takes.mjs autoPickTake). +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { autoPickTake, isWorkingTake, readVerdicts, setTakePicked } from "./takes.mjs"; +import { cutDiff, latestWorkingTake, readWorkingCut, workingCutLine } from "./workingCut.mjs"; + +const hash = (t) => createHash("sha256").update(t).digest("hex"); +const clip = (id, start = 0, end = 5) => ({ id, type: "clip", video: "v", start, end }); + +test("isWorkingTake: a whole-cut render of the manifest's own content only", () => { + const ok = { window: "full", baseHash: "h", draft: false }; + assert.equal(isWorkingTake(ok), true); + assert.equal(isWorkingTake({ ...ok, patch: { title: "x", render: {} } }), true, "a look patch is still the cut"); + assert.equal(isWorkingTake({ ...ok, window: { at: 0, dur: 30 } }), false, "a window preview"); + assert.equal(isWorkingTake({ ...ok, draft: true }), false, "a draft (not rendered)"); + assert.equal(isWorkingTake({ ...ok, quick: true }), false, "a quick render"); + assert.equal(isWorkingTake({ ...ok, style: "punchy" }), false, "a montage style"); + assert.equal(isWorkingTake({ ...ok, patch: { timeline: [] } }), false, "its own timeline"); + assert.equal(isWorkingTake({ ...ok, baseHash: null }), false, "made by hand"); +}); + +test("latestWorkingTake: the newest working take by builtAt", () => { + const t = (id, builtAt, extra = {}) => ({ id, builtAt, order: 1, window: "full", baseHash: "h", ...extra }); + const takes = [t("draft-21", "2026-10-31T10:00:00Z"), t("draft-22", "2026-11-01T14:57:00Z"), t("preview", "2026-11-01T16:00:00Z", { window: { at: 0, dur: 30 } }), t("mods", "2026-11-01T17:00:00Z", { patch: { timeline: [] } })]; + assert.equal(latestWorkingTake(takes)?.id, "draft-22"); + assert.equal(latestWorkingTake([]), null); +}); + +test("cutDiff: added, removed, moved (off the longest kept run) and changed, in words", () => { + const before = { title: "a", timeline: [clip("a"), clip("b"), clip("c"), clip("d"), clip("e")] }; + const after = { title: "a", timeline: [clip("a"), clip("c"), clip("b", 0, 4), clip("e"), clip("f")] }; + const d = cutDiff(before, after); + assert.deepEqual(d.removed, ["d"]); + assert.deepEqual(d.added, ["f"]); + assert.equal(d.moved.length, 1, "one of b/c moved, not both"); + assert.deepEqual(d.changed, [{ id: "b", what: "trimmed" }]); + assert.equal(d.rest, false); + assert.equal(d.count, 4); + assert.ok(d.words.includes("d removed") && d.words.includes("f added")); + assert.equal(cutDiff(before, before).count, 0); + assert.equal(cutDiff(before, { ...before, title: "b" }).count, 1, "the rest of the manifest counts once"); +}); + +async function project() { + const dir = await mkdtemp(path.join(os.tmpdir(), "working-cut-")); + await mkdir(path.join(dir, "takes"), { recursive: true }); + return dir; +} +async function writeTake(dir, id, doc, manifest = null) { + await mkdir(path.join(dir, "takes", id), { recursive: true }); + await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "different", preview: "preview.mp4", ...doc })); + if (manifest) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(manifest)); +} + +test("readWorkingCut: the latest take, no edits when the manifest is its base, else the edits in words", async () => { + const dir = await project(); + try { + const m1 = { timeline: [clip("a"), clip("b"), clip("c")] }; + const text1 = JSON.stringify(m1); + await writeFile(path.join(dir, "video.manifest.json"), text1); + await writeTake(dir, "draft-1", { window: "full", baseHash: "old", builtAt: "2026-10-01T00:00:00Z" }); + await writeTake(dir, "draft-2", { window: "full", baseHash: hash(text1), builtAt: "2026-11-01T00:00:00Z", seconds: 125 }, m1); + let w = await readWorkingCut(dir); + assert.equal(w.latest?.id, "draft-2"); + assert.deepEqual(w.edits, { count: 0, words: [], same: true }); + assert.equal(workingCutLine(w), "Latest: draft-2 · 2:05 · no edits since"); + // An edit since: b moved after c, a removed. + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ timeline: [clip("c"), clip("b")] })); + w = await readWorkingCut(dir); + assert.equal(w.edits?.same, false); + assert.equal(w.edits?.count, 2); + assert.match(workingCutLine(w), /\+2 edits since/); + assert.ok(w.edits?.words.includes("a removed")); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("autoPickTake: a working take is picked; a pinned pick wins; a partial take never", async () => { + const dir = await project(); + try { + const group = ["draft-1", "draft-2", "prev"]; + const w1 = { id: "draft-1", window: "full", baseHash: "h1" }; + assert.deepEqual((await autoPickTake(dir, w1, group)).picked, true); + assert.equal((await readVerdicts(dir))["draft-1"]?.picked, true); + // A window preview: never picked. + const r = await autoPickTake(dir, { id: "prev", window: { at: 0, dur: 30 }, baseHash: "h2" }, group); + assert.equal(r.picked, false); + assert.equal((await readVerdicts(dir))["draft-1"]?.picked, true); + // The next working take moves the pick. + await autoPickTake(dir, { id: "draft-2", window: "full", baseHash: "h2" }, group); + let v = await readVerdicts(dir); + assert.equal(v["draft-2"]?.picked, true); + assert.equal(v["draft-1"], undefined, "a cleared row that says nothing is removed"); + // Pinned to draft-1: a newer working take does not move it. + await setTakePicked(dir, "draft-1", group, { pinned: true }); + const r3 = await autoPickTake(dir, { id: "draft-3", window: "full", baseHash: "h3" }, [...group, "draft-3"]); + assert.equal(r3.picked, false); + assert.match(r3.why, /pinned to draft-1/); + v = await readVerdicts(dir); + assert.equal(v["draft-1"]?.pinned, true); + assert.equal(v["draft-3"], undefined); + // Unpinned: the next one is picked again, and the pin is gone with the pick. + await setTakePicked(dir, "draft-1", group, { pinned: false }); + assert.equal((await autoPickTake(dir, { id: "draft-3", window: "full", baseHash: "h3" }, [...group, "draft-3"])).picked, true); + v = JSON.parse(await readFile(path.join(dir, "takes", "verdicts.json"), "utf8")); + assert.equal(v["draft-3"].picked, true); + assert.equal(v["draft-1"], undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +});