// FORK A TAKE AS A VARIANT, and the takes of a project's variants side by // side (UI notes 2026-10-30, item 19: "variants as separate project copies" // -- `emberparadox/v-a-cold-open` … `v-d-bookends`, each copied by hand from // the walked cut, a README saying what it was). // // HOW A VARIANT IS STORED, as those were: a project of its own BESIDE its // parent (a project is a leaf of the walk, lib/projects/walk.mjs, so it // cannot sit inside one), so every tool -- the walk, the cut, takes, Deliver // -- works on it unchanged. What the fork adds is the record the hand copies // carried only in prose: // // //video.manifest.json the take's manifest (the one it was // rendered from; a draft's, resolved), // its `slug` the variant's name // //variant.json { variantOf, fromTake, takeLabel, // forkedAt, baseHash } -- what makes it // a variant of , and of which take // //README.md the hand copies' sentence, written // //out/clips-raw, LINKS to the parent's (a take's own // out/narration out/ links them the same way): the // fetched media is reused, never copied // // a link to the parent's, for each of its // top-level files or folders the manifest // names by a relative path (shots/, posts- // media/ …), so those paths still resolve; // module-config.json is COPIED (a variant's // modules are its own to change) // //takes// the take itself, its preview a HARD // LINK (no copy of the bytes), its // take.json naming where it came from -- // so the variant opens with the take it // was forked from, already rendered // // Refused: a take that is rendering now (its manifest is being written), a // name that is not one path segment or is already taken. // // `variantFamily` reads it back: the parent and every project beside it whose // variant.json names it -- whose takes the compare page lays side by side. // // Plain ESM: the CLI runs it under bare node. import { copyFile, link, lstat, mkdir, readdir, readFile, rename, stat, symlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { isSegment, sharedWalk } from "../projects/walk.mjs"; import { renderHolds } from "./takeHousekeeping.mjs"; import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs"; import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const VARIANT_FILE = "variant.json"; /** Copied, never linked: what a variant may change of its own. */ const COPIED = ["module-config.json"]; /** Never linked or copied: the project's own state. */ const OWN = new Set(["out", "takes", "revisions", "exports", "notes.json", MANIFEST, VARIANT_FILE, "README.md", ...COPIED]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); const exists = (p) => lstat(p).then(() => true, () => false); async function writeAtomic(file, text) { const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } export class ForkRefused extends Error { /** @param {string} message @param {number} [status] */ constructor(message, status = 409) { super(message); this.status = status; } } /** A project's variant.json, checked, or null. */ export async function readVariant(dir) { const v = await readJson(path.join(dir, VARIANT_FILE)); return isObj(v) && typeof v.variantOf === "string" && v.variantOf ? v : null; } /** The default name for a fork of `take`: `v-`. */ export const defaultVariantName = (take) => `v-${take}`.slice(0, 64); /** * Every relative path a manifest names whose first segment is an entry of the * project directory (`shots/x.png` → `shots`), the project's own state left out. * * @param {unknown} manifest * @param {Set} entries the project directory's entries */ export function referencedAssets(manifest, entries) { const out = new Set(); const walk = (v) => { if (typeof v === "string") { if (!v || v.length > 512 || path.isAbsolute(v) || /^[a-z]+:\/\//i.test(v) || v.includes("..")) return; const first = v.split(/[\\/]/)[0]; if (first && entries.has(first) && !OWN.has(first)) out.add(first); return; } if (Array.isArray(v)) for (const x of v) walk(x); else if (isObj(v)) for (const x of Object.values(v)) walk(x); }; walk(manifest); return [...out].sort(); } /** * Fork take `takeId` of `project` as a variant: a project beside it (see the header). * * @param {{ id: string, dir: string }} project * @param {string} takeId * @param {{ name?: string | null, now?: () => Date }} [opts] * @returns {Promise<{ id: string, dir: string, name: string, take: { id: string, linked: boolean } | null, links: string[], copied: string[], variant: Record }>} */ export async function forkTakeAsVariant(project, takeId, { name = null, now = () => new Date() } = {}) { if (!isTakeId(takeId)) throw new ForkRefused("not a take id", 400); const listing = await listTakes(project.dir); const take = listing.takes.find((t) => t.id === takeId); if (!take) throw new ForkRefused(`${project.id} has no take ${takeId}`, 404); const holds = (await renderHolds(project.dir, takeId)).filter((h) => h.startsWith("it is rendering")); if (holds.length) throw new ForkRefused(`take ${takeId} is not forked: ${holds[0]}`); const vname = String(name ?? "").trim() || defaultVariantName(takeId); if (!isSegment(vname) || vname.length > 64) throw new ForkRefused(`"${vname}" is not a project name: letters, digits, . _ - (one segment)`, 400); const parentDir = path.dirname(project.dir); const dir = path.join(parentDir, vname); if (await exists(dir)) throw new ForkRefused(`${vname} exists beside ${project.id} — name the variant something else`); const folder = path.posix.dirname(project.id); const id = folder === "." ? vname : `${folder}/${vname}`; // The take's manifest: the one it was rendered from, else (a draft) resolved from its patch. const takeDir = path.join(takesDirOf(project.dir), takeId); let manifest = await readJson(path.join(takeDir, MANIFEST)); if (!isObj(manifest)) { const { resolveTakeManifest } = await import("./takeManifest.mjs"); manifest = (await resolveTakeManifest(project.dir, takeId)).manifest; } if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new ForkRefused(`take ${takeId} has no manifest to fork`, 422); const doc = { ...manifest, slug: vname }; const text = JSON.stringify(doc, null, 2) + "\n"; await mkdir(dir); await writeAtomic(path.join(dir, MANIFEST), text); const variant = { variantOf: project.id, fromTake: takeId, takeLabel: take.label, forkedAt: now().toISOString(), baseHash: hashText(text), }; await writeAtomic(path.join(dir, VARIANT_FILE), JSON.stringify(variant, null, 2) + "\n"); await writeAtomic( path.join(dir, "README.md"), `# ${vname}\n\nA variant of \`${project.id}\`, forked ${variant.forkedAt.slice(0, 10)} from its take \`${takeId}\` (${take.label}).\n` + `Its manifest is that take's; its clips' media is the parent's (out/clips-raw is a link).\n`, ); // The fetched media and the voices, linked as a take's out/ links them. const links = []; await mkdir(path.join(dir, "out"), { recursive: true }); for (const n of SHARED_OUT) { const src = path.join(project.dir, "out", n); if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue; await symlink(src, path.join(dir, "out", n)); links.push(`out/${n}`); } // The project's files the manifest names by a relative path, linked; its own config copied. const entries = new Set(await readdir(project.dir).catch(() => [])); for (const seg of referencedAssets(doc, entries)) { await symlink(path.join(project.dir, seg), path.join(dir, seg)); links.push(seg); } const copied = []; for (const n of COPIED) { if (!entries.has(n)) continue; await copyFile(path.join(project.dir, n), path.join(dir, n)); copied.push(n); } // The take itself: its preview hard-linked (a rendered take), its manifest and take.json beside it. let forkedTake = null; const preview = path.join(takeDir, take.preview || PREVIEW); if (!take.draft && (await stat(preview).then((s) => s.isFile(), () => false))) { const dst = path.join(takesDirOf(dir), takeId); await mkdir(dst, { recursive: true }); let linked = true; try { await link(preview, path.join(dst, PREVIEW)); } catch { linked = false; } if (linked) { await writeAtomic(path.join(dst, MANIFEST), text); const raw = (await readJson(path.join(takeDir, TAKE_FILE))) ?? {}; const tj = { ...raw, id: takeId, preview: PREVIEW, // The variant's manifest IS this take's: nothing patched over it. kind: "reference", patch: null, style: null, changes: [], baseHash: variant.baseHash, forkedFrom: { project: project.id, take: takeId }, }; delete tj.draft; await writeAtomic(path.join(dst, TAKE_FILE), JSON.stringify(tj, null, 2) + "\n"); } forkedTake = { id: takeId, linked }; } return { id, dir, name: vname, take: forkedTake, links, copied, variant }; } /** * A project's variant family: its parent (itself, when it is no variant) and * every project beside the parent whose variant.json names it, each with its * takes. `self` is the project asked about. * * @param {{ id: string, dir: string }} project * @param {{ root: string }} o the reports root (the walk) * @returns {Promise<{ parent: string, members: Array<{ id: string, dir: string, variantOf: string | null, fromTake: string | null, takeLabel: string | null, forkedAt: string | null, takes: Array> }> }>} */ export async function variantFamily(project, { root }) { const own = await readVariant(project.dir); const parentId = own?.variantOf ?? project.id; const all = await sharedWalk(root, { since: Date.now() }); const parent = all.find((p) => p.id === parentId) ?? null; const folder = path.posix.dirname(parentId); const beside = all.filter((p) => path.posix.dirname(p.id) === folder); const members = []; for (const p of beside) { const v = p.id === parentId ? null : await readVariant(p.dir); if (p.id !== parentId && v?.variantOf !== parentId) continue; const listing = await listTakes(p.dir).catch(() => ({ takes: [] })); members.push({ id: p.id, dir: p.dir, variantOf: v?.variantOf ?? null, fromTake: typeof v?.fromTake === "string" ? v.fromTake : null, takeLabel: typeof v?.takeLabel === "string" ? v.takeLabel : null, forkedAt: typeof v?.forkedAt === "string" ? v.forkedAt : null, takes: listing.takes, }); } // The parent first, then its variants by name. members.sort((a, b) => (a.id === parentId ? -1 : b.id === parentId ? 1 : a.id.localeCompare(b.id))); return { parent: parent ? parentId : parentId, members }; }