// THE WORKING DRAFT AND ITS SAVED VERSIONS (umtool redesign, lane L3; operator, // 1 Nov 2026: "Most of the time I'll only really be working on the latest // cut/draft rather than the picked one"). // // The project's video.manifest.json IS the draft: every UI edit lands in it. // A take is a SAVED VERSION of it, frozen: // // takes//base.manifest.json the draft as it was, byte for byte -- the // version resolves over THIS, never over the // draft as it is now (takeManifest.mjs) // takes//take.json `version: true, draft: true, patch: null, // window: "full"`, its baseHash the base's // takes/draft.json the draft's PARENT `{ from, hash, at }`: the // version it was last saved as or opened from // (a file, so listTakes never lists it) // // saveVersion(project, { label }) the draft frozen as the next `v` // openVersion(project, id) a version copied INTO the draft -- the // draft saved first when it has edits // since its parent, one undo point // freezeTakes(project, { apply }) legacy takes given a frozen base // (opt-in, a dry run by default) // // VERSION IDS are `v1`, `v2`, … -- the next number above every `v` // directory under takes/ (made or not), so a name is never reused and never // collides with a take an agent named by hand. // // Both writers hold the MANIFEST LOCK (manifest.mjs withManifestLock), the one // every manifest write takes in this process, so a save and an open are each // one step against the bench's edits; across processes the token is the guard. // // Plain ESM: `umtool takes save|open|freeze` runs it under bare node. import { createHash } from "node:crypto"; import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { applyStructural, manifestToken, replaceManifestLocked, StaleToken, withManifestLock } from "./manifest.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { BASE_FILE, DRAFT_FILE, frozenBaseText, isTakeId, listTakes, readDraftFile, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { readWorkingCut } from "./workingCut.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const MANIFEST = "video.manifest.json"; export const VERSION_RE = /^v(\d{1,6})$/; const hashText = (text) => createHash("sha256").update(text).digest("hex"); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); export class VersionRefused extends Error { /** @param {string} message */ constructor(message) { super(message); this.name = "VersionRefused"; } } /** The draft's parent pointer (takes/draft.json), or null. */ export const readDraft = readDraftFile; /** * Write takes/draft.json (tmp + rename). `from` null removes it. `base`: the * manifest an open wrote when the version opened has no frozen form of its * own (a legacy take merged) -- what the draft's edits are counted from. * @param {string} projectDir * @param {{ from: string | null, hash?: string | null, at?: string | null, base?: Record | null }} d */ export async function writeDraft(projectDir, { from, hash = null, at = null, base = null }) { const file = path.join(takesDirOf(projectDir), DRAFT_FILE); if (!from) { await rm(file, { force: true }); return null; } if (!isTakeId(from)) throw new Error(`"${from}" is not a take id`); await mkdir(path.dirname(file), { recursive: true }); const doc = { from, hash, at: at ?? new Date().toISOString(), ...(base ? { base } : {}) }; const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); return doc; } /** * Every version number in use or ever pointed at: each `v` directory under * takes/ (made or not), the draft pointer's `from`, and each undo point's * pointer sidecar (revisions/*.draft.json) -- so a version deleted while an * Undo could still name it as the draft's parent is never reborn as another. */ async function usedVersionNumbers(projectDir) { const nums = new Set(); const add = (id) => { const m = VERSION_RE.exec(String(id ?? "")); if (m) nums.add(Number(m[1])); }; for (const x of await readdir(takesDirOf(projectDir)).catch(() => [])) add(x); add((await readDraftFile(projectDir))?.from); const rev = path.join(projectDir, "revisions"); for (const x of await readdir(rev).catch(() => [])) { if (!x.endsWith(".draft.json")) continue; add(await readFile(path.join(rev, x), "utf8").then((t) => JSON.parse(t)?.from, () => null)); } return nums; } /** The next free version id: `v` over every version number in use or ever pointed at (usedVersionNumbers). */ export async function nextVersionId(projectDir) { const used = await usedVersionNumbers(projectDir); return `v${Math.max(0, ...used) + 1}`; } /** * CLAIM the next version id: its directory made with a non-recursive mkdir, * which only one process can win -- on EEXIST (another process, the CLI beside * the app, took it first) the next number is tried. Returns the id and its dir. */ export async function claimVersionId(projectDir) { const root = takesDirOf(projectDir); await mkdir(root, { recursive: true }); let n = Math.max(0, ...(await usedVersionNumbers(projectDir))) + 1; for (;;) { const dir = path.join(root, `v${n}`); try { await mkdir(dir); return { id: `v${n}`, dir }; } catch (e) { if (/** @type {any} */ (e)?.code !== "EEXIST") throw e; n += 1; } } } async function writeAtomic(file, text) { const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } /** * saveVersion's body, inside the manifest lock: the draft's text copied byte * for byte to takes//base.manifest.json, then take.json (LAST: until then * the directory is a work dir the listing ignores), then draft.json. * * @param {string} projectDir * @param {{ label?: string | null, now?: Date, force?: boolean, why?: string | null }} opts */ async function saveVersionLocked(projectDir, { label = null, now = new Date(), force = false, why = null } = {}) { const text = await readFile(path.join(projectDir, MANIFEST), "utf8").catch(() => null); if (text === null) throw new VersionRefused(`the project has no ${MANIFEST} to save`); try { if (!isObj(JSON.parse(text))) throw new Error("not an object"); } catch (e) { throw new VersionRefused(`${MANIFEST} does not parse; not saving it (${e instanceof Error ? e.message : e})`); } const working = await readWorkingCut(projectDir, { manifestText: text }); if (!force && working.parent && working.edits?.count === 0) { return { saved: false, id: working.parent.id, why: `no edits since ${working.parent.id}: nothing to save`, edits: working.edits, parent: working.parent.id }; } const { id, dir } = await claimVersionId(projectDir); const { takes } = await listTakes(projectDir); const parentTake = working.parent ? takes.find((t) => t.id === working.parent?.id) : null; const group = parentTake?.group ?? takes.filter((t) => t.window === "full").at(-1)?.group ?? "takes"; const order = Math.max(0, ...takes.map((t) => t.order)) + 1; const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim().slice(0, 200) : ""; const iso = now.toISOString(); const baseHash = hashText(text); await writeAtomic(path.join(dir, BASE_FILE), text); const doc = { id, group, order, label: l || (why ? why : working.parent ? `Saved draft (from ${working.parent.id})` : "Saved draft"), kind: "reference", summary: "", changes: working.edits?.words?.length ? working.edits.words.slice(0, 40) : [], preview: "preview.mp4", seconds: null, builtAt: null, style: null, patch: null, window: "full", version: true, draft: true, draftedAt: iso, savedAt: iso, baseHash, ...(working.parent ? { draftedFrom: working.parent.id } : {}), }; await writeAtomic(path.join(dir, TAKE_FILE), JSON.stringify(doc, null, 2) + "\n"); await writeDraft(projectDir, { from: id, hash: baseHash, at: iso }); return { saved: true, id, label: doc.label, edits: working.edits, parent: working.parent?.id ?? null, baseHash }; } /** * SAVE THE DRAFT AS A VERSION: the next `v`, frozen. Nothing is saved when * the draft has no edits since its parent (`saved: false`, naming it) unless * `force`. The pick (verdicts.json) is never touched: saving never unpins. * * @param {{ id: string, dir: string }} project * @param {{ label?: string | null, now?: Date, force?: boolean }} [opts] */ export async function saveVersion(project, { label = null, now = new Date(), force = false } = {}) { return withManifestLock(() => saveVersionLocked(project.dir, { label, now, force })); } /** * What the walk and the review pass write on an entry: a verdict and its words, a walk note, the ★. A draft that * differs from its parent only in these is still that version, for its verdict (judgeDraft). */ export const REVIEW_FIELDS = ["verdict", "correction", "reason", "rejectNote", "walkNote", "star"]; /** A manifest with the review fields taken off every timeline entry (a copy). */ export function withoutReviewFields(m) { const out = JSON.parse(JSON.stringify(m ?? {})); if (Array.isArray(out.timeline)) for (const e of out.timeline) if (isObj(e)) for (const k of REVIEW_FIELDS) delete e[k]; return out; } /** * THE REVIEW PASS'S VERDICT ON THE DRAFT (umtool redesign L7b), one locked call: a verdict is a version's, so -- * the draft differs from its parent version ONLY in what the walk and the review pass write (REVIEW_FIELDS): * it IS that version -- the parent is judged, nothing saved; * else (or no parent): the draft is saved as the next version (saveVersionLocked; at no edits at all that is * the parent again, nothing saved) and that version is judged. * A clear (null) never saves: it clears the parent's when the draft is that version, else it is refused. * Returns `{ judged, saved, entry }`: which version took the verdict, and whether one was saved for it. * * @param {{ id: string, dir: string }} project * @param {"like" | "maybe" | "no" | null} verdict null clears it * @param {{ note?: string, now?: Date }} [o] */ export async function judgeDraft(project, verdict, { note, now = new Date() } = {}) { const { setTakeVerdict } = await import("./takes.mjs"); const { versionManifestOf } = await import("./takeMaker.mjs"); return withManifestLock(async () => { const text = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null); if (text === null) throw new VersionRefused(`the project has no ${MANIFEST}`); const working = await readWorkingCut(project.dir, { manifestText: text }); if (working.parent) { const v = await versionManifestOf(project.dir, working.parent.id).catch(() => null); if (v && sameContent(withoutReviewFields(JSON.parse(text)), withoutReviewFields(v.manifest))) { const r = await setTakeVerdict(project.dir, working.parent.id, { verdict, ...(note !== undefined ? { note } : {}) }); return { judged: working.parent.id, saved: false, entry: r.entry }; } } // A clear has nothing to save for: a version is saved FOR a verdict, never for taking one away. The draft that // is not its parent has no verdict to clear (re-review should-fix 3, 10 Nov). if (verdict === null) { if (working.parent && working.edits?.count === 0) { const r = await setTakeVerdict(project.dir, working.parent.id, { verdict: null, ...(note !== undefined ? { note } : {}) }); return { judged: working.parent.id, saved: false, entry: r.entry }; } throw new VersionRefused( working.parent ? `the draft has edits since ${working.parent.id}: it is not a version, so it has no verdict to clear (clear a version's with umtool takes verdict

clear)` : "the draft has never been saved as a version: it has no verdict to clear", ); } const s = await saveVersionLocked(project.dir, { now, why: "Saved for its verdict (the review pass)" }); const r = await setTakeVerdict(project.dir, s.id, { verdict, ...(note !== undefined ? { note } : {}) }); return { judged: s.id, saved: !!s.saved, entry: r.entry }; }); } /** * What opening take `id` would write into the draft, and how: * "frozen" a saved version: its base (with any patch laid over it since) * "rendered" a legacy rendered take of the cut's own timeline: the manifest it was * rendered from (pickTake's copy, "Use this take") * "merge" a legacy take with a timeline of its own, or one never rendered: its * patch over the draft as it is now (promoteTake's merge) -- so a walk * made since its render is what opens * * @param {string} projectDir * @param {string} id * @param {Record} draft the draft, parsed */ export async function openedManifestOf(projectDir, id, draft) { const { loadMontageStyles, mergePatch, versionManifestOf } = await import("./takeMaker.mjs"); const v = await versionManifestOf(projectDir, id); if (v) return { manifest: v.manifest, how: /** @type {const} */ ("frozen") }; const { takeSpecOf } = await import("./takeManifest.mjs"); const spec = await takeSpecOf(projectDir, id); if (!spec) throw new VersionRefused(`no take ${id}`); if (!spec.made) throw new VersionRefused(`take ${id} is only named by a recipe — nothing made to open`); const ownTimeline = isObj(spec.patch) && Array.isArray(spec.patch.timeline); const doc = JSON.parse(await readFile(path.join(takesDirOf(projectDir), id, TAKE_FILE), "utf8")); // The manifest it rendered is what it IS only while its patch has not been edited since the render (a walk, // a CLI take-scoped edit: `editedAt` after `builtAt`) -- Play ?take= plays the patch, so the open merges it. const editedSince = typeof doc.editedAt === "string" && doc.editedAt && !(typeof doc.builtAt === "string" && doc.builtAt && doc.editedAt <= doc.builtAt); const renderedText = doc.draft === true || editedSince ? null : await readFile(path.join(takesDirOf(projectDir), id, MANIFEST), "utf8").catch(() => null); const rendered = renderedText !== null ? JSON.parse(renderedText) : null; // NEVER a preset resolved into the draft: the rendered file has its preset laid in (presetApplied); it goes // back to naming it, as the draft did (unresolvePreset), so the draft keeps following its preset. if (!ownTimeline && isObj(rendered) && Array.isArray(rendered.timeline)) return { manifest: await unresolvePreset(rendered), how: /** @type {const} */ ("rendered") }; // The take's style and patch merged over the draft as it is (promoteTake's merge) -- RFC 7386 only, the // draft's `preset` left named, never resolved. let stylePatch = null; if (spec.style) { stylePatch = (await loadMontageStyles()).styles[spec.style]?.patch ?? null; if (!stylePatch) { if (isObj(rendered) && Array.isArray(rendered.timeline)) return { manifest: await unresolvePreset(rendered), how: /** @type {const} */ ("rendered") }; throw new VersionRefused(`take ${id}: its style "${spec.style}" is not installed, and it has no rendered manifest`); } } const merged = [stylePatch, spec.patch].filter(Boolean).reduce((m, p) => mergePatch(m, p), draft); if (!isObj(merged) || !Array.isArray(merged.timeline)) throw new VersionRefused(`take ${id}: the patched manifest has no timeline`); // The build's structure rules, over the draft becoming the take's (promoteTake's check). const next = JSON.parse(JSON.stringify(draft)); applyStructural(next, (m) => { for (const k of Object.keys(m)) delete m[k]; Object.assign(m, JSON.parse(JSON.stringify(merged))); }); return { manifest: next, how: /** @type {const} */ ("merge") }; } /** * A manifest with its preset RESOLVED (resolvePresetLayers: `preset` deleted, `presetApplied` set, the * preset's render keys laid in) back to NAMING it: `preset` again, and every render leaf whose value is the * preset's own taken out (the preset puts it back). It resolves to what it was; an override stays. A manifest * not resolved is returned as it is. * * @param {Record} m */ export async function unresolvePreset(m) { if (!isObj(m) || typeof m.presetApplied !== "string" || !m.presetApplied) return m; const { loadPreset } = await import("umtool-report-to-video/presets"); let preset; try { preset = loadPreset(m.presetApplied); } catch { return m; // a preset gone: the resolved manifest is all there is } const strip = (node, pre) => { for (const k of Object.keys(pre)) { if (!(k in node)) continue; if (isObj(pre[k]) && isObj(node[k])) { strip(node[k], pre[k]); if (!Object.keys(node[k]).length) delete node[k]; } else if (sameContent(node[k], pre[k])) delete node[k]; } }; const { presetApplied, ...rest } = JSON.parse(JSON.stringify(m)); const out = { preset: presetApplied, ...rest }; if (isObj(out.render) && isObj(preset.render)) { strip(out.render, preset.render); if (!Object.keys(out.render).length) delete out.render; } return out; } /** Deep equality that ignores key order (a manifest written by another writer orders its keys its own way). */ export function sameContent(a, b) { const canon = (v) => (Array.isArray(v) ? v.map(canon) : isObj(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v); return JSON.stringify(canon(a)) === JSON.stringify(canon(b)); } /** * Would opening `id` write nothing? When the draft already holds what it is (by content), or -- main's rule * for a LEGACY take -- it is the draft's parent with no edits since (its rendered file is preset-resolved and * carries its look patch; the draft is the same cut, naming its preset). * * @param {string} projectDir * @param {string} id * @param {Record} draft * @param {Awaited>} working * @param {Record} opened what openedManifestOf would write */ async function noopOpen(projectDir, id, draft, working, opened) { if (sameContent(opened, draft)) return true; const legacy = (await frozenBaseText(projectDir, id)) === null; if (!legacy || working.parent?.id !== id || working.edits?.count !== 0) return false; // Opened before (the pointer keeps what that open wrote): the content says it, not the rule. const pointer = await readDraftFile(projectDir); return !(pointer?.from === id && pointer.base); } /** The undo point's sidecar: the draft pointer as it was before the write the snapshot takes back. */ export const draftSidecarOf = (snapshotRel) => snapshotRel.replace(/\.manifest\.json$/, ".draft.json"); /** * OPEN A VERSION IN THE DRAFT, under the manifest lock: * 1. the draft saved as the next version first when it has edits since its * parent (or has no parent at all) -- nothing in it is lost; * 2. the version's manifest written over the draft (openedManifestOf), through * the manifest writer with an undo point taken EVERY time (`every: 0`, * `auto-before-open-`; "Undo open " restores the draft as it was, * and the draft pointer beside it); * 3. takes/draft.json naming the opened version. * The pick and the pins (verdicts.json) are never touched: opening is not * "Use this take". Opening a version the draft already holds (by content) writes nothing; a write from another process since the start is a StaleToken, and a failed open removes the version it saved and puts the pointer back. * * @param {{ id: string, dir: string, kind?: string }} project * @param {string} id * @param {{ token?: string | null, now?: Date }} [opts] */ export async function openVersion(project, id, { token = null, now = new Date(), _beforeWrite = null } = {}) { if (!isTakeId(id)) throw new VersionRefused(`"${id}" is not a take id`); const run = () => withManifestLock(async () => { const current = await manifestToken(project.dir); if (token !== null && current !== token) throw new StaleToken(token, current); const { takes } = await listTakes(project.dir); if (!takes.some((t) => t.id === id)) throw new VersionRefused(`no take ${id} in this project`); const text = await readFile(path.join(project.dir, MANIFEST), "utf8"); const draft = JSON.parse(text); const working = await readWorkingCut(project.dir, { manifestText: text }); // What opening it would write, decided BEFORE anything is saved (a refusal leaves nothing behind). const { manifest, how } = await openedManifestOf(project.dir, id, draft); // Unchanged: the draft already holds what the version is, by content (a version's "No intro" since its // save is not; it opens) -- or a legacy take that is the draft's parent with no edits (main's rule). The // pointer is set when it named another. if (await noopOpen(project.dir, id, draft, working, manifest)) { if (working.parent?.id !== id || working.parent?.via !== "draft") { await writeDraft(project.dir, { from: id, hash: hashText(text), at: now.toISOString(), base: how === "frozen" ? null : draft }); } return { opened: id, how: "unchanged", saved: null, snapshot: null, token: current, unchanged: true, edits: 0 }; } const edits = working.edits?.count ?? null; const pointerBeforeSave = await readDraftFile(project.dir); let saved = null; // Nothing is lost when the draft IS a version's frozen base byte for byte (only that version's patch // differs since -- a "No intro"): no second, byte-identical copy of it. const parentBase = working.parent ? await frozenBaseText(project.dir, working.parent.id) : null; const openedBase = await frozenBaseText(project.dir, id); const kept = parentBase === text || openedBase === text; if (!kept && (!working.parent || working.edits === null || working.edits.count > 0)) { const r = await saveVersionLocked(project.dir, { now, force: true, why: `Draft before opening ${id}` }); saved = r.saved ? r.id : null; } const draftBefore = await readDraftFile(project.dir); const op = `open-${id}`.slice(0, 40).replace(/-+$/, ""); let r; try { if (_beforeWrite) await _beforeWrite(); // The token read at the start: a write from another process (the CLI) since is a StaleToken, never lost. r = await replaceManifestLocked(project.dir, manifest, { op, every: 0, token: current }); } catch (e) { // The open did not happen: no stray version, the draft named as it was. if (saved) await rm(path.join(takesDirOf(project.dir), saved), { recursive: true, force: true }).catch(() => {}); await writeDraft(project.dir, pointerBeforeSave ?? { from: null }).catch(() => {}); throw e; } // The undo point remembers the draft pointer, so Undo puts the parent back too (manifest.mjs undoStructural). const rel = /** @type {any} */ (r.snapshot)?.rel; if (rel && !(/** @type {any} */ (r.snapshot).skipped)) { await writeFile(path.join(project.dir, draftSidecarOf(rel)), JSON.stringify(draftBefore ?? { from: null }, null, 2) + "\n", "utf8").catch(() => {}); } const written = await readFile(path.join(project.dir, MANIFEST), "utf8"); // Not a frozen version: the draft's edits are counted from what was written (readWorkingCut). await writeDraft(project.dir, { from: id, hash: hashText(written), at: now.toISOString(), base: how === "frozen" ? null : JSON.parse(written) }); return { opened: id, how, saved, snapshot: r.snapshot, token: r.token, unchanged: false, edits, undo: `Undo open ${id}` }; }); // The generated-manifest guard, as every whole-manifest writer runs inside (edit-guard.mjs). if (project.kind) { const { result, editNotes } = await withEditNotes(/** @type {any} */ (project), run); return { ...result, editNotes }; } return run(); } /** Would opening `id` write nothing -- the draft already holds what it is? (OpenInDraftPage's straight-on.) */ export async function openIsNoop(projectDir, id) { try { const text = await readFile(path.join(projectDir, MANIFEST), "utf8"); const draft = JSON.parse(text); const { manifest } = await openedManifestOf(projectDir, id, draft); return await noopOpen(projectDir, id, draft, await readWorkingCut(projectDir, { manifestText: text }), manifest); } catch { return false; } } /** * FREEZE LEGACY TAKES (opt-in; a dry run unless `apply`): a take made before * versions follows the project's manifest as it is now (its patch over it). * Frozen, it gets a base of its own -- the manifest it was RENDERED from * (takes//video.manifest.json) when it has one, else the draft as it is * now -- and `version: true`; its style and patch stay, laid over the base. * Each row says what the take resolves to today against what it would * resolve to frozen (cutDiff, in words), so nothing changes unseen. * * @param {{ id: string, dir: string }} project * @param {{ ids?: string[] | null, apply?: boolean, now?: Date }} [opts] `ids` null: every take */ export async function freezeTakes(project, { ids = null, apply = false, now = new Date() } = {}) { return withManifestLock(async () => { const { takes, skipped } = await listTakes(project.dir); const { resolveTakeManifest } = await import("./takeManifest.mjs"); const { resolvePresetLayers } = await import("umtool-report-to-video/presets"); const { loadMontageStyles } = await import("./takeMaker.mjs"); const { cutDiff } = await import("./workingCut.mjs"); const draftText = await readFile(path.join(project.dir, MANIFEST), "utf8").catch(() => null); const wanted = ids ? takes.filter((t) => ids.includes(t.id)) : takes; const missing = ids ? ids.filter((x) => !takes.some((t) => t.id === x)) : []; /** @type {Array<{ id: string, action: "frozen" | "would-freeze" | "already" | "refused", source?: "rendered" | "draft", differs?: number, words?: string[], why?: string }>} */ const rows = []; let styles = null; for (const t of wanted) { if ((await frozenBaseText(project.dir, t.id)) !== null) { rows.push({ id: t.id, action: "already" }); continue; } const rendered = t.draft ? null : await readFile(path.join(takesDirOf(project.dir), t.id, MANIFEST), "utf8").catch(() => null); const baseText = rendered ?? draftText; if (baseText === null) { rows.push({ id: t.id, action: "refused", why: "no rendered manifest, and the project has no manifest" }); continue; } let today = null; try { today = (await resolveTakeManifest(project.dir, t.id)).manifest; } catch (e) { today = null; } let after = null; try { let stylePatch = null; if (t.style) { styles ??= (await loadMontageStyles()).styles; stylePatch = styles[t.style]?.patch ?? null; } after = resolvePresetLayers(JSON.parse(baseText), [stylePatch, t.patch]); } catch (e) { rows.push({ id: t.id, action: "refused", why: `its base does not resolve: ${e instanceof Error ? e.message : e}` }); continue; } const d = today && after ? cutDiff(today, after) : null; const row = { id: t.id, action: /** @type {"frozen" | "would-freeze"} */ (apply ? "frozen" : "would-freeze"), source: /** @type {"rendered" | "draft"} */ (rendered !== null ? "rendered" : "draft"), differs: d ? d.count : 0, words: d ? d.words : [] }; if (apply) { const dir = path.join(takesDirOf(project.dir), t.id); const takeFile = path.join(dir, TAKE_FILE); // take.json under the take writer's own lock (takeEdit.mjs): a take-scoped edit in this process waits. const { withTakeEditLock } = await import("./takeEdit.mjs"); await withTakeEditLock(async () => { const doc = JSON.parse(await readFile(takeFile, "utf8")); await writeAtomic(path.join(dir, BASE_FILE), baseText); doc.version = true; doc.frozenAt = now.toISOString(); doc.frozenFrom = row.source; await writeAtomic(takeFile, JSON.stringify(doc, null, 2) + "\n"); }); } rows.push(row); } return { project: project.id, apply, rows, missing, skipped }; }); }