commit f2f42ef159cc313177229ed44c682147aa9cdf4d
parent 4f7c9c1ecad92d1a3d06f2cbf000817d066007b1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 14:16:50 -0500
Merge lane/take-writers: Play's Edit on a take with its own timeline edits that take, prep and fetch --take, umtool new <folder>/<slug>, the corpus path from any cwd -- the 2 Nov kr1 edit that reached in-her-words's cut cannot happen again (Edit opens the take's bench in place, take.json written, the manifest byte-identical); a take's clips prepared and fetched from its manifest as its walk reads it (a draft too, its own prep status/queue/lock); REPO_ROOT falls back to the module's own checkout, so a script run from a project dir finds the corpus
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
31 files changed, 1032 insertions(+), 201 deletions(-)
diff --git a/plans/spin-off-videos.md b/plans/spin-off-videos.md
@@ -59,7 +59,8 @@ Two umtool features landed on the way and stay: a receipt's `at`/`hold` (fly in
## Lanes
-1. **`lane/take-writers`** (M) — `timeline --take insert|split|window`; `fetch --take`; `prep --take` (status keyed
+1. **`lane/take-writers`** (M; built 2 Nov without the `timeline --take insert|split|window` writers: Play's Edit on an
+ own-timeline take, `prep --take`, `fetch --take`, the cwd fix, `new --folder`) — `timeline --take insert|split|window`; `fetch --take`; `prep --take` (status keyed
by take + id, so a take's widened clip never collides with the cut's); a draft's manifest materialized for
prep/trailer/walk. Fixes the prep cwd dependence. **Play's Edit on a take with its own timeline goes to that take's walk bench** (its patch), never the project's clip of the same id — the 2 Nov kr1 edit that reached `in-her-words`'s cut. Tests: a take with a take-only clip fetches, preps, walks and
renders with no hand JSON; the parent's prep status is untouched.
@@ -133,8 +134,11 @@ Order 1 → 2 → 3, 4 alongside. 1 and 2 alone remove most of the hand work abo
## Open
-- **The prep cwd dependence**: `prep-take.mjs` run with cwd = the project dir planned every clip `no-window`; the
- same run from `umtool/` found each window. Root-cause in `projectCache`/`windowsFor` before lane 1 builds on it.
+- ~~**The prep cwd dependence**~~ (fixed in `lane/take-writers`): not `projectCache`/`windowsFor` — `lib/paths.mjs`'s
+ `REPO_ROOT`. A process that is not a `umtool/bin` entry walked the cwd for `pnpm-workspace.yaml` and, finding none
+ above a project directory, fell back to the cwd's PARENT, so `CHANNELS_DIR` was `<folder>/transcripts/channels`
+ (nothing) and every corpus window vanished. It now falls back to the checkout the module itself is in
+ (`moduleRepoRoot`) before that; `paths.test.mjs` and `benchPrepTake.test.mjs` run it from other directories.
- **Speaker as data**: the Kirsche filter was the quote's `Kirsche:` prefix. A `speaker` field on entries (or the
speaker-check's result, `speaker-check.json`) would make "every clip of X" a real filter.
- **Callbacks in an update video**: the same id across the folder is the contract; is a folder-wide clip index
diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts
@@ -58,9 +58,9 @@ export async function POST(request: Request) {
if (running) return Response.json({ error: `a job is already running (${running.kind}) — export when it is done`, running: jobView(running) }, { status: 409, headers });
let manifestPath: string | null = null;
if (take && !need.held) {
- const { writePlayManifest } = await import("@/lib/report/takeManifest.mjs");
- const { readManifest } = await import("@/lib/projects/report.mjs");
- manifestPath = await writePlayManifest(project.dir, take, await readManifest(project.dir));
+ // The take's own manifest (a take-only clip, a take's bounds), never the project's under the take's name.
+ const { resolveTakeManifest, writePlayManifest } = await import("@/lib/report/takeManifest.mjs");
+ manifestPath = await writePlayManifest(project.dir, take, (await resolveTakeManifest(project.dir, take)).manifest);
}
const steps = await exportSteps(project, clip, {
take,
diff --git a/umtool/app/api/report/prep/route.ts b/umtool/app/api/report/prep/route.ts
@@ -1,5 +1,6 @@
import { projectRef } from "@/lib/projects";
import { benchPrepState, queueBenchPrep } from "@/lib/report/benchPrep.mjs";
+import { isTakeId } from "@/lib/report/takes.mjs";
export const dynamic = "force-dynamic";
@@ -8,16 +9,28 @@ export const dynamic = "force-dynamic";
// by a runner in the background (`umtool prep <project> --run`), one clip at a
// time in the machine's heavy slot. The Cut tab's "Prepare clips for the walk".
//
-// GET ?project=<id> ready / to prepare / failed / not fetched, and the runner when one is alive
-// POST { project, clips? } queue them (all when none are named); returns at once
+// GET ?project=<id>[&take=<id>] ready / to prepare / failed / not fetched, and the runner when one is alive
+// POST { project, take?, clips? } queue them (all when none are named); returns at once
+//
+// `take`: a take's clips (the take's walk), its manifest as the walk reads it
+// (a draft's too), its own status and runner (`umtool prep <p> --take <id>`).
const headers = { "cache-control": "no-store" };
+/** The take named, or null; an error string when it is not a take id. */
+function takeOf(v: unknown): string | null | { error: string } {
+ if (v === undefined || v === null || v === "") return null;
+ const t = String(v);
+ return isTakeId(t) ? t : { error: `"${t}" is not a take id` };
+}
+
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, headers });
+ const take = takeOf(url.searchParams.get("take"));
+ if (take && typeof take === "object") return Response.json(take, { status: 400, headers });
try {
- const s = await benchPrepState({ id: project.id, dir: project.dir });
+ const s = await benchPrepState({ id: project.id, dir: project.dir }, { take });
return Response.json({ ...s, items: undefined }, { headers });
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
@@ -25,15 +38,17 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- const b = (await request.json().catch(() => null)) as { project?: unknown; clips?: unknown } | null;
+ const b = (await request.json().catch(() => null)) as { project?: unknown; clips?: unknown; take?: unknown } | null;
if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
const project = await projectRef(String(b.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
const clips = Array.isArray(b.clips) ? b.clips.map(String).filter(Boolean) : null;
+ const take = takeOf(b.take);
+ if (take && typeof take === "object") return Response.json(take, { status: 400, headers });
const ref = { id: project.id, dir: project.dir };
try {
- const q = await queueBenchPrep(ref, clips, { retry: true });
- const s = await benchPrepState(ref);
+ const q = await queueBenchPrep(ref, clips, { retry: true, take });
+ const s = await benchPrepState(ref, { take });
// A runner just started may not hold its lock yet: it is running all the same.
return Response.json(
{ ...s, running: s.running || q.started, items: undefined, queued: q.queued.length, started: q.started, off: !!q.off },
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -46,7 +46,7 @@
// --draft-all is Draft everything: the drafts between manifest and the fast build;
// --deck adds the on-screen deck to a cut with none before the flips
// umtool index [--rebuild] [--prune] [--since MS] [--json]
-// umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
+// umtool new <slug> | <folder>/<slug> [--folder <folder>] [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>]
// [--site-origin URL] [--seed chapters|frames [--target S]] [--brand archilyzer-media]
// umtool doctor [--json] exit 1 if the report pipeline is missing a tool
// or the media root is set and not there
@@ -783,8 +783,10 @@ async function runFetchViaEditor(p, clipId, need, { take = null } = {}) {
const { editorFetchSteps } = await import("../lib/report/driver.mjs");
let manifestPath = null;
if (take) {
- const { writePlayManifest } = await import("../lib/report/takeManifest.mjs");
- manifestPath = await writePlayManifest(p.dir, take, await readManifest(p.dir));
+ // The TAKE's manifest (its walk's: the project's now with the take's patches), so a clip only
+ // the take has -- or the take's own bounds for a clip of the cut's id -- is what is asked for.
+ const { resolveTakeManifest, writePlayManifest } = await import("../lib/report/takeManifest.mjs");
+ manifestPath = await writePlayManifest(p.dir, take, (await resolveTakeManifest(p.dir, take)).manifest);
}
const [step] = editorFetchSteps(p, clipId, { padBefore: need.padBefore, padAfter: need.padAfter }, { manifestPath });
const { spawn } = await import("node:child_process");
@@ -900,6 +902,8 @@ function usage() {
" --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
" umtool index [--rebuild] [--prune] [--since MS] [--json]",
" umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters|frames]",
+ " <folder>/<slug>, or --folder <folder>: the project in a folder of the reports tree (its id",
+ " <folder>/<slug>, routed /projects/<folder>/<slug>) — a spin-off beside its parent",
" --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — the events",
" ranked (scoops, milestones, swings, pots, level-ups) into --target <seconds> (default 240), the",
" deck on with the stats region drawing frameScan.overlay over each clip",
@@ -1639,7 +1643,7 @@ async function cmdNew() {
const slug = positional[0];
if (!slug) {
die(
- "usage: umtool new <slug> [--kind report-video] [--title T]\n" +
+ "usage: umtool new <slug> | <folder>/<slug> [--folder <folder>] [--kind report-video] [--title T]\n" +
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
" [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" +
" [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]\n" +
@@ -1654,6 +1658,7 @@ async function cmdNew() {
r = await scaffoldReportVideo({
root: REPORTS_ROOT,
slug,
+ folder: val("--folder") ?? null,
title: val("--title"),
from: val("--from") ?? null,
siteOrigin: val("--site-origin") ?? null,
@@ -1683,8 +1688,8 @@ async function cmdNew() {
if (val("--seed") === "reactions" && !has("--no-analyze")) {
const { clipsCommand } = await import("../lib/report/reactions.mjs");
const log = json ? (s) => console.error(s) : (s) => console.log(s);
- if (!json) console.log(`${r.dir}\n running umtool clips analyze ${slug} …`);
- analyzed = await clipsCommand(["analyze", slug], { log, err: (s) => console.error(s) });
+ if (!json) console.log(`${r.dir}\n running umtool clips analyze ${r.id} …`);
+ analyzed = await clipsCommand(["analyze", r.id], { log, err: (s) => console.error(s) });
}
if (json) return out({ ok: true, ...r, ...(analyzed !== null ? { analyzed: analyzed === 0 } : {}) });
@@ -1709,6 +1714,6 @@ async function cmdNew() {
console.log(` Two finished videos shipped with QR codes that resolve to nothing.`);
}
console.log(` 2. write the timeline (umtool/docs/authoring.md)`);
- console.log(` 3. umtool check ${slug}`);
- console.log(` 4. umtool build ${slug} --preset fast`);
+ console.log(` 3. umtool check ${r.id}`);
+ console.log(` 4. umtool build ${r.id} --preset fast`);
}
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -321,7 +321,8 @@ export type ClipBenchData = {
* returns -- the project's cut at this clip -- and the take that was playing,
* if one was (its render does not change when this manifest does).
*/
- fromPlay?: { href: string; take: string | null } | null;
+ /** Opened from Play: where Back lands; the take that was playing; `editsTake`: this bench edits that take (its own timeline). */
+ fromPlay?: { href: string; take: string | null; editsTake?: boolean } | null;
/** Walk → Play: the cut from this clip (the bench opened on its own, not from Play, not a take's). */
playHere?: string | null;
/** The working cut's name (lib/report/workingCut.mjs): the latest whole-cut take and the edits since it. */
@@ -3028,12 +3029,19 @@ export default function ClipBench({
<p data-walk-quote="" className="m-0 font-serif text-[18px] leading-snug text-text">
{draft.quote.trim() ? `“${draft.quote.trim()}”` : <span className="text-muted">no quote on this entry</span>}
</p>
- {data.fromPlay?.take && (
- <p data-walk-take-note={data.fromPlay.take} className="m-0 text-[12.5px] leading-snug text-text-2">
- Opened from take <span className="font-mono">{data.fromPlay.take}</span>. Edits here go to the project’s cut, not
- to the take’s render, so Back plays the project’s cut.
- </p>
- )}
+ {data.fromPlay?.take &&
+ (data.fromPlay.editsTake ? (
+ <p data-walk-take-note={data.fromPlay.take} data-walk-take-edits="take" className="m-0 text-[12.5px] leading-snug text-text-2">
+ Opened from take <span className="font-mono">{data.fromPlay.take}</span>, which has its own timeline. Edits here go to the
+ take (<code className="font-mono">takes/{data.fromPlay.take}/take.json</code>), never the project’s cut; Back plays
+ the take.
+ </p>
+ ) : (
+ <p data-walk-take-note={data.fromPlay.take} className="m-0 text-[12.5px] leading-snug text-text-2">
+ Opened from take <span className="font-mono">{data.fromPlay.take}</span>. Edits here go to the project’s cut, not
+ to the take’s render, so Back plays the project’s cut.
+ </p>
+ ))}
</div>
{cached && (
<EdgeStrip
@@ -3290,8 +3298,10 @@ export default function ClipBench({
{unsaved ? "Save and back to the cut" : "‹ Back to the cut"}
</button>
{data.fromPlay.take && (
- <span data-back-take={data.fromPlay.take} className="ml-2 text-[11.5px] text-muted-2">
- edits go to the project’s cut, not take {data.fromPlay.take}
+ <span data-back-take={data.fromPlay.take} data-back-take-edits={data.fromPlay.editsTake ? "take" : "cut"} className="ml-2 text-[11.5px] text-muted-2">
+ {data.fromPlay.editsTake
+ ? `edits go to take ${data.fromPlay.take}, not the project’s cut`
+ : <>edits go to the project’s cut, not take {data.fromPlay.take}</>}
</span>
)}
</>,
diff --git a/umtool/components/projects/TakeWalkPage.tsx b/umtool/components/projects/TakeWalkPage.tsx
@@ -9,6 +9,7 @@ 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";
+import BenchPrepPanel from "./report/BenchPrepPanel";
// `/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
@@ -79,6 +80,8 @@ export default async function TakeWalkPage({
{all ? "walk only the clips needing a verdict" : "walk every clip (judged ones too)"}
</Link>
</div>
+ {/* The take's own prep: its clips' excerpts and waveforms made before the walk opens them. */}
+ <BenchPrepPanel project={project.id} take={take} />
{w.take?.editable && (
<TakeActions project={project.id} take={take} draft={!!w.take?.draft} walkHref={null} edited compact />
)}
diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx
@@ -27,6 +27,10 @@ import type { BenchTopSpec } from "@/lib/report/benchData";
// the CUT's order here (p / n are the reel strip's neighbours). Back on Play
// the view is read again (router.refresh: the bench may have saved), and
// Play recomposes only when the manifest's token moved.
+//
+// A TAKE WITH ITS OWN TIMELINE is edited on its own bench (PlayCut's Edit:
+// `/takes/<take>/clip/<id>?from=play`) -- in place too, the bench's data asked
+// with `walkTake`, so its saves go into the take's patch and Back plays it.
// ---------------------------------------------------------------------------
type View = { kind: "play" } | { kind: "clip"; id: string; href: string };
@@ -43,13 +47,21 @@ const Ctx = createContext<CutAppApi | null>(null);
/** Play's handle on the app: null when Play is drawn on its own (a test page, an old build). */
export const useCutApp = () => useContext(Ctx);
-/** The clip id in a bench address of this project, or null. */
-function clipOf(pathname: string, project: string): string | null {
- const base = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/clip/`;
- if (!pathname.startsWith(base)) return null;
- const rest = pathname.slice(base.length);
- return rest && !rest.includes("/") ? decodeURIComponent(rest) : null;
+/**
+ * The clip id in a bench address of this project, or null: the cut's
+ * (`/clip/<id>`) or a take's (`/takes/<take>/clip/<id>`, `take` set).
+ */
+function benchOf(pathname: string, project: string): { id: string; take: string | null } | null {
+ const root = `/projects/${project.split("/").map(encodeURIComponent).join("/")}/`;
+ if (!pathname.startsWith(root)) return null;
+ const rest = pathname.slice(root.length).split("/");
+ if (rest.length === 2 && rest[0] === "clip" && rest[1]) return { id: decodeURIComponent(rest[1]), take: null };
+ if (rest.length === 4 && rest[0] === "takes" && rest[1] && rest[2] === "clip" && rest[3]) {
+ return { id: decodeURIComponent(rest[3]), take: decodeURIComponent(rest[1]) };
+ }
+ return null;
}
+const clipOf = (pathname: string, project: string): string | null => benchOf(pathname, project)?.id ?? null;
const isPlay = (pathname: string, project: string) => pathname === `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`;
export default function CutApp({ project, playTop, children }: { project: string; playTop: React.ReactNode; children: React.ReactNode }) {
@@ -80,6 +92,9 @@ export default function CutApp({ project, playTop, children }: { project: string
q.set("project", project);
q.set("clip", id);
q.set("order", "cut");
+ // A take's bench (its own timeline): the take's clip, its saves into the take's patch.
+ const walkTake = benchOf(u.pathname, project)?.take;
+ if (walkTake) q.set("walkTake", walkTake);
return fetch(`/api/report/bench?${q.toString()}`, { cache: "no-store" }).then(async (r) => ({ ok: r.ok, status: r.status, body: (await r.json().catch(() => ({}))) as Bench & { error?: string } }));
},
[project],
@@ -149,7 +164,7 @@ export default function CutApp({ project, playTop, children }: { project: string
return;
}
const id = clipOf(u.pathname, project);
- if (id && !u.pathname.includes("/takes/")) {
+ if (id) {
openClip(id, `${u.pathname}${u.search}`);
return;
}
@@ -189,7 +204,7 @@ export default function CutApp({ project, playTop, children }: { project: string
if (!a || a.target === "_blank") return;
const u = new URL(a.href, window.location.origin);
if (u.origin !== window.location.origin) return;
- if (isPlay(u.pathname, project) || (clipOf(u.pathname, project) && !u.pathname.includes("/takes/"))) {
+ if (isPlay(u.pathname, project) || clipOf(u.pathname, project)) {
e.preventDefault();
e.stopPropagation();
navigate(`${u.pathname}${u.search}`);
diff --git a/umtool/components/projects/report/BenchPrepPanel.tsx b/umtool/components/projects/report/BenchPrepPanel.tsx
@@ -7,6 +7,7 @@ import { buttonVariants } from "@/components/ui/button";
// first-open work -- a long recording's excerpt, the waveform -- made by a
// runner in the background, one clip at a time in the heavy slot, so opening
// a clip on the walk does not wait on ffmpeg. A status line and one button.
+// With `take` (the take's walk): the take's clips, its own runner.
type PrepState = {
counts: { clips: number; ready: number; todo: number; failed: number; noWindow: number; excerpts: number };
@@ -19,20 +20,22 @@ type PrepState = {
const POLL_MS = 2500;
-export default function BenchPrepPanel({ project }: { project: string }) {
+export default function BenchPrepPanel({ project, take = null }: { project: string; take?: string | null }) {
const [s, setS] = useState<PrepState | null>(null);
const [asking, setAsking] = useState(false);
const [err, setErr] = useState<string | null>(null);
const load = useCallback(async () => {
- const r = await fetch(`/api/report/prep?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const q = new URLSearchParams({ project });
+ if (take) q.set("take", take);
+ const r = await fetch(`/api/report/prep?${q.toString()}`, { cache: "no-store" });
const j = (await r.json().catch(() => ({}))) as PrepState;
if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
else {
setErr(null);
setS(j);
}
- }, [project]);
+ }, [project, take]);
useEffect(() => {
void load();
@@ -56,7 +59,7 @@ export default function BenchPrepPanel({ project }: { project: string }) {
const r = await fetch("/api/report/prep", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project }),
+ body: JSON.stringify({ project, ...(take ? { take } : {}) }),
});
const j = (await r.json().catch(() => ({}))) as PrepState;
if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
@@ -69,7 +72,7 @@ export default function BenchPrepPanel({ project }: { project: string }) {
const run = s?.runner;
return (
- <div className="flex flex-wrap items-center gap-2" data-bench-prep="" data-bench-prep-state={s?.running ? "running" : left ? "todo" : "ready"}>
+ <div className="flex flex-wrap items-center gap-2" data-bench-prep={take ?? ""} data-bench-prep-state={s?.running ? "running" : left ? "todo" : "ready"}>
{left > 0 && !s?.running && (
<button
type="button"
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -6,7 +6,7 @@ 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 } from "@/lib/hrefs";
+import { clipBenchHref, takeClipHref } 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";
@@ -80,8 +80,13 @@ import AddPost from "./AddPost";
// and offset, never by raw cut seconds: the edit just changed this clip's
// length, which moves every cut second after it. The page is a fresh server
// render of the manifest (force-dynamic), so the new edges are what plays. A
-// take's Edit goes to the project's manifest too (a take's render does not
-// change), and its Back plays the project's cut; the bench says so.
+// take WITHOUT a timeline of its own plays the project's cut as it is now, so
+// its Edit goes to the project's manifest, and the bench says so. A take WITH
+// its own timeline (`ownTimeline`: its patch replaces the timeline) is a cut
+// of its own: its Edit opens the TAKE's bench on the clip (`…/takes/<take>/
+// clip/<id>?from=play`), whose saves go into takes/<take>/take.json, and
+// Back plays that take -- never the project's clip of the same id (2 Nov: an
+// edge fixed on `kirsche-7`'s kr1 landed in the project's cut).
//
// ON A PHONE (the phone design brief): one document, the player pinned at the
// top -- a strip once the transport has scrolled under it -- the strip, Now
@@ -575,8 +580,11 @@ 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: view.take?.defaulted ? null : take } });
- }, [project, take, now, view.take?.defaulted]);
+ const at = Math.round(Math.max(0, e.t - it.from) * 100) / 100;
+ // A take with its own timeline: ITS bench, its patch (never the project's clip of the same id).
+ if (take && view.take?.ownTimeline) return takeClipHref(project, take, it.id, { play: { at } });
+ return clipBenchHref(project, it.id, { play: { at, take: view.take?.defaulted ? null : take } });
+ }, [project, take, now, view.take?.defaulted, view.take?.ownTimeline]);
/** 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();
@@ -916,7 +924,7 @@ export default function PlayCut({
{view.take.defaulted ? "the latest take, " : ""}take “{view.take.label}”: the project’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)"
+ ? " — it has its own timeline: edits to the cut do not show in it; Edit this clip opens the take's own bench (its patch)"
: " · edits here go to the cut, and show at once"}
</p>
) : (
@@ -1020,15 +1028,17 @@ export default function PlayCut({
{/* The clip on the bench, and back here after (E). */}
<button
type="button"
- data-play-edit=""
+ data-play-edit={take && view.take?.ownTimeline ? "take" : ""}
disabled={!item?.clip}
onClick={editHere}
className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
title={
item?.clip
- ? take
- ? "edit this clip on the bench (E): the edit goes to the project's cut, not this take's render; Back plays the project's cut"
- : "edit this clip on the bench (E); Back to the cut returns here"
+ ? take && view.take?.ownTimeline
+ ? `edit this clip on take ${take}'s bench (E): the edit goes to the take's own timeline (takes/${take}/take.json), never the project's cut; Back plays this take`
+ : take
+ ? "edit this clip on the bench (E): the edit goes to the project's cut, not this take's render; Back plays the project's cut"
+ : "edit this clip on the bench (E); Back to the cut returns here"
: "a card is not edited on the clip bench"
}
>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -39,7 +39,7 @@ Inbox cannot disagree about what is wrong with one.
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
-| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold |
+| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
| `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch |
| `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building |
@@ -64,8 +64,8 @@ Inbox cannot disagree about what is wrong with one.
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--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, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), 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)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off` · `candidates [--add]` | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips ([knobs.md](knobs.md#the-trailers-beats)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
-| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
-| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). **Exit 1** when a clip failed (`--wait`) |
+| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) |
+| `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`) |
| `prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]` · `prune --all [--keep N] [--older-than 3d] [--yes] [--json]` | **the takes' work files** (the Takes page's **Free work files**): per take its work — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — counted by inode (a file hard-linked into two takes is counted once and freed only when both let it go), what freeing it gives back, or why it is kept: a running build or the take one builds from (never freed), the picked or current take, a pin in `takes/prune.json`, the newest `--keep` (2) of its group, anything modified within `--older-than` (3d), the `--from` bases of those. A dry run unless `--yes`; `--take X --anyway` frees a take the policy keeps. Renders, previews, take.json and manifests are never touched. **Exit 1** when a path could not be removed ([report-video.md](report-video.md#a-takes-work-files-and-pruning-them)) |
| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
| `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -278,6 +278,12 @@ and **‹ Back to the cut** returns to the same clip, second and take without Pl
header's links walk the CUT's order — the reel strip's neighbours, judged or not ("40 of 127") — not the
walk's. Opened on its own, the bench's head has **▶ Play the cut from here**.
+Play on a take WITH ITS OWN TIMELINE (its patch replaces the timeline — a tight version, a spin-off) opens
+the take's bench instead ([Walking a take](#walking-a-take), `…/takes/<take>/clip/<id>?from=play`): the
+save goes into the take's patch, never the project's clip of the same id, the head says **edits go to take
+`<take>`, not the project's cut**, and **‹ Back to the cut** plays the take. A take without a timeline of its
+own plays the project's cut as it is now, so its Edit stays the project's bench, as it says.
+
### What the walk skips
The walk visits the clips that still **need judgement** and are **fetched**, in
@@ -429,6 +435,14 @@ take** and **Undo take edit** (the take's newest edit taken back, whichever it w
re-render is not offered: a take is rendered whole (**Render full** on the Takes page, or `umtool
take <p> --id <take> --full`).
+**Prepared before you open it, per take.** The take's walk page carries **Prepare clips for the walk**,
+and `umtool prep <project> --take <take>` makes the same excerpts and waveforms the take's bench would make
+on first open — from the take's manifest as the walk reads it (a draft's too, nothing rendered), with the
+take's own status, queue and runner (`out/bench-excerpts/takes/<take>/`), so a take's clip that carries the
+cut's id with other bounds never shares the cut's prep state. A save on the take's walk that moves an edge
+queues it as the cut's writes do. `umtool fetch <project> --take <take>` asks the editor for the take's
+windows (a clip only the take has included) as the Cut tab's **Fetch windows** asks for the cut's.
+
**`?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.
@@ -437,6 +451,8 @@ The terminal reads the same walk (`lib/report/walkData.mjs`, also `GET /api/repo
```
umtool walk <project> --take <take> [--all] [--json]
+umtool prep <project> --take <take> [--status | --wait] [--json] # its excerpts and waveforms, ahead
+umtool fetch <project> --take <take> [--dry-run | --wait] [--json] # its windows, from the editor
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]
```
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -494,7 +494,9 @@ that take rendered (`0` when the manifest's hash is the take's `baseHash`; `lib/
takes are a switch beside it (pills, the rest behind **N more**), **manifest only** the bare manifest; the pick (Use
this take, below) is named small only when it is not the latest. Every edit made in Play — a reorder, Reject, the
bench — writes the PROJECT's manifest, which a working take plays as it is now, so the latest take shows it at once;
-a take with its own timeline says so and offers no structural edit (its walk edits it). `umtool takes ls <p>` prints
+a take with its own timeline says so and offers no structural edit (its walk edits it), and its **Edit this clip**
+opens the TAKE's bench on the clip (`/projects/<p>/takes/<take>/clip/<id>?from=play`): the save goes into
+`takes/<take>/take.json`, never the project's clip of the same id, and **‹ Back to the cut** plays that take. `umtool takes ls <p>` prints
the same line first and marks `latest`; the Takes page shows it and a **latest** badge. **Re-render the take** (the
clip editor and the clip deck) remakes the latest take — it used to need a pick when there were two whole-cut takes.
@@ -518,7 +520,8 @@ take.
but never unmounted, so its composed deck, decoded sound, measured edges, the strip's zoom and the take stay as they
were (`components/projects/cutApp/CutApp.tsx`; the bench's data is `GET /api/report/bench`, the same function its own
page renders from, `lib/report/benchData.ts`). The address moves by `history.pushState` to the bench's
-(`/clip/<id>?from=play&at&take&order=cut`): the browser's Back and Forward step between the two, a reload or a link is
+(`/clip/<id>?from=play&at&take&order=cut`; on a take with its own timeline, the take's bench,
+`/takes/<take>/clip/<id>?from=play&at&order=cut`): the browser's Back and Forward step between the two, a reload or a link is
the bench's own page, and **‹ Back to the cut** goes back the entries it pushed (no second Play in the history). Inside
Play the bench walks the CUT's order (`order=cut`: p / n are the reel strip's neighbours, judged or not, `40 of 127`;
the neighbours are read ahead). Back on Play the view is read again in place (`GET /api/report/play-view`), the deck
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -1876,6 +1876,8 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
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") });
+// play-take-edit.spec.ts: the same draft take with its own timeline, played and edited from Play (its own copy).
+makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-take-edit-fixture", title: "The Play Take Edit Fixture" });
// Cut integrity (UI notes 2026-10-30): the cite following the edge, repeatOf, ★ and walk notes, take patch markers, the QR link check (cut-integrity.spec.ts).
makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// ui-ops.spec's own project and channels (UI notes #9 #10 #15 #18).
diff --git a/umtool/e2e/fixtures/take-walk-fixture.mjs b/umtool/e2e/fixtures/take-walk-fixture.mjs
@@ -13,6 +13,10 @@
// t01c 6.20-8.50 no verdict
//
// Synthetic, like every fixture.
+//
+// `name`/`title`: the same project under another name, for a spec that must
+// not share it -- play-take-edit-fixture (play-take-edit.spec.ts: Play on the
+// take, Edit, an edge saved into the take and never the manifest).
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import path from "node:path";
@@ -24,17 +28,17 @@ const write = (dir, name, text) => {
const json = (doc) => JSON.stringify(doc, null, 2) + "\n";
/**
- * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ * @param {{ reports: string, manifest: Function, cachedWindow: string, name?: string, title?: 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");
+export function makeTakeWalkFixture({ reports, manifest, cachedWindow, name = "take-walk-fixture", title = "The Take Walk Fixture" }) {
+ const dir = path.join(reports, name);
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" }, [
+ json(manifest(name, title, { siteOrigin: "https://archive.example" }, [
clip("w01", 1.0, 8.0, { verdict: "confirmed", quote: "the whole of it" }),
])),
);
diff --git a/umtool/e2e/phone-walk.spec.ts b/umtool/e2e/phone-walk.spec.ts
@@ -294,17 +294,18 @@ test("Play → Edit this clip → move an edge → Back: the new bounds are what
await expect(root).toHaveAttribute("data-play-item", "c02");
await page.keyboard.press("k");
- // A take: the edit goes to the project's cut, and the bench says so; Back
- // returns to Play as it was -- the take still playing (Play and the bench
- // are one app: Play was never unmounted).
+ // A take with its own timeline (`short`: c04 then c01): the edit goes to
+ // THE TAKE, on its own bench, and the bench says so; Back returns to Play
+ // as it was -- the take still playing (Play and the bench are one app: Play
+ // was never unmounted). play-take-edit.spec.ts proves the save lands there.
await page.goto(urls.playHref(PLAY, { take: "short" }));
await expect(root).toHaveAttribute("data-play-item", "c04");
// E (the key is live once hydrated, which the first render cannot show).
await expect(async () => {
await page.keyboard.press("e");
- await expect(page).toHaveURL(/\/clip\/c04\?from=play.*take=short/, { timeout: 1500 });
+ await expect(page).toHaveURL(/\/takes\/short\/clip\/c04\?from=play/, { timeout: 1500 });
}).toPass({ timeout: 15_000 });
- await expect(page.locator('[data-back-take="short"]')).toContainText("not take short");
+ await expect(page.locator('[data-back-take="short"]')).toContainText("edits go to take short, not the project");
await page.locator("[data-back-to-play]").click();
await expect(page).toHaveURL(/\/play\?take=short&clip=c04/, { timeout: 20_000 });
await expect(root).toHaveAttribute("data-play-cut", "short");
diff --git a/umtool/e2e/play-take-edit.spec.ts b/umtool/e2e/play-take-edit.spec.ts
@@ -0,0 +1,99 @@
+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";
+
+// ---------------------------------------------------------------------------
+// PLAY'S EDIT ON A TAKE WITH ITS OWN TIMELINE edits THAT TAKE (2 Nov: an edge
+// fixed from Play on `kirsche-7`'s kr1 landed in the project's
+// video.manifest.json, the cut's clip of the same id, not in the take).
+//
+// play-take-edit-fixture (fixtures/take-walk-fixture.mjs, written for this
+// file alone): the master is one clip, w01 1.00-8.00; the DRAFT take `tight`
+// replaces the timeline (its own timeline) with t01a, t01b 3.50-6.00 and
+// t01c, all inside the cached vid1 0-9 s window. Edit from Play on the take
+// opens the TAKE's bench in place; an edge saved there lands in
+// takes/tight/take.json and the project's manifest stays byte for byte.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const P = "reports/play-take-edit-fixture";
+const TAKE = "tight";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "play-take-edit-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const takeClip = (id: string) =>
+ (JSON.parse(readFileSync(path.join(DIR, "takes", TAKE, "take.json"), "utf8")).patch.timeline as { id: string; start: number; end: number }[]).find(
+ (e) => e.id === id,
+ )!;
+
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+});
+
+test("Play on a take with its own timeline → Edit opens the TAKE's bench; an edge saved there is the take's, the manifest untouched; Back plays the take", async ({ page }) => {
+ const before = manifestText();
+ expect(takeClip("t01b").end).toBe(6);
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(P, { take: TAKE }));
+ const root = page.locator("[data-play-cut]");
+ await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 });
+ await expect(page.locator(`[data-play-take="${TAKE}"]`)).toContainText("Edit this clip opens the take's own bench");
+ await page.locator('[data-play-row="t01b"]').press("Enter");
+ await expect(root).toHaveAttribute("data-play-item", "t01b");
+ const edit = page.locator("[data-play-edit]");
+ await expect(edit).toHaveAttribute("data-play-edit", "take");
+ await expect(edit).toHaveAttribute("title", /takes\/tight\/take\.json/);
+ await edit.click();
+
+ // In place, on the take's bench: its address, its note, its edits.
+ const bench = page.locator('[data-cut-app-bench="t01b"]');
+ await expect(bench.locator('[data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page).toHaveURL(new RegExp(`/takes/${TAKE}/clip/t01b\\?from=play.*order=cut`));
+ await expect(bench.locator("[data-bench-kind]")).toHaveText("Take walk");
+ await expect(bench.locator(`[data-back-take="${TAKE}"]`)).toHaveAttribute("data-back-take-edits", "take");
+ await expect(bench.locator(`[data-back-take="${TAKE}"]`)).toContainText(`edits go to take ${TAKE}, not the project`);
+ await page.screenshot({ path: test.info().outputPath("play-take-edit-bench.png") });
+
+ // An edge: the end +0.05 s (`.`), saved.
+ const save = bench.locator("[data-save-window]");
+ await expect(async () => {
+ await page.locator("body").press(".");
+ await expect(save).toBeEnabled({ timeout: 500 });
+ }).toPass({ timeout: 10_000 });
+ await save.click();
+ await expect.poll(() => takeClip("t01b").end).toBeGreaterThan(6);
+ expect(takeClip("t01b").start).toBe(3.5);
+ expect(manifestText(), "the project's manifest is byte-identical").toBe(before);
+
+ // Back to the cut: Play on the same take, the same clip.
+ await bench.locator("[data-back-to-play]").click();
+ await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown");
+ await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}`));
+ await expect(root).toHaveAttribute("data-play-item", "t01b");
+ await expect(page.locator(`[data-play-take="${TAKE}"]`)).toBeVisible();
+ expect(manifestText()).toBe(before);
+});
+
+test("a reload of the take's bench from Play is the take's bench page: Back to the cut plays the take", async ({ page }) => {
+ await page.goto(urls.takeClipHref(P, TAKE, "t01c", { play: { at: 0.5 } }));
+ await expect(page.locator('[data-walk-take-edits="take"]')).toContainText("never the project’s cut");
+ const back = page.locator("[data-back-to-play]");
+ await expect(back).toBeVisible();
+ await back.click();
+ await expect(page).toHaveURL(new RegExp(`/play\\?take=${TAKE}&clip=t01c&at=0\\.50`));
+});
+
+test("a take WITHOUT its own timeline keeps today's Edit: the project's bench", async ({ page }) => {
+ // play-walk-fixture's draft-1 is a whole-cut take (no timeline in its patch).
+ await page.goto(urls.playHref("reports/play-walk-fixture", { take: "draft-1" }));
+ const root = page.locator("[data-play-cut]");
+ await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 });
+ await page.locator('[data-play-row="c02"]').press("Enter");
+ const edit = page.locator("[data-play-edit]");
+ await expect(edit).toHaveAttribute("data-play-edit", "");
+ await edit.click();
+ await expect(page.locator('[data-cut-app-bench="c02"] [data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page).toHaveURL(/\/projects\/reports\/play-walk-fixture\/clip\/c02\?from=play/);
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -315,11 +315,21 @@ export function takeWalkHref(project: string, take: string, q: NoteOpt & { all?:
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 {
+/**
+ * The clip bench on one of a take's clips: its saves go into the take's patch, never the project's manifest.
+ * `play`: opened from Play on this take (Edit this clip, on a take with its own timeline) -- the bench offers
+ * "Back to the cut", landing on Play of THIS take `at` seconds into the clip.
+ */
+export function takeClipHref(
+ project: string,
+ take: string,
+ clip: string,
+ q: NoteOpt & { all?: boolean; play?: { at?: number | null } | null } = {},
+): string {
+ const play = q.play;
return withQuery(
`/projects/${encodePath(project)}/takes/${encodeURIComponent(take)}/clip/${encodeURIComponent(clip)}`,
- { all: q.all },
+ { all: q.all, ...(play ? { from: "play", at: play.at != null && play.at > 0 ? play.at.toFixed(2) : null } : {}) },
q.note,
);
}
diff --git a/umtool/lib/paths.mjs b/umtool/lib/paths.mjs
@@ -8,6 +8,7 @@ import { existsSync, realpathSync } from "node:fs";
import { lstat, realpath } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
+import { fileURLToPath } from "node:url";
import { SONG_DATA, SONG_REPORTS } from "../song/paths.mjs";
import { ARTICLES_KEY } from "./articles/key.mjs";
@@ -173,12 +174,14 @@ export function mediaMirror(abs, { reportsRoot = REPORTS_ROOT, mediaRoot = MEDIA
* The checkout this runs in: the nearest directory at or above `start` holding
* pnpm-workspace.yaml, or `start`'s parent when there is none.
*
- * Walked from the CWD, not from import.meta.url: the Next app imports this
+ * Walked from the CWD first, not from import.meta.url: the Next app imports this
* module (eleven API routes), and Turbopack rewrites module URLs into
* .next/server/chunks, so a path derived from one points at the build output
* -- the SONG_CODE rule in lib/paths.ts. `next dev`, `next start` and the CLI
* all run with cwd inside the checkout (the app at umtool/, which is what the
- * fallback assumes). report-to-video/cues.mjs keeps its import.meta.url walk:
+ * fallback assumes). A process standing in NO checkout -- a script run from a
+ * project directory -- gets the checkout this module is in (moduleRepoRoot),
+ * never the cwd's parent. report-to-video/cues.mjs keeps its import.meta.url walk:
* only its CLI entry points (build-video, resolve-windows) read that default.
*
* EVERY PATH OP ON A cwd-DERIVED VALUE CARRIES `turbopackIgnore`. Turbopack
@@ -193,16 +196,50 @@ export function mediaMirror(abs, { reportsRoot = REPORTS_ROOT, mediaRoot = MEDIA
* at run time are unchanged. scripts/next-build-trace.test.mjs holds the line.
*/
export function findRepoRoot(start) {
+ return findCheckout(start) ?? path.resolve(/* turbopackIgnore: true */ start, "..");
+}
+
+/** The nearest directory at or above `start` holding pnpm-workspace.yaml, or null. */
+export function findCheckout(start) {
let dir = path.resolve(/* turbopackIgnore: true */ start);
for (;;) {
if (existsSync(path.join(/* turbopackIgnore: true */ dir, "pnpm-workspace.yaml"))) return dir;
const up = path.dirname(/* turbopackIgnore: true */ dir);
- if (up === dir) return path.resolve(/* turbopackIgnore: true */ start, "..");
+ if (up === dir) return null;
dir = up;
}
}
/**
+ * The checkout THIS MODULE is in -- `<repo>/umtool/lib/paths.mjs` -- or null
+ * (a bundle, where import.meta.url is not the file on disk: the Next server's
+ * cwd walk answers there).
+ *
+ * The last word before the cwd's parent, for a process that is neither a
+ * umtool/bin entry nor standing in a checkout: a script that imports
+ * lib/report/benchPrep.mjs and runs from a project directory under
+ * REPORTS_DIR. Before this, the cwd walk found no pnpm-workspace.yaml there
+ * and fell back to the cwd's PARENT, so CHANNELS_DIR was
+ * `<folder>/transcripts/channels` -- nothing -- and every clip planned
+ * `no-window`; the same script run from umtool/ found each window (2 Nov,
+ * emberparadox/in-her-words). The answer must not depend on where the caller
+ * stands.
+ *
+ * @param {string} [url] the module URL (a test passes its own)
+ * @returns {string | null}
+ */
+export function moduleRepoRoot(url = import.meta.url) {
+ try {
+ if (!String(url).startsWith("file:")) return null;
+ const real = realpathSync(/* turbopackIgnore: true */ fileURLToPath(url));
+ const repo = path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ real), "..", "..");
+ return existsSync(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ repo, "pnpm-workspace.yaml")) ? repo : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
* The checkout a umtool CLI belongs to -- `<repo>/umtool/bin/<cli>.mjs` as the
* entry script (`process.argv[1]`) -- or null for anything else (the Next
* server, a test runner, report-to-video's own CLIs).
@@ -230,7 +267,11 @@ export function cliRepoRoot(entry) {
return existsSync(path.join(/* turbopackIgnore: true */ repo, "pnpm-workspace.yaml")) ? repo : null;
}
-export const REPO_ROOT = cliRepoRoot(process.argv[1]) ?? findRepoRoot(process.cwd());
+// The entry script's checkout (a umtool CLI), else the one the cwd is in (the
+// Next server, a test runner), else this module's own (a script run from
+// anywhere -- a project directory), else the cwd's parent.
+export const REPO_ROOT =
+ cliRepoRoot(process.argv[1]) ?? findCheckout(process.cwd()) ?? moduleRepoRoot() ?? findRepoRoot(process.cwd());
export const CHANNELS_DIR = path.resolve(
/* turbopackIgnore: true */
diff --git a/umtool/lib/paths.test.mjs b/umtool/lib/paths.test.mjs
@@ -8,7 +8,8 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
-import { cliRepoRoot } from "./paths.mjs";
+import { fileURLToPath } from "node:url";
+import { cliRepoRoot, findCheckout, moduleRepoRoot } from "./paths.mjs";
const PATHS = new URL("./paths.mjs", import.meta.url);
@@ -67,3 +68,30 @@ test("a CLI run from outside its checkout reads that checkout's sites and channe
);
assert.equal(set.sites, away);
});
+
+test("a script run from outside every checkout reads the corpus of the checkout its modules are in, not the cwd's parent", (t) => {
+ // Not a umtool/bin entry, so cliRepoRoot is null; the cwd has no
+ // pnpm-workspace.yaml above it (a project directory under REPORTS_DIR).
+ // Before moduleRepoRoot the cwd's PARENT was the "checkout", and every clip
+ // planned no-window (2 Nov, emberparadox/in-her-words).
+ const away = mkdtempSync(path.join(tmpdir(), "umtool-away-"));
+ t.after(() => rmSync(away, { recursive: true, force: true }));
+ const project = path.join(away, "folder", "project");
+ mkdirSync(project, { recursive: true });
+ const probe = path.join(away, "probe.mjs");
+ writeFileSync(
+ probe,
+ `const p = await import(${JSON.stringify(PATHS.href)});\n` +
+ "console.log(JSON.stringify({ repo: p.REPO_ROOT, channels: p.CHANNELS_DIR }));\n",
+ );
+ const env = { ...process.env };
+ for (const k of ["SITES_DIR", "CHANNELS_DIR", "TRANSCRIPTS_DIR"]) delete env[k];
+ const repo = path.resolve(path.dirname(fileURLToPath(PATHS)), "..", "..");
+ for (const cwd of [project, away, path.join(repo, "umtool")]) {
+ const got = JSON.parse(execFileSync(process.execPath, [probe], { cwd, env, encoding: "utf8" }));
+ assert.deepEqual(got, { repo, channels: path.join(repo, "transcripts", "channels") }, `from ${cwd}`);
+ }
+ assert.equal(moduleRepoRoot(PATHS.href), repo);
+ assert.equal(moduleRepoRoot("https://example.invalid/paths.mjs"), null);
+ assert.equal(findCheckout(project), null);
+});
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -3,7 +3,7 @@
// different skeletons.
//
// Plain ESM: `umtool new` runs from a terminal with no server.
-import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
+import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { BRAND_IDS } from "umtool-report-to-video/brand-ids";
import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut";
@@ -11,6 +11,8 @@ import { capInstances, instancesAsClips, phraseScan } from "yt-dlp-transcript-co
import { PARAM_BOUNDS, normalizeScope } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
import { writeReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
+import { RESERVED_BROWSE, detectKind, skipsDir } from "./kinds.mjs";
+import { MAX_DEPTH, isSegment } from "./walk.mjs";
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
// A channel's directory name: mixed case is a channel too (HasanAbiVODs3); no separators, no dot first.
@@ -237,6 +239,60 @@ const capNote = (max, kept, found) =>
: `Capped at ${max} (--max): all ${found} instance(s) kept`;
/**
+ * Where a new project goes: `slug` alone (REPORTS_ROOT's top level), `folder`
+ * + `slug`, or `slug` given as `folder/slug` (2 Nov: `umtool new
+ * emberparadox/kirsche` refused, and the only way into a folder was
+ * `REPORTS_DIR=~/reports/emberparadox umtool new kirsche`). The id is the path
+ * under the root, as walkProjects names it, so the project routes as
+ * `/projects/<folder>/<slug>`.
+ *
+ * Refused: a slug that will not route; a folder segment that will not
+ * (walk.mjs isSegment), is a dot-directory, a directory the walk skips, or the
+ * reserved first segment; deeper than the walk looks (MAX_DEPTH); a folder
+ * that IS a project, or sits inside one -- a project is a leaf, so one made
+ * under it would never be listed.
+ *
+ * @param {string} root
+ * @param {string} slugArg
+ * @param {string | null} folderArg
+ * @returns {Promise<{ id: string, slug: string, folder: string | null }>}
+ */
+export async function projectPlace(root, slugArg, folderArg = null) {
+ const raw = String(slugArg ?? "").replace(/^\/+|\/+$/g, "");
+ const parts = raw.split("/");
+ const slug = parts.pop() ?? "";
+ const folderParts = [
+ ...String(folderArg ?? "").replace(/^\/+|\/+$/g, "").split("/").filter(Boolean),
+ ...parts,
+ ];
+ if (!SLUG_RE.test(slug)) {
+ throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
+ }
+ for (const seg of folderParts) {
+ if (!isSegment(seg) || seg.startsWith(".") || skipsDir(seg)) throw new Error(`folder "${folderParts.join("/")}": "${seg}" will not route`);
+ }
+ if (folderParts.length && RESERVED_BROWSE.includes(folderParts[0])) {
+ throw new Error(`folder "${folderParts[0]}" is a reserved address (/projects/${folderParts[0]}/…) — the project would never be reached`);
+ }
+ if (folderParts.length + 1 > MAX_DEPTH) {
+ throw new Error(`${[...folderParts, slug].join("/")} is ${folderParts.length + 1} levels deep; the project list looks ${MAX_DEPTH} down`);
+ }
+ // A folder that is a project (or is inside one): the new project would be a leaf's child.
+ for (let i = 1; i <= folderParts.length; i += 1) {
+ const at = path.join(root, ...folderParts.slice(0, i));
+ const names = await readdir(at).then((n) => new Set(n), () => null);
+ if (!names) break;
+ let declared = null;
+ if (names.has("project.json")) declared = await readFile(path.join(at, "project.json"), "utf8").then((t) => JSON.parse(t), () => null);
+ if (detectKind(names, declared)) {
+ throw new Error(`${folderParts.slice(0, i).join("/")} is a project, not a folder — a project inside it would never be listed`);
+ }
+ }
+ const folder = folderParts.length ? folderParts.join("/") : null;
+ return { id: folder ? `${folder}/${slug}` : slug, slug, folder };
+}
+
+/**
* Write the project. Refuses an existing directory and a slug that will not
* route; everything else it cannot know is written EMPTY so `check` blocks.
*
@@ -259,12 +315,10 @@ const capNote = (max, kept, found) =>
*
* @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | "auto" | null, segment?: string | null, sitesDir?: string }} args
*/
-export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null, sitesDir = undefined }) {
- if (!SLUG_RE.test(String(slug ?? ""))) {
- throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
- }
- const dir = path.join(root, slug);
- if (dir !== path.resolve(root, slug) || path.dirname(dir) !== path.resolve(root)) {
+export async function scaffoldReportVideo({ root, slug: slugArg, folder: folderArg = null, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null, sitesDir = undefined }) {
+ const { id, slug, folder } = await projectPlace(root, slugArg, folderArg);
+ const dir = path.join(root, ...id.split("/"));
+ if (dir !== path.resolve(root, id) || path.dirname(dir) !== path.resolve(root, folder ?? ".")) {
throw new Error("refusing to create outside the tree");
}
if (await stat(dir).then(() => true, () => false)) throw new Error(`${dir} already exists`);
@@ -426,11 +480,11 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
const used = pass.doc.proposals.filter((p) => p.used);
const host = pass.doc.speakers.find((s) => s.role === "host");
notes.push(`${pass.doc.proposals.length} proposal(s), ${used.length} in the cut: ${Math.round(used.reduce((n, p) => n + p.end - p.start, 0))} s of a ${pass.doc.params.target} s target (--target)`);
- notes.push(`the host: speaker ${host ? host.index : "?"} of ${pass.doc.speakers.length} (by turn statistics — flip it in the clip editor or with umtool clips propose ${slug} --host N)`);
+ notes.push(`the host: speaker ${host ? host.index : "?"} of ${pass.doc.speakers.length} (by turn statistics — flip it in the clip editor or with umtool clips propose ${id} --host N)`);
notes.push(...(pass.notes ?? []));
const read = pass.doc.params.scope;
- if (read) notes.push(`only ${read[0]}–${read[1] ?? "the end"} s of the recording is read (--scope${reactionsScope === "auto" ? ` auto${pass.doc.segment ? `: ${pass.doc.segment}` : ""}` : ""}; umtool clips segments ${slug} lists the narrated videos)`);
- notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${slug} runs the laugh scan and the voices on the sound, then proposes again`);
+ if (read) notes.push(`only ${read[0]}–${read[1] ?? "the end"} s of the recording is read (--scope${reactionsScope === "auto" ? ` auto${pass.doc.segment ? `: ${pass.doc.segment}` : ""}` : ""}; umtool clips segments ${id} lists the narrated videos)`);
+ notes.push(`laughs from the transcript only (${pass.doc.laughs.length}); umtool clips analyze ${id} runs the laugh scan and the voices on the sound, then proposes again`);
if (pass.rec.wordsFrom === "cues") notes.push("no word timings: edges sit on the cues; pnpm ops transcribe {path, words:true, out: <project>/words.json} gives words, then umtool clips propose");
if (!pass.doc.proposals.length) notes.push("nothing to propose: no host comments or laughs were found");
}
@@ -541,7 +595,8 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
return {
dir,
kind: "report-video",
- id: slug,
+ id,
+ ...(folder ? { folder } : {}),
title: finalTitle,
from: src,
citations: citations.length,
diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts
@@ -228,16 +228,20 @@ export async function clipBenchData(
// so "Back to the cut" survives walking on; `at` is only ever the clip Play
// was on. Back lands on the PROJECT's cut, positioned by clip id plus the
// offset into it -- never by raw cut seconds, which the edit just moved for
- // 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 = !take && search.from === "play";
+ // everything after this clip. A take without a timeline of its own plays
+ // the project's cut, so its Edit lands here and its Back is the project's
+ // cut too, and the bench says so (`take`). A take WITH its own timeline is
+ // walked on its own bench (`take`: `…/takes/<take>/clip/<id>?from=play`):
+ // its saves go into the take's patch, and Back plays that take.
+ const fromPlay = search.from === "play";
const withOrder = (h: string) => (order === "cut" ? `${h}${h.includes("?") ? "&" : "?"}order=cut` : h);
- const playTake = fromPlay && search.take ? search.take : null;
+ const playTake = take && fromPlay ? take : 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) =>
- take ? takeClipHref(project.id, take, id, { all }) : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {}));
+ take
+ ? withOrder(takeClipHref(project.id, take, id, { all, play: fromPlay ? {} : null }))
+ : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {}));
data.walkHrefs = {
prev: prev ? href(prev) : null,
next: next ? href(next) : null,
@@ -255,12 +259,13 @@ export async function clipBenchData(
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 })])),
+ clipHref: Object.fromEntries(data.siblings.map((sb: { id: string }) => [sb.id, takeClipHref(project.id, take, sb.id, { all, play: fromPlay ? {} : null })])),
at: timeline.findIndex((e) => e.id === clipId),
entries: timeline.length,
};
}
- data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake } : null;
+ // `editsTake`: this bench writes the take Play was playing (its own timeline), not the project's cut.
+ data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake, editsTake: !!take } : null;
// Walk → Play (the audit's "no way back"): the cut, from this clip.
data.playHere = take || fromPlay ? null : playHref(project.id, { clip: clipId });
// The working cut's name: the bench edits the project's manifest, the latest take is what it was made into.
diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs
@@ -54,6 +54,7 @@ import { MIX_CACHE, REPORTS_ROOT, inside } from "../paths.mjs";
import { analysisCacheFile } from "../analyse.mjs";
import { clipsOf, readManifest } from "../projects/report.mjs";
import { UMTOOL_DIR } from "./driver.mjs";
+import { isTakeId } from "./takes.mjs";
import { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.mjs";
/** An excerpt cut's resident set (234 MB, measured: a 2-minute 720p excerpt of a 1080p stream) plus the runner. */
@@ -61,11 +62,44 @@ export const PREP_ESTIMATE_MB = 400;
/** Where the prep keeps its state: beside the excerpts it makes. */
export const prepDirOf = (projectDir) => path.join(/* turbopackIgnore: true */ projectDir, "out", "bench-excerpts");
-const statusFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep-status.json");
-const pendingFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-pending");
-const lockFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-run.lock");
+
+// A TAKE'S PREP (`umtool prep <p> --take <id>`, the take's walk) keeps its own
+// status, queue, lock and log, under out/bench-excerpts/takes/<id>/: a take's
+// clip may carry the cut's id with other bounds (a widened kf3), and a
+// failure, a queued request or a runner of one must never read as the
+// other's. The excerpts themselves are shared -- named by their seconds of the
+// source, so one cut serves every clip that opens the same seconds.
+/**
+ * The directory a prep's state lives in: the project's, or a take's.
+ * @param {string} projectDir
+ * @param {string | null} [take]
+ */
+export function prepStateDirOf(projectDir, take = null) {
+ if (!take) return prepDirOf(projectDir);
+ if (!isTakeId(take)) throw new Error(`"${take}" is not a take id`);
+ return path.join(/* turbopackIgnore: true */ prepDirOf(projectDir), "takes", take);
+}
+const statusFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep-status.json");
+const pendingFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-pending");
+const lockFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-run.lock");
/** The runner's stdout and stderr (the heavy slot's waiting lines land here). */
-export const prepLogOf = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep.log");
+export const prepLogOf = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep.log");
+
+/**
+ * The manifest a prep reads: the project's, or -- with `take` -- the take's as
+ * its walk reads it (takeManifest.mjs resolveTakeManifest: the project's
+ * manifest now, the style's patch, then the take's, merged). A DRAFT take
+ * (recorded, nothing rendered) has one too: nothing here waits for a render,
+ * and the windows prepared are the ones the take's bench will open.
+ *
+ * @param {{ dir: string }} project
+ * @param {string | null} [take]
+ */
+export async function prepManifestOf(project, take = null) {
+ if (!take) return readManifest(project.dir);
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ return (await resolveTakeManifest(project.dir, take)).manifest;
+}
const alive = (pid) => {
if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -104,17 +138,19 @@ const alive = (pid) => {
* of THIS window failed reads `failed` until the window changes (an explicit
* prep tries it again; a trigger does not).
*
+ * `take`: the take's clips (prepManifestOf), its failures from its own status.
+ *
* @param {{ id: string, dir: string }} project
* @param {any} [manifest]
- * @param {{ clips?: string[] | null, cache?: any, mixCache?: string }} [opts]
+ * @param {{ clips?: string[] | null, cache?: any, mixCache?: string, take?: string | null }} [opts]
* @returns {Promise<{ items: PrepItem[], counts: { clips: number, ready: number, todo: number, failed: number, noWindow: number, excerpts: number } }>}
*/
-export async function benchPrepPlan(project, manifest = null, { clips = null, cache = null, mixCache = MIX_CACHE } = {}) {
- const m = manifest ?? (await readManifest(project.dir));
+export async function benchPrepPlan(project, manifest = null, { clips = null, cache = null, mixCache = MIX_CACHE, take = null } = {}) {
+ const m = manifest ?? (await prepManifestOf(project, take));
const want = clips && clips.length ? new Set(clips) : null;
const all = clipsOf(m).filter((c) => !want || want.has(c.id));
const c = cache ?? (await projectCache(project, m));
- const failures = (await readPrepStatus(project.dir))?.failed ?? {};
+ const failures = (await readPrepStatus(project.dir, take))?.failed ?? {};
/** @type {PrepItem[]} */
const items = [];
for (const clip of all) {
@@ -185,21 +221,21 @@ export const publicItem = ({ win, ...rest }) => rest;
* }} PrepStatus
*/
-/** @param {string} dir @returns {Promise<PrepStatus | null>} */
-export async function readPrepStatus(dir) {
+/** @param {string} dir @param {string | null} [take] @returns {Promise<PrepStatus | null>} */
+export async function readPrepStatus(dir, take = null) {
try {
- return JSON.parse(await readFile(statusFile(dir), "utf8"));
+ return JSON.parse(await readFile(statusFile(dir, take), "utf8"));
} catch {
return null;
}
}
-/** @param {string} dir @param {PrepStatus} st */
-async function writePrepStatus(dir, st) {
- await mkdir(prepDirOf(dir), { recursive: true });
- const tmp = `${statusFile(dir)}.tmp-${process.pid}`;
+/** @param {string} dir @param {PrepStatus} st @param {string | null} [take] */
+async function writePrepStatus(dir, st, take = null) {
+ await mkdir(prepStateDirOf(dir, take), { recursive: true });
+ const tmp = `${statusFile(dir, take)}.tmp-${process.pid}`;
await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`);
- await rename(tmp, statusFile(dir));
+ await rename(tmp, statusFile(dir, take));
}
/**
@@ -208,15 +244,16 @@ async function writePrepStatus(dir, st) {
* runner that was killed: it reads as stopped).
*
* @param {{ id: string, dir: string }} project
- * @param {{ clips?: string[] | null, plan?: Awaited<ReturnType<typeof benchPrepPlan>> }} [opts]
+ * @param {{ clips?: string[] | null, plan?: Awaited<ReturnType<typeof benchPrepPlan>>, take?: string | null }} [opts]
*/
-export async function benchPrepState(project, { clips = null, plan = null } = {}) {
- const p = plan ?? (await benchPrepPlan(project, null, { clips }));
- const st = await readPrepStatus(project.dir);
- const holder = lockHolder(project.dir);
+export async function benchPrepState(project, { clips = null, plan = null, take = null } = {}) {
+ const p = plan ?? (await benchPrepPlan(project, null, { clips, take }));
+ const st = await readPrepStatus(project.dir, take);
+ const holder = lockHolder(project.dir, take);
const running = !!holder || (st?.state === "running" && alive(Number(st.pid)));
return {
project: project.id,
+ take,
counts: p.counts,
running,
runner: running
@@ -244,12 +281,14 @@ export async function benchPrepState(project, { clips = null, plan = null } = {}
* analyse?: (abs: string) => Promise<unknown>,
* onEvent?: (ev: Record<string, unknown>) => void,
* mixCache?: string,
+ * take?: string | null,
* }} [opts]
* @returns {Promise<{ done: string[], failed: string[], skipped: number }>}
*/
export async function runBenchPrep(project, {
clips = null,
retry = false,
+ take = null,
slot = (_cmd, fn) => fn(),
ensure = (win) => ensureWindowFile(win),
analyse = null,
@@ -257,9 +296,10 @@ export async function runBenchPrep(project, {
mixCache = MIX_CACHE,
} = {}) {
const analyseOne = analyse ?? (async (abs) => (await import("../analyse.mjs")).analyseFile(abs, { cacheDir: mixCache }));
- const plan = await benchPrepPlan(project, null, { clips, mixCache });
+ const plan = await benchPrepPlan(project, null, { clips, mixCache, take });
const todo = plan.items.filter((i) => i.state === "todo" || (retry && i.state === "failed"));
- const prev = await readPrepStatus(project.dir);
+ const prev = await readPrepStatus(project.dir, take);
+ const put = (st) => writePrepStatus(project.dir, st, take);
/** @type {PrepStatus} */
const status = {
pid: process.pid,
@@ -276,26 +316,26 @@ export async function runBenchPrep(project, {
const it = plan.items.find((i) => i.id === id);
if (it && it.window?.name !== status.failed[id].window) delete status.failed[id];
}
- await writePrepStatus(project.dir, status);
- onEvent({ ev: "start", project: project.id, total: todo.length, ready: plan.counts.ready, noWindow: plan.counts.noWindow });
+ await put(status);
+ onEvent({ ev: "start", project: project.id, ...(take ? { take } : {}), total: todo.length, ready: plan.counts.ready, noWindow: plan.counts.noWindow });
const done = [];
const failed = [];
for (const it of todo) {
const t0 = Date.now();
status.current = { id: it.id, step: "waiting" };
- await writePrepStatus(project.dir, status);
+ await put(status);
onEvent({ ev: "clip", id: it.id, step: "waiting", n: done.length + failed.length + 1, total: todo.length });
try {
- await slot(["umtool-prep", project.id, it.id], async () => {
+ await slot(["umtool-prep", project.id, ...(take ? ["--take", take] : []), it.id], async () => {
if (!it.cut) {
status.current = { id: it.id, step: "cutting" };
- await writePrepStatus(project.dir, status);
+ await put(status);
onEvent({ ev: "clip", id: it.id, step: "cutting", window: it.window?.name });
await ensure(it.win);
}
if (!it.peaks) {
status.current = { id: it.id, step: "analysing" };
- await writePrepStatus(project.dir, status);
+ await put(status);
onEvent({ ev: "clip", id: it.id, step: "analysing" });
const abs = absOf(it.win);
if (!abs) throw new Error("the window is outside the roots");
@@ -312,12 +352,12 @@ export async function runBenchPrep(project, {
onEvent({ ev: "clip-failed", id: it.id, error });
}
status.done = done.length + failed.length;
- await writePrepStatus(project.dir, status);
+ await put(status);
}
status.current = null;
status.state = failed.length ? "failed" : "done";
status.endedAt = new Date().toISOString();
- await writePrepStatus(project.dir, status);
+ await put(status);
onEvent({ ev: "end", done: done.length, failed: failed.length, skipped: plan.items.length - todo.length });
return { done, failed, skipped: plan.items.length - todo.length };
}
@@ -326,45 +366,45 @@ export async function runBenchPrep(project, {
// The queue and the run lock.
// ---------------------------------------------------------------------------
-/** The live runner's pid, or null (a lock naming a dead pid is dropped). @param {string} dir */
-export function lockHolder(dir) {
+/** The live runner's pid, or null (a lock naming a dead pid is dropped). @param {string} dir @param {string | null} [take] */
+export function lockHolder(dir, take = null) {
let raw;
try {
- raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8");
+ raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8");
} catch {
return null;
}
const pid = Number(String(raw).trim());
if (alive(pid)) return pid;
try {
- unlinkSync(/* turbopackIgnore: true */ lockFile(dir));
+ unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take));
} catch {
/* somebody else dropped it */
}
return null;
}
-/** Take the run lock, or false when a live runner holds it. @param {string} dir */
-export function tryLock(dir) {
+/** Take the run lock, or false when a live runner holds it. @param {string} dir @param {string | null} [take] */
+export function tryLock(dir, take = null) {
for (let i = 0; i < 2; i += 1) {
try {
- const fd = openSync(/* turbopackIgnore: true */ lockFile(dir), "wx");
+ const fd = openSync(/* turbopackIgnore: true */ lockFile(dir, take), "wx");
writeSync(fd, `${process.pid}\n`);
closeSync(fd);
return true;
} catch (e) {
if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e;
- if (lockHolder(dir)) return false;
+ if (lockHolder(dir, take)) return false;
}
}
return false;
}
-/** @param {string} dir */
-export function unlock(dir) {
+/** @param {string} dir @param {string | null} [take] */
+export function unlock(dir, take = null) {
try {
- if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8").trim()) === process.pid) {
- unlinkSync(/* turbopackIgnore: true */ lockFile(dir));
+ if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8").trim()) === process.pid) {
+ unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take));
}
} catch {
/* not ours, or gone */
@@ -375,10 +415,11 @@ export function unlock(dir) {
* Add a request to the project's queue. `clips: null` is every clip.
* @param {string} dir
* @param {{ clips: string[] | null, retry?: boolean }} req
+ * @param {string | null} [take]
*/
-export async function appendPrepRequest(dir, req) {
- await mkdir(prepDirOf(dir), { recursive: true });
- await appendFile(pendingFile(dir), `${JSON.stringify({ clips: req.clips ?? null, retry: !!req.retry, at: Date.now() })}\n`);
+export async function appendPrepRequest(dir, req, take = null) {
+ await mkdir(prepStateDirOf(dir, take), { recursive: true });
+ await appendFile(pendingFile(dir, take), `${JSON.stringify({ clips: req.clips ?? null, retry: !!req.retry, at: Date.now() })}\n`);
}
/**
@@ -387,12 +428,13 @@ export async function appendPrepRequest(dir, req) {
* asks for all), `retry` if any does. Null when the queue is empty.
*
* @param {string} dir
+ * @param {string | null} [take]
* @returns {Promise<{ clips: string[] | null, retry: boolean } | null>}
*/
-export async function takePrepRequests(dir) {
- const taking = `${pendingFile(dir)}.${process.pid}`;
+export async function takePrepRequests(dir, take = null) {
+ const taking = `${pendingFile(dir, take)}.${process.pid}`;
try {
- await rename(pendingFile(dir), taking);
+ await rename(pendingFile(dir, take), taking);
} catch {
return null;
}
@@ -429,24 +471,28 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
* instead of leaving the queue to the runner that holds it.
*
* @param {{ id: string, dir: string }} project
+ * `take`: the take's queue, under the take's lock (prepStateDirOf).
+ *
+ * @param {{ id: string, dir: string }} project
* @param {Parameters<typeof runBenchPrep>[1] & { initial?: { clips: string[] | null, retry?: boolean } | null, wait?: boolean, pollMs?: number }} [opts]
* @returns {Promise<{ runs: number, done: string[], failed: string[], held: boolean }>}
*/
export async function drainPrepQueue(project, { initial = null, wait = false, pollMs = 2000, ...run } = {}) {
- await mkdir(prepDirOf(project.dir), { recursive: true });
+ const take = run.take ?? null;
+ await mkdir(prepStateDirOf(project.dir, take), { recursive: true });
const done = [];
const failed = [];
let runs = 0;
let own = initial;
for (;;) {
- if (!tryLock(project.dir)) {
+ if (!tryLock(project.dir, take)) {
if (!wait) return { runs, done, failed, held: true };
await sleep(pollMs);
continue;
}
try {
for (;;) {
- const queued = await takePrepRequests(project.dir);
+ const queued = await takePrepRequests(project.dir, take);
const req = own && queued ? mergeRequests([own, queued]) : own ?? queued;
own = null;
if (!req) break;
@@ -456,11 +502,11 @@ export async function drainPrepQueue(project, { initial = null, wait = false, po
failed.push(...r.failed);
}
} finally {
- unlock(project.dir);
+ unlock(project.dir, take);
}
// A request appended after the last look and before the unlock saw a live
// runner and started none: look once more, now that the lock is free.
- if (!existsSync(/* turbopackIgnore: true */ pendingFile(project.dir))) return { runs, done, failed, held: false };
+ if (!existsSync(/* turbopackIgnore: true */ pendingFile(project.dir, take))) return { runs, done, failed, held: false };
wait = false;
}
}
@@ -483,9 +529,9 @@ function onPath(name) {
* both. Pure apart from the PATH probe.
*
* @param {string} projectId
- * @param {{ wait?: boolean, clips?: string[] | null, retry?: boolean, ndjson?: boolean, has?: (name: string) => boolean }} [opts]
+ * @param {{ wait?: boolean, clips?: string[] | null, retry?: boolean, ndjson?: boolean, take?: string | null, has?: (name: string) => boolean }} [opts]
*/
-export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, has = onPath } = {}) {
+export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, take = null, has = onPath } = {}) {
const prefix = [
...(has("nice") ? ["nice", "-n", "19"] : []),
...(has("ionice") ? ["ionice", "-c3"] : []),
@@ -496,6 +542,7 @@ export function runnerArgv(projectId, { wait = false, clips = null, retry = fals
path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"),
"prep",
projectId,
+ ...(take ? ["--take", take] : []),
"--run",
...(wait ? ["--wait"] : []),
...(clips && clips.length ? ["--clips", clips.join(",")] : []),
@@ -504,18 +551,22 @@ export function runnerArgv(projectId, { wait = false, clips = null, retry = fals
];
}
-/** Start a detached runner, its output appended to prep.log. @param {{ id: string, dir: string }} project */
-export function spawnPrepRunner(project) {
- const argv = runnerArgv(project.id);
+/**
+ * Start a detached runner, its output appended to prep.log (the take's, for a take).
+ * @param {{ id: string, dir: string }} project
+ * @param {{ take?: string | null }} [opts]
+ */
+export function spawnPrepRunner(project, { take = null } = {}) {
+ const argv = runnerArgv(project.id, { take });
// The log is the last runs', not a history: past 1 MB it starts again.
const big = (() => {
try {
- return statSync(/* turbopackIgnore: true */ prepLogOf(project.dir)).size > 1024 * 1024;
+ return statSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take)).size > 1024 * 1024;
} catch {
return false;
}
})();
- const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir), big ? "w" : "a");
+ const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take), big ? "w" : "a");
try {
const child = spawn(argv[0], argv.slice(1), {
cwd: UMTOOL_DIR,
@@ -541,23 +592,25 @@ export function spawnPrepRunner(project) {
* then prepares each queued clip whole. `retry` also takes clips whose last
* prep failed (an explicit ask; a trigger leaves them).
*
+ * `take`: the take's clips, queued for the take's own runner (`umtool prep <p> --take <id> --run`).
+ *
* @param {{ id: string, dir: string }} project
* @param {string[] | null} [clips]
- * @param {{ excerptsOnly?: boolean, retry?: boolean, start?: (project: { id: string, dir: string }) => number | null, plan?: any }} [opts]
+ * @param {{ excerptsOnly?: boolean, retry?: boolean, take?: string | null, start?: (project: { id: string, dir: string }, opts: { take: string | null }) => number | null, plan?: any }} [opts]
* @returns {Promise<{ queued: string[], started: boolean, pid: number | null, off?: boolean }>}
*/
-export async function queueBenchPrep(project, clips = null, { excerptsOnly = false, retry = false, start = spawnPrepRunner, plan = null } = {}) {
+export async function queueBenchPrep(project, clips = null, { excerptsOnly = false, retry = false, take = null, start = spawnPrepRunner, plan = null } = {}) {
if (process.env.UMTOOL_BENCH_PREP === "0") return { queued: [], started: false, pid: null, off: true };
- const p = plan ?? (await benchPrepPlan(project, null, { clips }));
+ const p = plan ?? (await benchPrepPlan(project, null, { clips, take }));
const queued = p.items
.filter((i) => i.state === "todo" || (retry && i.state === "failed"))
.filter((i) => !excerptsOnly || (i.excerpt && !i.cut))
.map((i) => i.id);
- if (!queued.length) return { queued, started: false, pid: lockHolder(project.dir) };
- await appendPrepRequest(project.dir, { clips: queued, retry });
- const holder = lockHolder(project.dir);
+ if (!queued.length) return { queued, started: false, pid: lockHolder(project.dir, take) };
+ await appendPrepRequest(project.dir, { clips: queued, retry }, take);
+ const holder = lockHolder(project.dir, take);
if (holder) return { queued, started: false, pid: holder };
- return { queued, started: true, pid: start(project) };
+ return { queued, started: true, pid: start(project, { take }) };
}
/**
diff --git a/umtool/lib/report/benchPrepTake.test.mjs b/umtool/lib/report/benchPrepTake.test.mjs
@@ -0,0 +1,175 @@
+// A TAKE'S PREP (`umtool prep <p> --take <id>`, the take's walk): the take's
+// clips planned from its manifest as the walk reads it -- a DRAFT's too, no
+// render -- with its own status, queue and runner, so a take's clip that
+// carries the cut's id with other bounds never shares the cut's state. And
+// the plan does not depend on the process's working directory (2 Nov: run
+// from the project's directory it planned every clip no-window).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import path from "node:path";
+import os from "node:os";
+import { execFileSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "bench-prep-take-"));
+// The roots are read when paths.mjs loads.
+const ENV = {
+ MIX_ROOTS: root,
+ REPORTS_DIR: path.join(root, "reports"),
+ CHANNELS_DIR: path.join(root, "channels"),
+ SAVED_VIDEOS_DIR: path.join(root, "saved"),
+ UMTOOL_CACHE_DIR: path.join(root, "cache"),
+};
+Object.assign(process.env, ENV);
+delete process.env.UMTOOL_BENCH_PREP;
+
+const prep = await import("./benchPrep.mjs");
+const trigger = await import("./benchPrepTrigger.mjs");
+const { updateTakeClip } = await import("./takeEdit.mjs");
+
+test.after(() => rm(root, { recursive: true, force: true }));
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const dir = path.join(root, "reports", "folder", "p");
+const project = { id: "folder/p", dir };
+const raw = path.join(dir, "out", "clips-raw");
+
+const clip = (id, video, start, end, extra = {}) => ({ type: "clip", id, video, channel: "chan", start, end, ...extra });
+/** The cut: kf3 on vid at 10-14; kr1 on vs. */
+const MANIFEST = { slug: "p", provenance: { channelSlug: "chan" }, timeline: [clip("kf3", "vid", 10, 14), clip("kr1", "vs", 2, 5)] };
+/**
+ * A DRAFT take whose patch replaces the timeline (its own timeline): kf3
+ * WIDENED to 8-20 (the cut's id, other bounds), and ke1 -- a clip only the
+ * take has, on a recording the cut never cites, held only in the corpus.
+ */
+const TAKE = {
+ id: "spin",
+ group: "takes",
+ order: 1,
+ label: "Spin-off",
+ kind: "different",
+ summary: "",
+ changes: [],
+ preview: "preview.mp4",
+ seconds: null,
+ builtAt: null,
+ style: null,
+ patch: { timeline: [clip("kf3", "vid", 8, 20), clip("ke1", "vnew", 12, 18)] },
+ window: null,
+ draft: true,
+ draftedAt: "2026-11-02T12:00:00.000Z",
+};
+
+async function fresh() {
+ await rm(dir, { recursive: true, force: true });
+ await mkdir(raw, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(MANIFEST, null, 2)}\n`);
+ await mkdir(path.join(dir, "takes", "spin"), { recursive: true });
+ await writeFile(path.join(dir, "takes", "spin", "take.json"), `${JSON.stringify(TAKE, null, 2)}\n`);
+ // Windows by NAME (the listing reads seconds from names; nothing here decodes them).
+ await writeFile(path.join(raw, "vid_0.00-30.00.mp4"), "x");
+ await writeFile(path.join(raw, "vs_0.00-10.00.mp4"), "x");
+ // ke1's window: in the CORPUS (the editor's fetch lands there), not in the project.
+ const corpus = path.join(root, "channels", "chan", "data", "vnew", "clips");
+ await mkdir(corpus, { recursive: true });
+ await writeFile(path.join(corpus, "10.00-30.00.mp4"), "x");
+ await rm(path.join(root, "cache"), { recursive: true, force: true });
+}
+
+test("a draft take's plan is its own timeline: the take-only clip found in the corpus, the widened clip on its own bounds", async () => {
+ await fresh();
+ const cut = await prep.benchPrepPlan(project);
+ assert.deepEqual(cut.items.map((i) => i.id), ["kf3", "kr1"]);
+ const take = await prep.benchPrepPlan(project, null, { take: "spin" });
+ assert.deepEqual(take.items.map((i) => [i.id, i.state, i.window?.name]), [
+ ["kf3", "todo", "vid_0.00-30.00.mp4"],
+ ["ke1", "todo", "10.00-30.00.mp4"],
+ ]);
+ assert.equal(take.counts.noWindow, 0);
+ // The state of each lives apart.
+ assert.equal(prep.prepStateDirOf(dir), path.join(dir, "out", "bench-excerpts"));
+ assert.equal(prep.prepStateDirOf(dir, "spin"), path.join(dir, "out", "bench-excerpts", "takes", "spin"));
+ assert.throws(() => prep.prepStateDirOf(dir, "../x"), /not a take id/);
+ await assert.rejects(prep.benchPrepPlan(project, null, { take: "nope" }), /no take nope/);
+});
+
+test("a take's failure is the take's: the cut's clip of the same id stays as it was", async () => {
+ await fresh();
+ const r = await prep.runBenchPrep(project, {
+ take: "spin",
+ clips: ["kf3"],
+ analyse: async () => {
+ throw new Error("the take's kf3 would not decode");
+ },
+ });
+ assert.deepEqual(r.failed, ["kf3"]);
+ const takeStatus = await prep.readPrepStatus(dir, "spin");
+ assert.equal(takeStatus.failed.kf3.window, "vid_0.00-30.00.mp4");
+ assert.match(takeStatus.failed.kf3.error, /would not decode/);
+ assert.equal(await prep.readPrepStatus(dir), null, "the cut's status file is not written");
+ const cut = await prep.benchPrepPlan(project);
+ assert.equal(cut.items.find((i) => i.id === "kf3").state, "todo");
+ const take = await prep.benchPrepState(project, { take: "spin" });
+ assert.equal(take.take, "spin");
+ assert.equal(take.items.find((i) => i.id === "kf3").state, "failed");
+ // A take's runner is its own lock: the cut's is free while it holds the take's.
+ assert.equal(prep.tryLock(dir, "spin"), true);
+ assert.equal(prep.lockHolder(dir), null);
+ assert.equal(prep.lockHolder(dir, "spin"), process.pid);
+ prep.unlock(dir, "spin");
+ assert.equal(prep.lockHolder(dir, "spin"), null);
+});
+
+test("queueing a take's prep writes the take's queue and starts the take's runner; the argv carries --take", async () => {
+ await fresh();
+ const started = [];
+ const q = await prep.queueBenchPrep(project, null, { take: "spin", start: (p, o) => (started.push([p.id, o.take]), 4242) });
+ assert.deepEqual(q, { queued: ["kf3", "ke1"], started: true, pid: 4242 });
+ assert.deepEqual(started, [["folder/p", "spin"]]);
+ assert.ok(existsSync(path.join(dir, "out", "bench-excerpts", "takes", "spin", ".prep-pending")));
+ assert.ok(!existsSync(path.join(dir, "out", "bench-excerpts", ".prep-pending")), "nothing in the cut's queue");
+ assert.deepEqual(await prep.takePrepRequests(dir, "spin"), { clips: ["kf3", "ke1"], retry: false });
+ const argv = prep.runnerArgv("folder/p", { take: "spin", has: () => false });
+ assert.deepEqual(argv.slice(-5), ["prep", "folder/p", "--take", "spin", "--run"]);
+});
+
+test("a save on the take's walk queues the take's prep for that clip, never the cut's", async () => {
+ await fresh();
+ const asked = [];
+ trigger.setBenchPrepQueue(async (p, clips, opts) => {
+ asked.push([p.id, clips, opts.take ?? null]);
+ });
+ try {
+ await updateTakeClip(dir, "spin", "kf3", { end: 21 });
+ await trigger.settleBenchPrepTriggers();
+ } finally {
+ trigger.setBenchPrepQueue(null);
+ }
+ assert.deepEqual(asked, [["folder/p", ["kf3"], "spin"]]);
+ const doc = JSON.parse(await readFile(path.join(dir, "takes", "spin", "take.json"), "utf8"));
+ assert.equal(doc.patch.timeline[0].end, 21);
+ assert.equal(JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")).timeline[0].end, 14);
+});
+
+test("the plan is the same from any working directory: the project's own, umtool's, the filesystem root", async () => {
+ await fresh();
+ const probe = path.join(root, "probe.mjs");
+ await writeFile(
+ probe,
+ `const p = await import(${JSON.stringify(new URL("./benchPrep.mjs", import.meta.url).href)});\n` +
+ `const r = await p.benchPrepPlan(${JSON.stringify(project)}, null, { take: process.argv[2] || null });\n` +
+ "console.log(JSON.stringify(r.items.map((i) => [i.id, i.state, i.window?.name ?? null])));\n",
+ );
+ const env = { ...process.env, ...ENV };
+ const runs = [];
+ for (const cwd of [dir, path.join(HERE, "..", ".."), "/"]) {
+ for (const take of ["", "spin"]) runs.push([cwd, take, execFileSync(process.execPath, [probe, take], { cwd, env, encoding: "utf8" }).trim()]);
+ }
+ for (const [cwd, take, got] of runs) {
+ assert.equal(got, take ? '[["kf3","todo","vid_0.00-30.00.mp4"],["ke1","todo","10.00-30.00.mp4"]]' : '[["kf3","todo","vid_0.00-30.00.mp4"],["kr1","todo","vs_0.00-10.00.mp4"]]', `from ${cwd}${take ? ` --take ${take}` : ""}`);
+ }
+});
diff --git a/umtool/lib/report/benchPrepTrigger.mjs b/umtool/lib/report/benchPrepTrigger.mjs
@@ -1,6 +1,7 @@
// The bench prep's TRIGGER: after a write that may need a new excerpt (a
// window moved, a clip inserted, split, merged, duplicated, restored) and
-// after a fetch lands, queue prep for the clips it touched (benchPrep.mjs).
+// after a fetch lands, queue prep for the clips it touched (benchPrep.mjs) --
+// of the cut, or of a take (a write to its patch, a fetch for it).
//
// Never holds the writer: the writer has already written when this is called,
// it returns at once, and the work -- a plan of a few stats, then at most a
@@ -15,7 +16,7 @@
const inFlight = new Set();
/**
- * @typedef {(project: { id: string, dir: string }, clips: string[] | null, opts: { excerptsOnly: boolean }) => Promise<unknown>} QueueFn
+ * @typedef {(project: { id: string, dir: string }, clips: string[] | null, opts: { excerptsOnly: boolean, take?: string | null }) => Promise<unknown>} QueueFn
*/
/** @type {QueueFn | null} a test's stand-in for queueBenchPrep */
let queueOverride = null;
@@ -32,18 +33,22 @@ export function setBenchPrepQueue(fn) {
* in a walk) starts a runner only when an excerpt is missing; a FETCH that
* landed passes false, so the new windows' waveforms are made too.
*
+ * `take`: a write to a TAKE's patch (its walk's save, `umtool window
+ * --take`), or a fetch for one -- the take's clips, queued for the take's
+ * own runner (benchPrep.mjs prepStateDirOf).
+ *
* @param {string} dir the project directory (the manifest's)
* @param {string[] | null} clips null: every clip
- * @param {{ excerptsOnly?: boolean }} [opts]
+ * @param {{ excerptsOnly?: boolean, take?: string | null }} [opts]
*/
-export function benchPrepAfterWrite(dir, clips, { excerptsOnly = true } = {}) {
+export function benchPrepAfterWrite(dir, clips, { excerptsOnly = true, take = null } = {}) {
if (process.env.UMTOOL_BENCH_PREP === "0") return;
const p = (async () => {
const m = await import("./benchPrep.mjs");
const project = m.projectOfDir(dir);
if (!project) return;
const queue = queueOverride ?? m.queueBenchPrep;
- await queue(project, clips, { excerptsOnly });
+ await queue(project, clips, { excerptsOnly, ...(take ? { take } : {}) });
})().catch(() => {
/* a trigger never fails a write */
});
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -393,15 +393,20 @@ export async function exportNeeds(project, clipId, { take = null, kind = "cut",
const e = got.entry;
if (kind === "cut") return { entry: e, want: null, held: !!got.source, padBefore: 0, padAfter: 0 };
const want = exportSpan(e, got.render, { kind, context, span });
- const held = !!(await heldWindow(project, e, want));
+ const held = !!(await heldWindow(project, e, want, take));
const pad = (v) => Math.min(EXPORT_CONTEXT.max, Math.max(0, Math.ceil(v)));
return { entry: e, want, held, padBefore: pad(e.start - want.from), padAfter: pad(want.to - e.end) };
}
-/** The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows). */
-async function heldWindow(project, entry, want) {
+/**
+ * The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows).
+ * A take's clip is looked up through the TAKE's manifest: the corpus dirs listed are its clips' videos, and a clip only the take has
+ * cites a recording the cut may not.
+ */
+async function heldWindow(project, entry, want, take = null) {
const { projectCache } = await import("./serve.mjs");
- const cache = await projectCache(project);
+ const manifest = take ? (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest : null;
+ const cache = await projectCache(project, manifest);
return cache.containing(entry.video, want.from + 0.02, want.to - 0.02) ?? null;
}
diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs
@@ -10,6 +10,8 @@
// … [--reason "…"] the provenance reason (default: "<title> montage", or the title)
// … --refetch <clipId>[,<clipId>…] evict those clips' cached windows first (the editor's evict-clips,
// --refetch-video <slug>/<id> `covering` their fetch spans), then fetch as usual
+// … --take <id> a TAKE's clips (its walk's manifest; a draft's too), the run
+// recorded with `take` in fetch-runs.json
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import {
EditorError,
@@ -40,6 +42,8 @@ export const FETCH_USAGE = [
" … --refetch <clipId>[,<clipId>…] evict the cached windows overlapping those clips' fetch spans first",
" … --refetch-video <slug>/<id> the same for every window this project asks of that video",
" (the editor's evict-clips; with --dry-run the eviction is a dry run too and nothing is deleted)",
+ " … --take <id> a take's clips instead of the cut's: the take's manifest as its walk reads it (a draft's",
+ " too — nothing rendered), so a clip only the take has is fetched; --status follows its last run",
"",
`Every run is recorded in <project>/${FETCH_RUNS_FILE}; \`umtool fallback\` reads it for the refused windows.`,
"The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).",
@@ -77,12 +81,20 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
const json = args.includes("--json");
const words = [];
let reason = null;
+ let take = null;
const refetchClips = [];
const refetchVideos = [];
for (let i = 0; i < args.length; i += 1) {
if (args[i] === "--reason") {
reason = args[i + 1] ?? "";
i += 1;
+ } else if (args[i] === "--take") {
+ take = args[i + 1] ?? "";
+ i += 1;
+ if (!take || take.startsWith("--")) {
+ err(`--take needs a take id\n${FETCH_USAGE}`);
+ return 2;
+ }
} else if (args[i] === "--refetch" || args[i] === "--refetch-video") {
const v = args[i + 1];
if (!v || v.startsWith("--")) {
@@ -103,31 +115,43 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
const project = r.project;
+ const who = take ? `${project.id} take ${take}` : project.id;
+ if (take) {
+ const { isTakeId } = await import("./takes.mjs");
+ if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id`);
+ }
if (args.includes("--status")) {
- const run = lastStartedRun(await readFetchRuns(project.dir));
- if (!run) throw new CliError(`${project.id} has no started fetch run in ${FETCH_RUNS_FILE}`);
+ const run = lastStartedRun(await readFetchRuns(project.dir), { take });
+ if (!run) throw new CliError(`${who} has no started fetch run in ${FETCH_RUNS_FILE}`);
const states = await followRun(cfg, project.dir, run);
// A run that has ended landed what it landed: the bench's prep for it.
if (states.length && states.every((st) => TERMINAL.has(st.status)) && states.some((st) => st.status === "done")) {
- benchPrepAfterWrite(project.dir, null, { excerptsOnly: false });
+ benchPrepAfterWrite(project.dir, null, { excerptsOnly: false, take });
}
- if (json) out(JSON.stringify({ project: project.id, run: { at: run.at, jobIds: run.jobIds }, jobs: states }, null, 2));
+ if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), run: { at: run.at, jobIds: run.jobIds }, jobs: states }, null, 2));
else {
- out(`${project.id}: the run of ${run.at}`);
+ out(`${who}: the run of ${run.at}`);
for (const st of states) out(stateLine(st));
for (const st of states) for (const f of st.failed ?? []) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`);
}
return 0;
}
- const { body, skipped } = await projectFetchBody(project, { reason });
+ let fetched;
+ try {
+ fetched = await projectFetchBody(project, { reason, take });
+ } catch (e) {
+ if (take) throw new CliError(`${project.id}: ${e instanceof Error ? e.message : String(e)}`);
+ throw e;
+ }
+ const { body, skipped } = fetched;
if (args.includes("--body")) {
out(JSON.stringify(body, null, 1));
return 0;
}
if (!body.items.length) {
- out(`${project.id}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`);
+ out(`${who}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`);
return 0;
}
const dryRun = args.includes("--dry-run");
@@ -157,27 +181,27 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (dryRun && !json) out(" (a dry run evicts nothing, so those windows still read as cached below)");
}
const answer = await postFetchWindows(cfg, body, { dryRun });
- const run = await recordFetchRun(project.dir, { body, answer, refetch });
+ const run = await recordFetchRun(project.dir, { body, answer, refetch, take });
const summary = summarizeAnswer(answer);
if (!dryRun && !args.includes("--wait")) {
- if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2));
+ if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2));
else {
- out(`${project.id}: ${body.items.length} window(s) asked${skipped.length ? `, ${skipped.length} skipped` : ""}`);
+ out(`${who}: ${body.items.length} window(s) asked${skipped.length ? `, ${skipped.length} skipped` : ""}`);
for (const l of summaryLines(summary)) out(l);
}
return summary.refused.length && !summary.jobs.length ? 1 : 0;
}
if (dryRun) {
- if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2));
+ if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2));
else {
- out(`${project.id}: ${body.items.length} window(s) — the dry run${skipped.length ? ` (${skipped.length} skipped: ${skipped.map((s) => `${s.clipId} ${s.why}`).join(", ")})` : ""}`);
+ out(`${who}: ${body.items.length} window(s) — the dry run${skipped.length ? ` (${skipped.length} skipped: ${skipped.map((s) => `${s.clipId} ${s.why}`).join(", ")})` : ""}`);
for (const l of summaryLines(summary)) out(l);
}
return 0;
}
// --wait: follow every job to its end.
if (!json) {
- out(`${project.id}: ${body.items.length} window(s) asked`);
+ out(`${who}: ${body.items.length} window(s) asked`);
for (const l of summaryLines(summary)) out(l);
}
let states = [];
@@ -195,9 +219,9 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con
await sleep(pollMs);
}
// What landed, prepared for the walk (a runner in the background; bin/umtool.mjs waits for the queueing only).
- if (states.some((st) => st.status === "done")) benchPrepAfterWrite(project.dir, null, { excerptsOnly: false });
+ if (states.some((st) => st.status === "done")) benchPrepAfterWrite(project.dir, null, { excerptsOnly: false, take });
const failed = states.flatMap((st) => st.failed ?? []);
- if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary, jobsEnded: states }, null, 2));
+ if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary, jobsEnded: states }, null, 2));
else {
for (const f of failed) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`);
if (failed.length) out(`${failed.length} window(s) failed — \`umtool fallback ${project.id} --dry-run\` finds a stand-in for each refused one`);
diff --git a/umtool/lib/report/fetchTake.test.mjs b/umtool/lib/report/fetchTake.test.mjs
@@ -0,0 +1,116 @@
+// `umtool fetch <p> --take <id>`: a take's clips asked of the editor as the
+// cut's are -- one fetch-windows batch, recorded in fetch-runs.json -- from
+// the take's manifest as its walk reads it, so a DRAFT take (nothing
+// rendered) whose clip is only in its patch is fetched with no hand JSON.
+//
+// Run with: pnpm test:scripts
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-take-"));
+process.env.REPORTS_DIR = root;
+process.env.UMTOOL_CACHE_DIR = path.join(root, ".cache");
+delete process.env.UMTOOL_BENCH_PREP;
+const { lastStartedRun, projectFetchBody, readFetchRuns } = await import("./fetchWindows.mjs");
+const { fetchCommand } = await import("./fetchCli.mjs");
+const trigger = await import("./benchPrepTrigger.mjs");
+test.after(() => rm(root, { recursive: true, force: true }));
+
+const clip = (id, video, start, end) => ({ type: "clip", id, channel: "chan", video, start, end });
+const MANIFEST = { slug: "p", title: "In her words", provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline: [clip("kf3", "vid", 10, 14)] };
+const TAKE = {
+ id: "spin",
+ group: "takes",
+ order: 1,
+ label: "Spin-off",
+ kind: "different",
+ summary: "",
+ changes: [],
+ preview: "preview.mp4",
+ seconds: null,
+ builtAt: null,
+ style: null,
+ window: null,
+ draft: true,
+ draftedAt: "2026-11-02T12:00:00.000Z",
+ // Its own timeline: the cut's kf3 widened, and ke1 only the take has.
+ patch: { timeline: [clip("kf3", "vid", 8, 20), clip("ke1", "vnew", 100, 110)] },
+};
+const dir = path.join(root, "folder", "p");
+
+/** A fake editor: routes -> answers, every request recorded. */
+function fakeEditor(routes) {
+ const seen = [];
+ const f = async (url, init = {}) => {
+ const u = new URL(url);
+ const key = `${init.method ?? "GET"} ${u.pathname}`;
+ seen.push({ key, body: init.body ? JSON.parse(init.body) : null });
+ const r = typeof routes[key] === "function" ? routes[key](init.body ? JSON.parse(init.body) : null) : routes[key];
+ if (!r) return new Response(JSON.stringify({ ok: false, error: "not found" }), { status: 404 });
+ return new Response(JSON.stringify(r), { status: 200, headers: { "content-type": "application/json" } });
+ };
+ return { fetch: f, seen };
+}
+
+test("fetch --take: the take's clips (a draft's), one batch, the run recorded as the take's; the cut's last run is not it", async () => {
+ await mkdir(path.join(dir, "takes", "spin"), { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2));
+ await writeFile(path.join(dir, "takes", "spin", "take.json"), JSON.stringify(TAKE, null, 2));
+ const manifestBefore = await readFile(path.join(dir, "video.manifest.json"), "utf8");
+
+ const { body } = await projectFetchBody({ id: "folder/p", dir }, { take: "spin" });
+ assert.deepEqual(body.items.map((i) => [i.clipId, i.id, i.from, i.to]), [
+ ["kf3", "vid", 5, 23],
+ ["ke1", "vnew", 97, 113],
+ ]);
+ assert.equal(body.manifest, path.join(dir, "takes", "spin", "take.json"));
+ assert.equal(body.requestedBy, "umtool:folder/p");
+ const cutBody = (await projectFetchBody({ id: "folder/p", dir })).body;
+ assert.deepEqual(cutBody.items.map((i) => [i.clipId, i.from, i.to]), [["kf3", 7, 17]]);
+
+ let polls = 0;
+ const ed = fakeEditor({
+ "POST /api/ops/fetch-windows": (b) => ({ ok: true, dryRun: false, groups: [], cached: [], inFlight: [], unresolved: [], refused: [], jobs: [{ platform: "youtube", queueKey: "clips:youtube", jobId: "J9", items: b.items.length }], jobIds: ["J9"], jobId: "J9" }),
+ "GET /api/ops/job/J9": () => ({ ok: true, job: { id: "J9", status: ++polls < 2 ? "running" : "done" } }),
+ "GET /api/jobs/J9/log": { content: "Fetch windows: 2 fetched.\n", nextOffset: 10, status: "archived" },
+ });
+ const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch };
+ const lines = [];
+ const asked = [];
+ trigger.setBenchPrepQueue(async (p, clips, opts) => {
+ asked.push([p.id, clips, opts.take ?? null, opts.excerptsOnly]);
+ });
+ try {
+ const run = (args) => fetchCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 });
+ assert.equal(await run(["folder/p", "--take", "spin", "--wait"]), 0, lines.join("\n"));
+ await trigger.settleBenchPrepTriggers();
+ assert.deepEqual(ed.seen[0].body.items.map((i) => i.clipId), ["kf3", "ke1"]);
+ assert.match(lines.join("\n"), /folder\/p take spin: 2 window\(s\) asked/);
+ // What landed is prepared for the TAKE's walk.
+ assert.deepEqual(asked, [["folder/p", null, "spin", false]]);
+
+ const doc = await readFetchRuns(dir);
+ assert.equal(doc.runs.length, 1);
+ assert.equal(doc.runs[0].take, "spin");
+ assert.equal(lastStartedRun(doc), null, "the cut has no started run of its own");
+ assert.deepEqual(lastStartedRun(doc, { take: "spin" }).jobIds, ["J9"]);
+
+ lines.length = 0;
+ assert.equal(await run(["folder/p", "--status", "--take", "spin"]), 0);
+ assert.match(lines.join("\n"), /folder\/p take spin: the run of/);
+ lines.length = 0;
+ assert.equal(await run(["folder/p", "--status"]), 1, "the cut's --status does not read the take's run");
+ assert.match(lines.join("\n"), /folder\/p has no started fetch run/);
+
+ lines.length = 0;
+ assert.equal(await run(["folder/p", "--take", "nope", "--body"]), 1);
+ assert.match(lines.join("\n"), /no take nope/);
+ assert.equal(await run(["folder/p", "--take"]), 2);
+ } finally {
+ trigger.setBenchPrepQueue(null);
+ }
+ assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), manifestBefore, "the project's manifest is untouched");
+});
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -170,12 +170,26 @@ export function bodyHash(body) {
/**
* The body for a project on disk: its manifest, its rulings.
+ *
+ * `take` (`umtool fetch <p> --take <id>`): the TAKE's clips -- its manifest
+ * as its walk reads it (takeManifest.mjs resolveTakeManifest: the project's
+ * now, the style's patch, the take's), so a clip only the take has (in its
+ * patch, not the cut) is asked for, and a DRAFT take needs no render first.
+ * The body names takes/<id>/take.json as the manifest it came from.
+ *
* @param {{ id: string, dir: string }} project
- * @param {{ reason?: string | null }} [opts]
+ * @param {{ reason?: string | null, take?: string | null }} [opts]
*/
-export async function projectFetchBody(project, { reason = null } = {}) {
- const manifestPath = path.join(project.dir, MANIFEST_FILE);
- const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+export async function projectFetchBody(project, { reason = null, take = null } = {}) {
+ let manifestPath = path.join(project.dir, MANIFEST_FILE);
+ let manifest;
+ if (take) {
+ const [{ resolveTakeManifest }, { takesDirOf, TAKE_FILE }] = await Promise.all([import("./takeManifest.mjs"), import("./takes.mjs")]);
+ manifest = (await resolveTakeManifest(project.dir, take)).manifest;
+ manifestPath = path.join(takesDirOf(project.dir), take, TAKE_FILE);
+ } else {
+ manifest = JSON.parse(await readFile(manifestPath, "utf8"));
+ }
const rulings = await readMontageRulings(project.dir);
return { manifest, manifestPath, ...fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason }) };
}
@@ -367,10 +381,11 @@ async function writeRuns(projectDir, doc) {
/**
* Record a run (the dry run or the start).
* @param {string} projectDir
- * @param {{ body: Record<string, any>, answer: Record<string, any>, refetch?: Record<string, any>[] | null, now?: Date }} r
+ * @param {{ body: Record<string, any>, answer: Record<string, any>, refetch?: Record<string, any>[] | null, take?: string | null, now?: Date }} r
* `refetch`: what a `--refetch` evicted first (one entry per video).
+ * `take`: the run asked for a take's clips (`umtool fetch --take`); recorded on the run.
*/
-export function recordFetchRun(projectDir, { body, answer, refetch = null, now = new Date() }) {
+export function recordFetchRun(projectDir, { body, answer, refetch = null, take = null, now = new Date() }) {
return withRunsLock(async () => {
const doc = await readFetchRuns(projectDir);
const summary = summarizeAnswer(answer);
@@ -382,6 +397,7 @@ export function recordFetchRun(projectDir, { body, answer, refetch = null, now =
jobIds: summary.jobs.map((j) => j.jobId),
summary,
...(refetch ? { refetch } : {}),
+ ...(take ? { take } : {}),
};
doc.runs.push(run);
doc.runs = doc.runs.slice(-FETCH_RUNS_KEPT);
@@ -407,8 +423,12 @@ export function recordJobOutcome(projectDir, jobId, { status, platform = null, f
});
}
-/** The newest run that started jobs, or null. */
-export const lastStartedRun = (doc) => [...(doc?.runs ?? [])].reverse().find((r) => !r.dryRun && r.jobIds?.length) ?? null;
+/**
+ * The newest run that started jobs, or null: of the cut (no `take`), or of
+ * that take -- a take's run is never read as the cut's last, nor the other way.
+ */
+export const lastStartedRun = (doc, { take = null } = {}) =>
+ [...(doc?.runs ?? [])].reverse().find((r) => !r.dryRun && r.jobIds?.length && (r.take ?? null) === (take ?? null)) ?? null;
/**
* Follow a run's jobs once: each job not yet recorded as ended is asked for its
diff --git a/umtool/lib/report/prepCli.mjs b/umtool/lib/report/prepCli.mjs
@@ -4,6 +4,8 @@
// umtool prep <project> [--clips a,b] [--json] queue it; a runner starts in the background
// umtool prep <project> [--clips a,b] --wait run it here and wait (the same runner, niced)
// umtool prep <project> --status [--json] what is ready, what is not, the runner if one is alive
+// … --take <id> a TAKE's clips (its walk's manifest -- a draft's too),
+// its own status, queue and runner
//
// `--run` is the runner itself (what the queue starts): it takes the
// project's run lock and drains the queue, one clip at a time, each in the
@@ -25,6 +27,8 @@ export const PREP_USAGE = [
"usage: umtool prep <project> [--clips a,b] [--json] queue the clips' excerpts and waveforms for the walk; returns at once",
" umtool prep <project> [--clips a,b] --wait the same, here, until it is done",
" umtool prep <project> --status [--json] ready / to prepare / not fetched, and the runner",
+ " … --take <id> a take's clips instead of the cut's: the take's manifest as its walk reads it (a draft's",
+ " too, nothing rendered), its own status, queue and runner (out/bench-excerpts/takes/<id>/)",
"",
"One clip at a time, each in the heavy slot (estimate " + PREP_ESTIMATE_MB + " MB), under nice -n 19 and ionice -c3.",
"A clip already prepared (its excerpt cut from its recording as it is now, its waveform cached) is skipped.",
@@ -42,13 +46,14 @@ export function stateLine(s) {
const cur = s.runner.current;
parts.push(`preparing ${Math.min(s.runner.done + 1, s.runner.total)} of ${s.runner.total}${cur ? ` — ${cur.id}, ${cur.step === "waiting" ? "waiting for the heavy slot" : cur.step}` : ""} (pid ${s.runner.pid})`);
}
- return `${s.project}: ${parts.join(" · ")}`;
+ return `${s.project}${s.take ? ` take ${s.take}` : ""}: ${parts.join(" · ")}`;
}
const stamp = () => new Date().toISOString().slice(11, 19);
/** The runner's progress as lines (stderr, and prep.log when it runs detached). */
export function eventLine(project, ev) {
+ if (ev.ev === "start" && ev.take) project = `${project} take ${ev.take}`;
switch (ev.ev) {
case "start":
return `${stamp()} prep ${project}: ${ev.total} to prepare (${ev.ready} ready${ev.noWindow ? `, ${ev.noWindow} not fetched` : ""})`;
@@ -76,10 +81,18 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
const json = args.includes("--json");
const words = [];
let clips = null;
+ let take = null;
for (let i = 0; i < args.length; i += 1) {
if (args[i] === "--clips") {
clips = String(args[i + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
i += 1;
+ } else if (args[i] === "--take") {
+ take = String(args[i + 1] ?? "");
+ i += 1;
+ if (!take || take.startsWith("--")) {
+ err(`--take needs a take id\n${PREP_USAGE}`);
+ return 2;
+ }
} else if (!args[i].startsWith("--")) words.push(args[i]);
}
const [projectArg] = words;
@@ -97,12 +110,23 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
return 1;
}
const project = { id: r.project.id, dir: r.project.dir };
+ if (take) {
+ // The take must resolve (recorded, or named by a recipe), before anything is queued.
+ try {
+ const { prepManifestOf } = await import("./benchPrep.mjs");
+ await prepManifestOf(project, take);
+ } catch (e) {
+ err(`${project.id}: ${e instanceof Error ? e.message : String(e)}`);
+ return 1;
+ }
+ }
// ---- the runner ----------------------------------------------------------
if (args.includes("--run")) {
const ndjson = args.includes("--ndjson");
const { withRenderSlot } = await import("../../report-to-video/heavy-gate.mjs");
const res = await drainPrepQueue(project, {
+ take,
initial: args.includes("--wait") ? { clips, retry: args.includes("--retry") } : null,
wait: args.includes("--wait"),
slot: (cmd, fn) => withRenderSlot(cmd, fn, { estimateMb: PREP_ESTIMATE_MB }),
@@ -115,7 +139,7 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
}
if (args.includes("--status")) {
- const s = await benchPrepState(project, { clips });
+ const s = await benchPrepState(project, { clips, take });
if (json) out(JSON.stringify(s, null, 2));
else {
out(stateLine(s));
@@ -126,7 +150,7 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
// ---- --wait: the runner, here --------------------------------------------
if (args.includes("--wait")) {
- const argv = runnerArgv(project.id, { wait: true, clips, retry: true });
+ const argv = runnerArgv(project.id, { wait: true, clips, retry: true, take });
const code = await new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: UMTOOL_DIR, stdio: ["ignore", "inherit", "inherit"], env: process.env });
child.on("error", (e) => {
@@ -135,20 +159,20 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons
});
child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1)));
});
- const s = await benchPrepState(project, { clips });
+ const s = await benchPrepState(project, { clips, take });
if (json) out(JSON.stringify(s, null, 2));
else out(stateLine(s));
return Number(code) === 0 ? 0 : 1;
}
// ---- queue it --------------------------------------------------------------
- const q = await queueBenchPrep(project, clips, { retry: true });
- const s = await benchPrepState(project, { clips });
+ const q = await queueBenchPrep(project, clips, { retry: true, take });
+ const s = await benchPrepState(project, { clips, take });
if (json) out(JSON.stringify({ ...s, queued: q.queued, started: q.started, pid: q.pid, ...(q.off ? { off: true } : {}) }, null, 2));
else {
out(stateLine(s));
if (q.off) out(" UMTOOL_BENCH_PREP=0: nothing queued");
- else if (q.queued.length) out(` queued ${q.queued.length}: ${q.started ? `runner started (pid ${q.pid})` : `the runner already going takes them (pid ${q.pid})`}; its log is out/bench-excerpts/prep.log`);
+ else if (q.queued.length) out(` queued ${q.queued.length}: ${q.started ? `runner started (pid ${q.pid})` : `the runner already going takes them (pid ${q.pid})`}; its log is out/bench-excerpts/${take ? `takes/${take}/` : ""}prep.log`);
else out(" nothing to prepare");
}
return 0;
diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs
@@ -46,6 +46,7 @@ import {
replaceManifest,
} from "./manifest.mjs";
import { withEditNotes } from "./edit-guard.mjs";
+import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
import { resolveTakeManifest } from "./takeManifest.mjs";
import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs";
import { stampOf } from "./snapshots.mjs";
@@ -188,7 +189,7 @@ async function editTakeTimeline(projectDir, id, op, token, mutate, { now = new D
*/
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(
+ const r = await editTakeTimeline(
projectDir,
id,
edit === "trim" ? "clip" : edit,
@@ -196,6 +197,9 @@ export async function updateTakeClip(projectDir, id, clipId, patch, { token = nu
(m) => patchClipEntry(m, clipId, patch, { edit, now: now.toISOString(), dir: projectDir }),
{ now },
);
+ // A moved extent may need a new bench excerpt -- the take's (its own prep): queued, never waited for.
+ if (r.entry?.start !== r.before?.start || r.entry?.end !== r.before?.end) benchPrepAfterWrite(projectDir, [clipId], { take: id });
+ return r;
}
/**
diff --git a/umtool/lib/scaffold-folder.test.mjs b/umtool/lib/scaffold-folder.test.mjs
@@ -0,0 +1,76 @@
+// `umtool new <folder>/<slug>` and `umtool new <slug> --folder <folder>`: a
+// project made inside a folder of the reports tree, its id the path under the
+// root, routed as walkProjects routes it (2 Nov: `umtool new
+// emberparadox/kirsche` refused "will not route", and the way in was
+// REPORTS_DIR=<folder>).
+//
+// Run with: pnpm test:scripts
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { projectPlace, scaffoldReportVideo } from "./projects/scaffold.mjs";
+import { walkProjects } from "./projects/walk.mjs";
+
+const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "bin", "umtool.mjs");
+
+test("folder/slug and --folder both make <folder>/<slug>, an id that routes and lists in its folder", async (t) => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-new-folder-"));
+ t.after(() => rm(tmp, { recursive: true, force: true }));
+ const root = path.join(tmp, "reports");
+ // The parent: a project already in the folder.
+ const r1 = await scaffoldReportVideo({ root, slug: "emberparadox/in-her-words", channelsDir: path.join(tmp, "channels") });
+ assert.equal(r1.id, "emberparadox/in-her-words");
+ assert.equal(r1.folder, "emberparadox");
+ assert.equal(r1.dir, path.join(root, "emberparadox", "in-her-words"));
+ const r2 = await scaffoldReportVideo({ root, slug: "kirsche", folder: "emberparadox", channelsDir: path.join(tmp, "channels") });
+ assert.equal(r2.id, "emberparadox/kirsche");
+ assert.equal(r2.dir, path.join(root, "emberparadox", "kirsche"));
+ const doc = JSON.parse(await readFile(path.join(r2.dir, "video.manifest.json"), "utf8"));
+ assert.equal(doc.slug, "kirsche", "the manifest's slug is the project's own name");
+ const listed = await walkProjects(root);
+ assert.deepEqual(
+ listed.map((p) => [p.id, p.folder, p.routing]),
+ [
+ ["emberparadox/in-her-words", "emberparadox", "ok"],
+ ["emberparadox/kirsche", "emberparadox", "ok"],
+ ],
+ );
+ // A flat slug is as it was.
+ const r3 = await scaffoldReportVideo({ root, slug: "flat-one", channelsDir: path.join(tmp, "channels") });
+ assert.equal(r3.id, "flat-one");
+ assert.equal(r3.folder, undefined);
+ await assert.rejects(scaffoldReportVideo({ root, slug: "emberparadox/kirsche", channelsDir: path.join(tmp, "channels") }), /already exists/);
+});
+
+test("what will not route is refused before anything is written", async (t) => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-new-folder-"));
+ t.after(() => rm(tmp, { recursive: true, force: true }));
+ const root = path.join(tmp, "reports");
+ await assert.rejects(projectPlace(root, "Kirsche", "emberparadox"), /will not route/);
+ await assert.rejects(projectPlace(root, "kirsche", "../out"), /will not route/);
+ await assert.rejects(projectPlace(root, "kirsche", ".hidden"), /will not route/);
+ await assert.rejects(projectPlace(root, "at/kirsche"), /reserved/);
+ await assert.rejects(projectPlace(root, "a/b/c/d/e"), /levels deep/);
+ // Inside a project: a project is a leaf, so the new one would never be listed.
+ await mkdir(path.join(root, "parent"), { recursive: true });
+ await writeFile(path.join(root, "parent", "video.manifest.json"), "{}\n");
+ await assert.rejects(projectPlace(root, "parent/child"), /is a project, not a folder/);
+ assert.deepEqual(await projectPlace(root, "/a/b/"), { id: "a/b", slug: "b", folder: "a" });
+ assert.deepEqual(await projectPlace(root, "c", "a/b"), { id: "a/b/c", slug: "c", folder: "a/b" });
+ assert.equal(await stat(path.join(root, "a")).then(() => true, () => false), false);
+});
+
+test("the CLI: umtool new <folder>/<slug> and --folder print the project's id in their next steps", async (t) => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-new-folder-"));
+ t.after(() => rm(tmp, { recursive: true, force: true }));
+ const env = { ...process.env, REPORTS_DIR: path.join(tmp, "reports"), CHANNELS_DIR: path.join(tmp, "channels"), UMTOOL_CACHE_DIR: path.join(tmp, "cache") };
+ const a = JSON.parse(execFileSync(process.execPath, [CLI, "new", "emberparadox/kirsche", "--json"], { env, encoding: "utf8" }));
+ assert.equal(a.id, "emberparadox/kirsche");
+ const b = execFileSync(process.execPath, [CLI, "new", "kirsche-2", "--folder", "emberparadox"], { env, encoding: "utf8" });
+ assert.match(b, /umtool check emberparadox\/kirsche-2/);
+ assert.ok((await stat(path.join(tmp, "reports", "emberparadox", "kirsche-2", "video.manifest.json"))).isFile());
+});