Archilyzer · Source

archilyzer

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

commit f38dd7c816328760afbf2333063536d158e0294c
parent a883551c7c9cb81bb5d5db9da783191dae251c53
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 18:55:37 -0500

umtool: a version's edits counted by content, opens decided by content, ids claimed, the token held (L3 review 1, 3, 4, 5)

1 (blocker). readWorkingCut laid the parent version's PATCH over the draft
  before comparing, so a key the patch sets masked the draft's own edit of it
  (v2 "No intro" + an intro added to the draft counted 0 edits; open(v1) then
  saved nothing and the intro lived only in a prunable snapshot). A saved
  version is now compared as the draft would hold it (versionManifestOf: its
  base with any patch merged) against the draft AS IT IS. openVersion decides
  "unchanged" by content -- open(v2) with its No intro not yet in the draft
  opens it -- and the Open in draft page goes straight on only then, as a 307
  (state-dependent; never a cacheable 308).
3. A legacy rendered take whose patch was edited after its render
  (editedAt > builtAt) opens by its patch, not the stale rendered manifest.
4. Version ids are claimed with a non-recursive mkdir that advances on EEXIST,
  and a number the draft pointer or an undo point's sidecar still names is
  never reused.
5. openVersion hands the token it read at the start to the write, so a CLI
  write in between is a StaleToken, not lost; a failed open removes the
  version it saved and puts the draft pointer back.
Nit: freezeTakes writes take.json under the take writer's lock.

Tests (versions.test.mjs): the masking probe both ways, the edited-since-render
open, exclusive claims and sidecar-held numbers, the race through a
_beforeWrite hook. e2e specs expect 307.

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

Diffstat:
Mumtool/components/projects/OpenInDraftPage.tsx | 12+++++++-----
Mumtool/docs/clip-bench.md | 2+-
Mumtool/docs/knobs.md | 6++++--
Mumtool/e2e/play-take-edit.spec.ts | 4++--
Mumtool/e2e/take-walk.spec.ts | 4++--
Mumtool/lib/hrefs.ts | 2+-
Mumtool/lib/report/takeEdit.mjs | 2+-
Mumtool/lib/report/versions.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/lib/report/versions.test.mjs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/workingCut.mjs | 47++++++++++++++++++++++++++++++-----------------
10 files changed, 278 insertions(+), 52 deletions(-)

diff --git a/umtool/components/projects/OpenInDraftPage.tsx b/umtool/components/projects/OpenInDraftPage.tsx @@ -1,18 +1,18 @@ import Link from "next/link"; -import { notFound, permanentRedirect } from "next/navigation"; +import { notFound, redirect } from "next/navigation"; import { buttonVariants } from "@/components/ui/button"; import { clipBenchHref, openInDraftHref, playHref, postBenchHref, projectsHref } from "@/lib/hrefs"; import type { ProjectRef } from "@/lib/project-types"; import { manifestToken } from "@/lib/report/manifest.mjs"; import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; -import { nextVersionId } from "@/lib/report/versions.mjs"; +import { nextVersionId, openIsNoop } from "@/lib/report/versions.mjs"; import { readWorkingCut } from "@/lib/report/workingCut.mjs"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; // `/projects/<project>/takes/<take>/open` -- OPEN A VERSION IN THE DRAFT (umtool redesign L3; // lib/report/versions.mjs openVersion). Every edit lands in the draft (the project's manifest); a saved -// version is frozen, so editing one means copying it into the draft first. When <take> is the draft's -// parent with no edits since, there is nothing to copy: a 308 straight on to the draft's bench on `clip` +// version is frozen, so editing one means copying it into the draft first. When the draft already holds what +// <take> is, there is nothing to copy: a 307 straight on to the draft's bench on `clip` // (a post item's with `post=1`), else to Play of the draft. Otherwise it asks -- "Open v1 in draft? Your // draft (2 edits) is saved as v4 first." -- and the button is a plain form POST (no script needed) to // /api/report/takes/open, which lands on the same place. @@ -47,7 +47,9 @@ export default async function OpenInDraftPage({ : playHref(project.id); const working = await readWorkingCut(project.dir); const edits = working.edits?.count ?? null; - if (working.parent?.id === take && edits === 0) permanentRedirect(dest); + // Nothing to copy (the draft already holds what the take is): straight on. A 307, not a 308 -- the answer + // depends on the draft as it is now, and a browser must never remember it. + if (await openIsNoop(project.dir, take)) redirect(dest); const willSave = !working.parent || working.edits === null || (edits ?? 0) > 0; const next = await nextVersionId(project.dir); const here = openInDraftHref(project.id, take, { clip: where, post, play: fromPlay ? { at: atS } : null }); diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -318,7 +318,7 @@ The take walk (`/projects/<project>/takes/<take>/walk`) and a take's bench edit lands in the draft): it asks — *Open tight in draft? Your draft (2 edits since v3) is saved as v4 first.* — copies the take into the draft (a take with its own timeline by its patch over the draft, as **Make this the cut** merges it), then opens THIS bench on the draft's clip. When the take is the draft's -parent with no edits, the address goes straight on (308). Nothing in the UI writes a take's patch. +the draft already holds what the take is (its parent with no edits), the address goes straight on (307). Nothing in the UI writes a take's patch. A take's clips are still walked from a terminal, every save into the take's patch (`takes/<take>/take.json`), never the project's manifest: `umtool walk <p> --take <take>`, `umtool window <p> <clip> --take <take> …` and diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -625,8 +625,10 @@ expected the cut). A take is a **saved version** — FROZEN: under the manifest lock, with an undo point taken EVERY time; **Undo** puts the draft back as it was and its parent with it (a sidecar of the snapshot). A legacy take with its own timeline opens by its patch over the draft (as `take --promote` merges it: a walk made since its render is what opens), another legacy take as the manifest it - was rendered from (as `takes pick` copies it). Opening the draft's own parent with no edits writes nothing — its - Open in draft page goes straight on (308) to the draft's bench. + was rendered from (as `takes pick` copies it) — unless its patch was edited since that render, when it opens by its + patch too. Version ids are claimed with an exclusive mkdir (the CLI beside the app never gets the same one), and a + number a draft pointer or an undo point's sidecar still names is never reused. Opening a version the draft already holds (compared by content: a version's "No intro" since its save is a difference) writes nothing — its + Open in draft page goes straight on (307: it depends on the draft now) to the draft's bench. - **One undo stack.** In the app every edit is its own undo point (`revisions/<stamp>-auto-before-<op>`, the server process sets it for itself at boot — a step it spawns keeps the terminal's throttle) — a clip's edges included (`auto-before-trim`) — so two trims a minute apart are two **Undo last edit**s; from a terminal the old throttle stands (one per op every two minutes, so an agent's diff --git a/umtool/e2e/play-take-edit.spec.ts b/umtool/e2e/play-take-edit.spec.ts @@ -92,12 +92,12 @@ test("a take's old bench address from Play asks first: the draft (1 edit since t expect(manifestText()).toBe(before); }); -test("Edit on the draft's own parent with no edits goes straight on (308) to the draft's bench", async ({ page, request }) => { +test("Edit on the draft's own parent with no edits goes straight on (307) to the draft's bench", async ({ page, request }) => { // Saved: the draft is v2 now, no edits since. const r = await request.post("/api/report/takes/save", { data: { project: P } }); expect(await r.json()).toMatchObject({ saved: true, id: "v2" }); const res = await request.get(`/projects/${P}/takes/v2/open?clip=t01c&from=play&at=0.50`, { maxRedirects: 0 }); - expect(res.status()).toBe(308); + expect(res.status()).toBe(307); expect(res.headers()["location"]).toMatch(/\/projects\/reports\/play-take-edit-fixture\/clip\/t01c\?from=play&at=0\.50/); await page.goto(urls.playHref(P, { take: "v2" })); const root = page.locator("[data-play-cut]"); diff --git a/umtool/e2e/take-walk.spec.ts b/umtool/e2e/take-walk.spec.ts @@ -96,11 +96,11 @@ test("a take's old bench address: asked, opened, then the DRAFT's bench on the c expect(takeText()).toBe(takeBefore); }); -test("the draft's own parent with no edits: the old bench address goes straight on (308)", async ({ request }) => { +test("the draft's own parent with no edits: the old bench address goes straight on (307)", async ({ request }) => { const r = await request.post("/api/report/takes/save", { data: { project: PROJECT } }); expect(await r.json()).toMatchObject({ saved: true, id: "v2" }); const res = await request.get(urls.takeClipHref(PROJECT, "v2", "t01c"), { maxRedirects: 0 }); - expect(res.status()).toBe(308); + expect(res.status()).toBe(307); expect(res.headers()["location"]).toMatch(/\/projects\/reports\/take-walk-fixture\/clip\/t01c$/); // A take that is not the parent still asks. const asks = await request.get(urls.takeWalkHref(PROJECT, TAKE), { maxRedirects: 0 }); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -379,7 +379,7 @@ export function takeClipHref( /** * OPEN A VERSION IN THE DRAFT (umtool redesign L3; components/projects/OpenInDraftPage.tsx): the page that * asks first -- "Open v1 in draft? Your draft (N edits) is saved as vN+1 first." -- or, when the version is - * the draft's parent with no edits, goes straight on (308) to the draft's bench on `clip` (a post item's when + * the draft's parent with no edits, goes straight on (307) to the draft's bench on `clip` (a post item's when * `post`), else to Play of the draft. `play`: opened from Play (the bench's Back returns to Play, `at` seconds * into the clip). */ diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -81,7 +81,7 @@ let queue = Promise.resolve(); * @param {() => Promise<T>} fn * @returns {Promise<T>} */ -function withTakeEditLock(fn) { +export function withTakeEditLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs @@ -76,13 +76,53 @@ export async function writeDraft(projectDir, { from, hash = null, at = null, bas return doc; } -/** The next free version id: `v<N+1>` over every `v<N>` directory under takes/ (made or not). */ +/** + * Every version number in use or ever pointed at: each `v<N>` 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<N+1>` over every version number in use or ever pointed at (usedVersionNumbers). */ export async function nextVersionId(projectDir) { - const names = await readdir(takesDirOf(projectDir)).catch(() => []); - const taken = new Set(names); - let n = Math.max(0, ...names.map((x) => Number(VERSION_RE.exec(x)?.[1] ?? 0))) + 1; - while (taken.has(`v${n}`)) n += 1; - return `v${n}`; + 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) { @@ -111,7 +151,7 @@ async function saveVersionLocked(projectDir, { label = null, now = new Date(), f 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 = await nextVersionId(projectDir); + 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"; @@ -119,8 +159,6 @@ async function saveVersionLocked(projectDir, { label = null, now = new Date(), f const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim().slice(0, 200) : ""; const iso = now.toISOString(); const baseHash = hashText(text); - const dir = path.join(takesDirOf(projectDir), id); - await mkdir(dir, { recursive: true }); await writeAtomic(path.join(dir, BASE_FILE), text); const doc = { id, @@ -183,7 +221,10 @@ export async function openedManifestOf(projectDir, id, draft) { 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")); - const renderedText = doc.draft === true ? null : await readFile(path.join(takesDirOf(projectDir), id, MANIFEST), "utf8").catch(() => null); + // 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); if (!ownTimeline && renderedText !== null) { const m = JSON.parse(renderedText); if (isObj(m) && Array.isArray(m.timeline)) return { manifest: m, how: /** @type {const} */ ("rendered") }; @@ -211,13 +252,13 @@ export const draftSidecarOf = (snapshotRel) => snapshotRel.replace(/\.manifest\. * 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 the draft's own parent with no edits writes nothing. + * "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() } = {}) { +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 () => { @@ -226,20 +267,38 @@ export async function openVersion(project, id, { token = null, now = new Date() 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 }); - if (working.parent?.id === id && working.edits?.count === 0) { + // 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 BY CONTENT: the draft already holds what the version is (a version's "No intro" since its save + // is not; it opens). The pointer is set when it named another. + if (JSON.stringify(manifest) === JSON.stringify(draft)) { + 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; if (!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 { manifest, how } = await openedManifestOf(project.dir, id, JSON.parse(text)); const op = `open-${id}`.slice(0, 40).replace(/-+$/, ""); - const r = await replaceManifestLocked(project.dir, manifest, { op, every: 0 }); + 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)) { @@ -258,6 +317,18 @@ export async function openVersion(project, id, { token = null, now = new Date() 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 JSON.stringify(manifest) === JSON.stringify(draft); + } 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). @@ -317,12 +388,16 @@ export async function freezeTakes(project, { ids = null, apply = false, now = ne if (apply) { const dir = path.join(takesDirOf(project.dir), t.id); const takeFile = path.join(dir, TAKE_FILE); - 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"); + // 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); } diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs @@ -313,3 +313,137 @@ test("undo points are pruned to the newest N; a named snapshot is never pruned", await rm(root, { recursive: true, force: true }); } }); + +// ---- the review's fixes (L3 review, 9 Nov) ---- + +test("a version's patch never masks a draft edit: v2 'No intro' and an intro in the draft is an edit; open(v2) saves the draft, then brings its No intro in; open(v1) after another intro saves it first", async () => { + const { root, dir, proj } = await project(); + const setIntro = async (on) => { + const m = JSON.parse(await text(dir)); + if (on) m.render.intro = "boot-dark"; + else delete m.render.intro; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + }; + try { + await saveVersion(proj); // v1: no intro + await moveEntry(dir, "c", 0); + await setIntro(true); + await saveVersion(proj); // v2: with the intro + // v2 "No intro" since (its patch): the draft still has the intro -- that IS a difference from v2. + const v2doc = await json(path.join(dir, "takes", "v2", "take.json")); + v2doc.patch = { render: { intro: null } }; + await writeFile(path.join(dir, "takes", "v2", "take.json"), JSON.stringify(v2doc, null, 2) + "\n"); + let w = await readWorkingCut(dir); + assert.equal(w.parent?.id, "v2"); + assert.equal(w.edits?.count, 1, "the draft's intro is not masked by v2's patch"); + const withIntro = await text(dir); + const o2 = await openVersion(proj, "v2"); + assert.equal(o2.unchanged, false, "not 'unchanged': v2's No intro is not in the draft"); + assert.equal(o2.saved, "v3", "the draft (with its intro) saved first"); + assert.equal(await readFile(path.join(dir, "takes", "v3", "base.manifest.json"), "utf8"), withIntro); + assert.ok(!("intro" in JSON.parse(await text(dir)).render), "v2's No intro reached the draft"); + assert.equal((await openVersion(proj, "v2")).unchanged, true, "now the draft holds it"); + w = await readWorkingCut(dir); + assert.deepEqual([w.parent?.id, w.edits?.count], ["v2", 0]); + // An intro added to the draft again: an edit (v2's patch does not hide it), so open(v1) saves it first. + await setIntro(true); + assert.equal((await readWorkingCut(dir)).edits?.count, 1); + const o1 = await openVersion(proj, "v1"); + assert.equal(o1.saved, "v4"); + assert.equal(JSON.parse(await readFile(path.join(dir, "takes", "v4", "base.manifest.json"), "utf8")).render.intro, "boot-dark"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a legacy rendered take whose patch was edited after its render opens by its patch, not the stale render", async () => { + const { root, dir, proj } = await project(); + try { + await mkdir(path.join(dir, "takes", "r"), { recursive: true }); + await writeFile(path.join(dir, "takes", "r", "video.manifest.json"), JSON.stringify({ ...MANIFEST, title: "Rendered" }, null, 2)); + const doc = { id: "r", group: "takes", order: 1, label: "r", kind: "different", preview: "preview.mp4", window: "full", baseHash: "x", builtAt: "2026-11-01T00:00:00Z", patch: { title: "Walked since" } }; + await writeFile(path.join(dir, "takes", "r", "take.json"), JSON.stringify({ ...doc, editedAt: "2026-11-02T00:00:00Z" })); + const o = await openVersion(proj, "r"); + assert.equal(o.how, "merge"); + assert.equal(JSON.parse(await text(dir)).title, "Walked since"); + // Not edited since its render: the rendered manifest, as before. + await writeFile(path.join(dir, "takes", "r", "take.json"), JSON.stringify({ ...doc, editedAt: "2026-10-31T00:00:00Z" })); + const o2 = await openVersion(proj, "r"); + assert.equal(o2.how, "rendered"); + assert.equal(JSON.parse(await text(dir)).title, "Rendered"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("version ids: claimed exclusively (two claims at once get two ids); a number a pointer or an undo sidecar names is never reused", async () => { + const { root, dir } = await project(); + try { + const { claimVersionId } = await import("./versions.mjs"); + const [a, b] = await Promise.all([claimVersionId(dir), claimVersionId(dir)]); + assert.notEqual(a.id, b.id); + assert.deepEqual([a.id, b.id].sort(), ["v1", "v2"]); + // v5 deleted, but an undo point's sidecar still names it: never v5 again. + await mkdir(path.join(dir, "revisions"), { recursive: true }); + await writeFile(path.join(dir, "revisions", "20261109-100000-auto-before-open-v1.draft.json"), JSON.stringify({ from: "v5" })); + assert.equal(await nextVersionId(dir), "v6"); + await writeFile(path.join(dir, "takes", "draft.json"), JSON.stringify({ from: "v9" })); + assert.equal((await claimVersionId(dir)).id, "v10"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("openVersion: a write from another process between its read and its write is a StaleToken -- nothing lost, the version it saved removed, the pointer put back", async () => { + const { root, dir, proj } = await project(); + try { + await saveVersion(proj); // v1 + await moveEntry(dir, "c", 0); // an edit: open(v1) saves first + const pointer = await readDraft(dir); + let theirs = ""; + await assert.rejects( + openVersion(proj, "v1", { + _beforeWrite: async () => { + // The CLI, another process: a write the lock cannot see (its mtime moves the token). + await new Promise((r) => setTimeout(r, 20)); + const m = JSON.parse(await text(dir)); + m.title = "Written by the CLI"; + theirs = JSON.stringify(m, null, 2) + "\n"; + await writeFile(path.join(dir, "video.manifest.json"), theirs); + }, + }), + (e) => e?.name === "StaleToken", + ); + assert.equal(await text(dir), theirs, "the other write stands"); + await assert.rejects(stat(path.join(dir, "takes", "v2")), "no stray v2"); + assert.deepEqual(await readDraft(dir), pointer, "the pointer as it was"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a working take rendered while the draft was opened leaves the opened pointer alone", async () => { + const { root, dir, proj } = await project(); + try { + const render = async (job) => { + // Mid-render, somebody opens a version (the pointer moves). + await writeFile(path.join(dir, "takes", "draft.json"), JSON.stringify({ from: "v1", hash: null, at: "2026-11-09T00:00:00Z" })); + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }; + await mkdir(path.join(dir, "takes"), { recursive: true }); + await makeTake(dir, { id: "full-1", label: "Full", window: "full" }, { render, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + assert.equal((await readDraft(dir))?.from, "v1", "the open's pointer stands"); + // Nothing moved it this time: the new working take is the draft's parent. + await makeTake(dir, { id: "full-2", label: "Full 2", window: "full" }, { render: async (job) => { + const file = path.join(job.outDir, `${job.slug}.mp4`); + await writeFile(file, "mp4"); + return { file }; + }, styles: {}, probe: async () => 9, record: false, pruneAfter: false }); + assert.equal((await readDraft(dir))?.from, "full-2"); + void proj; + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/workingCut.mjs b/umtool/lib/report/workingCut.mjs @@ -11,13 +11,14 @@ // builtAt (then order) // parent what the draft was last saved as or opened from: takes/draft.json // `from` (versions.mjs), else `latest` -// edits since the parent: 0 when a hash says the draft is what it wrote -// (draft.json's, or the parent's baseHash); else the entries added, -// removed, moved and changed between the parent frozen (a version's -// base, or the manifest a legacy take RENDERED) and the draft with -// the parent's patch -- in words ("aw3 removed", "mc1 moved"); null -// when there is nothing frozen to compare (a legacy take's rendered -// manifest pruned) +// edits since the parent, in words ("aw3 removed", "mc1 moved"): a saved +// version as the draft would hold it (versionManifestOf: its base +// with any patch merged) against the draft AS IT IS; a legacy take +// opened in the draft, what the open wrote against the draft as it +// is; any other legacy take (main's rule), the manifest it RENDERED +// against the draft with its patch -- 0 at once when a hash says the +// draft is what was written; null when there is nothing frozen to +// compare (a legacy take's rendered manifest pruned) // picked the group pick in verdicts.json (secondary: "Use this take", // auto-picked for each new working take unless pinned) // @@ -170,16 +171,31 @@ export async function readWorkingCut(projectDir, { manifestText = null } = {}) { const text = manifestText ?? (await readFile(/* turbopackIgnore: true */ path.join(projectDir, MANIFEST), "utf8").catch(() => null)); let edits = null; const h = text !== null ? hashText(text) : null; - if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true }; - else if (text !== null && fromDraft && draft?.base && !(await hasFrozenBase(projectDir, parentTake.id))) { - // A legacy take opened by merging its patch: the edits since the open, against what it wrote. + const diffOf = (a, b) => { + const d = cutDiff(a, b); + return { count: d.count, words: d.words, same: d.count === 0 }; + }; + if (text !== null && (await hasFrozenBase(projectDir, parentTake.id))) { + // A SAVED VERSION: the version as the draft would hold it (its base, with any patch laid over it since -- a + // "No intro" toggle) against the draft AS IT IS. Never the version's patch over the draft: a key the patch + // sets would mask the draft's own edit of it. + try { + const { versionManifestOf } = await import("./takeMaker.mjs"); + const v = await versionManifestOf(projectDir, parentTake.id); + edits = v && v.exact && hashText(v.text) === h ? { count: 0, words: [], same: true } : v ? diffOf(v.manifest, JSON.parse(text)) : null; + } catch { + edits = null; + } + } else if (text !== null && fromDraft && draft?.base) { + // A legacy take opened in the draft: the edits since the open, against what it wrote (as it is, no patch). try { - const d = cutDiff(draft.base, JSON.parse(text)); - edits = { count: d.count, words: d.words, same: d.count === 0 }; + edits = draft.hash === h ? { count: 0, words: [], same: true } : diffOf(draft.base, JSON.parse(text)); } catch { edits = null; } - } else if (text !== null) { + } else if (h !== null && ((fromDraft && draft?.hash === h) || parentTake.baseHash === h)) edits = { count: 0, words: [], same: true }; + else if (text !== null) { + // A legacy take (main's rule): the manifest it rendered against the draft with its patch laid over it. const { frozenManifestOf, resolveTakeManifest } = await import("./takeManifest.mjs"); const frozen = await frozenManifestOf(projectDir, parentTake.id); let now = null; @@ -188,10 +204,7 @@ export async function readWorkingCut(projectDir, { manifestText = null } = {}) { } catch { now = null; } - if (frozen && isObj(now)) { - const d = cutDiff(frozen.manifest, now); - edits = { count: d.count, words: d.words, same: d.count === 0 }; - } + if (frozen && isObj(now)) edits = diffOf(frozen.manifest, now); } return { latest: latestOut, parent, edits, picked, takes: takes.length }; }