commit 04c46263ab8063d4de1497d804100566dcfcfe96 parent 6729ed86d3ed4ca452049385317cd87afa133750 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Tue, 10 Nov 2026 10:36:04 -0500 Merge lane/owed-fixes: the owed umtool fixes -- restore a removed clip, import items into the draft, take-walk code gone and the take-scope verbs deprecated, claim= clears, a shard cache that revalidates, the e2e harness refuses an inherited corpus, the intro-play race, umtool's icon and the plain avatar (overnight E1) - timeline <p> restore <id> / removed, POST /api/report/timeline {op:"restore"}, a Removed list with Restore on the Cut tab - "Add items from another project" imports into the draft (timeline <p> import-item); the route refuses flag words in refs - S6 deprecation lines on --in-take / --take writes / /api/report/takes/timeline; take-walk bench code removed - umtool set <p> <clip> claim= clears every mark in the draft - createJsonCache versions: cue walk and linkCheck revalidate by the manifest's generatedAt - e2e: an inherited REPORTS_DIR or CHANNELS_DIR is refused (SONG_DIR allowed; realpath compare); shared-fixture order fixed - writePlayManifest: a tmp name per write (two at once lost a rename) - umtool/app/icon.svg; common/brand/archilyzer-avatar.svg + 1024 png - projects.spec's two siteOrigin reds on main fixed (L5's rail fixtures) Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
53 files changed, 1300 insertions(+), 285 deletions(-)
diff --git a/common/brand/archilyzer-avatar-1024.png b/common/brand/archilyzer-avatar-1024.png Binary files differ. diff --git a/common/brand/archilyzer-avatar.svg b/common/brand/archilyzer-avatar.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#151b20"/><g transform="translate(51.2 51.2) scale(0.8)"><rect x="112" y="128" width="288" height="44" rx="22" fill="#3f4c56"/><polygon points="112,210 172,234 112,258" fill="#e7edf1"/><rect x="188" y="212" width="212" height="44" rx="22" fill="#e7edf1"/><rect x="112" y="296" width="232" height="44" rx="22" fill="#3f4c56"/><rect x="112" y="380" width="152" height="44" rx="22" fill="#3f4c56"/></g></svg> +\ No newline at end of file diff --git a/common/lib/brandAvatar.test.ts b/common/lib/brandAvatar.test.ts @@ -0,0 +1,32 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { ICON_PALETTES, markSvg } from "./brand"; + +// common/brand/archilyzer-avatar.svg + archilyzer-avatar-1024.png: the profile +// picture the operator chose on 9 Nov (PLAIN over Signal), copied verbatim from +// the approved pair. They are the source of truth for the avatar on every +// account; nothing renders them. This holds the SVG to the mark's geometry so a +// change to MARK cannot leave the picture silently off-model: it is markSvg's +// maskable variant (full-bleed ground, lines at 0.8 in the safe zone) on the +// parent slate, lit achromatic, with the dim the pair was drawn with before +// 2026-09-27's 3:1 bump (#3f4c56; the live mark's is ICON_PALETTES.archilyzer.dim). +const AVATAR_DIM = "#3f4c56"; +const file = (name: string) => fileURLToPath(new URL(`../brand/${name}`, import.meta.url)); + +test("the avatar SVG is the parent mark, maskable, plain (achromatic lit)", () => { + const svg = readFileSync(file("archilyzer-avatar.svg"), "utf8").trimEnd(); + assert.equal( + svg, + markSvg({ ground: ICON_PALETTES.archilyzer.ground, dim: AVATAR_DIM, lit: ICON_PALETTES.archilyzer.lit }, { variant: "maskable" }), + ); +}); + +test("the avatar PNG is a 1024 x 1024 PNG", () => { + const png = readFileSync(file("archilyzer-avatar-1024.png")); + assert.deepEqual([...png.subarray(0, 8)], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + assert.equal(png.subarray(12, 16).toString("ascii"), "IHDR"); + assert.equal(png.readUInt32BE(16), 1024); + assert.equal(png.readUInt32BE(20), 1024); +}); diff --git a/plans/brand-and-themes.md b/plans/brand-and-themes.md @@ -1296,6 +1296,7 @@ S4 ships after release 10's cut and is **not part of the site rollout**: it touc - **Mark M2 · Signal.** The parent mark's geometry, lit in Signal: ground `#151b20`, dim `#3f4c56`, lit `#5fa8a0`. (Dim `#586977` since 2026-09-27, with the parent mark's; see "The design".) The avatar uses the maskable variant (scale 0.8 on full-bleed ground). +- **The profile picture is PLAIN** (operator, 2026-11-09, over the Signal one): `common/brand/archilyzer-avatar.svg` + `archilyzer-avatar-1024.png` are its source of truth (maskable, achromatic lit, dim `#3f4c56`; `common/lib/brandAvatar.test.ts`). - **Lockup "flush · caps matched".** The `Archi|lyzer` wordmark sits over `MEDIA`: - Both are Archivo at wdth 118. The wordmark is 720 / 380 at -0.01em; MEDIA is 700, in Signal. - MEDIA's size is **1.035×** the wordmark's, and it is letter-spaced to exactly the wordmark's diff --git a/umtool/app/api/report/bench/route.ts b/umtool/app/api/report/bench/route.ts @@ -4,7 +4,8 @@ import { clipBenchData } from "@/lib/report/benchData"; export const dynamic = "force-dynamic"; // THE CLIP BENCH'S DATA as JSON, for Play's in-place bench (components/projects/cutApp/CutApp.tsx): -// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] +// GET ?project=<id>&clip=<id>[&take=<id>][&from=play&at=<s>][&order=cut] (`take`: the take Play was on, for +// Back; the clip is always the draft's -- a take's clip is never benched, L3) // // The same function the bench's own page renders from (lib/report/benchData.ts), // so the bench inside Play and the one on its own page cannot disagree. A clip @@ -15,7 +16,7 @@ export async function GET(request: Request) { if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const clip = q.get("clip") ?? ""; const search = Object.fromEntries([...q.entries()].filter(([k]) => k !== "project" && k !== "clip")); - const r = await clipBenchData(project, clip, { search, take: q.get("walkTake") || null, order: q.get("order") === "cut" ? "cut" : "walk" }); + const r = await clipBenchData(project, clip, { search, order: q.get("order") === "cut" ? "cut" : "walk" }); if (!r) return Response.json({ error: `${clip} is not a clip of the cut` }, { status: 404 }); return Response.json(r, { headers: { "cache-control": "no-store" } }); } diff --git a/umtool/app/api/report/takes/timeline/route.ts b/umtool/app/api/report/takes/timeline/route.ts @@ -4,6 +4,7 @@ import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; import { insertTakeEntry, moveTakeEntry, removeTakeEntry, takeToken, undoTakeEdit } from "@/lib/report/takeEdit.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; import { isTakeId } from "@/lib/report/takes.mjs"; +import { takeEditDeprecation } from "@/lib/report/takeDeprecation.mjs"; export const dynamic = "force-dynamic"; @@ -22,6 +23,13 @@ export const dynamic = "force-dynamic"; // timeline, as the project's GET /api/report/timeline lists it (Add a clip's place picker, on a take). // // A stale token is a 409; a structure the build would refuse is a 400 with its sentences. +// +// DEPRECATED (L3 S6): no page calls it (edits land in the draft; a take is opened there first). Each call says +// so in one line on the server's stderr and answers with a `Deprecation: true` header. +const deprecated = (project: string | null, take: string | null) => { + console.warn(takeEditDeprecation("/api/report/takes/timeline", { project, take })); + return { deprecation: "true" }; +}; export async function GET(request: Request) { const url = new URL(request.url); const take = url.searchParams.get("take"); @@ -39,7 +47,7 @@ export async function GET(request: Request) { channel: str(e.channel), words: (str(e.quote) ?? str(e.text) ?? str(e.title) ?? "").replace(/\s+/g, " ").slice(0, 60), })); - return Response.json({ take, token: await takeToken(project.dir, take), timeline }, { headers: { "cache-control": "no-store" } }); + return Response.json({ take, token: await takeToken(project.dir, take), timeline }, { headers: { "cache-control": "no-store", ...deprecated(project.id, take) } }); } catch (e) { const message = e instanceof Error ? e.message : String(e); return Response.json({ error: message }, { status: /^no take /.test(message) ? 404 : 400 }); @@ -55,6 +63,7 @@ export async function POST(request: Request) { const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const take = body.take; + const dep = deprecated(project.id, take); const token = body.token === undefined || body.token === null ? null : String(body.token); const at = body.at === undefined || body.at === null ? null : Number(body.at); const id = typeof body.id === "string" ? body.id : ""; @@ -74,7 +83,7 @@ export async function POST(request: Request) { } else { return Response.json({ error: "op must be move, remove, undo or insert" }, { status: 400 }); } - return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store" } }); + return Response.json({ ok: true, op: body.op, take, ...r }, { headers: { "cache-control": "no-store", ...dep } }); } catch (e) { if (e instanceof StaleToken) return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); diff --git a/umtool/app/api/report/takes/tools/route.ts b/umtool/app/api/report/takes/tools/route.ts @@ -2,6 +2,8 @@ import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; import { lintCommand } from "@/lib/report/lintCli.mjs"; import { takeCommand } from "@/lib/report/takeCli.mjs"; +import { timelineCommand } from "@/lib/report/timelineCli.mjs"; +import { ImportRefused, draftImportArgv } from "@/lib/report/takeImport.mjs"; import { isTakeId, listTakes } from "@/lib/report/takes.mjs"; import { REPORTS_ROOT } from "@/lib/paths"; import { addStep } from "@/lib/queue/store.mjs"; @@ -18,9 +20,11 @@ export const dynamic = "force-dynamic"; // -> { exit, report: { ok, errors[], warnings[], entries } } // POST { project, take, op: "draft-from", id?, label? } umtool take <p> --id <id> --draft --from <take> --json // -> { exit, id, report } (id: the next free `<take>-d<n>` when none is given) -// POST { project, take, op: "import", refs: "<project>:<item>[,…]", after?, before?, dryRun? } -// umtool take <p> --id <take> --import-item … [--dry-run] --json -// -> { exit, report } +// POST { project, op: "import", refs: "<project>:<item>[,…]", after?, before?, dryRun? } +// umtool timeline <p> import-item … [--dry-run] --json: INTO +// -> { exit, report } THE DRAFT (the Cut tab's Add items from another project; L3: +// every edit lands in the draft). With `take`: the old take +// patch path, umtool take <p> --id <take> --import-item … // POST { project, op: "draft-new", label, group?, style?, patch?, window? } // umtool take <p> --id <slug of label> --label L --draft // -> { exit, id, report } [--group G] [--style S] [--patch-json P] [--full | --at A --dur D] @@ -87,6 +91,18 @@ export async function POST(request: Request) { kickQueue(); return Response.json({ exit: 0, queued: step.qid }, { headers: { "cache-control": "no-store" } }); } + if (body.op === "import" && !take) { + // Every word checked before it becomes argv (draftImportArgv): no flag rides in on the refs. + let argv: string[]; + try { + argv = draftImportArgv(project.id, { refs: body.refs, after: body.after, before: body.before, dryRun: !!body.dryRun }); + } catch (e) { + if (e instanceof ImportRefused) return Response.json({ error: e.message }, { status: 400 }); + throw e; + } + const exit = await timelineCommand(argv, { root: REPORTS_ROOT, out: io.log, err: io.err }); + return answer(exit); + } if (!take) return Response.json({ error: `${String(body.op)} needs a take` }, { status: 400 }); if (body.op === "draft-from") { let id = typeof body.id === "string" && body.id ? body.id : null; diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -15,6 +15,7 @@ import { removeSection, sectionsOf, rejectClip, + restoreRemoved, removeWrongSpeaker, removePost, undoStructural, @@ -50,6 +51,7 @@ export const dynamic = "force-dynamic"; // remove { id, at? } // reject { id, at?, reason, note? } rejected (rejectReasons.mjs) and removed, on record // wrong-speaker { id, at?, correction? } reject with the reason wrong-speaker +// restore { id } un-reject: a removed clip back from the newest revision holding it // duplicate { id, at? } // insert { afterId: id | null, at?, entry: "<channel>/<video>@<start>-<end>" | { type, … } } // teaser { id, at?, patch: { lines?, beat?, dip?, tail?, tailWait? } } @@ -157,6 +159,9 @@ export async function POST(request: Request) { case "reject": // Rejected for `reason` (rejectReasons.mjs) and removed in one write, on the record (removed.json). return rejectClip(dir, id, String(body.reason ?? ""), { token, at, note: typeof body.note === "string" ? body.note : null }); + case "restore": + // Un-reject: the removed clip back, as the newest revision holding it had it, at its old place. + return restoreRemoved(dir, id, { token }); case "duplicate": return duplicateEntry(dir, id, { token, at }); case "insert": diff --git a/umtool/app/icon.svg b/umtool/app/icon.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="112" fill="#151b20"/><rect x="112" y="128" width="288" height="44" rx="22" fill="#586977"/><polygon points="112,210 172,234 112,258" fill="#5fa8a0"/><rect x="188" y="212" width="212" height="44" rx="22" fill="#5fa8a0"/><rect x="112" y="296" width="232" height="44" rx="22" fill="#586977"/><rect x="112" y="380" width="152" height="44" rx="22" fill="#586977"/></svg> diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -1163,6 +1163,7 @@ async function cmdWindow() { // same rules, an undo point first -- never into the project's manifest. const take = val("--take"); if (take !== undefined) { + (await import("../lib/report/takeDeprecation.mjs")).warnTakeEdit("window --take", { project: p.id, take }); try { const { updateTakeClip } = await import("../lib/report/takeEdit.mjs"); const res = await updateTakeClip(p.dir, take, clipId, patch); diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -328,37 +328,11 @@ 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). */ - /** 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). */ + fromPlay?: { href: string; take: string | null } | null; + /** Walk → Play: the cut from this clip (the bench opened on its own, not from Play). */ playHere?: string | null; /** The working cut's name (lib/report/workingCut.mjs): the latest whole-cut take and the edits since it. */ working?: WorkingCut; - /** - * WALKING A TAKE (/projects/<p>/takes/<take>/clip/<id>): the clip is the - * take's -- the project's manifest with the take's patch applied -- and - * every save goes into the take's patch (takes/<id>/take.json), never the - * project's manifest. Every route this bench calls is asked with `take`. - * `all`: the walk visits every fetched clip, judged or not. - */ - take?: { - id: string; - label: string; - draft: boolean; - /** take.json exists, so there is somewhere for an edit to land (a recipe-only take is read only). */ - editable: boolean; - all: boolean; - /** The Takes page, and this walk's own start (with `all` as it is). */ - takesHref: string; - walkHref: string; - /** The same clip on the walk of every clip / of the unjudged ones. */ - toggleAllHref: string; - /** Clip id -> its bench address on this take's walk (siblings link through it). */ - clipHref: Record<string, string>; - /** This clip's index in the take's timeline, and the timeline's length (the strip's moves). */ - at: number; - entries: number; - } | null; }; const hms = (t: number) => { @@ -407,8 +381,6 @@ type UndoRec = { before: Record<string, unknown>; /** The Confirm carried a moved window, so Undo puts the edges back too. */ moved: boolean; - /** Walking a take: the take the Confirm was written into. */ - take?: string | null; }; const readUndo = (): UndoRec | null => { try { @@ -555,13 +527,9 @@ export default function ClipBench({ // The project's notes: this clip's row notes, and the edit notes a save on a // generated manifest leaves (the save says so, and they are re-read). const notes = useSharedNotes({ project: data.project }); - // Walking a take: every route is asked about the TAKE's clip, and every - // save lands in the take's patch (see ClipBenchData.take). - const takeId = data.take?.id ?? null; - const tq = takeId ? `&take=${encodeURIComponent(takeId)}` : ""; - const takeBody = takeId ? { take: takeId } : {}; - // Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk. - const clipExport = useClipExport(data.project, takeId); + // The DRAFT's clip, always (L3): a take's clip is never benched -- its old address is Open in draft. + // Export clip (ClipExport.tsx): this clip, clean, into the project's exports/. + const clipExport = useClipExport(data.project, null); const [clip, setClip] = useState<Clip>(data.clip); // Export ▾'s full exchange starts from the clip's saved extent. const clipAround = useMemo(() => ({ start: clip.start, end: clip.end }), [clip.start, clip.end]); @@ -581,7 +549,7 @@ export default function ClipBench({ const after = edgesAfter(clip, sel, mode); // Where the render will actually cut the drafted selection (bench/RenderGhosts.tsx): the // desk's waveform and the phone's edge strip both draw it. - const renderEdges = useRenderEdges(data.project, clip, { from: after.start, to: after.end }, takeId, { cutStart: after.cutStart, cutEnd: after.cutEnd }); + const renderEdges = useRenderEdges(data.project, clip, { from: after.start, to: after.end }, null, { cutStart: after.cutStart, cutEnd: after.cutEnd }); /** The patch that writes a span as the handles' (no mute mark): edgesAfter, as keys. */ const edgePatch = useCallback( (span: { from: number; to: number }): WindowPatch => { @@ -759,10 +727,11 @@ export default function ClipBench({ } catch { /* nothing to clear */ } - if (u.project !== data.project || (u.take ?? null) !== takeId || (u.next !== data.clip.id && u.clip !== data.clip.id)) return; + // A record a take's walk left (`take` set, before L3) is not this bench's to undo. + if (u.project !== data.project || (u as { take?: unknown }).take || (u.next !== data.clip.id && u.clip !== data.clip.id)) return; if (Date.now() - u.at >= UNDO_MS) return; setUndo(u); - }, [data.project, data.clip.id, takeId]); + }, [data.project, data.clip.id]); useEffect(() => { if (!undo) return; const id = window.setTimeout(() => setUndo(null), Math.max(0, undo.at + UNDO_MS - Date.now())); @@ -790,10 +759,10 @@ export default function ClipBench({ // What plays (bench/benchMedia.ts): the widest cached window, on the source clock. const media = useMemo( - () => sourceWindowMedia({ project: data.project, clip: clip.id, take: takeId, win: cached }), + () => sourceWindowMedia({ project: data.project, clip: clip.id, take: null, win: cached }), // The window by its name and the version of its bytes: a refresh returning the same one is the same media. // eslint-disable-next-line react-hooks/exhaustive-deps - [data.project, clip.id, takeId, cached?.name, cached?.v, cached?.from, cached?.to], + [data.project, clip.id, cached?.name, cached?.v, cached?.from, cached?.to], ); // Read by play() at the moment it schedules, so a mark moved since the last // render is the one you hear -- without re-creating play() on every nudge. @@ -842,7 +811,7 @@ export default function ClipBench({ void (async () => { const r = await fetch( `/api/report/cues?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}` + - `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}${tq}`, + `&from=${(view.from - peekPad).toFixed(2)}&to=${(view.to + peekPad).toFixed(2)}`, { cache: "no-store" }, ); if (!r.ok || !live) return; @@ -852,7 +821,7 @@ export default function ClipBench({ return () => { live = false; }; - }, [data.project, clip.id, view.from, view.to, peekPad, tq]); + }, [data.project, clip.id, view.from, view.to, peekPad]); // ---- playback preferences ------------------------------------------------ useEffect(() => setPlayback(readPlayback()), []); @@ -1033,7 +1002,7 @@ export default function ClipBench({ const r = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current, ...patch }), + body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current, ...patch }), }); const j = (await r.json()) as Record<string, unknown>; lastSaved.current = j; @@ -1238,7 +1207,7 @@ export default function ClipBench({ // A verdict is a state change, and a thumb lands where it did not mean to. const before = (lastSaved.current?.before ?? null) as Record<string, unknown> | null; if (before) { - const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win, take: takeId }; + const rec: UndoRec = { project: data.project, clip: clip.id, next: data.next, at: Date.now(), before, moved: !!win }; try { sessionStorage.setItem(UNDO_KEY, JSON.stringify(rec)); } catch { @@ -1260,8 +1229,7 @@ export default function ClipBench({ async (u: UndoRec) => { setUndo(null); const b = u.before; - const uq = u.take ? `&take=${encodeURIComponent(u.take)}` : ""; - const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}${uq}`, { + const r = await fetch(`/api/report/clip?project=${encodeURIComponent(u.project)}&clip=${encodeURIComponent(u.clip)}`, { cache: "no-store", }); if (!r.ok) { @@ -1280,11 +1248,11 @@ export default function ClipBench({ const w = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: u.project, clip: u.clip, ...(u.take ? { take: u.take } : {}), token: tok, ...patch }), + body: JSON.stringify({ project: u.project, clip: u.clip, token: tok, ...patch }), }); const j = (await w.json()) as Record<string, unknown>; if (!w.ok) { - setNote(j.stale ? `could not undo: the ${u.take ? "take" : "manifest"} changed since — reload` : `could not undo: ${String(j.error ?? w.status)}`); + setNote(j.stale ? "could not undo: the manifest changed since — reload" : `could not undo: ${String(j.error ?? w.status)}`); return; } if (wroteNotes(j)) void notes.reload(); @@ -1304,11 +1272,7 @@ export default function ClipBench({ const q = new URLSearchParams(window.location.search); q.delete("at"); const qs = q.toString(); - router.push( - u.take - ? `/projects/${u.project}/takes/${encodeURIComponent(u.take)}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}` - : `/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`, - ); + router.push(`/projects/${u.project}/clip/${encodeURIComponent(u.clip)}${qs ? `?${qs}` : ""}`); }, // `notes.reload` is the stable part of `notes`. // eslint-disable-next-line react-hooks/exhaustive-deps @@ -1744,7 +1708,7 @@ export default function ClipBench({ const refresh = useCallback(async (): Promise<ClipBenchData | null> => { const r = await fetch( - `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`, + `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}`, { cache: "no-store" }, ); if (!r.ok) return null; @@ -1787,7 +1751,6 @@ export default function ClipBench({ body: JSON.stringify({ project: data.project, clip: clip.id, - ...takeBody, padBefore: round2(pads.padBefore), padAfter: round2(pads.padAfter), ...storedAsk, @@ -1858,7 +1821,7 @@ export default function ClipBench({ const r = await fetch("/api/report/fetch", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, full: true }), + body: JSON.stringify({ project: data.project, clip: clip.id, full: true }), }); if (!r.ok) { const j = (await r.json()) as { error?: string }; @@ -1945,7 +1908,7 @@ export default function ClipBench({ const r = await fetch("/api/report/cut", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project: data.project, clip: clip.id, ...takeBody, token: token.current }), + body: JSON.stringify({ project: data.project, clip: clip.id, token: token.current }), }); const j = (await r.json()) as { ok?: boolean; @@ -2132,8 +2095,7 @@ export default function ClipBench({ const padLabelForCue = (c: Cue) => c.end > view.to ? `+${padsForCue(c).padAfter} s` : `−${padsForCue(c).padBefore} s`; - // A take's clip has no segment of the project's (ClipBenchPage passes none). - const segSrc = segment && !takeId + const segSrc = segment ? `/api/report/segment?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}&v=${segmentMtime ?? 0}` : null; @@ -2177,7 +2139,7 @@ export default function ClipBench({ const ok = () => !returnState.current.busy && returnState.current.clean; if (!ok()) return; const r = await fetch( - `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}${tq}`, + `/api/report/clip?project=${encodeURIComponent(data.project)}&clip=${encodeURIComponent(clip.id)}`, { cache: "no-store" }, ).catch(() => null); if (!r?.ok) return; @@ -2203,7 +2165,7 @@ export default function ClipBench({ setDraft(emptyDraft(next)); setOs(osDraftOf(next.onscreen)); } - }, [data.project, clip.id, tq]); + }, [data.project, clip.id]); const resyncRef = useRef(resync); resyncRef.current = resync; useEffect(() => { @@ -2661,19 +2623,12 @@ 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 && - (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> - ))} + {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> + )} </div> {cached && ( <EdgeStrip @@ -2770,12 +2725,12 @@ export default function ClipBench({ /** * Reject ▾ (RejectClip) on this clip: the bench's own writer for a keep in * place (its token, its state), the project's structural write for a - * removal -- and on a take's walk, a keep only (a take's timeline is a patch). + * removal. */ const rejectPanel = (className: string, opened = false) => ( <RejectClip project={data.project} - take={takeId ?? null} + take={null} hotkey={opened ? false : "digits"} control={opened ? undefined : rejectCtl} initialOpen={opened} @@ -2930,10 +2885,8 @@ 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} 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 data-back-take={data.fromPlay.take} data-back-take-edits="cut" className="ml-2 text-[11.5px] text-muted-2"> + edits go to the project’s cut, not take {data.fromPlay.take} </span> )} </>, @@ -2961,12 +2914,11 @@ export default function ClipBench({ {/* On a phone the banner is one muted line under Notes (phoneNotesHead). The wrapper only when there is a banner: an empty one would be a flex item, and a gap, on the desk. */} - {data.generatedBy && !data.take && ( + {data.generatedBy && ( <div className="max-md:hidden"> <GeneratedBanner generatedBy={data.generatedBy} /> </div> )} - {/* A take's clip is never benched from the UI now (L3: Open in draft first); `umtool window --take` edits one. */} {/* ---- where you are, where you can go, and what will be burned in ---- */} <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents"> {/* On a phone both counts are the place bar's `50/51` and its hairline. */} @@ -2979,7 +2931,7 @@ export default function ClipBench({ ready {data.ready} of {data.needing} needing judgement </span> {/* The working cut's name: what this bench edits, and the latest take it was made into. */} - {data.working && !data.take && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} + {data.working && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} {!data.fetched && ( <span className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")} data-clip-unfetched=""> not fetched yet @@ -3540,7 +3492,7 @@ export default function ClipBench({ Fetch whole source via editor </button> {/* A window known bad, evicted and fetched again: a queue step (lane/ui-simplify). */} - <RefetchButton project={data.project} clip={clip.id} take={takeId} disabled={!!busy} /> + <RefetchButton project={data.project} clip={clip.id} take={null} disabled={!!busy} /> {storedOffered && ( <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> )} @@ -3841,33 +3793,20 @@ export default function ClipBench({ nothing rendered for this clip yet </div> )} - {data.take ? ( - // The one-clip render builds the PROJECT's segment; a take is rendered whole. - <p data-take-no-rerender="" className="text-[11px] leading-snug text-[var(--color-dim)]"> - A take is rendered as a whole, from its own patch:{" "} - <Link href={data.take.takesHref} className="ink-link"> - Render on the Takes page - </Link>{" "} - or <code className="font-mono">umtool take {data.project} --id {data.take.id} --full</code>. - </p> - ) : ( - <> - <button - type="button" - data-rerender="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - onClick={() => void rerender()} - > - Re-render this clip - </button> - <p className="text-[11px] leading-snug text-[var(--color-dim)]"> - One clip, no crossfade, no chapters — it overwrites this clip’s segment and - nothing else. The header is drawn by ffmpeg from a text file, so this is the only - place the line above can be checked rather than believed. - </p> - </> - )} + <button + type="button" + data-rerender="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + onClick={() => void rerender()} + > + Re-render this clip + </button> + <p className="text-[11px] leading-snug text-[var(--color-dim)]"> + One clip, no crossfade, no chapters — it overwrites this clip’s segment and + nothing else. The header is drawn by ffmpeg from a text file, so this is the only + place the line above can be checked rather than believed. + </p> </div> {/* ---- lock, explained rather than labelled ---- */} @@ -3961,7 +3900,7 @@ export default function ClipBench({ {siblings.map((sb) => ( <li key={sb.id} data-sibling={sb.id} className="leading-snug"> <Link - href={data.take?.clipHref[sb.id] ?? `/projects/${data.project}/clip/${sb.id}`} + href={`/projects/${data.project}/clip/${sb.id}`} className="font-mono ink-link" > {sb.id} diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -11,19 +11,12 @@ export default async function ClipBenchPage({ project, clipId, search = {}, - take = null, }: { project: ProjectRef; clipId: string; search?: Record<string, string | undefined>; - /** - * WALKING A TAKE (`/projects/<p>/takes/<take>/clip/<id>`): the clip is the - * take's -- the project's manifest with the take's patch applied - * (lib/report/walkData.mjs) -- and the bench's saves go into the take. - */ - take?: string | null; }) { - const { data, top } = await clipBenchDataOr404(project, clipId, { search, take, order: search.order === "cut" ? "cut" : "walk" }); + const { data, top } = await clipBenchDataOr404(project, clipId, { search, order: search.order === "cut" ? "cut" : "walk" }); return ( // The bench shell (P4b): its top bar here, the body -- the work, the // verdict bar, the reader -- in ClipBench, which owns their state. diff --git a/umtool/components/projects/TakeTools.tsx b/umtool/components/projects/TakeTools.tsx @@ -15,8 +15,9 @@ import PlayLink from "./PlayLink"; // // Check before render umtool lint <p> --take <t> // New draft from this take umtool take <p> --id <t>-d<n> --draft --from <t> -// Add items from another umtool take <p> --id <t> --import-item <src>:<a,b> [--after|--before <e>] -// project [--dry-run]: Preview shows the plan, Import does it +// Add items from another umtool timeline <p> import-item <src>:<a,b> [--after|--before <e>] +// project (the Cut tab) [--dry-run]: INTO THE DRAFT (L3: every edit lands there; E1, 9 Nov) -- +// Preview shows the plan, Import does it // --------------------------------------------------------------------------- type Tools = { exit: number; report: Record<string, unknown> | null; said?: string; id?: string; error?: string }; @@ -97,8 +98,8 @@ export function DraftFromButton({ project, take }: { project: string; take: stri type Entry = { id: string; type: string; words?: string }; -/** Add items from another project: cloned into this take only, their files hard-linked in; Preview first. */ -export function ImportItems({ project, take }: { project: string; take: string }) { +/** Add items from another project: cloned into the DRAFT, their files hard-linked in; Preview first. */ +export function ImportItems({ project }: { project: string }) { const router = useRouter(); const [open, setOpen] = useState(false); const [source, setSource] = useState(""); @@ -112,8 +113,8 @@ export function ImportItems({ project, take }: { project: string; take: string } const [done, setDone] = useState<Tools | null>(null); useEffect(() => { if (!open) return; - // The take's entries as Play reads them (its frozen manifest, or its patch over the draft): where an item lands. - void fetch(`/api/report/play-view?${new URLSearchParams({ project, take })}`, { cache: "no-store" }) + // The draft's entries as Play reads them: where an item lands. + void fetch(`/api/report/play-view?${new URLSearchParams({ project })}`, { cache: "no-store" }) .then((r) => r.json()) .then((j) => setEntries(Array.isArray(j.entries) ? (j.entries as { id: string; type: string; heading?: string }[]).map((e) => ({ id: e.id, type: e.type, words: e.heading })) : [])) .catch(() => {}); @@ -121,11 +122,11 @@ export function ImportItems({ project, take }: { project: string; take: string } .then((r) => r.json()) .then((j) => setProjects(((j.pieces ?? []) as { id: string; kind: string }[]).filter((p) => p.kind === "project" && p.id.startsWith("p:")).map((p) => p.id.slice(2)))) .catch(() => {}); - }, [open, project, take]); + }, [open, project]); const refs = items.trim() ? `${source.trim()}:${items.replace(/\s+/g, "")}` : ""; const run = async (dryRun: boolean) => { setBusy(true); - const r = await tool({ project, take, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun }); + const r = await tool({ project, op: "import", refs, ...(where === "after" && anchor ? { after: anchor } : where === "before" && anchor ? { before: anchor } : {}), dryRun }); setBusy(false); if (dryRun) { setPlan(r); @@ -139,14 +140,14 @@ export function ImportItems({ project, take }: { project: string; take: string } const input = "rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[3px] text-[11.5px] text-text outline-none focus:border-signal"; const rows = (t: Tools | null) => ((t?.report as { items?: { id: string; action: string; at?: { index?: number; after?: string | null; before?: string | null } }[] } | null)?.items ?? []); return ( - <span className="inline-flex basis-full flex-col gap-1.5" data-take-import={take}> + <span className="inline-flex basis-full flex-col gap-1.5" data-take-import="draft"> <button type="button" data-action="import-open" aria-expanded={open} onClick={() => setOpen((o) => !o)} className={cn(buttonVariants({ variant: open ? "pressed" : "outline", size: "sm" }), "self-start")}> Add items from another project </button> {open && ( <span className="flex flex-wrap items-center gap-1.5 rounded border border-seam p-2 text-[11.5px]"> - <input data-import-source="" list={`import-projects-${take}`} value={source} onChange={(e) => setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} /> - <datalist id={`import-projects-${take}`}> + <input data-import-source="" list="import-projects-draft" value={source} onChange={(e) => setSource(e.target.value)} placeholder="project (e.g. emberparadox/mr-obvious-unhinged)" className={cn(input, "w-72 font-mono")} /> + <datalist id="import-projects-draft"> {projects.filter((p) => p !== project).map((p) => ( <option key={p} value={p} /> ))} @@ -172,7 +173,7 @@ export function ImportItems({ project, take }: { project: string; take: string } Preview </button> <button type="button" data-action="import-go" disabled={busy || !refs || !source.trim()} onClick={() => void run(false)} className={buttonVariants({ variant: "go", size: "sm" })}> - Import into {take} + Import into the draft </button> </span> )} @@ -221,14 +222,16 @@ export function CheckJoinsButton({ project, take }: { project: string; take: str ); } -/** The take's tools, as a take card's or a take walk's row. */ -export default function TakeTools({ project, take, editable = true, rendered = false }: { project: string; take: string; editable?: boolean; rendered?: boolean }) { +/** + * The take's tools, as a take card's row. Add items from another project is the draft's now (the Cut tab): + * a take is not edited in place (L3). + */ +export default function TakeTools({ project, take, rendered = false }: { project: string; take: string; rendered?: boolean }) { return ( <span className="flex flex-wrap items-start gap-1.5" data-take-tools={take}> <LintButton project={project} take={take} /> {rendered && <CheckJoinsButton project={project} take={take} />} <DraftFromButton project={project} take={take} /> - {editable && <ImportItems project={project} take={take} />} </span> ); } diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -876,7 +876,7 @@ function TakeCard({ </p> )} {/* Everything but play, judge, walk and render, folded (lane/ui-simplify): Options the common, Advanced the rare. */} - <Options id="take-card" hint="use · rebuild · check · draft · import · fork · compare"> + <Options id="take-card" hint="use · rebuild · check · draft · fork · compare"> <div className="flex flex-wrap items-center gap-1.5"> {!t.draft && ( <button @@ -902,7 +902,7 @@ function TakeCard({ </button> )} </div> - <TakeTools project={project} take={t.id} editable={walkable} rendered={!!t.builtAt && !t.draft} /> + <TakeTools project={project} take={t.id} rendered={!!t.builtAt && !t.draft} /> <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}> <ForkVariant project={project} take={t.id} ready={ready} /> <CompareWith project={project} take={t.id} options={compareOptions} /> diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx @@ -28,9 +28,8 @@ import type { BenchTopSpec } from "@/lib/report/benchData"; // 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. +// A take's clip is not benched here (L3): its old address +// (`/takes/<take>/clip/<id>`) is the Open in draft page, a navigation of its own. // --------------------------------------------------------------------------- type View = { kind: "play" } | { kind: "clip"; id: string; href: string }; @@ -47,21 +46,13 @@ 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: 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 { +/** The clip id in a bench address of this project (`/clip/<id>`), or null. */ +function clipOf(pathname: string, project: string): string | 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; + return rest.length === 2 && rest[0] === "clip" && rest[1] ? decodeURIComponent(rest[1]) : 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 }) { @@ -92,9 +83,6 @@ 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], diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -17,7 +17,7 @@ import { AddClipToggle } from "../AddClip"; import { Advanced, Options } from "@/components/ui/disclosure"; import PronunciationPanel from "../PronunciationPanel"; import AddPosts from "../AddPosts"; -import { LintButton } from "../TakeTools"; +import { ImportItems, LintButton } from "../TakeTools"; import TightWindowsPanel from "./TightWindowsPanel"; import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { Fragment } from "react"; @@ -38,6 +38,9 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/ import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; import IntroRow from "./IntroEditor"; +import RemovedClips, { type RemovedRow } from "./RemovedClips"; +import { readRemoved, removedOutOfCut } from "@/lib/report/manifest.mjs"; +import { rejectReasonOf } from "@/lib/report/rejectReasons.mjs"; // The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector. import { InspectorToggle, WhenOpen } from "../inspector/shared"; import TitleInspector from "../inspector/TitleInspector"; @@ -64,6 +67,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor verdict: "confirmed" | "incorrect" | "rejected" | "unreviewed"; }[]; const clips = entries.filter((e) => e.kind === "clip"); + // The clips taken out on record and still out (removed.json), each with Restore (un-reject). + const removed: RemovedRow[] = (removedOutOfCut(await readRemoved(project.dir), m) as Record<string, unknown>[]).map((r) => ({ + id: String(r.id), + channel: typeof r.channel === "string" ? r.channel : null, + video: typeof r.video === "string" ? r.video : null, + start: typeof r.start === "number" ? r.start : null, + end: typeof r.end === "number" ? r.end : null, + why: rejectReasonOf(String(r.reason ?? ""))?.label ?? String(r.reason ?? "removed"), + note: typeof r.note === "string" ? r.note : typeof r.correction === "string" ? r.correction : null, + when: typeof r.when === "string" ? r.when : null, + })); // The walk's ★ clips, as trailer beats (lib/report/trailerCandidates.mjs). const candidates = trailerCandidates(m); // How much of the cut has been walked. One definition, shared with the bench @@ -463,6 +477,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {!postsFirst && <AddPosts project={project.id} channels={postChannels} />} {/* Check before render, on the cut itself (umtool lint <p>): the build's lint and the files its posts name. */} {entries.length > 0 && <LintButton project={project.id} />} + {/* Items of another project into the draft (umtool timeline <p> import-item): cloned, their files linked in. */} + <ImportItems project={project.id} /> {/* A montage's instances, ruled by ear before a render (release 34). */} {montage.length > 0 && ( <Link @@ -635,6 +651,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </section> )} + <RemovedClips project={project.id} rows={removed} /> + {/* --- corrections ------------------------------------------------ */} {/* Not a decision and not a defect in the CUT: a correction says the diff --git a/umtool/components/projects/report/RemovedClips.tsx b/umtool/components/projects/report/RemovedClips.tsx @@ -0,0 +1,82 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { clipBenchHref } from "@/lib/hrefs"; +import { announceManifestChanged, refusalOf, timelineOp } from "../timelineApi"; + +// THE REMOVED LIST (the Cut tab): the clips taken out on record (removed.json: Reject, Wrong speaker) that are +// still out of the cut, newest first, each with Restore -- un-reject (lib/report/manifest.mjs restoreRemoved): +// the clip back as the newest revision holding it had it, at its old place, every later write kept. The CLI +// twin is `umtool timeline <p> removed` and `restore <id>`. + +export type RemovedRow = { + id: string; + channel: string | null; + video: string | null; + start: number | null; + end: number | null; + why: string; + note: string | null; + when: string | null; +}; + +export default function RemovedClips({ project, rows }: { project: string; rows: RemovedRow[] }) { + const router = useRouter(); + const [busy, setBusy] = useState<string | null>(null); + const [said, setSaid] = useState<{ id: string; ok: boolean; text: string } | null>(null); + const restore = async (id: string) => { + setBusy(id); + setSaid(null); + // No token: a restore is an insert, never a rollback, so a write since this page read the cut is kept, not refused. + const res = await timelineOp(project, null, "restore", { id }); + setBusy(null); + if (!res.ok) { + setSaid({ id, ok: false, text: refusalOf(res) }); + return; + } + const j = res.json as { at?: number; notPutBack?: string[] }; + const left = Array.isArray(j.notPutBack) && j.notPutBack.length ? ` Not put back: ${j.notPutBack.join("; ")}.` : ""; + setSaid({ id, ok: true, text: `${id} is back in the cut at ${j.at}.${left}` }); + announceManifestChanged(project); + router.refresh(); + }; + if (!rows.length && !said) return null; + return ( + <section data-removed-clips="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <h2 className="micro mb-1.5">removed from the cut — {rows.length}</h2> + {rows.length > 0 && ( + <ul className="space-y-1"> + {rows.map((r) => ( + <li key={r.id} data-removed-clip={r.id} className="flex flex-wrap items-baseline gap-x-2 text-[12px] leading-snug"> + <Link href={clipBenchHref(project, r.id)} className="ink-link font-mono text-[11px]"> + {r.id} + </Link> + <span className="text-[11px] text-[var(--color-dim)]"> + {r.channel ?? "?"}/{r.video ?? "?"} @ {r.start ?? "?"}–{r.end ?? "?"} + </span> + <span data-removed-why=""> + {r.why} + {r.note ? `: ${r.note}` : ""} + </span> + {r.when && <span className="text-[11px] text-[var(--color-dim)]">{r.when.slice(0, 10)}</span>} + <Button type="button" size="sm" variant="outline" className="ml-auto" data-removed-restore={r.id} disabled={busy !== null} onClick={() => void restore(r.id)}> + {busy === r.id ? "Restoring…" : "Restore"} + </Button> + </li> + ))} + </ul> + )} + {said && ( + <p role="status" data-removed-said={said.ok ? "ok" : "refused"} className={`mt-1 text-[12px] ${said.ok ? "" : "text-[var(--color-bad)]"}`}> + {said.text} + </p> + )} + <p className="mt-1.5 text-[11px] text-[var(--color-dim)]"> + <code className="font-mono">umtool timeline {project} restore <id></code> + </p> + </section> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -104,7 +104,7 @@ Inbox cannot disagree about what is wrong with one. | `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` | | `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | -| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | +| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `import-item <src>:<item>[,…]` clones items of another project INTO THE DRAFT, as `take --import-item` does into a take (their files hard-linked in, placed `--after`/`--before` an entry or by date, again: updated in place or unchanged; the Cut tab's **Add items from another project**); `removed` lists the clips on that record still out of the cut, and `restore <id>` un-rejects one — the entry from the newest revision that holds it (claim, quote, cite and edges as they were) at its old place (after the entry before it there, else before the one after), every later write kept, an undo point first, and what its removal re-anchored or dropped listed as `not put back:` (the Cut tab's **Removed** list, **Restore**); `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | | `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo \| insert <spec> --after <id>\|-]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it. `insert` puts a clip (`<channel>/<video>@<start>-<end>`) into the take only (`takeEdit.mjs insertTakeEntry`) -- the app's **+ Add a clip to <take> only** on the take walk page, and Play's **+ Add a clip here** on a take with its own timeline | @@ -309,6 +309,9 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `timeline <project> duplicate <id> [--at N]` | an entry twice | form · *draft* | | `timeline <project> reject <id> not-matching\|wrong-speaker\|irrelevant\|repeats\|weak\|privacy\|other [--note NOTE]` | an entry rejected and removed, on the record | form · *draft* | | `timeline <project> wrong-speaker <id> [--correction CORRECTION]` | an entry removed: the wrong speaker | form · *draft* | +| `timeline <project> import-item <refs>… [--after AFTER] [--before BEFORE] [--as AS] [--dry-run]` | items of another project into the draft, their files linked in | form · *draft* | +| `timeline <project> removed` | the clips removed on record and still out of the cut | form · *project* | +| `timeline <project> restore <id>` | un-reject: a removed clip back as it was, at its old place | form · *draft* | | `timeline <project> post <post>` | a post added, or the one with its id replaced | form · *draft* | | `timeline <project> post-remove <id>` | a post out of the cut | form · *draft* | | `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -304,7 +304,9 @@ that mentions the seizure in question and one before it. The Marks box is on eve mark's); **Remove** one; **Clear** them all. - **From a terminal:** `umtool set <p> <clip> mark.add=<verdict>[@<sec>]` (or a JSON object with knobs), `mark.remove=<id>`, `mark.verdict=<verdict> [--mark <id>]`, `marks='[…]'` (all; `marks=` none); the `claim.*` keys - set the first mark's knobs, or `--mark <id>`'s. `umtool show` prints a clip's marks (`--json`: `marks`, each with + set the first mark's knobs, or `--mark <id>`'s. `claim=` (or `claim=none`) takes the clip's claim pin off — every + mark it carries — on the draft; a version's clip is cleared after **Open in draft** (`umtool takes open <p> <v>`), + so `claim= --take <v>` is refused and says so. `umtool show` prints a clip's marks (`--json`: `marks`, each with `stampsOn`). - **On a teaser** (a post shown as a text card; lane counter-zero): a teaser carries marks as a clip does — stamped over the card, counted, validated — with `at` in seconds from the CARD's start (after a dip's black), 0 to its @@ -718,6 +720,10 @@ in `removed.json` — or **Reject, keep in place** writes the verdict only, for it is the same flow with its reason preset ([report-video.md](report-video.md#verdict--what-the-walk-said)). Not on a take. +| knob | UI | CLI | route | +|---|---|---|---| +| un-reject: a removed clip back — the entry from the newest revision that holds it (claim, quote, cite, edges as they were), at its old place, every later write kept; what its removal re-anchored or dropped is said, not put back | the Cut tab's **removed from the cut** list (the clips on record in `removed.json` still out), **Restore** | `umtool timeline <p> removed` (the list), `umtool timeline <p> restore <id>` | `POST /api/report/timeline {op: "restore", id}` | + **Play and the clip bench are one app.** **Edit this clip** (E) opens the bench IN PLACE: Play is hidden and paused 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 @@ -1620,6 +1626,7 @@ has the recipe. | | From a terminal | What it writes | |---|---|---| | a draft from another take | `umtool take <p> --id <t> --draft --from <take> [--label L] [--patch F]` | `takes/<t>/take.json`: that take's style and patch (yours over it); nothing rendered | +| items of another project **into the draft** | `umtool timeline <p> import-item <project>:<item>[,<item>…] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | the same clone into the project's own cut (the draft), one undo point of the project's (`umtool timeline <p> undo`); the Cut tab's Options, **Add items from another project** | | items of another project into the take | `umtool take <p> --id <t> --import-item <project>:<item>[,<item>…] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | the entries cloned (narration, takes, pick, knobs) into the take's timeline, one undo point; their files **hard-linked** into `<p>` (another file at a path: `imports/<source>/…`); authors' pictures the take lacks into its `postAvatars`. Again: `updated` in place, or `unchanged` (no write) | | a post item's knobs, in the take | `umtool posts set-item <p> <item> k=v … --in-take <t>` (or `--take <t>`) | the take's entry; a piece made context or hidden that its read reads is re-joined first, as on the project | | the read's pieces, in the take | `umtool posts roles <p> <item> --set n=role --in-take <t>` | the take's entry's take parts | @@ -1630,9 +1637,10 @@ has the recipe. | an effect | `umtool posts fx <p> <item> add caption … --in-take <t>` | the take's entry's `fx` | | look, check, take back | `umtool timeline <p> --take <t>` · `umtool lint <p> --take <t>` (exit 0 clean) · `umtool timeline <p> --take <t> undo` | — / — / the take's newest edit, byte for byte | -**In umtool** (lane/ui-simplify): a take card's Options have **Check before render** (the lint), **New draft from this -take** (the next free `<take>-d<n>`) and **Add items from another project** (the project, the items, by date or -after/before an entry; **Preview** is `--dry-run`, then **Import into <take>**); New take has **Save as a draft**. The +**In umtool** (lane/ui-simplify): a take card's Options have **Check before render** (the lint) and **New draft from this +take** (the next free `<take>-d<n>`); **Add items from another project** is the Cut tab's, into the DRAFT (E1, 9 Nov: +the project, the items, by date or after/before an entry; **Preview** is `--dry-run`, then **Import into the draft** — +`umtool timeline <p> import-item`; a take's patch is the terminal's `take --import-item`); New take has **Save as a draft**. The post bench's take-only scope and the take walk's **+ Add a clip to <take> only** are RETIRED (umtool redesign L3: every UI edit lands in the draft — open the take in the draft first); their writes are the terminal's (`--in-take`, `umtool timeline <p> --take <t> insert <spec> --after <id>`, `POST /api/report/post-narration {…, inTake}`). diff --git a/umtool/e2e/fixtures/ingredient-rail-fixture.mjs b/umtool/e2e/fixtures/ingredient-rail-fixture.mjs @@ -22,6 +22,7 @@ // Synthetic, like every fixture. import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; +import { archiveMomentUrl } from "umtool-report-to-video/site-links"; export const RAIL_SITE = "http://127.0.0.1:9"; @@ -58,11 +59,18 @@ export function makeIngredientRailFixture({ reports, channels, manifest, cachedW write(rv, "transcript.cues.json", JSON.stringify({ version: 2, source: "whisper", id: "v7rembd1", title: "The Rumble Rail Recording", duration: 120, cues: [{ start: 0, end: 4, text: "rumble." }] })); // ── the projects ── - const origin = { siteOrigin: RAIL_SITE, channelSlug: "railchan" }; - const a = manifest("rail-a", "The Rail A Fixture", origin, [ + // provenance.siteOrigin stays public-looking (a loopback origin is a BLOCKING decision, projects.spec), and each + // clip's citeUrl names RAIL_SITE explicitly -- the moment URL the origin would have derived, on the placeholder. + const PUBLIC = "https://archive.example"; + const origin = { siteOrigin: PUBLIC, channelSlug: "railchan" }; + const cited = (m) => { + for (const e of m.timeline) e.citeUrl = archiveMomentUrl({ ...e, channel: e.channel ?? m.provenance.channelSlug }, m.provenance, e.start ?? 0, { origin: RAIL_SITE }); + return m; + }; + const a = cited(manifest("rail-a", "The Rail A Fixture", origin, [ { type: "clip", id: "ra1", video: "railvid", start: 12, end: 20, cite: 12, section: 0, quote: "the rail recording says line 2." }, { type: "clip", id: "ra2", video: "railvid", start: 100, end: 110, cite: 100, section: 0, quote: "the rail recording says line 17." }, - ]); + ])); const aDir = path.join(reports, "rail-a"); write(aDir, "video.manifest.json", a); const base = manifest("rail-a", "The Rail A Fixture", origin, [a.timeline[0]]); @@ -74,10 +82,10 @@ export function makeIngredientRailFixture({ reports, channels, manifest, cachedW write(aDir, "quote-check.json", { version: 1, checkedAt: "2026-11-06T12:00:00.000Z", clips: { ra1: { status: "ok", offset: 0.02, against: "cues", cut: { from: 12, to: 20 }, quote: "the rail recording says line 2." } } }); const bDir = path.join(reports, "rail-b"); - write(bDir, "video.manifest.json", manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }])); + write(bDir, "video.manifest.json", cited(manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }]))); write(path.join(bDir, "out"), "links.json", { version: 1, checkedAt: "2026-11-07T00:00:00.000Z", fetched: 1, origins: {}, links: [{ clip: "rb1", url: `${RAIL_SITE}/?v=railchan%2Frailvid&t=15`, state: "ok", origin: RAIL_SITE }] }); const rDir = path.join(reports, "rail-r"); - write(rDir, "video.manifest.json", manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: RAIL_SITE, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }])); + write(rDir, "video.manifest.json", cited(manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: PUBLIC, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }]))); return { aDir, bDir, rDir }; } diff --git a/umtool/e2e/fixtures/post-narration-fixture.mjs b/umtool/e2e/fixtures/post-narration-fixture.mjs @@ -13,7 +13,7 @@ // it back before each test. // // Synthetic, like every fixture. -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { spawnSync } from "node:child_process"; import path from "node:path"; @@ -22,6 +22,45 @@ const ff = (args) => { if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`); }; +/** + * Every file the fixture writes under its narration/, relative to it. Nothing + * else under narration/ is the fixture's: it is a take, a part, a cache or a + * trash a spec made. + */ +export const POST_NARRATION_OWN_FILES = ["posts/11/take-1.orpheus-zac.wav", "posts/11/take-1.orpheus-zac.wav.heard.json"]; + +/** + * Put the fixture's narration/ back to what it built, removing what any spec + * left there. Several specs share this project (long-reads writes a take-7 of + * p-11 and re-reads it into more), and a new take is numbered past every + * take-N on disk (report-to-video/post-narration.mjs nextTakeNumber) -- so + * without this, which spec ran first decided post-narration's take numbers. + * @param {string} dir the project's directory + */ +export function resetPostNarrationFiles(dir) { + const root = path.join(dir, "narration"); + const keep = new Set(POST_NARRATION_OWN_FILES.map((f) => path.join(root, f))); + const prune = (d) => { + let entries = []; + try { + entries = readdirSync(d, { withFileTypes: true }); + } catch { + return false; + } + let kept = false; + for (const e of entries) { + const p = path.join(d, e.name); + if (e.isDirectory() && !e.isSymbolicLink()) { + if (prune(p)) kept = true; + else rmSync(p, { recursive: true, force: true }); + } else if (keep.has(p)) kept = true; + else rmSync(p, { force: true }); + } + return kept; + }; + prune(root); +} + /** @param {{ reports: string, deckManifest: Function }} o */ export function makePostNarrationFixture({ reports, deckManifest }) { const name = "post-narration-fixture"; diff --git a/umtool/e2e/long-reads.spec.ts b/umtool/e2e/long-reads.spec.ts @@ -4,6 +4,7 @@ import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "n import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { resetPostNarrationFiles } from "./fixtures/post-narration-fixture.mjs"; // --------------------------------------------------------------------------- // LONG READS (operator, 4 Nov, a 6.5-minute post): a read's parts RE-TIMED with @@ -38,6 +39,13 @@ const picked = () => { test.beforeAll(() => { if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); }); +// The project is shared (post-narration, post-captions, picture-replies, thread-* read it after this file): leave +// it as the fixture built it -- its manifest, and no take-7 or re-read of p-11 on disk to number their takes past. +test.afterAll(() => { + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + resetPostNarrationFiles(DIR); +}); test.beforeEach(() => { test.setTimeout(120_000); copyFileSync(`${MANIFEST}.pristine`, MANIFEST); diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -5,6 +5,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSyn import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { resetPostNarrationFiles } from "./fixtures/post-narration-fixture.mjs"; // --------------------------------------------------------------------------- // NARRATED POST ITEMS (report-to-video/post-narration.mjs; knobs.md, "A narrated @@ -47,12 +48,10 @@ test.beforeEach(() => { copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); - for (const f of ["take-2.orpheus-zac.wav", "take-2.recorded-operator.wav", "take-3.recorded-operator.wav", "take-2.convert-zac.wav", "take-3.convert-zac.wav", "take-2.pause-orpheus.wav", "take-2.revoice-orpheus.wav"]) rmSync(path.join(DIR, "narration", "posts", "11", f), { force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", "take-2.recorded-operator.parts"), { recursive: true, force: true }); - // The parts cache a re-voice's phrase lands in (the fixture has none of its own). - rmSync(path.join(DIR, "narration", "parts-cache"), { recursive: true, force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", ".trash"), { recursive: true, force: true }); - rmSync(path.join(DIR, "narration", "posts", "11", ".recording-operator"), { recursive: true, force: true }); + // narration/ back to the fixture's own two files: this test's takes, parts, the parts cache a re-voice's phrase + // lands in, .trash and .recording-* -- and ANOTHER spec's (long-reads leaves a take-7 of p-11, and a new take is + // numbered past every take-N on disk, so the run order used to decide this spec's take numbers). + resetPostNarrationFiles(DIR); }); const root = (page: Page) => page.locator("[data-play-cut]"); diff --git a/umtool/e2e/shell.spec.ts b/umtool/e2e/shell.spec.ts @@ -246,3 +246,14 @@ test("the head glides, and does not under reduced motion", async ({ page }) => { await expect(page.locator("[data-lit-list] .lit-head[data-placed]").first()).toBeAttached(); expect(await duration()).toMatch(/^0s/); }); + +test("every page links the umtool icon -- the parent mark lit in Signal -- and it is served", async ({ page, request }) => { + await page.goto(urls.homeHref()); + const href = await page.locator("head link[rel=icon][type='image/svg+xml']").first().getAttribute("href"); + expect(href).toMatch(/^\/icon\.svg/); + const res = await request.get(href!); + expect(res.status()).toBe(200); + expect(res.headers()["content-type"]).toContain("image/svg+xml"); + // Signal's on-dark value is the lit line (common/lib/brand.ts ACCENTS.signal.onDark). + expect(await res.text()).toContain('fill="#5fa8a0"'); +}); diff --git a/umtool/e2e/take-items.spec.ts b/umtool/e2e/take-items.spec.ts @@ -4,6 +4,7 @@ import { readFileSync, statSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; +import { openPanel } from "./panels"; // --------------------------------------------------------------------------- // A TAKE'S OWN ITEMS (umtool/docs/cli.md, "Edit a take, not the project"): @@ -103,3 +104,32 @@ test("Play on the take plays the imported item: its row between p-1 and p-3, nar await page.goto(urls.playHref(P, { bare: true })); await expect(page.locator("[data-play-row]")).toHaveCount(2); }); + +test("the Cut tab's Add items from another project imports INTO THE DRAFT (L3): Preview writes nothing, Import adds p-2 to the project's cut, its files linked; the source untouched", async ({ page }) => { + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut"); + const box = page.locator('[data-take-import="draft"]'); + await box.locator('[data-action="import-open"]').click(); + await box.locator("[data-import-source]").fill(S); + await box.locator("[data-import-items]").fill("p-2"); + await box.locator('[data-action="import-preview"]').click(); + await expect(page.locator('[data-import-result="plan"] [data-import-row="p-2"]')).toContainText("p-2 added"); + // REMOVED_LIST_SHOTS=<dir> (the lane's shots): the draft import at 1366×768. + if (process.env.REMOVED_LIST_SHOTS) { + await page.setViewportSize({ width: 1366, height: 768 }); + await box.scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(process.env.REMOVED_LIST_SHOTS, "draft-import.png") }); + } + expect(text(DIR), "a preview writes nothing").toBe(projectBefore); + await expect(box.locator('[data-action="import-go"]')).toHaveText("Import into the draft"); + await box.locator('[data-action="import-go"]').click(); + await expect(page.locator('[data-import-result="done"]')).toHaveAttribute("data-import-exit", "0"); + await expect.poll(() => (JSON.parse(text(DIR)).timeline as Entry[]).map((e) => e.id)).toEqual(["p-1", "p-2", "p-3"]); + expect(statSync(path.join(DIR, "narration/posts/2/take-1.orpheus-thread.wav")).ino).toBe(statSync(path.join(SRC, "narration/posts/2/take-1.orpheus-thread.wav")).ino); + expect(text(SRC)).toBe(sourceBefore); + // The take cards no longer carry it: a take is opened in the draft first. + await page.goto(urls.takesHref(P)); + await openPanel(page, "options", "take-card"); + await expect(page.locator(`[data-take-tools="${TAKE}"]`)).toBeVisible(); + await expect(page.locator("[data-take-import]")).toHaveCount(0); +}); diff --git a/umtool/e2e/take-walk.spec.ts b/umtool/e2e/take-walk.spec.ts @@ -58,6 +58,20 @@ test("the Takes page: the draft take and the saved version each Play and Open in await expect(page.locator('[data-take="v1"] [data-take-draft="v1"]')).toContainText("saved version — not rendered"); }); +test("the bench's data is the draft's whatever a take is named: a take's clip is not benched (its take paths are gone, E1)", async ({ request }) => { + // t01a is the take's, not the draft's: once the bench walked the take with `walkTake`; now it is a 404. + const theirs = await request.get(`/api/report/bench?project=${encodeURIComponent(PROJECT)}&clip=t01a&walkTake=${TAKE}`); + expect(theirs.status()).toBe(404); + const ours = await request.get(`/api/report/bench?project=${encodeURIComponent(PROJECT)}&clip=w01&walkTake=${TAKE}&take=${TAKE}&from=play`); + expect(ours.status()).toBe(200); + const j = (await ours.json()) as { data: { take?: unknown; fromPlay: { take: string } }; top: { kind: string } }; + expect(j.data.take).toBeUndefined(); + expect(j.top.kind).toBe("Clip bench"); + // `take` with from=play is only the take Play was on: Back keeps it, edits go to the draft. + expect(j.data.fromPlay.take).toBe(TAKE); + expect(manifestText()).toBe(masterBefore); +}); + test("the walk's old address asks to open the take in the draft; the walk's data route still reads the take", async ({ page, request }) => { await page.goto(urls.takeWalkHref(PROJECT, TAKE)); const ask = page.locator(`[data-open-draft="${TAKE}"]`); diff --git a/umtool/e2e/timeline-edit.spec.ts b/umtool/e2e/timeline-edit.spec.ts @@ -36,6 +36,7 @@ test.beforeEach(() => { copyFileSync(PRISTINE, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); + rmSync(path.join(DIR, "removed.json"), { force: true }); }); /** The project page on the tab that holds `name`: the timeline (the Cut), or the on-screen panel's structure editors (Build). */ @@ -157,3 +158,28 @@ test("a post added, then removed; the fact-check's labels once the deck is on", .poll(() => ((manifest().render.chrome as { factcheck?: { tally?: unknown } }).factcheck ?? {}).tally) .toEqual({ showAt: "first" }); }); + +test("the Removed list: a rejected clip is listed and Restore puts it back as it was, at its old place", async ({ page, request }) => { + // a03 (a02 carries the post p1: rejecting it is refused by the build). + const a03 = manifest().timeline.find((e) => e.id === "a03")!; + const rej = await request.post("/api/report/timeline", { data: { project: PROJECT, op: "reject", id: "a03", reason: "repeats", note: "covered by a01" } }); + expect(rej.ok(), await rej.text()).toBe(true); + await expect.poll(order).toEqual(["t1", "a01", "a02"]); + await open(page); + const list = page.locator("[data-removed-clips]"); + await expect(list.locator("[data-removed-clip]")).toHaveCount(1); + await expect(list.locator('[data-removed-clip="a03"] [data-removed-why]')).toContainText("covered by a01"); + // REMOVED_LIST_SHOTS=<dir>: the list at a laptop's 1366×768. + if (process.env.REMOVED_LIST_SHOTS) { + await page.setViewportSize({ width: 1366, height: 768 }); + await list.scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(process.env.REMOVED_LIST_SHOTS, "removed-list.png") }); + } + await list.locator('[data-removed-restore="a03"]').click(); + await expect(list.locator('[data-removed-said="ok"]')).toContainText("a03 is back in the cut at 3"); + await expect.poll(order).toEqual(["t1", "a01", "a02", "a03"]); + // The entry as it was before the reject: no verdict, every field it had. + expect(manifest().timeline.find((e) => e.id === "a03")).toEqual(a03); + await expect.poll(() => shownOrder(page)).toEqual(["t1", "a01", "a02", "a03"]); + await expect(page.locator("[data-removed-clip]")).toHaveCount(0); +}); diff --git a/umtool/lib/brandIcon.test.ts b/umtool/lib/brandIcon.test.ts @@ -0,0 +1,17 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { markSvg } from "yt-dlp-transcript-common/lib/brand"; +import { MEDIA_MARK_PALETTE } from "yt-dlp-transcript-common/lib/brandMedia"; + +// umtool/app/icon.svg is umtool's favicon (Next's app/icon.svg file convention +// links it from every page). umtool makes the media, so its icon is the parent +// mark lit in Signal -- mark M2, the slate ground and dim of +// ICON_PALETTES.archilyzer with Signal's on-dark lit line -- and it must stay +// the mark: markSvg is the geometry, this file a copy of it. Regenerate with +// markSvg(MEDIA_MARK_PALETTE) if this fails. +test("app/icon.svg is markSvg(MEDIA_MARK_PALETTE), byte for byte", () => { + const file = fileURLToPath(new URL("../app/icon.svg", import.meta.url)); + assert.equal(readFileSync(file, "utf8").trimEnd(), markSvg(MEDIA_MARK_PALETTE)); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -906,7 +906,7 @@ export const GROUPS = [ ["`timeline <project> teaser-insert [--at start\\|end \\| --after <id> \\| --before <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"] [--hold S] [--line …] \\| --lines-json <json\\|@file> [--json]`", "a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], ["`timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\\|@file>` · `undo`", - "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"], + "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `import-item <src>:<item>[,…]` clones items of another project INTO THE DRAFT, as `take --import-item` does into a take (their files hard-linked in, placed `--after`/`--before` an entry or by date, again: updated in place or unchanged; the Cut tab's **Add items from another project**); `removed` lists the clips on that record still out of the cut, and `restore <id>` un-rejects one — the entry from the newest revision that holds it (claim, quote, cite and edges as they were) at its old place (after the entry before it there, else before the one after), every later write kept, an undo point first, and what its removal re-anchored or dropped listed as `not put back:` (the Cut tab's **Removed** list, **Restore**); `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"], ["`timeline <project> insert (--to-section N \\| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]`", "a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press))"], ["`timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\\|@file\\|id…>`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -379,6 +379,11 @@ function timeline() { tl("duplicate", "draft", "an entry twice", [id(), num("--at")]), tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })]), tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })]), + tl("import-item", "draft", "items of another project into the draft, their files linked in", [ + many("refs", { required: true, item: "ref", help: "<project>:<item>[,<item>…], one per line" }), opt("--after"), opt("--before"), opt("--as"), dry(), + ]), + tl("removed", "project", "the clips removed on record and still out of the cut", []), + tl("restore", "draft", "un-reject: a removed clip back as it was, at its old place", [arg("id", { help: "the removed clip's id (timeline removed lists them)" })]), tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]), tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]), tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]), diff --git a/umtool/lib/e2eEnvGuard.mjs b/umtool/lib/e2eEnvGuard.mjs @@ -0,0 +1,65 @@ +// The umtool e2e suite's refusal of an inherited data root. +// +// Playwright hands the app server, the editor stub and every CLI a spec spawns +// this shell's whole environment. The config confines what it sets (the +// fixture's SONG_DIR, CHANNELS_DIR, ...), but a variable it does NOT set wins +// by inheritance: REPORTS_DIR is read before the fixture's SONG_REPORTS_DIR +// (lib/paths.mjs REPORTS_ROOT), and a spec's own spawn of a CLI with +// `{ ...process.env }` carries CHANNELS_DIR and SONG_DIR along. On 2 Nov a run +// that inherited them wrote fixture state into real projects under ~/reports. +// +// So a data root in the environment is refused, loudly and by name, unless it +// already points inside the suite's own fixture. Unset (or empty) is the +// normal case; the gate scripts `unset REPORTS_DIR CHANNELS_DIR SONG_DIR`. +// +// SONG_DIR IS NOT ONE OF THEM. It is the documented way to run the song-data +// specs against a copy (AGENTS.md; e2e/fixtures/make-fixture.mjs), and only the +// fixture builder reads it -- READ-ONLY, to derive the empty-state copy and link +// the heavy audio; the app server is given the fixture's own SONG_DIR after it. +import { realpathSync } from "node:fs"; +import path from "node:path"; + +/** The variables that name a data root the suite must never inherit. */ +export const INHERITED_DATA_ROOTS = ["REPORTS_DIR", "CHANNELS_DIR"]; + +/** A path with its links resolved (a worktree reached through a symlinked parent), else as given. */ +const real = (p) => { + const abs = path.resolve(p); + try { + return realpathSync(abs); + } catch { + // Missing: resolve the nearest parent that exists, and keep the rest as written. + const parent = path.dirname(abs); + return parent === abs ? abs : path.join(real(parent), path.basename(abs)); + } +}; + +const inside = (p, root) => { + const rel = path.relative(real(root), real(p)); + return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)); +}; + +/** + * Every inherited data root that is not the fixture's, as `{ name, value }`. + * @param {Record<string, string | undefined>} env + * @param {string} fixture the suite's fixture directory (e2e/.e2e-song) + */ +export function foreignDataRoots(env, fixture) { + const root = fixture; + return INHERITED_DATA_ROOTS.filter((name) => { + const v = env[name]; + return typeof v === "string" && v.trim() !== "" && !inside(v, root); + }).map((name) => ({ name, value: env[name] })); +} + +/** The refusal, naming each variable; null when there is nothing to refuse. */ +export function dataRootRefusal(env, fixture) { + const bad = foreignDataRoots(env, fixture); + if (!bad.length) return null; + return ( + `umtool e2e refuses to run: ${bad.map((b) => `${b.name}=${b.value}`).join(", ")} ` + + `${bad.length === 1 ? "is" : "are"} set in this shell and not the suite's fixture (${path.resolve(fixture)}). ` + + `The app server and the CLIs the specs spawn inherit it and would read and write real data there ` + + `(2 Nov: a run wrote fixture state into ~/reports). Unset it: \`unset ${bad.map((b) => b.name).join(" ")}\`.` + ); +} diff --git a/umtool/lib/e2eEnvGuard.test.mjs b/umtool/lib/e2eEnvGuard.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { dataRootRefusal, foreignDataRoots } from "./e2eEnvGuard.mjs"; + +const FIX = "/w/umtool/e2e/.e2e-song"; + +test("nothing set, or set empty, is the normal case", () => { + assert.equal(dataRootRefusal({}, FIX), null); + assert.equal(dataRootRefusal({ REPORTS_DIR: "", CHANNELS_DIR: " " }, FIX), null); +}); + +test("a root inside the fixture is the suite's own, and passes", () => { + assert.equal(dataRootRefusal({ CHANNELS_DIR: `${FIX}/channels`, REPORTS_DIR: FIX }, FIX), null); +}); + +test("an inherited REPORTS_DIR or CHANNELS_DIR anywhere else is refused, naming each variable", () => { + const env = { REPORTS_DIR: "/home/u/reports", CHANNELS_DIR: "/home/u/transcripts/channels", HOME: "/home/u" }; + assert.deepEqual(foreignDataRoots(env, FIX).map((b) => b.name), ["REPORTS_DIR", "CHANNELS_DIR"]); + const msg = dataRootRefusal(env, FIX); + assert.match(msg, /REPORTS_DIR=\/home\/u\/reports/); + assert.match(msg, /CHANNELS_DIR=\/home\/u\/transcripts\/channels/); + assert.match(msg, /unset REPORTS_DIR CHANNELS_DIR/); +}); + +test("SONG_DIR elsewhere is accepted: the documented copy the fixture builder reads from, and nothing else sees", () => { + assert.equal(dataRootRefusal({ SONG_DIR: "/elsewhere/song-copy/data" }, FIX), null); + assert.deepEqual(foreignDataRoots({ SONG_DIR: "/elsewhere", REPORTS_DIR: "/home/u/reports" }, FIX).map((b) => b.name), ["REPORTS_DIR"]); +}); + +test("a sibling whose name merely starts with the fixture's is not inside it", () => { + assert.deepEqual(foreignDataRoots({ CHANNELS_DIR: `${FIX}-other/channels` }, FIX).map((b) => b.name), ["CHANNELS_DIR"]); + assert.deepEqual(foreignDataRoots({ REPORTS_DIR: `${FIX}/../reports` }, FIX).map((b) => b.name), ["REPORTS_DIR"]); +}); + +test("a worktree reached through a symlinked parent is its own fixture, either way round", async () => { + const root = await mkdtemp(path.join(tmpdir(), "e2e-guard-")); + try { + const realFix = path.join(root, "real", "umtool", ".e2e-song"); + await mkdir(path.join(realFix, "channels"), { recursive: true }); + await symlink(path.join(root, "real"), path.join(root, "link")); + const viaLink = path.join(root, "link", "umtool", ".e2e-song"); + assert.equal(dataRootRefusal({ CHANNELS_DIR: path.join(viaLink, "channels") }, realFix), null); + assert.equal(dataRootRefusal({ CHANNELS_DIR: path.join(realFix, "channels"), REPORTS_DIR: path.join(viaLink, "reports-not-yet") }, viaLink), null); + assert.deepEqual(foreignDataRoots({ REPORTS_DIR: path.join(root, "real", "elsewhere") }, viaLink).map((b) => b.name), ["REPORTS_DIR"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -38,6 +38,7 @@ import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; import { walkProjects } from "../projects/walk.mjs"; export const USAGE_INDEX_FORMAT = "umtool-usage-index"; @@ -148,7 +149,9 @@ export async function buildUsageIndex({ reportsRoot, channelsDir, previous = nul return dir; }; - const projects = (await walk(reportsRoot)).filter((p) => p.kind === "report-video" || p.kind === undefined); + // A project whose kind makes takes is one whose manifests hold clips (the registry says which; a kind id is + // never written here -- e2e/projects.spec.ts). A walk that reports no kind (a test's) is read as one. + const projects = (await walk(reportsRoot)).filter((p) => p.kind === undefined || kindMakesTakes(p.kind)); const files = {}; let parsed = 0; let reused = 0; diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts @@ -1,5 +1,5 @@ import { notFound } from "next/navigation"; -import { projectsHref, clipBenchHref, ingredientHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs"; +import { projectsHref, clipBenchHref, ingredientHref, playHref } from "@/lib/hrefs"; import type { ClipBenchData } from "@/components/projects/ClipBench"; import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell"; import { @@ -27,6 +27,10 @@ import type { ProjectRef } from "@/lib/project-types"; // `order: "cut"` (the bench opened inside Play): p / n step along the CUT -- // the reel strip's neighbours, every clip judged or not -- not the walk's // recording order; the walk is a different journey. +// +// The DRAFT's clips only (L3): a take's clip is never benched -- its old +// address (`…/takes/<t>/clip/<id>`) is the Open in draft page -- so there is +// no take here (the take walk's paths went with E1, 9 Nov). /** BenchTop's props, as data (the server page and the app both draw it). */ export type BenchTopSpec = { @@ -46,18 +50,18 @@ export type BenchTopSpec = { }; /** - * @returns null when the clip is not a clip of the cut (or the take) -- the page's 404 + * @returns null when the clip is not a clip of the cut -- the page's 404 */ export async function clipBenchData( project: ProjectRef, clipId: string, - { search = {}, take = null, order = "walk" }: { search?: Record<string, string | undefined>; take?: string | null; order?: "walk" | "cut" } = {}, + { search = {}, order = "walk" }: { search?: Record<string, string | undefined>; order?: "walk" | "cut" } = {}, ): Promise<{ data: ClipBenchData; top: BenchTopSpec } | null> { // `?all=1`: the walk visits every fetched clip, judged or not. const all = search.all === "1"; let walk: Awaited<ReturnType<typeof walkOf>>; try { - walk = await walkOf(project, { take, all }); + walk = await walkOf(project, { all }); } catch { return null; } @@ -95,9 +99,8 @@ export async function clipBenchData( const windows = await windowsFor(project, entry, await projectCache(project, manifest)); // The mtime rides along so a re-render busts the browser's cache: the segment // is written back to the SAME path, and without it the player would keep - // showing the cut from before the edit. A take's clip has none: the - // project's segments are the project's cut. - const seg = take ? null : await segmentFor(project, clipId); + // showing the cut from before the edit. + const seg = await segmentFor(project, clipId); const widest = windows[0] ?? null; const view = widest ? { from: widest.from, to: widest.to } @@ -176,7 +179,7 @@ export async function clipBenchData( endsSentence: entry.endsSentence ?? null, noPunctuation: !!entry.noPunctuation, sourceDuration: entry.duration ?? null, - segment: take ? null : (seg?.rel ?? entry.segment ?? null), + segment: seg?.rel ?? entry.segment ?? null, segmentMtime: seg?.mtimeMs ?? null, // What the header would say with no overrides. Shown beside the fields that // replace it, because "the archive says 2019" is the whole reason `date` @@ -200,7 +203,7 @@ export async function clipBenchData( ).length, cues: cues?.cues ?? [], siblings: siblingsOf(manifest, clipId), - // The project's manifest token, or -- walking a take -- the take's. + // The project's manifest token. token: walk.token, fetchPad: manifest.render?.fetchPad ?? 3, // The widest the fetch route will go. The BUTTON has to know it: it names @@ -225,67 +228,41 @@ export async function clipBenchData( }; // The piece this view belongs to: the article's when an article claims the project (P4a-2). - // Walking a take, Back is the take's walk (its overview), on the Takes page's side. - const back = take ? takeWalkHref(project.id, take, { all }) : await pieceHrefOfProject(project.id, { tab: "cut" }); + const back = await pieceHrefOfProject(project.id, { tab: "cut" }); // ---- opened from Play the cut ("Edit this clip") -------------------------- // // `?from=play` rides every walk link from here (p / n / Confirm's advance), // 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 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. + // everything after this clip. An address that names the take Play was on + // (`?take=`) keeps it on Back, and the bench says its edits go to the cut. const fromPlay = search.from === "play"; const withOrder = (h: string) => (order === "cut" ? `${h}${h.includes("?") ? "&" : "?"}order=cut` : h); - const playTake = take && fromPlay ? take : fromPlay && search.take ? search.take : null; + const playTake = 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 - ? withOrder(takeClipHref(project.id, take, id, { all, play: fromPlay ? {} : null })) - : withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); + const href = (id: string) => withOrder(clipBenchHref(project.id, id, fromPlay ? { play: { take: playTake } } : {})); data.walkHrefs = { prev: prev ? href(prev) : null, next: next ? href(next) : null, back, - backLabel: take ? `take ${take}` : project.name, + backLabel: project.name, }; - if (take && walk.take) { - const timeline = (manifest.timeline ?? []) as { id: string }[]; - data.take = { - id: take, - label: walk.take.label, - draft: walk.take.draft, - editable: walk.take.editable, - all, - 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, play: fromPlay ? {} : null })])), - at: timeline.findIndex((e) => e.id === clipId), - entries: timeline.length, - }; - } - // `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; + data.fromPlay = fromPlay ? { href: playHref(project.id, { take: playTake, clip: clipId, at }), take: playTake } : null; // Walk → Play (the audit's "no way back"): the cut, from this clip. - data.playHere = take || fromPlay ? null : playHref(project.id, { clip: clipId }); + data.playHere = 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. - data.working = take - ? null - : await readWorkingCut(project.dir).catch(() => null); + data.working = await readWorkingCut(project.dir).catch(() => null); const top: BenchTopSpec = { - trail: take ? [{ href: projectsHref(), label: "Projects" }, { href: takesHref(project.id), label: `${project.name} · takes` }] : [{ href: projectsHref(), label: "Projects" }], - back: { href: back, label: take ? `take ${take}` : project.name }, - kind: take ? "Take walk" : order === "cut" ? "Clip bench · the cut's order" : "Clip bench", + trail: [{ href: projectsHref(), label: "Projects" }], + back: { href: back, label: project.name }, + kind: order === "cut" ? "Clip bench · the cut's order" : "Clip bench", here: clipId, // The walk on a phone draws its own place bar (ClipBench). phone: "hidden", // The head's slot: Back to the cut (from Play), or Play from here. - slot: fromPlay || !take, + slot: true, pos: { index: order === "cut" ? ci + 1 : i + 1, total: order === "cut" ? cutClips.length : clips.length }, prev: prev ? { href: href(prev), label: prev, attrs: { "data-clip-nav": "prev" } } : null, next: next ? { href: href(next), label: next, attrs: { "data-clip-nav": "next" } } : null, diff --git a/umtool/lib/report/cast.test.mjs b/umtool/lib/report/cast.test.mjs @@ -74,7 +74,7 @@ const CH = path.join(ROOT, "channels"); ); await mkdir(DIR, { recursive: true }); await writeFile(path.join(DIR, "video.manifest.json"), JSON.stringify({ - schemaVersion: 1, slug: "voices", title: "Voices", kind: "report-video", provenance: { channelsDir: "../channels", channelSlug: "chan" }, + schemaVersion: 1, slug: "voices", title: "Voices", provenance: { channelsDir: "../channels", channelSlug: "chan" }, render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } }, timeline, }, null, 2)); await wavOf(path.join(DIR, "narration", "posts", "1", "take-1.orpheus-zac.wav"), VOICE_A, 1.5); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -58,7 +58,7 @@ const GAP_KEYS = ["gaps", "gap.add", "gap.remove"]; export const VERTICAL_SET_KEYS = Object.freeze(["vertical", "vertical.crop", "vertical.layout", "vertical.aspect"]); export const SIDE_SET_KEYS = Object.freeze(["side", "side.item", "side.post", "side.from", "side.to", "side.place"]); const SET_KEYS = [ - ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, + "claim", ...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS, ...FX_KEYS, ...GAP_KEYS, "chat", "hideModules", "shelfNote", // The vertical format (lane vertical): the clip's 9:16 crop and layout, and its side post. ...VERTICAL_SET_KEYS, ...SIDE_SET_KEYS, @@ -71,7 +71,9 @@ export const SET_USAGE = [ " (read from the last clip carrying the claim); claim.hold s (0.5–10); claim.stamp true|false;", " claim.count 1–99; claim.label ≤ 20 chars; claim.eventDate YYYY-MM-DD, the day the event it counts", " happened when not the clip's (a deck claim's window dates it so: render.chrome.deck.claims).", - " The claim.* keys set the clip's first mark, or --mark <id>'s.", + " The claim.* keys set the clip's first mark, or --mark <id>'s. `claim=` (or claim=none) takes the clip's claim", + " pin off -- every mark it carries, as marks= does -- on the DRAFT; a version's clip is opened in the draft first", + " (umtool takes open <p> <v>), so claim= with --take is refused.", " Marks (a clip may carry up to 8, each its own stamp and count): mark.add=<verdict>[@<sec>] adds one", " (the verdict by name or by this cut's label, e.g. Episodes@190.2; a JSON object for its knobs too);", " mark.remove=<id>; mark.verdict=<verdict> (the first mark's, or --mark <id>'s; every clip carrying", @@ -225,6 +227,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const markChanges = []; /** @type {Record<string, unknown>} */ const entryPatch = {}; + let claimOff = false; for (const [key, value] of parseAssignments(rest)) { if (!SET_KEYS.includes(key)) throw new CliError(`${key} is not a clip knob (${SET_KEYS.join(", ")})`); if (key === "layout") { @@ -272,6 +275,16 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso } continue; } + if (key === "claim") { + // The clip's claim pin, off (owed 6 Nov: there was no way to take one off but a hand edit). Only clearing: + // a claim is added as a mark (mark.add=<verdict>[@<s>]), its id and verdict edited in the On-screen table. + if (value !== null && !(typeof value === "string" && /^\s*none\s*$/i.test(value))) { + throw new CliError(`claim=${typeof value === "string" ? value : JSON.stringify(value)}: claim= (or claim=none) takes the clip's claim off; to add one, mark.add=<verdict>[@<source second>]`); + } + claimOff = true; + markChanges.push({ set: null }); + continue; + } if (MARK_KEYS.includes(key)) { markChanges.push(markChangeOf(key, value, mark)); continue; @@ -284,6 +297,12 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const takeFlag = flags.get("--take"); const take = typeof takeFlag === "string" && takeFlag ? takeFlag : null; if (flags.has("--take") && !take) throw new CliError("--take needs a take id"); + // A version is frozen (L3): its clip's claim comes off in the draft, after Open in draft brings the version there. + if (take && claimOff) { + throw new CliError( + `claim= --take ${take}: a version's clips are not edited in place -- open it in the draft first (umtool takes open ${project.id} ${take}), then \`umtool set ${project.id} ${clipId} claim=\``, + ); + } if (take && (markChanges.length || Object.keys(claim).length)) throw new CliError("--take sets a take's entry knobs; claim.* and marks are the project's (set them without --take)"); // `blur.on=` (or false): no blur at all, whatever else was given. if (Object.keys(blur).length) entryPatch.blur = "on" in blur && (blur.on === null || blur.on === false) ? null : blur; @@ -339,7 +358,7 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso return 0; } if (results.marks) { - out(`${clipId}: ${results.marks.length ? `marks ${results.marks.map((m) => markLine(m, results.stampsOnByMark?.[m.id], clipId)).join(" | ")}` : "no marks"}`); + out(`${clipId}: ${results.marks.length ? `marks ${results.marks.map((m) => markLine(m, results.stampsOnByMark?.[m.id], clipId)).join(" | ")}` : claimOff ? "no claim (its pin taken off)" : "no marks"}`); if (results.added) out(` added ${results.added.join(", ")}`); } if (results.claim) { diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -153,6 +153,34 @@ test("umtool set: claim and audio knobs through the writers; key= clears; a bad assert.equal("layout" in (await read(dir)).timeline[0], false); }); +test("umtool set claim=: the clip's claim pin off on the draft; claim=none too; a value or --take is refused", async () => { + const dir = await project("claimoff"); + const { lines, run } = runner(setCommand); + assert.equal(await run("claimoff", "c01", "claim=x"), 2); + assert.match(lines.at(-1), /claim= \(or claim=none\) takes the clip's claim off; to add one, mark\.add=/); + assert.deepEqual((await read(dir)).timeline[0].claim, { id: "k1", verdict: "CONTRADICTED" }, "untouched"); + // A version (L3): refused, with the way there -- nothing written to the take or the draft. + const { draftTake } = await import("./takeMaker.mjs"); + await draftTake(dir, { id: "v1", label: "Version 1", patch: {} }); + const takeBefore = await readFile(path.join(dir, "takes", "v1", "take.json"), "utf8"); + assert.equal(await run("claimoff", "c01", "claim=", "--take", "v1"), 2); + assert.match(lines.at(-1), /open it in the draft first \(umtool takes open claimoff v1\)/); + assert.equal(await readFile(path.join(dir, "takes", "v1", "take.json"), "utf8"), takeBefore); + assert.deepEqual((await read(dir)).timeline[0].claim, { id: "k1", verdict: "CONTRADICTED" }); + // The draft: the pin comes off. + assert.equal(await run("claimoff", "c01", "claim="), 0, lines.join("\n")); + assert.equal("claim" in (await read(dir)).timeline[0], false); + assert.match(lines.at(-1), /c01: no claim \(its pin taken off\)/); + // A clip of two marks: claim=none takes both (claims), as marks= would. + const m = await read(dir); + m.timeline[1].claims = [{ id: "a", verdict: "CONTRADICTED", at: 32 }, { id: "b", verdict: "CONTRADICTED", at: 38 }]; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + assert.equal(await run("claimoff", "c02", "claim=none", "--json"), 0, lines.join("\n")); + const c2 = (await read(dir)).timeline[1]; + assert.equal("claims" in c2 || "claim" in c2, false); + assert.deepEqual(JSON.parse(lines.at(-1)).marks, []); +}); + test("umtool look: the fact-check's stamp, a verdict's stamp word, markers, layout, the ladder, a look key", async () => { const dir = await project("look"); const { lines, run } = runner(lookCommand); diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -28,7 +28,7 @@ // Plain ESM: the CLI runs it under bare node. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; -import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; +import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; @@ -247,9 +247,12 @@ export async function checkLinks( let found = false; let error = null; try { - found = has(await getJson(pageUrl)); + // Keyed by the manifest's generation (cues.mjs pagesVersionOf), so a shard cached from an older deploy is + // fetched again rather than read. + const version = pagesVersionOf(man.doc); + found = has(await getJson(pageUrl, { version })); // A cached shard older than the deploy: read it again, once. - if (!found) found = has(await getJson(pageUrl, { refresh: true })); + if (!found) found = has(await getJson(pageUrl, { refresh: true, version })); } catch (e) { error = errText(e); } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -77,7 +77,7 @@ import { DELIVERABLES_MODES } from "./storage.mjs"; import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo"; import { SCENE_DEFAULTS, validatePostSceneRender } from "umtool-report-to-video/post-media-scene"; import { PICTURE_REPLY_DEFAULTS, validatePictureReplyRender } from "umtool-report-to-video/post-picture"; -import { createSnapshot, listSnapshots } from "./snapshots.mjs"; +import { createSnapshot, listSnapshots, readSnapshot } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; import { syncPatchMarkers, syncSectionMarkers } from "./patchMarkers.mjs"; @@ -2482,6 +2482,20 @@ async function structural(dir, op, token, mutate, { snapshotEvery = undefined, p } /** + * A structural edit of the DRAFT by a writer outside this file (takeImport.mjs importDraftItems): `mutate` over + * the manifest in the lock, the build's checks, an undo point, the take patches' markers following -- what every + * structural writer here does. Returns mutate's result with `snapshot` and `token`. + * + * @param {string} dir + * @param {string} op the undo point's name (`auto-before-<op>`) + * @param {string | null} token + * @param {(m: Record<string, any>) => any} mutate + */ +export async function editDraftStructure(dir, op, token, mutate) { + return structural(dir, op, token, (m) => mutate(m)); +} + +/** * Move one entry to `toIndex` (its index in the timeline AFTER the move). * `sectionEnter` is recomputed by report-to-video's own rule (sections.mjs), * and only on a manifest that already uses it. @@ -2594,6 +2608,107 @@ export async function rejectClip(dir, id, reason, { token = null, at = null, not return { ...res, record }; } +/** + * The clips removed on record (removed.json) that are still out of the cut, one per id -- its newest removal -- + * newest first. A clip put back (undo, restore) drops off; its lines stay on record. + * + * @param {Array<Record<string, any>>} rows readRemoved's + * @param {Record<string, any> | null} manifest + */ +export function removedOutOfCut(rows, manifest) { + const inCut = new Set((manifest?.timeline ?? []).map((e) => (isObj(e) ? e.id : null))); + const seen = new Set(); + const out = []; + for (const r of [...(rows ?? [])].reverse()) { + const id = isObj(r) && typeof r.id === "string" ? r.id : null; + if (!id || seen.has(id)) continue; + seen.add(id); + if (!inCut.has(id)) out.push(r); + } + return out; +} + +/** + * The newest revision of the manifest (revisions/, newest first; then a legacy copy) whose timeline holds clip `id`: the entry as it + * was there -- claim, quote, cite, edges and all -- with the ids before and after it. null when none does. + * + * @param {string} dir + * @param {string} id + */ +export async function removedClipInRevisions(dir, id) { + // The undo points in revisions/ first, newest first; then a legacy copy beside the manifest (the writer's + // rate-limited .bak, a hand-made copy), which may be older than they are. + const snaps = await listSnapshots(dir); + for (const snap of [...snaps.filter((x) => !x.legacy), ...snaps.filter((x) => x.legacy)]) { + let m = null; + try { + m = await readSnapshot(dir, snap.rel); + } catch { + continue; + } + const tl = Array.isArray(m?.timeline) ? m.timeline : []; + const k = tl.findIndex((e) => isObj(e) && e.id === id && e.type === "clip"); + if (k < 0) continue; + const ids = (xs) => xs.map((e) => (isObj(e) ? e.id : null)).filter((x) => typeof x === "string"); + return { entry: JSON.parse(JSON.stringify(tl[k])), from: snap.rel, before: ids(tl.slice(0, k)).reverse(), after: ids(tl.slice(k + 1)) }; + } + return null; +} + +/** + * UN-REJECT: put clip `id`, taken out of the cut (Reject, Wrong speaker, a plain remove), back -- the entry from + * the newest revision that holds it, so its claim, quote, cite and edges are as they were, at its old place: after + * the nearest entry that came before it there and is still in the cut, else before the nearest that came after + * it, else at the index its removal was recorded at. Every later write to the cut is kept (it is an insert, not + * a rollback); an undo point first. What its removal re-anchored or dropped (a marker moved, a deck claim, its + * claim group) is not put back, and is returned as `notPutBack` to say so. The draft's only: a version is opened + * in the draft first. `umtool timeline <p> restore <id>`, the Cut tab's Removed list. + * + * @param {string} dir + * @param {string} id + * @param {{ token?: string | null }} [opts] + */ +export async function restoreRemoved(dir, id, { token = null } = {}) { + if (takeScopeOf(dir)) throw new Error("a removed clip is restored into the draft (open the version in the draft first)"); + const clipId = String(id ?? "").trim(); + if (!clipId) throw new Error("restore needs the removed clip's id"); + const record = (await readRemoved(dir)).filter((r) => isObj(r) && r.id === clipId).at(-1) ?? null; + return prepAfter(dir, clipIdOf, structural(dir, "restore", token, (m, found) => { + if (m.timeline.some((e) => isObj(e) && e.id === clipId)) throw new Error(`${clipId} is in the cut already`); + if (!found) { + throw new Error( + `no revision of the manifest holds ${clipId} (revisions/ keeps the newest ${AUTO_SNAPSHOT_KEEP} undo points)` + + (record ? `: re-add it from its record -- umtool timeline <p> insert ${record.channel}/${record.video}@${record.start}-${record.end}` : ""), + ); + } + const tl = m.timeline; + const indexOf = (x) => tl.findIndex((e) => isObj(e) && e.id === x); + let at = -1; + let placed = null; + for (const x of found.before) { + const k = indexOf(x); + if (k >= 0) { + at = k + 1; + placed = { after: x }; + break; + } + } + if (at < 0) { + for (const x of found.after) { + const k = indexOf(x); + if (k >= 0) { + at = k; + placed = { before: x }; + break; + } + } + } + if (at < 0) at = Math.max(0, Math.min(tl.length, Number.isInteger(record?.at) ? record.at : tl.length)); + tl.splice(at, 0, found.entry); + return { id: clipId, at, entry: found.entry, from: found.from, ...(placed ?? {}), notPutBack: Array.isArray(record?.reanchored) ? record.reanchored : [] }; + }, { prepare: () => removedClipInRevisions(dir, clipId) })); +} + /** Copy one entry to just after itself, under a fresh id. A copied claim is dropped (one claim, one entry). * * @param {string} dir * @param {string} id diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -771,6 +771,8 @@ async function inTakeCommand({ verb, take, rest }, { root, out, err }) { } if (!words[1]) throw new CliError(`which project? umtool posts ${verb} <project> … --in-take ${take}`); const project = await projectOf(words[1], root); + // Deprecated (L3 S6): it still lands, and says so in one line naming the project as parsed. + err((await import("./takeDeprecation.mjs")).takeEditDeprecation(`posts ${verb} --in-take`, { project: project.id, take })); const { isTakeId, takesDirOf, TAKE_FILE } = await import("./takes.mjs"); if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id (lower-case letters, digits, dashes)`); if (!(await stat(path.join(takesDirOf(project.dir), take, TAKE_FILE)).catch(() => null))) { diff --git a/umtool/lib/report/restore-removed.test.mjs b/umtool/lib/report/restore-removed.test.mjs @@ -0,0 +1,100 @@ +// UN-REJECT (owed 6 Nov: removed.json keeps id/window/reason only): `umtool timeline <p> restore <id>` puts a +// removed clip back from the newest revision that holds it -- claim, quote, cite and edges as they were -- at its +// old place, every later write kept; `removed` lists what is still out. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-restore-")); +process.env.REPORTS_DIR = ROOT; +const { MANIFEST_NAME, readRemoved, rejectClip, removeEntry, removedOutOfCut, restoreRemoved, updateClip } = await import("./manifest.mjs"); +const { timelineCommand } = await import("./timelineCli.mjs"); + +const C02 = { + type: "clip", id: "c02", channel: "chan", video: "v2", start: 30, end: 44, cutStart: 31.2, cutEnd: 42.8, lockEnd: true, + cite: 31, quote: "the whole sentence, as cited", citeUrl: "https://example.test/v/chan/v2?t=31", + claim: { id: "k1", verdict: "CONTRADICTED", at: 35, label: "1 SEIZURE" }, +}; +const base = () => ({ + schemaVersion: 1, slug: "r", title: "R", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 20 }, + structuredClone(C02), + { type: "clip", id: "c03", video: "v3", start: 50, end: 60 }, + ], +}); +async function project(name) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(base(), null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); +const ids = async (dir) => (await read(dir)).timeline.map((e) => e.id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("restore: the rejected clip back as it was, at its old place, every later write kept", async () => { + const dir = await project("back"); + await rejectClip(dir, "c02", "irrelevant", { note: "off topic" }); + assert.deepEqual(await ids(dir), ["c01", "c03"]); + // Later writes: c01 trimmed, a clip inserted at the end. The restore must keep both. + await updateClip(dir, "c01", { start: 11, end: 19 }); + const m = await read(dir); + m.timeline.push({ type: "clip", id: "c04", video: "v4", start: 70, end: 80 }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + assert.deepEqual(removedOutOfCut(await readRemoved(dir), await read(dir)).map((r) => r.id), ["c02"]); + + const r = await restoreRemoved(dir, "c02"); + assert.equal(r.at, 1); + assert.equal(r.after, "c01"); + assert.match(r.from, /^revisions\/.*auto-before-reject\.manifest\.json$/); + const now = await read(dir); + assert.deepEqual(now.timeline.map((e) => e.id), ["c01", "c02", "c03", "c04"]); + // The entry as it was before the reject: no rejected verdict, claim/quote/cite/edges intact. + assert.deepEqual(now.timeline[1], C02); + assert.deepEqual([now.timeline[0].start, now.timeline[0].end], [11, 19], "the trim after the reject is kept"); + // Off the list; its line stays on record. + assert.deepEqual(removedOutOfCut(await readRemoved(dir), now), []); + assert.equal((await readRemoved(dir)).length, 1); + await assert.rejects(restoreRemoved(dir, "c02"), /c02 is in the cut already/); +}); + +test("restore: its neighbour before gone too, it goes before the one after; nothing holds it -- refused, naming the insert", async () => { + const dir = await project("neighbour"); + await rejectClip(dir, "c02", "weak"); + await removeEntry(dir, "c01"); + await restoreRemoved(dir, "c02"); + assert.deepEqual(await ids(dir), ["c02", "c03"]); + + const bare = await project("bare"); + await rejectClip(bare, "c02", "weak"); + await rm(path.join(bare, "revisions"), { recursive: true, force: true }); + await rm(path.join(bare, `${MANIFEST_NAME}.bak`), { force: true }); + await assert.rejects(restoreRemoved(bare, "c02"), /no revision of the manifest holds c02.*insert chan\/v2@30-44/s); + assert.deepEqual(await ids(bare), ["c01", "c03"], "nothing written"); +}); + +test("umtool timeline <p> removed | restore <id>: the list, then the clip back, with an undo point", async () => { + const dir = await project("cli"); + await rejectClip(dir, "c02", "repeats", { note: "covered by c01" }); + const lines = []; + const run = (...a) => timelineCommand(a, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); + assert.equal(await run("cli", "removed"), 0, lines.join("\n")); + assert.match(lines.join("\n"), /c02\s+chan\/v2@30-44\s+.*covered by c01/); + assert.match(lines.at(-1), /1 removed clip out of cli -- umtool timeline cli restore <id> puts one back/); + assert.equal(await run("cli", "restore", "c02"), 0, lines.join("\n")); + assert.match(lines.join("\n"), /restored c02 at 1 \(after c01\), as it was in revisions\//); + assert.match(lines.join("\n"), /undo point: revisions\/.*auto-before-restore/); + assert.deepEqual(await ids(dir), ["c01", "c02", "c03"]); + assert.equal(await run("cli", "removed", "--json"), 0); + assert.deepEqual(JSON.parse(lines.at(-1)).removed, []); + assert.equal(await run("cli", "restore", "c02"), 1); + assert.match(lines.at(-1), /c02 is in the cut already/); +}); diff --git a/umtool/lib/report/takeDeprecation.mjs b/umtool/lib/report/takeDeprecation.mjs @@ -0,0 +1,23 @@ +// THE TAKE-PATCH EDITS, DEPRECATED (umtool redesign L3, S6). Every edit lands in the working draft now; a saved +// version is frozen and is edited by opening it in the draft (`umtool takes open <p> <v>`). The CLI paths that +// still write a take's patch -- `--in-take`, `timeline --take`, `window --take` -- and the route behind the +// old take walk (/api/report/takes/timeline) keep working for now, each saying so in ONE line on stderr, so a +// script that leans on them hears it before they go. +// +// Plain ESM: the CLI and the route both read it. + +/** + * The one line, for `what` (the flag or route as typed) on take `take` of project `project`. + * @param {string} what + * @param {{ project?: string | null, take?: string | null }} [o] + */ +export function takeEditDeprecation(what, { project = null, take = null } = {}) { + const p = project ?? "<p>"; + const t = take ?? "<take>"; + return `umtool: ${what} is deprecated -- edits land in the draft now; open the take there first (umtool takes open ${p} ${t}) and edit without it`; +} + +/** Say it on stderr (once per call). */ +export function warnTakeEdit(what, o = {}, write = (s) => process.stderr.write(`${s}\n`)) { + write(takeEditDeprecation(what, o)); +} diff --git a/umtool/lib/report/takeDeprecation.test.mjs b/umtool/lib/report/takeDeprecation.test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { takeEditDeprecation, warnTakeEdit } from "./takeDeprecation.mjs"; + +test("the take-patch edits' deprecation: one line, naming the flag and the way there", () => { + const line = takeEditDeprecation("window --take", { project: "reports/x", take: "v2" }); + assert.equal(line, "umtool: window --take is deprecated -- edits land in the draft now; open the take there first (umtool takes open reports/x v2) and edit without it"); + assert.doesNotMatch(line, /\n/); + const said = []; + warnTakeEdit("--in-take", {}, (s) => said.push(s)); + assert.deepEqual(said, ["umtool: --in-take is deprecated -- edits land in the draft now; open the take there first (umtool takes open <p> <take>) and edit without it"]); +}); diff --git a/umtool/lib/report/takeEdit.test.mjs b/umtool/lib/report/takeEdit.test.mjs @@ -303,6 +303,9 @@ test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --p out.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "move", "t03a", "--to", "0"], io), 0, err.join("\n")); assert.match(out.join("\n"), /take tight: moved t03a: 3 -> 0/); + // Deprecated (L3 S6): one line on stderr for a write, and it still works; `ls` (a read) says nothing. + assert.deepEqual(err, ["umtool: timeline move --take is deprecated -- edits land in the draft now; open the take there first (umtool takes open proj tight) and edit without it"]); + err.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); // "Add to this take only" (lane/ui-simplify): a clip into the take's timeline, never the project's. const masterBefore = await masterText(dir); @@ -316,8 +319,10 @@ test("the CLI twins: umtool walk --take, umtool timeline --take, umtool take --p assert.equal(await timelineCommand(["proj", "--take", "tight", "undo"], io), 0, err.join("\n")); assert.equal(await timelineCommand(["proj", "--take", "tight", "insert", "chan/vid@1-5"], io), 2, "insert needs --after"); out.length = 0; + err.length = 0; assert.equal(await timelineCommand(["proj", "--take", "tight", "ls"], io), 0, err.join("\n")); assert.match(out.join("\n"), /4 entries in take tight of proj$/, "the move was undone: nothing left to undo"); + assert.deepEqual(err, [], "ls reads: no warning"); const log = []; const before = await masterText(dir); diff --git a/umtool/lib/report/takeImport.mjs b/umtool/lib/report/takeImport.mjs @@ -39,7 +39,7 @@ import { createReadStream } from "node:fs"; import { copyFile, link, lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { handleKey } from "umtool-report-to-video/post-avatars"; -import { applyStructural } from "./manifest.mjs"; +import { applyStructural, editDraftStructure, manifestToken } from "./manifest.mjs"; import { editTakeManifest, takeToken } from "./takeEdit.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; @@ -69,6 +69,36 @@ export function parseImportRef(ref) { return items.length ? { project: s.slice(0, i), items } : null; } +/** + * The argv of `umtool timeline <project> import-item …` for a page's ask (POST /api/report/takes/tools, op + * "import" with no take), every word CHECKED: the refs are split on whitespace, and a word that starts with "-" is + * refused -- a flag smuggled in the refs ("p:1 --take t1" would take the take-patch path, "--as x" rename the + * item) -- as is any word that is not `<project>:<item>[,<item>…]`. The anchor is an entry id. Throws + * ImportRefused (the route's 400) saying which word and why. + * + * @param {string} projectId + * @param {{ refs?: unknown, after?: unknown, before?: unknown, dryRun?: unknown }} ask + * @returns {string[]} + */ +export function draftImportArgv(projectId, { refs, after = null, before = null, dryRun = false }) { + const words = typeof refs === "string" ? refs.trim().split(/\s+/).filter(Boolean) : []; + if (!words.length) throw new ImportRefused("import needs <project>:<item>[,<item>…]"); + for (const w of words) { + if (w.startsWith("-")) throw new ImportRefused(`"${w}" is a flag, not an item: the refs are <project>:<item>[,<item>…] only`); + if (!parseImportRef(w)) throw new ImportRefused(`"${w}" is not <project>:<item>[,<item>…]`); + } + const anchor = (v, name) => { + if (v === null || v === undefined || v === "") return null; + const a = String(v); + if (!/^[A-Za-z0-9._:-]{1,120}$/.test(a) || a.startsWith("-")) throw new ImportRefused(`${name} "${a}" is not an entry id`); + return a; + }; + const a = anchor(after, "after"); + const b = anchor(before, "before"); + if (a && b) throw new ImportRefused("after or before, not both"); + return [projectId, "import-item", ...words, ...(a ? ["--after", a] : b ? ["--before", b] : []), ...(dryRun ? ["--dry-run"] : []), "--json"]; +} + /** The entry `ref` names in a timeline: its id, its post's id, or `p-<postId>`. */ export function findEntry(timeline, ref) { const r = String(ref ?? ""); @@ -194,22 +224,44 @@ export function postsInDateOrder(timeline) { } /** - * IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file). + * Items of other projects INTO THE DRAFT -- the project's own manifest, where every edit lands now (umtool + * redesign L3; E1, 9 Nov: the Cut tab's "Add items from another project"). importTakeItems with no take: the + * same clone, the same files linked in, the same placement and the same "again: unchanged", written through the + * draft's structural writer (an undo point of the project's, `umtool timeline <p> undo`). + * + * @param {{ id: string, dir: string }} project + * @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs + * @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts] + */ +export const importDraftItems = (project, refs, opts = {}) => importTakeItems(project, null, refs, opts); + +/** + * IMPORT ITEMS OF OTHER PROJECTS INTO A TAKE (see the head of the file) -- or, `take` null, into the draft + * (importDraftItems). * * @param {{ id: string, dir: string }} project the take's project - * @param {string} take + * @param {string | null} take * @param {Array<{ project: { id: string, dir: string }, item: string, as?: string | null }>} refs * @param {{ after?: string | null, before?: string | null, dryRun?: boolean, now?: Date }} [opts] */ export async function importTakeItems(project, take, refs, { after = null, before = null, dryRun = false, now = new Date() } = {}) { if (!refs.length) throw new ImportRefused("nothing to import"); if (after && before) throw new ImportRefused("--after or --before, not both"); - const busy = await renderingNow(project.dir, take); + const draft = take === null; + const busy = draft ? null : await renderingNow(project.dir, take); if (busy) throw new ImportRefused(`not imported: ${busy}`); - const takeNow = await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take + const takeNow = draft + ? { manifest: JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8").catch(() => { throw new ImportRefused(`${project.id} has no video.manifest.json`); })) } + : await resolveTakeManifest(project.dir, take); // throws, naming it, when there is no such take const tl = takeNow.manifest.timeline; const anchor = after ?? before; - if (anchor && !findEntry(tl, anchor)) throw new ImportRefused(`take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`); + if (anchor && !findEntry(tl, anchor)) { + throw new ImportRefused( + draft + ? `the draft has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id}\` lists them)` + : `take ${take} has no entry ${anchor} to put the item(s) ${after ? "after" : "before"} (\`umtool timeline ${project.id} --take ${take}\` lists them)`, + ); + } // Each source manifest read once, as it is on disk (never a take of it). /** @type {Map<string, Record<string, any>>} */ @@ -272,14 +324,10 @@ export async function importTakeItems(project, take, refs, { after = null, befor } } - const placed = []; - const write = await editTakeManifest( - project.dir, - take, - "import-item", - await takeToken(project.dir, take), - (m) => - applyStructural(m, (mm) => { + let placed = []; + /** The placement, over a manifest held in memory (the take's resolved one, or the draft's). */ + const place = (mm) => { + placed = []; const timeline = mm.timeline; const order = timeline.map((x) => (isObj(x) ? x.id : null)).join("\n"); let cursor = null; // the id the next item goes after (several items keep their order) @@ -317,9 +365,10 @@ export async function importTakeItems(project, take, refs, { after = null, befor pl.at = { index: i, after: i > 0 ? timeline[i - 1].id : null, before: i + 1 < timeline.length ? timeline[i + 1].id : null }; } return { ids: plans.map((p) => p.id) }; - }), - { now, dryRun }, - ); + }; + const write = draft + ? await writeDraft(project.dir, place, { dryRun }) + : await editTakeManifest(project.dir, take, "import-item", await takeToken(project.dir, take), (m) => applyStructural(m, place), { now, dryRun }); const items = plans.map((p) => { const pl = placed.find((x) => x.id === p.id); const n = isObj(p.entry.narration) ? p.entry.narration : null; @@ -343,7 +392,22 @@ export async function importTakeItems(project, take, refs, { after = null, befor dryRun, unchanged: write.unchanged, items, - revision: write.revision ? `takes/${take}/${write.revision.rel}` : null, + revision: draft ? write.revision : write.revision ? `takes/${take}/${write.revision.rel}` : null, token: write.token, }; } + +/** + * The draft's import write: the placement tried on a copy first -- nothing changed (or a dry run) writes nothing -- + * then done again inside the draft's structural writer, on the file as it is then. `revision`: its undo point. + */ +async function writeDraft(dir, place, { dryRun }) { + const token = await manifestToken(dir); + const now = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const tried = clone(now); + applyStructural(tried, place); + if (JSON.stringify(tried) === JSON.stringify(now)) return { unchanged: true, token, revision: null }; + if (dryRun) return { unchanged: false, dryRun: true, token, revision: null }; + const r = await editDraftStructure(dir, "import-item", token, place); + return { unchanged: false, token: r.token, revision: r.snapshot?.rel && !r.snapshot.skipped ? r.snapshot.rel : null }; +} diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs @@ -206,10 +206,17 @@ export async function cachedTakeManifest(projectDir, id) { return value; } -/** Write a take's play manifest (tmp + rename); returns its path. */ +// Each write's own tmp name. Play asks for a take's pages twice at once when it opens one -- the chrome preview +// (POST /api/report/chrome/preview) and the intro (POST /api/report/chrome/intro) both write this file, in one +// server process -- and with `<file>.<pid>.tmp` the two shared the tmp: the first rename took it, the second +// failed ENOENT, and Play said "the intro did not compose" (the intro-play flake, L8a/L4, 9 Nov). The last +// rename wins; both write the same take as it is. +let playManifestSeq = 0; + +/** Write a take's play manifest (tmp + rename); returns its path. Safe to call concurrently. */ export async function writePlayManifest(projectDir, id, manifest) { const file = playManifestPath(projectDir, id); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = `${file}.${process.pid}.${++playManifestSeq}.tmp`; await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/umtool/lib/report/takeManifest.test.mjs b/umtool/lib/report/takeManifest.test.mjs @@ -123,3 +123,19 @@ test("the play manifest is written beside the project's; the cache follows the f await rm(dir, { recursive: true, force: true }); } }); + +test("two writes of one take's play manifest at once both land (Play's preview and intro ask together)", async () => { + const dir = await project(); + try { + // Before, both used `<file>.<pid>.tmp`: one rename took the other's tmp and the second threw ENOENT. + const docs = Array.from({ length: 12 }, (_, i) => ({ timeline: [], n: i })); + const files = await Promise.all(docs.map((d) => writePlayManifest(dir, "short", d))); + assert.ok(files.every((f) => f === playManifestPath(dir, "short"))); + const n = JSON.parse(await readFile(playManifestPath(dir, "short"), "utf8")).n; + assert.ok(Number.isInteger(n) && n >= 0 && n < docs.length); + const { readdir } = await import("node:fs/promises"); + assert.deepEqual((await readdir(dir)).filter((f) => f.endsWith(".tmp")), []); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/takeScope.test.mjs b/umtool/lib/report/takeScope.test.mjs @@ -16,7 +16,7 @@ import { TakeScopeRefused, withTakeScope } from "./takeScope.mjs"; import { updateRender } from "./manifest.mjs"; import { readManifest } from "../projects/report.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; -import { postsInDateOrder, parseImportRef } from "./takeImport.mjs"; +import { ImportRefused, draftImportArgv, postsInDateOrder, parseImportRef } from "./takeImport.mjs"; import { lintCommand, namedFileProblems } from "./lintCli.mjs"; import { postsCommand } from "./postsCli.mjs"; import { takeCommand } from "./takeCli.mjs"; @@ -108,6 +108,8 @@ test("--in-take: set-item, narrate --pick, roles --set and fx land in the take's assert.match(r.out, /on take t1 \(its patch; scope-a's manifest untouched\): 1 edit\(s\), undo point takes\/t1\/revisions\/.*-auto-before-post-item\.take\.json -- umtool timeline scope-a --take t1 undo/); assert.equal(await text(a), before, "the project's manifest is never written"); assert.equal((await takeDoc(a, "t1")).patch.timeline.find((e) => e.id === "p-1").hold, 4); + // Deprecated (L3 S6): it still lands, and says so in one line on stderr. + assert.equal(r.err, "umtool: posts set-item --in-take is deprecated -- edits land in the draft now; open the take there first (umtool takes open scope-a t1) and edit without it"); // The alias: set-item's --take <t> is --in-take <t>; --json is the command's own object with the take. r = await posts("set-item", "scope-a", "p-1", "thread.group=g1", "--take", "t1", "--json"); assert.equal(r.code, 0, r.err); @@ -276,6 +278,71 @@ test("--import-item: an item of another project cloned into the take with its na assert.match(r.err, /has no entry p-77/); }); +test("timeline import-item: items of another project INTO THE DRAFT -- cloned, files linked, placed; again: unchanged; an undo point; the source untouched", async () => { + const src = await project("dimp-src", [narrated("20", "2026-10-30T12:30:00.000Z"), narrated("21", "2026-10-30T12:40:00.000Z")]); + for (const id of ["20", "21"]) { + await tone(path.join(src.dir, `narration/posts/${id}/take-1.orpheus-thread.wav`)); + await writeFile(path.join(src.dir, `narration/posts/${id}/take-1.parts.json`), "[]"); + } + await project("dimp-dst", [post("1", "2026-10-30T10:00:00.000Z"), post("3", "2026-10-30T13:00:00.000Z")]); + const srcBefore = await text(src); + const timeline = (...a) => cli(timelineCommand, a); + const dst = { dir: path.join(REPORTS, "dimp-dst") }; + const ids = async () => (await readManifest(dst.dir)).timeline.map((e) => e.id); + + // A dry run: the plan, nothing written, nothing linked. + let r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--dry-run", "--json"); + assert.equal(r.code, 0, r.err); + let doc = JSON.parse(r.out); + assert.deepEqual([doc.dryRun, doc.take, doc.items[0].at.index], [true, null, 1], "by date: between p-1 and p-3"); + assert.deepEqual(await ids(), ["p-1", "p-3"]); + assert.ok(!(await stat(path.join(dst.dir, "narration/posts/20")).catch(() => null)), "a dry run links nothing"); + + // Into the draft after p-1, in the order named; the files hard-linked; an undo point of the project's. + r = await timeline("dimp-dst", "import-item", "dimp-src:p-21,p-20", "--after", "p-1", "--json"); + assert.equal(r.code, 0, r.err); + doc = JSON.parse(r.out); + assert.deepEqual(doc.items.map((x) => [x.id, x.action]), [["p-21", "added"], ["p-20", "added"]]); + assert.match(doc.revision, /^revisions\/.*-auto-before-import-item\.manifest\.json$/); + assert.deepEqual(await ids(), ["p-1", "p-21", "p-20", "p-3"]); + const [s1, d1] = await Promise.all([stat(path.join(src.dir, "narration/posts/21/take-1.orpheus-thread.wav")), stat(path.join(dst.dir, "narration/posts/21/take-1.orpheus-thread.wav"))]); + assert.equal(d1.ino, s1.ino); + assert.equal(await text(src), srcBefore, "the source is only read"); + + // Again: unchanged, nothing written. + const before = await readFile(path.join(dst.dir, "video.manifest.json"), "utf8"); + r = await timeline("dimp-dst", "import-item", "dimp-src:p-21", "--json"); + doc = JSON.parse(r.out); + assert.deepEqual([doc.unchanged, doc.items[0].action, doc.revision], [true, "unchanged", null]); + assert.equal(await readFile(path.join(dst.dir, "video.manifest.json"), "utf8"), before); + // Words, and the refusals. + r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--before", "p-1"); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /p-20: moved from dimp-src:p-20 at 0, before p-1/); + // The undo point of a second import-item inside the undo window is the first's (autoSnapshot's rate). + assert.match(r.out, /the draft: 1 item\(s\)$/); + r = await timeline("dimp-dst", "import-item", "dimp-src:p-20", "--after", "p-77"); + assert.equal(r.code, 1); + assert.match(r.err, /the draft has no entry p-77/); + assert.equal((await timeline("dimp-dst", "import-item", "dimp-src")).code, 2); + assert.equal((await timeline("dimp-dst", "import-item", "dimp-src:p-99")).code, 1); +}); + +test("draftImportArgv: a page's import ask becomes checked argv -- no flag rides in on the refs, every word a ref, the anchor an entry id", () => { + assert.deepEqual(draftImportArgv("p", { refs: " src:p-1,p-2 other/x:7 ", after: "p-1", dryRun: true }), ["p", "import-item", "src:p-1,p-2", "other/x:7", "--after", "p-1", "--dry-run", "--json"]); + assert.deepEqual(draftImportArgv("p", { refs: "src:p-1", before: "c02" }), ["p", "import-item", "src:p-1", "--before", "c02", "--json"]); + const refused = (ask, re) => assert.throws(() => draftImportArgv("p", ask), (e) => e instanceof ImportRefused && re.test(e.message)); + refused({ refs: "src:p-1 --take t1" }, /"--take" is a flag, not an item/); + refused({ refs: "src:p-1 --as x" }, /"--as" is a flag/); + refused({ refs: "-x" }, /is a flag/); + refused({ refs: "src:p-1 t1" }, /"t1" is not <project>:<item>/); + refused({ refs: " " }, /import needs/); + refused({ refs: 7 }, /import needs/); + refused({ refs: "src:p-1", after: "--take" }, /after "--take" is not an entry id/); + refused({ refs: "src:p-1", before: "a b" }, /before "a b" is not an entry id/); + refused({ refs: "src:p-1", after: "a", before: "b" }, /not both/); +}); + test("--draft --from <take>: a draft that starts from another take's patch (a --patch over it), its timeline its own", async () => { const a = await project("draft-from", [post("1", "2026-10-30T10:00:00.000Z"), post("2", "2026-10-30T11:00:00.000Z")]); assert.equal((await take("draft-from", "--id", "base", "--label", "Base", "--draft", "--patch-json", JSON.stringify({ timeline: [post("2", "2026-10-30T11:00:00.000Z")], render: { posts: { slurs: { on: false } } } }))).code, 0); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -73,6 +73,9 @@ import { removeEntry, removeSection, rejectClip, + readRemoved, + removedOutOfCut, + restoreRemoved, sectionsOf, updateSection, removeWrongSpeaker, @@ -92,7 +95,7 @@ import { upsertPost, } from "./manifest.mjs"; -import { REJECT_REASON_IDS, rejectionOf } from "./rejectReasons.mjs"; +import { REJECT_REASON_IDS, rejectReasonOf, rejectionOf } from "./rejectReasons.mjs"; import { groupModel, parseOrderText } from "./claimGroups.mjs"; import { sectionModel } from "./sectionEdit.mjs"; @@ -123,6 +126,17 @@ export const TIMELINE_USAGE = [ ` <why> is ${REJECT_REASON_IDS.join("|")} -- not-matching and wrong-speaker are fact`, " errors (incorrect, the note its correction; not-matching needs one), the rest cut reasons (rejected; other needs a note)", " umtool timeline <project> wrong-speaker <id> [--correction TEXT] the same as reject <id> wrong-speaker", + " umtool timeline <project> import-item <src>:<item>[,<item>…] [<src>:…] [--after <id> | --before <id>] [--as <id>] [--dry-run]", + " items of another project INTO THE DRAFT: cloned as they are there (their card, context, knobs,", + " narration with its takes and pick), the files they name hard-linked in (another file at the path:", + " under imports/<src>/), placed after/before an entry (else by date among the posts, else at the end);", + " again: updated in place, or unchanged and nothing written; one undo point (the Cut tab's", + " Add items from another project)", + " umtool timeline <project> removed [--json] the clips taken out on record (removed.json) and still out", + " umtool timeline <project> restore <id> UN-REJECT: put a removed clip back -- the entry from the newest", + " revision that holds it (claim, quote, cite, edges intact) at its old place (after the entry", + " before it there), every later write kept; an undo point first; a marker or deck claim its", + " removal moved or dropped stays as it is, and is listed", " a removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; pair/status/deck-claim references dropped) and says so", " umtool timeline <project> post <json|@file> add a post, or replace the one with its id", " umtool timeline <project> post-remove <id>", @@ -184,9 +198,9 @@ export const TIMELINE_USAGE = [ ].join("\n"); const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; -const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; +const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; -const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]); +const VALUED = new Set(["--as", "--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo", "insert"]; @@ -552,7 +566,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => const project = await projectOf(projectArg, root); // A video entry (video-entry.mjs), into the cut or a take's timeline. if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json }); - if (flags.has("--take")) return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); + if (flags.has("--take")) { + // `ls` only reads; a write into a take's patch is the deprecated path (L3 S6). + if (verb !== "ls") err((await import("./takeDeprecation.mjs")).takeEditDeprecation(`timeline ${verb} --take`, { project: project.id, take: String(flags.get("--take")) })); + return await takeTimeline(project, String(flags.get("--take")), verb, rest, flags, { out, json }); + } const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); @@ -579,6 +597,22 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => if (verb === "threads") return await threadsCommand(project, manifest, { write: flags.has("--write"), only: flags.has("--conversation") ? String(flags.get("--conversation")) : null, json, out }); + if (verb === "import-item") return await importItemsIntoDraft(project, rest, flags, { root, out, err, json }); + + if (verb === "removed") { + const rows = removedOutOfCut(await readRemoved(project.dir), manifest); + if (json) { + out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), removed: rows }, null, 2)); + return 0; + } + for (const r of rows) { + const why = rejectReasonOf(String(r.reason ?? "")); + out(`${String(r.id).padEnd(10)} ${r.channel ?? "?"}/${r.video ?? "?"}@${r.start ?? "?"}-${r.end ?? "?"} ${why?.label ?? r.reason ?? ""}${r.note || r.correction ? `: ${r.note ?? r.correction}` : ""} (${String(r.when ?? "").slice(0, 16)}, was at ${r.at})`); + } + out(`${rows.length} removed clip${rows.length === 1 ? "" : "s"} out of ${project.id}${rows.length ? ` -- umtool timeline ${project.id} restore <id> puts one back` : ""}`); + return 0; + } + if (verb === "ls") { const rows = timelineRows(manifest); if (json) { @@ -718,6 +752,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write((token) => removeWrongSpeaker(project.dir, id, { token, at, correction }))); break; } + case "restore": { + const id = need(rest[0], "the removed clip's id (umtool timeline <project> removed lists them)"); + ({ result, editNotes } = await write((token) => restoreRemoved(project.dir, id, { token }))); + break; + } case "duplicate": { const id = need(rest[0], "an entry id"); ({ result, editNotes } = await write((token) => duplicateEntry(project.dir, id, { token, at }))); @@ -885,6 +924,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } out(summaryOf(verb, result, attribution)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + // What a restored clip's removal re-anchored or dropped stays as it is now: said, not undone. + for (const line of result.notPutBack ?? []) out(` not put back: ${line}`); // The claim groups following the edit (claimGroups.mjs syncGroups), and an import's words. for (const line of result.groupNotes ?? []) out(` groups: ${line}`); for (const line of result.notes ?? []) out(` ${line}`); @@ -916,6 +957,54 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } /** + * `umtool timeline <p> import-item <src>:<item>[,…] … [--after|--before <id>] [--as <id>] [--dry-run] [--json]`: + * items of other projects into the DRAFT (takeImport.mjs importDraftItems). EXIT 0 done (or unchanged) · 1 refused + * · 2 usage. + */ +async function importItemsIntoDraft(project, rest, flags, { root, out, err, json }) { + const { ImportRefused, importDraftItems, parseImportRef } = await import("./takeImport.mjs"); + if (!rest.length) throw new CliError("import-item needs <project>:<item>[,<item>…] (the item ids of another project)"); + const refs = []; + for (const raw of rest) { + const r = parseImportRef(raw); + if (!r) throw new CliError(`import-item takes <project>:<item>[,<item>…] (not ${raw})`); + for (const item of r.items) refs.push({ project: await projectOf(r.project, root), item, as: null }); + } + if (flags.has("--as")) { + if (refs.length !== 1) throw new CliError("--as names ONE item's id in the draft: import one item with it"); + refs[0].as = String(flags.get("--as")); + if (!/^[A-Za-z0-9._:-]{1,120}$/.test(refs[0].as)) throw new CliError(`--as ${refs[0].as}: an entry id is letters, digits, dots, dashes`); + } + if (flags.has("--after") && flags.has("--before")) throw new CliError("--after or --before, not both"); + const one = (k) => (typeof flags.get(k) === "string" && flags.get(k) ? String(flags.get(k)) : null); + let r; + try { + r = await importDraftItems(project, refs, { after: one("--after"), before: one("--before"), dryRun: flags.has("--dry-run") }); + } catch (e) { + if (e instanceof ImportRefused) { + err(`umtool timeline: ${e.message}`); + return 1; + } + throw e; + } + if (json) { + out(JSON.stringify({ ok: true, op: "import-item", ...r }, null, 2)); + return 0; + } + for (const x of r.items) { + const at = x.at ? ` at ${x.at.index}${x.at.after ? `, after ${x.at.after}` : ""}${x.at.before ? `, before ${x.at.before}` : ""}` : ""; + out(`${x.id}: ${r.dryRun ? `would be ${x.action}` : x.action} from ${x.ref}${at}`); + if (x.narration) out(` narration: ${x.narration.takes} take(s), pick ${x.narration.pick ?? "none"}${x.narration.file ? ` (${x.narration.file})` : ""}`); + const linked = x.files.filter((f) => !f.how.startsWith("already")); + if (x.files.length) out(` files: ${linked.length} ${r.dryRun ? "to link" : "linked"}, ${x.files.length - linked.length} already there${linked.some((f) => f.was) ? `; renamed (another file had the path): ${linked.filter((f) => f.was).map((f) => `${f.was} -> ${f.path}`).join(", ")}` : ""}`); + if (x.avatars.length) out(` authors' pictures added: ${x.avatars.join(", ")}`); + if (x.missing.length) err(` named but not in ${x.source}: ${x.missing.join(", ")}`); + } + out(r.unchanged ? `the draft: nothing changed (already imported as it is)` : r.dryRun ? `the draft: a dry run, nothing written (would import ${r.items.length} item(s))` : `the draft: ${r.items.length} item(s)${r.revision ? `; undo point ${r.revision} (umtool timeline ${project.id} undo)` : ""}`); + return 0; +} + +/** * `umtool timeline <p> --take <id> ls|move|remove|undo`: a take's timeline * (walk a take). The writes go into the take's patch through takeEdit.mjs -- * the same structure rules, an undo point of the take's own first -- and the @@ -1250,6 +1339,8 @@ function summaryOf(verb, r, attribution) { const why = rejectionOf(r.removed); return `removed ${r.id} (was at ${r.at}): ${why?.fact ? "marked incorrect" : "rejected"}, ${why?.label ?? r.record?.reason}`; } + case "restore": + return `restored ${r.id} at ${r.at}${r.after ? ` (after ${r.after})` : r.before ? ` (before ${r.before})` : ""}, as it was in ${r.from}`; case "duplicate": return `duplicated as ${r.id} at ${r.at}`; case "post": diff --git a/umtool/package.json b/umtool/package.json @@ -8,7 +8,7 @@ "build": "next build", "start": "next start --port ${UMTOOL_PORT:-3050}", "typecheck": "tsc --noEmit", - "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts", + "test": "tsx --test lib/brandIcon.test.ts lib/research/*.test.ts lib/inbox/*.test.ts lib/clips/*.test.ts", "e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test" }, "dependencies": { diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; +import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs"; // Test-only environment, declared here (one-core Phase 4 slice 3); every one // carries the E2E_ prefix: @@ -52,6 +53,19 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); +// The package is "type": "module", so there is no __dirname here. +const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), ".e2e-song"); + +// An inherited REPORTS_DIR / CHANNELS_DIR that is not the fixture's (SONG_DIR is read only by +// the fixture builder, and only to copy from: the documented way to run against a copy) +// is refused before anything runs -- before the start-mode build, the fixture +// builder or a single spec (lib/e2eEnvGuard.mjs; 2 Nov a run wrote into +// ~/reports). +{ + const refusal = dataRootRefusal(process.env, FIXTURE); + if (refusal) throw new Error(refusal); +} + // The preflight's per-platform pacing, against the fixture's stub yt-dlp: 50 ms, // not the 30 s a real YouTube probe waits. On process.env, so the app server // and every worker (and the CLIs they spawn) inherit it. @@ -100,9 +114,6 @@ const APP_SERVER = // is in common/lib/ports.mjs (so scripts/worktree.mjs gives a worktree its own) // and in package.json's --ports spec (so the preflight sees it). const STUB_PORT = portFor("EDITOR_STUB_PORT"); -// The package is "type": "module", so there is no __dirname here. -const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), ".e2e-song"); - // The suite NEVER runs against the real song dir. The tool writes to the same // files the CLI scripts do, and those hold thousands of real human verdicts -- // a spec that judged a clip would be indistinguishable from a person doing it. diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -53,8 +53,10 @@ // manifests through createJsonCache below, the same files on disk, and on a // post it cannot find it fetches them again and rewrites them. The cue walk // never refreshes, but it can read a corpus.json post-links rewrote: newer, so -// a channel the stale copy lacked is found. Manifest and shard URLs carry no -// version, so a cue window does not move because of it. +// a channel the stale copy lacked is found. Shard pages are cached by the +// generation of the transcripts manifest that named them (its generatedAt), so +// when linkCheck refreshes a manifest after an archive rebuild, the walk fetches +// that channel's pages again instead of reading the old build's forever. import { readFile, writeFile, mkdir, lstat, readlink, readdir, stat } from "node:fs/promises"; import path from "node:path"; @@ -78,12 +80,33 @@ export const DEFAULT_CACHE_DIR = // A shard page is capped at 8 MB and holds ~100 videos, so refetching one per // clip — across two separate processes, resolve-windows then build-video — is -// the difference between usable and painful. Cached by URL on disk; archives are -// rebuilt rarely and a stale page only matters if the cues themselves changed. +// the difference between usable and painful. Cached by URL on disk, and a page +// by the generation of the manifest that named it (pagesVersionOf): an archive +// rebuild bumps the manifest's generatedAt, and its pages are fetched again. function cacheKey(url) { return createHash("sha1").update(url).digest("hex") + ".json"; } +// The key a versioned copy on disk carries its version under (createJsonCache, +// `version`). No published document has a key like it. +export const CACHE_VERSION_KEY = "__umtoolCacheVersion"; + +/** A document as the disk cache holds it -> `{ version, body }` (version null when unversioned). */ +function unwrapCached(doc) { + if (doc && typeof doc === "object" && !Array.isArray(doc) && CACHE_VERSION_KEY in doc) { + return { version: doc[CACHE_VERSION_KEY], body: doc.body }; + } + return { version: null, body: doc }; +} + +/** + * The generation a channel's shard pages belong to: its transcripts manifest's + * `generatedAt` (every published manifest carries one), or null for a manifest + * without it -- whose pages are then cached by URL alone, as before. + */ +export const pagesVersionOf = (manifest) => + typeof manifest?.generatedAt === "string" && manifest.generatedAt ? manifest.generatedAt : null; + export function pageFileName(pageNumber) { return `page-${String(pageNumber).padStart(4, "0")}.json`; } @@ -170,6 +193,17 @@ export class CueLookupError extends Error { * `refreshAfterMs` ago. The default, Infinity, makes that "at most once per * process": a build re-reads a stale cached document once, never twice. A * long-lived server passes a window instead. + * + * `getJson(url, { version })` is for a document whose URL never changes but + * whose content belongs to a generation of something else -- a shard page to + * the `generatedAt` of the channel manifest that named it. The copy on disk is + * then stored with that version beside it (`{ [CACHE_VERSION_KEY]: v, body }`, + * the same one file per URL), and a cached copy of any other version (or of + * none) is a miss: the page is fetched again and the old generation's copy + * overwritten. Without this a page was kept forever while its manifest moved on + * (linkCheck refreshes manifests), so the walk could read a record from a page + * the new manifest no longer puts it on, or cues an archive rebuild rewrote. + * A read with no `version` takes either form. */ export function createJsonCache({ cacheDir = DEFAULT_CACHE_DIR, @@ -177,51 +211,59 @@ export function createJsonCache({ log = () => {}, refreshAfterMs = Infinity, } = {}) { + /** URL -> { version, body }: version null for a document cached without one. */ const mem = new Map(); /** URL -> when this cache last fetched it from the network (ms). */ const fetchedAt = new Map(); - /** URL -> the network fetch of it in progress. */ + /** URL (+ version) -> the network fetch of it in progress. */ const inflight = new Map(); - async function getJson(url, { refresh = false } = {}) { + const fits = (have, version) => version == null || have === version; + + async function getJson(url, { refresh = false, version = null } = {}) { const recent = fetchedAt.has(url) && Date.now() - fetchedAt.get(url) < refreshAfterMs; const useCache = !refresh || recent; - if (useCache && mem.has(url)) return mem.get(url); + const held = mem.get(url); + if (useCache && held && fits(held.version, version)) return held.body; const disk = cacheDir ? path.join(cacheDir, cacheKey(url)) : null; if (useCache && disk) { try { - const cached = JSON.parse(await readFile(disk, "utf8")); - mem.set(url, cached); - return cached; + const cached = unwrapCached(JSON.parse(await readFile(disk, "utf8"))); + if (fits(cached.version, version)) { + mem.set(url, cached); + return cached.body; + } + log(`stale ${url}: cached for ${cached.version ?? "no version"}, wanted ${version}`); } catch { /* cold cache */ } } // Callers that ask for the same URL while it is on its way share the one // fetch (umtool's preview routes run side by side). - if (inflight.has(url)) return inflight.get(url); + const flight = version == null ? url : `${url}\0${version}`; + if (inflight.has(flight)) return inflight.get(flight); const pending = (async () => { log(`fetch ${url}`); const res = await fetchImpl(url); if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); const json = await res.json(); - mem.set(url, json); + mem.set(url, { version, body: json }); fetchedAt.set(url, Date.now()); if (disk) { try { await mkdir(path.dirname(disk), { recursive: true }); - await writeFile(disk, JSON.stringify(json)); + await writeFile(disk, JSON.stringify(version == null ? json : { [CACHE_VERSION_KEY]: version, body: json })); } catch { // A cache we cannot write is a slow run, not a failed one. } } return json; })(); - inflight.set(url, pending); + inflight.set(flight, pending); try { return await pending; } finally { - inflight.delete(url); + inflight.delete(flight); } } @@ -285,7 +327,7 @@ export function createCueSource({ const manifest = await getJson(entry.manifests.transcripts); log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`); for (let n = 0; n < manifest.pageCount; n += 1) { - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) }); const hit = page.find( (r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted), ); @@ -327,7 +369,7 @@ export function createCueSource({ ); } - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) }); const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo); if (!record) { throw new CueLookupError( diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -14,6 +14,7 @@ import path from "node:path"; import { CAPTION_TRACK_RULE_VERSION, createCueSource, + createJsonCache, pageFileName, pageUrlFrom, siteOriginFromManifest, @@ -122,6 +123,60 @@ test("fetches each URL once, however many videos are read", async () => { ]); }); +// --- the disk cache follows the manifest's generation ---------------------- + +test("a shard page cached on disk is fetched again when its channel manifest's generatedAt moves", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const MAN = `${ORIGIN}/transcripts/chan/manifest.json`; + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + const gen1 = { ...ROUTES, [MAN]: { ...ROUTES[MAN], generatedAt: "2026-08-07T00:00:00.000Z" } }; + // A run against the first deploy fills the disk cache. + const seen1 = []; + const first = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen1) }).load("chan", "vid1"); + assert.equal(first.cues[1].text, "second line."); + assert.ok(seen1.includes(PAGE)); + + // A second process with the same generation reads everything from disk. + const seen2 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen2) }).load("chan", "vid1"); + assert.deepEqual(seen2, []); + + // The archive is rebuilt: the cues were rewritten and the manifest carries a new generatedAt. Something + // refreshes the manifest on disk (linkCheck does, with refresh: true) ... + const rewritten = { ...RECORD, cues: [{ start: 0, end: 3.1, text: "first line, re-transcribed" }, { start: 3.1, end: 5, text: "second." }] }; + const gen2 = { ...gen1, [MAN]: { ...gen1[MAN], generatedAt: "2026-11-01T00:00:00.000Z" }, [PAGE]: [rewritten] }; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(gen2) }).getJson(MAN, { refresh: true }); + + // ... and the cue walk, which never refreshes, follows it: the page of the old generation is a miss. + const seen3 = []; + const after = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen3) }).load("chan", "vid1"); + assert.deepEqual(seen3, [PAGE]); + assert.equal(after.cues[0].text, "first line, re-transcribed"); + + // And the refetched page is the one on disk now: a third run fetches nothing. + const seen4 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen4) }).load("chan", "vid1"); + assert.deepEqual(seen4, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("a versioned copy on disk still reads as the document to a caller that asks with no version", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES) }).getJson(PAGE, { version: "g1" }); + const seen = []; + const doc = await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES, seen) }).getJson(PAGE); + assert.deepEqual(doc, [RECORD]); + assert.deepEqual(seen, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + // --- local wins ------------------------------------------------------------- test("a local corpus is preferred over the network", async () => {