// A TAKE'S PREP (`umtool prep
--take `, 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}` : ""}`);
}
});