commit f407a8231674eb5b662f0fbec17407a3978946a0 parent 786e448915e81c1eade741a0928dd3c19762fc2f Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 11 Nov 2026 06:00:06 -0500 Merge lane/consolidate: the redesign's owed fixes -- a tally label is fitted, never refused; every temp name from one helper; a redo ends at any newer undo point; a write over 16 MB is answered 413; a basic-mode cut draws no QR and is never blocked for one; the review pass's Keep never overwrites a bench ruling (redesign E5) Also: `verdict clear` never saves a version; a failed Keep keeps the Fix note; a stale Fix shows what it said; the workspace's adders and drags refuse outside Edit on the draft; the Removed list names its channel; `take --import-item` says it is deprecated; the channel-context review's confirming press sits where the first press was. e2e: waits made deterministic where a whole-suite run under load showed a race (each spec change says why); no assertion weakened. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
150 files changed, 1170 insertions(+), 307 deletions(-)
diff --git a/common/lib/atomicFile.mjs b/common/lib/atomicFile.mjs @@ -0,0 +1,65 @@ +// THE ONE TEMP NAME for a file written beside its target and renamed over it, for plain-node modules (umtool's +// report-to-video and lib, common's .mjs stores) -- jsonFile-server.ts's writers are the TypeScript twin, in the +// same form: `<file>.tmp-<pid>-<seq>-<random>`. +// +// Unique per WRITE, not per process. `<file>.<pid>.tmp` was one name for every write a process made to a file, so +// two writes in flight at once (two requests in one server, two windows cut at once) shared it: the first rename +// took the other's half-written file, the second threw ENOENT (lib/report/takeManifest.mjs, writePlayManifest). +// The `.tmp-` infix is what a lister skips (lib/report/snapshots.mjs). `ext` keeps an extension a tool reads +// the format from (ffmpeg's `.mp4`); a hidden target (`.<name>`) keeps its temp hidden. +// +// A sweep test (umtool/lib/atomicFile-sweep.test.mjs) fails on a new `<pid>.tmp` name anywhere else. +import { randomBytes } from "node:crypto"; +import { renameSync, rmSync, writeFileSync } from "node:fs"; +import { rename, rm, writeFile } from "node:fs/promises"; + +/** @type {{ seq: number }} one counter however many copies of this module a process loads */ +const state = /** @type {any} */ (globalThis).__yttAtomicFile__ ?? (/** @type {any} */ (globalThis).__yttAtomicFile__ = { seq: 0 }); + +/** + * A temp path beside `file`, unique to this write. + * + * @param {string} file + * @param {{ ext?: string }} [opts] + * @returns {string} + */ +export function tmpPathFor(file, { ext = "" } = {}) { + state.seq += 1; + return `${file}.tmp-${process.pid}-${state.seq}-${randomBytes(4).toString("hex")}${ext}`; +} + +/** + * Write `data` to a unique temp beside `file`, then rename it over `file`; the temp is removed on any failure. + * + * @param {string} file + * @param {string | Uint8Array} data + * @param {import("node:fs").WriteFileOptions} [opts] + */ +export async function writeFileAtomic(file, data, opts) { + const tmp = tmpPathFor(file); + try { + await writeFile(tmp, data, opts); + await rename(tmp, file); + } catch (e) { + await rm(tmp, { force: true }).catch(() => {}); + throw e; + } +} + +/** + * writeFileAtomic's synchronous twin. + * + * @param {string} file + * @param {string | Uint8Array} data + * @param {import("node:fs").WriteFileOptions} [opts] + */ +export function writeFileAtomicSync(file, data, opts) { + const tmp = tmpPathFor(file); + try { + writeFileSync(tmp, data, opts); + renameSync(tmp, file); + } catch (e) { + rmSync(tmp, { force: true }); + throw e; + } +} diff --git a/common/lib/clips/reactions.mjs b/common/lib/clips/reactions.mjs @@ -12,6 +12,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { REACTIONS_VERSION, ROLES } from "./clips.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const REACTIONS_FILE = "reactions.json"; export { REACTIONS_VERSION }; @@ -33,7 +34,7 @@ export async function readReactions(dir) { /** Written whole: tmp + rename, so a reader never sees half a file. */ export async function writeReactions(dir, doc) { const file = reactionsFileOf(dir); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/clips/suggest.mjs b/common/lib/clips/suggest.mjs @@ -27,6 +27,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { cleanTurns, cleanWords, roleMap, wordsFromCues, wordsIn } from "./clips.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const SUGGESTIONS_FILE = "clip-suggestions.json"; export const SUGGEST_PROMPT_VERSION = "clips-suggest-1"; @@ -117,7 +118,7 @@ export async function writeSuggestions(dir, doc) { const r = parseSuggestionsDoc(doc); if ("error" in r) throw new Error(`not a suggestions doc: ${r.error}`); const file = suggestionsFileOf(dir); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(r.doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/montage/cueTextCache.mjs b/common/lib/montage/cueTextCache.mjs @@ -25,6 +25,7 @@ import { createReadStream, createWriteStream } from "node:fs"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { createInterface } from "node:readline"; +import { tmpPathFor } from "../atomicFile.mjs"; export const CACHE_VERSION = 3; @@ -149,7 +150,7 @@ export async function openChannelCache(cacheDir, channelsDir, slug, ids) { const nextIndex = {}; if (changed) { await mkdir(root, { recursive: true }); - tmp = `${dataFile}.${process.pid}.${Date.now()}.tmp`; + tmp = tmpPathFor(dataFile); out = createWriteStream(tmp, { encoding: "utf8" }); } @@ -191,7 +192,7 @@ export async function openChannelCache(cacheDir, channelsDir, slug, ids) { } await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve()))); await rename(tmp, dataFile); - const itmp = `${indexFile}.${process.pid}.tmp`; + const itmp = tmpPathFor(indexFile); await writeFile(itmp, JSON.stringify({ version: CACHE_VERSION, slug, videos: nextIndex }), "utf8"); await rename(itmp, indexFile); return true; diff --git a/common/lib/montage/speakerCheck.mjs b/common/lib/montage/speakerCheck.mjs @@ -29,6 +29,7 @@ import { scoreAgainst, voicedSamples, } from "./voiceMatch.mjs"; +import { tmpPathFor } from "../atomicFile.mjs"; export const SPEAKER_CHECK_FILE = "speaker-check.json"; export const SPEAKER_CHECK_VERSION = 1; @@ -199,7 +200,7 @@ export async function writeSpeakerCheck(dir, doc) { const prev = await readSpeakerCheck(dir); const sig = (d) => JSON.stringify((d?.speakers ?? []).map((s) => [s.name, s.clips, s.recordings])); const merged = prev && sig(prev) === sig(doc) ? { ...doc, clips: { ...prev.clips, ...doc.clips } } : doc; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`); await rename(tmp, file); return { file, doc: merged }; diff --git a/common/lib/montage/voiceMatch.mjs b/common/lib/montage/voiceMatch.mjs @@ -36,6 +36,7 @@ import { spawn } from "node:child_process"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "../atomicFile.mjs"; export const VOICE_MATCH_FILE = "voice-match.json"; export const VOICE_MATCH_VERSION = 1; @@ -625,7 +626,7 @@ export function voiceMatchSummary(doc) { /** Written whole: tmp + rename. */ export async function writeVoiceMatch(dir, doc) { const file = path.join(dir, VOICE_MATCH_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/common/lib/posts-server.ts b/common/lib/posts-server.ts @@ -11,7 +11,7 @@ // fetchers stop the same way), and uses the same "<extractor> <id>" line format // so common/lib/archive.ts parses it unchanged. -import { writeJsonAtomic } from "./jsonFile-server"; +import { writeFileAtomic, writeJsonAtomic } from "./jsonFile-server"; import path from "node:path"; import type { ForumWalkState } from "./forumWalk"; import type { TimelineBackfillState, TimelineSyncState } from "./timelineWalk"; @@ -256,20 +256,17 @@ export async function replaceChannelPosts( if (bucket) bucket.push(p); else byShard.set(shard, [p]); } - const tmpSuffix = `.tmp-${process.pid}-${Date.now()}`; for (const [shard, list] of byShard) { list.sort((a, b) => -comparePostsNewestFirst(a, b)); const file = shardPath(channelRoot, shard); - await writeFile(file + tmpSuffix, list.map((p) => JSON.stringify(p)).join("\n") + "\n", "utf8"); - await rename(file + tmpSuffix, file); + await writeFileAtomic(file, list.map((p) => JSON.stringify(p)).join("\n") + "\n"); } for (const shard of await listPostShards(channelRoot)) { if (!byShard.has(shard)) await rm(shardPath(channelRoot, shard), { force: true }); } const archive = channelPostsArchivePath(channelRoot); const lines = [...byId.values()].map((p) => `${p.platform} ${p.id}\n`).join(""); - await writeFile(archive + tmpSuffix, lines, "utf8"); - await rename(archive + tmpSuffix, archive); + await writeFileAtomic(archive, lines); return { shards: [...byShard.keys()].sort(), written: byId.size }; } diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs @@ -46,6 +46,7 @@ import { randomBytes } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "./atomicFile.mjs"; /** The memory floor a render in render mode is admitted on, absent HEAVY_MIN_FREE_MB. */ export const RENDER_PRIORITY_FLOOR_MB = 4000; @@ -128,7 +129,7 @@ export function readRenderPriorityState(file) { /** tmp + rename, so a reader never sees half a file. */ function writeState(file, state) { fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + const tmp = tmpPathFor(file); fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); fs.renameSync(tmp, file); } @@ -140,7 +141,7 @@ function writeState(file, state) { */ function createState(file, state) { fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`; + const tmp = tmpPathFor(file); fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`); try { fs.linkSync(tmp, file); diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -63,6 +63,7 @@ import type { VideoManifest } from "../videoOps"; import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export type { DraftTarget, Provenance } from "../../drafted.mjs"; @@ -248,7 +249,7 @@ export function mergeAlternatives(earlier: readonly DraftAlternative[], now: rea } async function writeJsonAtomic(file: string, value: unknown) { - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/common/lib/report/draft/tasks/project.ts b/common/lib/report/draft/tasks/project.ts @@ -10,6 +10,7 @@ import { copyFile, link, mkdir, readdir, readFile, rename, stat, writeFile } fro import path from "node:path"; import { projectOf, type Iteration } from "../../iterations"; import type { VideoManifest } from "../videoOps"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST_NAME = "video.manifest.json"; // umtool's snapshots (umtool/lib/report/snapshots.mjs): `revisions/<stamp>-<label>.manifest.json`. @@ -41,7 +42,7 @@ export async function readProjectReport(dir: string): Promise<Record<string, unk export async function writeManifest(dir: string, m: VideoManifest): Promise<void> { await mkdir(dir, { recursive: true }); const file = path.join(dir, MANIFEST_NAME); - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(m, null, 2)}\n`); await rename(tmp, file); } diff --git a/common/lib/report/groupProposals.mjs b/common/lib/report/groupProposals.mjs @@ -23,6 +23,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const GROUP_PROPOSALS_NAME = "group-proposals.json"; export const GROUPS_PROMPT_VERSION = "propose-groups-1"; @@ -209,7 +210,7 @@ export async function writeGroupProposals(dir, doc) { const errors = groupProposalsErrors(doc); if (errors.length) throw new Error(`not group proposals: ${errors.join("; ")}`); const file = fileOf(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/common/lib/report/videoAssistProposals.mjs b/common/lib/report/videoAssistProposals.mjs @@ -19,6 +19,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const ASSIST_PROPOSALS_NAME = "assist-proposals.json"; export const ASSIST_PROMPT_VERSION = "video-assist-1"; @@ -91,7 +92,7 @@ export async function writeAssistProposals(dir, doc) { const errors = proposalsErrors(doc); if (errors.length) throw new Error(`not proposals: ${errors.join("; ")}`); const file = fileOf(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/common/lib/research/caseStore-server.ts b/common/lib/research/caseStore-server.ts @@ -27,6 +27,7 @@ import { } from "./caseTypes"; import { CasePipelineError, checkFindingRow, normalizeDefinition, planBatches, rowGateText, wrapText } from "./casePipeline"; import { assertNoPrivateNames, withholdPrivateNames } from "./casePrivacy-server"; +import { tmpPathFor } from "../atomicFile.mjs"; const file = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name); @@ -52,7 +53,7 @@ async function readJsonFile<T>(p: string): Promise<T | null> { /** A whole file, to a temp name and a rename. */ export async function writeAtomic(p: string, body: string): Promise<void> { await mkdir(/* turbopackIgnore: true */ path.dirname(p), { recursive: true }); - const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(p); try { await writeFile(/* turbopackIgnore: true */ tmp, body); await rename(/* turbopackIgnore: true */ tmp, p); diff --git a/common/lib/waybackPages/store-server.ts b/common/lib/waybackPages/store-server.ts @@ -19,6 +19,7 @@ import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"; import { gunzipSync, gzipSync } from "node:zlib"; import { writeJsonAtomic } from "../jsonFile-server"; import { pageRecordId } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PAGES_DIRNAME = "pages"; export const PAGE_RAW_FILENAME = "raw.html.gz"; @@ -131,7 +132,7 @@ export async function writeStoredCapture( const dir = pageCaptureDir(channelRoot, capture.captureTs, capture.originalUrl); await mkdir(dir, { recursive: true }); const raw = path.join(dir, PAGE_RAW_FILENAME); - const tmp = `${raw}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(raw); await writeFile(tmp, gzipSync(body)); await rename(tmp, raw); await writeJsonAtomic(path.join(dir, PAGE_CAPTURE_FILENAME), capture); diff --git a/common/package.json b/common/package.json @@ -39,6 +39,7 @@ "./lib/clips/scan.mjs": "./lib/clips/scan.mjs", "./lib/clips/segments.mjs": "./lib/clips/segments.mjs", "./lib/clips/suggest.mjs": "./lib/clips/suggest.mjs", + "./lib/atomicFile.mjs": "./lib/atomicFile.mjs", "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", diff --git a/umtool/app/api/clip/[key]/audio/route.ts b/umtool/app/api/clip/[key]/audio/route.ts @@ -6,6 +6,7 @@ import { promisify } from "node:util"; import { CACHE_DIR, cacheFile } from "@/lib/paths"; import { sourceWav } from "@/lib/clips"; import { readWavWindow, encodeWav, peakOver } from "@/lib/wav"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -89,7 +90,7 @@ export async function GET(request: Request, ctx: { params: Promise<{ key: string body = await readFile(tmpMp3); await rename(tmpMp3, cached).catch(() => {}); } else { - const tmp = cacheFile(`${stamp}.wav.tmp`); + const tmp = tmpPathFor(cached); await writeFile(tmp, wav); await rename(tmp, cached).catch(() => {}); } diff --git a/umtool/app/api/report/post-narration/record/route.ts b/umtool/app/api/report/post-narration/record/route.ts @@ -56,7 +56,9 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body. + // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on + // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused + // even from curl, and so is a write from another site's page. const cross = crossSiteRefusal(request.headers); if (cross) return Response.json({ error: cross }, { status: 403 }); const refused = refuseCaller(request, "/api/report/post-narration/record"); diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -166,7 +166,9 @@ export async function GET(request: Request) { // is a multipart upload, so those are made on the cut's bench. const TAKE_OPS = new Set(["reread", "set", "fit"]); export async function POST(request: Request) { - // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body. + // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on + // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused + // even from curl, and so is a write from another site's page. const cross = crossSiteRefusal(request.headers); if (cross) return Response.json({ error: cross }, { status: 403 }); if ((request.headers.get("content-type") ?? "").startsWith("multipart/form-data")) return postHere(request); diff --git a/umtool/app/api/report/review-pass/route.ts b/umtool/app/api/report/review-pass/route.ts @@ -6,9 +6,9 @@ import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; -// THE REVIEW PASS's post and card marks (lib/report/reviewPass.mjs; the workspace's `?mode=review`). A clip's -// Keep / Fix is its walk verdict, written through the window writer (PUT /api/report/window); this is the store -// for what has none. +// THE REVIEW PASS's marks (lib/report/reviewPass.mjs; the workspace's `?mode=review`): any block's Fix (a clip's +// too: never its verdict), a post's or a card's Keep. A clip's Keep is its walk verdict, written through the window +// writer (PUT /api/report/window); the draft's verdict is POST /api/report/review-pass/verdict. // // GET ?project=<id> <project>/review-pass.json, as read // POST { project, block, mark: "keep"|"fix"|null, note? } one block's mark (null clears it); a Fix says what diff --git a/umtool/app/api/report/voices/route.ts b/umtool/app/api/report/voices/route.ts @@ -99,7 +99,9 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so refused cross-site here, before the body. + // OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on + // EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused + // even from curl, and so is a write from another site's page. const cross = crossSiteRefusal(request.headers); if (cross) return Response.json({ error: cross }, { status: 403 }); const refused = refuseCaller(request, "/api/report/voices"); diff --git a/umtool/components/projects/bench/walkVerdict.test.ts b/umtool/components/projects/bench/walkVerdict.test.ts @@ -0,0 +1,78 @@ +// The walk's verdict writer, outside the bench (bench/walkVerdict.ts): what a review pass's Keep may write, and in +// what order. No server: `fetch` is a fake that answers the clip GET and records the window PUT. +// +// Run with: pnpm --filter umtool exec tsx --test components/projects/bench/walkVerdict.test.ts +import { afterEach, test } from "node:test"; +import assert from "node:assert/strict"; +import { keepClip, writeWalkVerdict, type ClipWrite } from "./walkVerdict"; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; +}); + +/** A fake server: the clip GET answers `verdict` on token "t1"; the PUT is recorded and answered ok. */ +function fakeServer(verdict: string | null) { + const puts: Record<string, unknown>[] = []; + globalThis.fetch = (async (url: string, init?: RequestInit) => { + if (String(url).startsWith("/api/report/clip?")) return Response.json({ token: "t1", clip: { id: "c1", verdict } }); + if (String(url) === "/api/report/window" && init?.method === "PUT") { + const body = JSON.parse(String(init.body)) as Record<string, unknown>; + puts.push(body); + return Response.json({ ok: true, token: "t2", entry: { id: "c1", verdict: body.verdict } }); + } + return new Response("no", { status: 404 }); + }) as typeof fetch; + return puts; +} + +test("Keep is refused over a ruling the bench made since the view was read: the clip's verdict at write time decides, nothing is PUT", async () => { + for (const ruled of ["incorrect", "rejected"]) { + const puts = fakeServer(ruled); + const w = await writeWalkVerdict("p", "c1", { verdict: "confirmed" }); + assert.equal(w.ok, false); + assert.match(!w.ok ? w.error : "", new RegExp(`marked ${ruled} in the bench`)); + assert.deepEqual(puts, [], `nothing written over ${ruled}`); + } +}); + +test("Keep writes `confirmed` on the token its own read gave, over no verdict or over confirmed", async () => { + for (const now of [null, "confirmed"]) { + const puts = fakeServer(now); + const w = await writeWalkVerdict("p", "c1", { verdict: "confirmed" }); + assert.equal(w.ok, true); + assert.deepEqual(puts, [{ project: "p", clip: "c1", token: "t1", verdict: "confirmed" }]); + } +}); + +test("Keep on a clip carrying a Fix: the verdict is written FIRST, and the mark (its note) is taken back only once that write succeeded", async () => { + const calls: string[] = []; + const failing = async (): Promise<ClipWrite> => { + calls.push("verdict"); + return { ok: false, error: "HTTP 500", stale: false }; + }; + const clearMark = async () => { + calls.push("clear"); + return null; + }; + let r = await keepClip({ confirmed: false, hasMark: true, writeVerdict: failing, clearMark }); + assert.deepEqual(calls, ["verdict"], "a failed verdict write leaves the Fix mark"); + assert.deepEqual(r, { error: "HTTP 500", wrote: false }); + calls.length = 0; + const stale = async (): Promise<ClipWrite> => ({ ok: false, error: "stale", stale: true }); + r = await keepClip({ confirmed: false, hasMark: true, writeVerdict: stale, clearMark }); + assert.equal(calls.length, 0); + assert.match(String(r.error), /changed since/); + const ok = async (): Promise<ClipWrite> => { + calls.push("verdict"); + return { ok: true, entry: {}, token: "t2", json: {} }; + }; + r = await keepClip({ confirmed: false, hasMark: true, writeVerdict: ok, clearMark }); + assert.deepEqual(calls, ["verdict", "clear"]); + assert.deepEqual(r, { error: null, wrote: true }); + // Confirmed already: only the mark is taken back, nothing written. + calls.length = 0; + r = await keepClip({ confirmed: true, hasMark: true, writeVerdict: ok, clearMark }); + assert.deepEqual(calls, ["clear"]); + assert.deepEqual(r, { error: null, wrote: false }); +}); diff --git a/umtool/components/projects/bench/walkVerdict.ts b/umtool/components/projects/bench/walkVerdict.ts @@ -9,11 +9,23 @@ export type ClipWrite = | { ok: true; entry: Record<string, unknown>; token: string; json: Record<string, unknown> } | { ok: false; error: string; stale: boolean }; -/** One clip's patch through the window writer, on the clip's token as it is now. */ -export async function writeClipPatch(project: string, clip: string, patch: Record<string, unknown>): Promise<ClipWrite> { +/** + * One clip's patch through the window writer, on the clip's token as it is now. `refuse` sees the clip as that + * read gave it and may refuse the write (its words); the token is the same read's, so a write landing after it + * makes the PUT stale rather than overwritten. + */ +export async function writeClipPatch( + project: string, + clip: string, + patch: Record<string, unknown>, + refuse?: (clip: Record<string, unknown>) => string | null, +): Promise<ClipWrite> { const r = await fetch(`/api/report/clip?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}`, { cache: "no-store" }); if (!r.ok) return { ok: false, error: `HTTP ${r.status}`, stale: false }; - const tok = ((await r.json().catch(() => ({}))) as { token?: string }).token ?? null; + const got = (await r.json().catch(() => ({}))) as { token?: string; clip?: Record<string, unknown> }; + const said = refuse?.(got.clip ?? {}) ?? null; + if (said) return { ok: false, error: said, stale: false }; + const tok = got.token ?? null; const w = await fetch("/api/report/window", { method: "PUT", headers: { "content-type": "application/json" }, @@ -24,7 +36,41 @@ export async function writeClipPatch(project: string, clip: string, patch: Recor return { ok: true, entry: (j.entry ?? {}) as Record<string, unknown>, token: String(j.token ?? ""), json: j }; } -/** The walk's verdict a review pass writes: Keep (`confirmed`) -- never `incorrect`, the bench's fact-error ruling. */ +/** The words a Keep is refused with over a clip the bench ruled. */ +export const ruledInBench = (verdict: string) => `marked ${verdict} in the bench: the Full bench changes it`; + +/** + * The walk's verdict a review pass writes: Keep (`confirmed`) -- never `incorrect`, the bench's fact-error ruling, + * and never OVER it: the clip's verdict is read at write time (the view's entry may be older than a ruling the + * bench made since), and `confirmed` is refused over `incorrect` or `rejected`. + */ export function writeWalkVerdict(project: string, clip: string, v: { verdict: "confirmed" } | { verdict: "" }): Promise<ClipWrite> { - return writeClipPatch(project, clip, v); + return writeClipPatch(project, clip, v, (c) => { + const now = typeof c.verdict === "string" ? c.verdict : null; + return v.verdict === "confirmed" && (now === "incorrect" || now === "rejected") ? ruledInBench(now) : null; + }); +} + +/** + * A review pass's Keep on a clip, in the order that loses nothing: the verdict first (when it is not `confirmed` + * already), and only once it is written is the Fix mark it carried taken back -- a refused or failed write leaves + * the mark, and its note, where they were. `wrote`: a verdict was written (the draft changed). + */ +export async function keepClip(o: { + confirmed: boolean; + hasMark: boolean; + writeVerdict: () => Promise<ClipWrite>; + clearMark: () => Promise<string | null>; +}): Promise<{ error: string | null; wrote: boolean }> { + let wrote = false; + if (!o.confirmed) { + const w = await o.writeVerdict(); + if (!w.ok) return { error: w.stale ? "the draft changed since — try again" : w.error, wrote: false }; + wrote = true; + } + if (o.hasMark) { + const err = await o.clearMark(); + if (err) return { error: err, wrote }; + } + return { error: null, wrote }; } diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -39,7 +39,7 @@ 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 { readRemoved, removedOutOfCut, removedSourceOf } 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"; @@ -70,10 +70,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor // 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, + source: removedSourceOf(r, m), 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, diff --git a/umtool/components/projects/report/RemovedClips.tsx b/umtool/components/projects/report/RemovedClips.tsx @@ -14,10 +14,8 @@ import { announceManifestChanged, refusalOf, timelineOp } from "../timelineApi"; export type RemovedRow = { id: string; - channel: string | null; - video: string | null; - start: number | null; - end: number | null; + /** Where it came from (manifest.mjs removedSourceOf): `<channel>/<video> @ s–e`, the video alone, or "". */ + source: string; why: string; note: string | null; when: string | null; @@ -54,9 +52,7 @@ export default function RemovedClips({ project, rows }: { project: string; rows: <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> + {r.source && <span className="text-[11px] text-[var(--color-dim)]">{r.source}</span>} <span data-removed-why=""> {r.why} {r.note ? `: ${r.note}` : ""} diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -570,6 +570,9 @@ export default function PlayCut({ app.openClip(it?.id ?? "", h); return; } + // A navigation in flight: Play's own URL write (150 ms after the pause, `replaceState(null, …)`) would land on + // top of it and cancel it while its RSC round-trip is slow -- the push to a version's open page hung under load. + navigating.current = true; router.push(h); }, [editHref, router, setPlaying, placeHref, app, now, take]); const lastPlace = useRef(0); diff --git a/umtool/components/projects/workspace/BlockStrip.tsx b/umtool/components/projects/workspace/BlockStrip.tsx @@ -63,6 +63,7 @@ export default function BlockStrip({ plus, marks = null, menu, + canMove = true, }: { blocks: Block[]; selected: string | null; @@ -78,6 +79,8 @@ export default function BlockStrip({ marks?: Map<string, { mark: "keep" | "fix" | "ruled"; note: string | null }> | null; /** What a block's menu does (none: no menus). */ menu?: BlockActions; + /** Whether a block drags to a new place: only in Edit on the draft (the review pass and a version move nothing). */ + canMove?: boolean; }) { const ref = useRef<HTMLDivElement | null>(null); const [drag, setDrag] = useState<string | null>(null); @@ -139,7 +142,7 @@ export default function BlockStrip({ {blocks.map((b, i) => { const w = Math.round(Math.min(MAX_W, Math.max(MIN_W, b.seconds * PX_PER_S))); const on = b.id === selected; - const movable = b.at !== null && !busy; + const movable = canMove && b.at !== null && !busy; const menuOn = open?.i === i; return ( <div key={`${b.id}@${i}`} className="group relative flex shrink-0"> diff --git a/umtool/components/projects/workspace/ReviewPass.tsx b/umtool/components/projects/workspace/ReviewPass.tsx @@ -8,7 +8,7 @@ import { clipBenchHref, openInDraftHref } from "@/lib/hrefs"; import { blockAnswer, clipKeepable, clipVerdict, reviewProgress } from "@/lib/report/reviewPassModel.mjs"; import AnchoredNotes from "@/components/notes/AnchoredNotes"; import { useSharedNotes } from "@/components/notes/NotesProvider"; -import { writeWalkVerdict } from "../bench/walkVerdict"; +import { keepClip, ruledInBench, writeWalkVerdict } from "../bench/walkVerdict"; import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi"; import VersionVerdict from "../review/VersionVerdict"; import type { PlayEntry } from "../review/PlayCut"; @@ -108,19 +108,19 @@ export function useReviewPass(project: string, entries: PlayEntry[], on: boolean // A version on screen (readOnly.ts): its marks would land on the draft's blocks. if (readOnly) return READ_ONLY_SAID; if (mark === "fix" || e.type !== "clip") return postMark(e.id, mark, note); - if (!clipKeepable(e)) return `marked ${clipVerdict(e)} in the bench: the Full bench changes it`; - // A Fix it carried is taken back: kept now. - if (marks[e.id]) { - const err = await postMark(e.id, null, null); - if (err) return err; - } - if (clipVerdict(e) !== "confirmed") { - const w = await writeWalkVerdict(project, e.id, { verdict: "confirmed" }); - if (!w.ok) return w.stale ? "the draft changed since — try again" : w.error; + if (!clipKeepable(e)) return ruledInBench(String(clipVerdict(e))); + // The verdict first; a Fix it carried is taken back only once it is written (keepClip). + const r = await keepClip({ + confirmed: clipVerdict(e) === "confirmed", + hasMark: !!marks[e.id], + writeVerdict: () => writeWalkVerdict(project, e.id, { verdict: "confirmed" }), + clearMark: () => postMark(e.id, null, null), + }); + if (r.wrote) { setWritten((x) => ({ ...x, [e.id]: { mark: "keep", note: null } })); announceManifestChanged(project); } - return null; + return r.error; }, [project, readOnly, postMark, marks], ); @@ -244,6 +244,8 @@ export default function ReviewPass({ const answer = id ? (rv.answers.get(id) ?? null) : null; // Marked once, but the block is not what was reviewed any more (an edge, a post's words, another version opened). const changed = !!(id && rv.marks[id]?.stale); + // A Fix gone stale keeps what it said: shown under "changed since reviewed", and the Fix form opens on it. + const staleFix = changed && id && rv.marks[id]?.mark === "fix" ? (rv.marks[id]?.note ?? null) : null; // The bench's ruling on a clip (incorrect: a fact error, wrong speaker), shown and left as it is. const bench = entry?.type === "clip" && !clipKeepable(entry) @@ -266,9 +268,9 @@ export default function ReviewPass({ const openFix = useCallback(() => { if (!entry || readOnly) return; setNoting(false); - setFixText(answer?.mark === "fix" ? (answer.note ?? "") : ""); + setFixText(answer?.mark === "fix" ? (answer.note ?? "") : (staleFix ?? "")); setFixing(true); - }, [entry, readOnly, answer]); + }, [entry, readOnly, answer, staleFix]); // k / f / n: the block's answers (the workspace keeps Space and ← →). const keys = useRef({ go, openFix, setNoting }); @@ -358,6 +360,11 @@ export default function ReviewPass({ changed since reviewed </p> )} + {staleFix && !answer && ( + <p className="m-0 text-[12px] text-doubt-text" data-review-stale-fix=""> + it needed work: {staleFix} + </p> + )} {/* A clip the bench ruled (a fact error, wrong speaker): the pass shows it and never overwrites it. */} {bench && ( <p className="m-0 text-[12px] text-doubt-text" data-review-bench={bench.verdict}> diff --git a/umtool/components/projects/workspace/Workspace.tsx b/umtool/components/projects/workspace/Workspace.tsx @@ -21,7 +21,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner"; import PresentView, { type PresentPayload } from "../present/PresentView"; import ReviewPass, { useReviewPass } from "./ReviewPass"; import ReadinessBar, { type Readiness } from "./ReadinessBar"; -import { READ_ONLY_SAID, WorkspaceReadOnly, workspaceReadOnly } from "./readOnly"; +import { READ_ONLY_SAID, WorkspaceReadOnly, useWorkspaceReadOnly, workspaceReadOnly } from "./readOnly"; // --------------------------------------------------------------------------- // THE WORKSPACE (umtool redesign L7a): a report video's ONE screen, at its own @@ -720,7 +720,11 @@ export default function Workspace({ if (mode === "review") setAtEnd(false); select(id); }} - onMove={(id, at, to) => void move(id, at, to)} + // A block drags only in Edit on the draft: the review pass watches the cut, it never reorders it. + canMove={mode === "edit" && !readOnly} + onMove={(id, at, to) => { + if (mode === "edit" && !readOnly) void move(id, at, to); + }} marks={mode === "review" ? rv.answers : null} // A block's menu only in Edit on the draft: the workspace's one read-only flag (readOnly.ts) and the mode. menu={mode === "edit" && !readOnly ? menu : undefined} @@ -833,6 +837,16 @@ export default function Workspace({ /** +: what is added to the cut -- a clip (found, in/out on its cues), posts, a teaser or closing card. */ function AddPanels({ project, after, channels }: { project: string; after: string | null; channels: string[] }) { + // Every adder writes the draft: none while a version shows (readOnly.ts; the + is hidden then, but `?block=+` + // still selects it). + const readOnly = useWorkspaceReadOnly(); + if (readOnly) { + return ( + <p className="m-0 px-3 py-2 text-[12px] text-muted" data-ws-add-read-only=""> + {READ_ONLY_SAID} + </p> + ); + } return ( <div className="space-y-3 px-3 py-2" data-ws-add=""> <div className="flex items-baseline gap-2 border-b border-seam pb-1.5"> diff --git a/umtool/components/tools/DigestContextReview.tsx b/umtool/components/tools/DigestContextReview.tsx @@ -143,16 +143,17 @@ export default function DigestContextReview({ initial, promptChars }: { initial: </> ) : ( <> - <span className="text-[12px]" data-digest-confirm={n.slug}> - {n.slug}'s note becomes <code className="font-mono">digest-context.md</code>: every digest already made for this channel goes stale and - regenerates. - </span> + {/* The confirming press sits where the first press was: the sentence follows the buttons, so a second click in place confirms. */} <button type="button" data-digest-confirm-yes={n.slug} disabled={busy !== null} onClick={() => void decide(n, "yes")} className={buttonVariants({ size: "sm" })}> Make it active </button> <button type="button" disabled={busy !== null} onClick={() => setConfirming(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> Cancel </button> + <span className="text-[12px]" data-digest-confirm={n.slug}> + {n.slug}'s note becomes <code className="font-mono">digest-context.md</code>: every digest already made for this channel goes stale and + regenerates. + </span> </> )} {errors[n.slug] && ( diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -75,7 +75,7 @@ Inbox cannot disagree about what is wrong with one. | `take <project> --id <id> --draft --from <take> [--label L] [--patch F \| --patch-json J \| --set p=v …]` | a **draft made from another take**: that take's style and patch (a `--patch` merged over it), its label "<that label> (from <take>)" unless `--label`, nothing rendered; its timeline is its own from then on, and its render's `--from` (segments reused) is a separate flag of the render ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits)) | | `take <project> --id <id> --preview [--from <take>] [--at S --dur S \| --full] [--priority] [--json]` | the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes)) | | `take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]` | the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so | -| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** | +| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** | | `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") | | `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render | | `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -324,7 +324,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve |---|---|---|---| | `render.chrome.factcheck.stamp.scale` (0.5–2), `.motion` (`slam` `pop` `fade` `none`), `.opacity` (0.3–1) | Structure, **fact-check labels**: scale, motion, opacity | `umtool look <p> factcheck.stamp.scale=1.3 factcheck.stamp.motion=pop` | `POST /api/report/timeline {op: "factcheck", factcheck}` | | `render.chrome.factcheck.verdicts.<V>.stampLabel` — the stamp's word (singular, `SEIZURE`) beside `label` (the tally's, `SEIZURES`) | fact-check labels, the third column | `factcheck.verdicts.CONTRADICTED.stampLabel=SEIZURE` | same | -| `render.chrome.factcheck.verdicts.<V>.tallyLabel` — the deck tally cell's word (`PITCHES`) beside `label` (the finale's totals and stats keep the full `Huck's Blend pitches`). The cell never cuts a label short: without a `tallyLabel` it shows the `label` if it fits, else the longest run of the label's last words that fits (`Huck's Blend pitches` → `Blend pitches`); a `tallyLabel` that does not fit, or a `label` no run of whose last words fits, is refused by name at check time. Measured as drawn: 13 px capitals, 0.08 em spacing, 112 px, in Fira Sans Bold's advances (or 0.6 em a character in a `fontBold` named Mono) | none yet: `umtool look` | `umtool look <p> factcheck.verdicts.PARTLY.tallyLabel=Pitches` (`=` clears it) | `POST /api/report/timeline {op: "factcheck", factcheck}` | +| `render.chrome.factcheck.verdicts.<V>.tallyLabel` — the deck tally cell's word (`PITCHES`) beside `label` (the finale's totals and stats keep the full `Huck's Blend pitches`). Without a `tallyLabel` it shows the `label` if it fits, else the longest run of the label's last words that fits (`Huck's Blend pitches` → `Blend pitches`); a `tallyLabel` that does not fit, or a `label` no run of whose last words fits, is drawn smaller a pixel at a time down to 10 px, then cut with an ellipsis (factcheck.mjs `fitTallyLabel`) -- the chrome is never refused for it, and the lint names each label it shortened. Measured as drawn: 13 px capitals, 0.08 em spacing, 112 px, in Fira Sans Bold's advances (or 0.6 em a character in a `fontBold` named Mono) | none yet: `umtool look` | `umtool look <p> factcheck.verdicts.PARTLY.tallyLabel=Pitches` (`=` clears it) | `POST /api/report/timeline {op: "factcheck", factcheck}` | | `render.chrome.factcheck.tally.showAt` — `always` (default: every cell from the first frame, dim at 0) or `first` (a cell hidden until the stamp that gives it its first count lands, then it pops in — scale 0.5→1, 0.35 s, the markers' ease — already reading its count, and stays); one value for every cell, or `{ "<VERDICT>": "first" }` for each on its own (unnamed: `always`). A hidden cell keeps its place in the row; the finale's totals show every verdict as ever | fact-check labels, **pop in** per verdict (every one ticked writes `first`) | `umtool look <p> factcheck.tally.showAt=first`, or one cell: `factcheck.tally.showAt.PARTLY=first` (`factcheck.tally.showAt=` clears it) | same | | `render.chrome.deck.markers[]` — `{after, label ≤ 24, color?, align?, level?}`, at most 32; `align` `auto` `left` `right` `center`; `level` 1 (a section, the default) or 2 (a subsection of the section before it — a shorter tick in its parent's colour, a quieter label, "Section › Sub" in the section title; to every edit a section like any other; the cut's first marker must be a section) | On-screen, **markers**: add, the clip picker, label, colour, sub, align, ↑ ↓, remove | `umtool look <p> deck.markers='[{"after":"c03","label":"Rescue","align":"right"},{"after":"c05","label":"The vet","level":2}]'` · `umtool timeline <p> section-add --after c05 --label "The vet" --level 2` · `section-set <m> --level 1\|2` | `PUT /api/report/chrome {project, token, markers}` | | `render.chrome.deck.<key>` — any of the deck's own keys (`finale`, `pip`, …), as JSON; refused in the build's words when it does not know the key or the value | On-screen settings (the ones it has a field for) | `umtool look <p> deck.finale='{…}'` | — | @@ -2185,8 +2185,8 @@ The deck's tally as named series (`render.chrome.deck.counter`). A clip's mark n | Knob | Range · default | From a terminal | |---|---|---| -| `deck.counter.series[]` | 1–12 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 (≤ 32 as written) and fitting the cell, as the verdicts' are. Up to 8 the cells are 124 px; past 8 they narrow into one row of 1040 px (9 → 108 px, 10 → 96, 12 → 79), so the title keeps a column of about 520 px, and a label must fit the narrower cell (refused by name, never cut) | `umtool look <p> deck.counter='{"series":[{"id":"seizures","label":"Seizures","color":"#e5534b","stampLabel":"Seizure"}]}'` | -| `deck.counter.labels` | `caps` `as-written` · default `caps`: each cell's word capitalised on one line (its `tallyLabel`, else its label or the last words of it that fit). `as-written`: the label in its own case ("close to MAGA"), letter-spaced 0.02 em, broken between words into at most two lines, never cut to its last words -- a word wider than the cell, or a third line, is refused by name | `umtool look <p> deck.counter.labels=as-written` | +| `deck.counter.series[]` | 1–12 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 (≤ 32 as written), fitted to the cell as the verdicts' are. Up to 8 the cells are 124 px; past 8 they narrow into one row of 1040 px (9 → 108 px, 10 → 96, 12 → 79), so the title keeps a column of about 520 px, and a label wider than its cell is drawn smaller (down to 10 px), then cut with an ellipsis -- never a refused chrome; the lint names it | `umtool look <p> deck.counter='{"series":[{"id":"seizures","label":"Seizures","color":"#e5534b","stampLabel":"Seizure"}]}'` | +| `deck.counter.labels` | `caps` `as-written` · default `caps`: each cell's word capitalised on one line (its `tallyLabel`, else its label or the last words of it that fit). `as-written`: the label in its own case ("close to MAGA"), letter-spaced 0.02 em, broken between words into at most two lines, never cut to its last words -- one that does not fit is drawn smaller (down to 10 px), then a word or its second line is cut with an ellipsis; the lint names it | `umtool look <p> deck.counter.labels=as-written` | | `deck.counter.series[].shape` | `circle` `diamond` `square` `triangle` `ring` · default by place (a verdict's own) | same | | `deck.counter.series[].unit` | ≤ 24 · the noun a count claim's number reads (default its label, lower-cased) | same | | `deck.counter.show`, `.position`, `.showAt` | bool · `right` `left` · `always` `first` (a series' own `showAt` wins) · defaults `true`, `right`, `always`. A series that SAYS `always` (its own `showAt`, else the counter's) is a cell from the first frame, dim at 0, whether or not a mark ever counts it ("Left 0"); one with no `showAt` said, or `first`, is a cell once it is counted, so one never counted is not drawn. The cells show once the cut counts anything | same | diff --git a/umtool/e2e/add-clip.spec.ts b/umtool/e2e/add-clip.spec.ts @@ -76,9 +76,10 @@ test("Add a clip: find the words, in and out on the cues, after a row, added and await expect.poll(() => timeline().map((e) => e.id).indexOf(id!)).toBe(1); const e = timeline()[1]; expect(e).toMatchObject({ type: "clip", video: "vid1", start: 12.5, end: 21 }); - // Its window, through the editor's paced fetch: the job runs and ends (done, or the stub's own answer). - await expect(added).not.toHaveAttribute("data-add-clip-fetch", "running", { timeout: 60_000 }); - await expect(added).not.toHaveAttribute("data-add-clip-fetch", "idle"); + // Its window, through the editor's paced fetch: the job runs and ENDS (done, or the stub's own answer) before the + // test does -- "not running" was true while it was still idle, so the window (vid1 0.00-41.00, a 20 s pad each + // side) landed after the afterEach looked, and every later spec read a wider vid1 window (clip-bench, projects). + await expect(added).toHaveAttribute("data-add-clip-fetch", /^(done|failed)$/, { timeout: 60_000 }); }); test("Add a clip from a pasted link: the recording the cut already carries, at its time", async ({ page }) => { diff --git a/umtool/e2e/digest-context.spec.ts b/umtool/e2e/digest-context.spec.ts @@ -60,7 +60,12 @@ test("each note with its evidence; No refuses it and keeps the file; Yes, asked await expect(page.locator("[data-digest-pending]")).toHaveAttribute("data-digest-pending", "1"); // Yes asks first, with what it costs; Cancel writes nothing. + // The confirming button lands where the first press was (a second click in place confirms), the sentence after it. + const yesBox = await note("testchan").locator("[data-digest-yes]").boundingBox(); await note("testchan").locator("[data-digest-yes]").click(); + const confirmBox = await note("testchan").locator("[data-digest-confirm-yes]").boundingBox(); + expect(Math.abs((confirmBox?.x ?? -999) - (yesBox?.x ?? 0))).toBeLessThanOrEqual(2); + expect(Math.abs((confirmBox?.y ?? -999) - (yesBox?.y ?? 0))).toBeLessThanOrEqual(2); await expect(note("testchan").locator("[data-digest-confirm]")).toContainText("every digest already made for this channel goes stale and regenerates"); await page.screenshot({ path: test.info().outputPath("digest-context-confirm.png") }); await note("testchan").getByRole("button", { name: "Cancel" }).click(); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -945,6 +945,16 @@ writeProject( ]), ); +// The same cut in basic mode (a quick clip on a channel no public site carries): the footage alone draws no QR, so +// its missing origin blocks nothing (projects.spec: not among the siteOrigin defects). +{ + const m = manifest("basic-no-origin-fixture", "Basic, No Origin", {}, [ + { type: "clip", id: "c01", video: "vid1", start: 0, end: 3, cite: 0, section: 0, lock: true, quote: "q" }, + ]); + m.render = { ...m.render, mode: "basic" }; + writeProject("basic-no-origin-fixture", m); +} + writeProject( "localhost-fixture", manifest("localhost-fixture", "Localhost Origin", { siteOrigin: "http://localhost:3000" }, [ @@ -2171,9 +2181,9 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out }); const wsFile = path.join(wsDir, "video.manifest.json"); const wsM = JSON.parse(readFileSync(wsFile, "utf8")); - // The counter's cell word short enough for the tally's cell (play-cut-fixture's "Seizures" no longer fits since - // the tally's 72 px row): the deck COMPOSES here, so workspace.spec can say a composition failure is a regression. - wsM.render.chrome.factcheck.verdicts.CORROBORATED.tallyLabel = "Seized"; + // The counter's word is play-cut-fixture's "Seizures", wider than the tally's cell in the fixture's face: it is + // drawn smaller (factcheck.mjs fitTallyLabel) and the deck COMPOSES, so workspace.spec can say a composition + // failure is a regression. wsM.timeline.splice(2, 0, { type: "post", id: "p-5", post: "postchan-x/5", platform: "x", author: "Post Subject", handle: "postsubject", date: "2026-10-30T12:00:00.000Z", text: "The scale said 291 this morning. I said the scale was broken.", url: "https://x.com/postsubject/status/5", subjects: ["postsubject"], diff --git a/umtool/e2e/long-reads.spec.ts b/umtool/e2e/long-reads.spec.ts @@ -174,8 +174,8 @@ test("THE PROGRESS BAR in Play, with the read re-timed: it fills over the new re const seen: Array<[number, number]> = []; await expect .poll(async () => { - const s = Number(await player.getAttribute("data-post-s")); - const f = Number(await player.getAttribute("data-post-progress")); + // Both read at one instant (one evaluate): two reads a load apart are two clocks' worth of drift. + const [s, f] = await player.evaluate((el) => [Number(el.getAttribute("data-post-s")), Number(el.getAttribute("data-post-progress"))]); seen.push([s, f]); return f; }, { timeout: 20_000, intervals: [150] }) diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts @@ -56,6 +56,10 @@ test("the cut plays clip after clip on one clock; prev / next / keys; the strip await expect(page.locator("[data-play-counter-end]")).toHaveText("Seizures 3"); await expect(page.locator("[data-play-strip-at]")).toContainText("Seizures 0"); await expect(page.locator("[data-play-clock]")).toContainText("00:00 / 00:09"); + // The deck composes: "Seizures" is wider than the tally's cell in the fixture's face, and is drawn smaller + // (factcheck.mjs fitTallyLabel) -- never "the chrome did not compose". + await expect(root(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); + await expect(page.locator("[data-play-compose-error]")).toHaveCount(0); // Hovering a cell names it: the clip, its recording's date, how long it plays. await page.locator('[data-play-row="c02"]').hover(); await expect(page.locator('[data-play-strip-hover="c02"]')).toHaveText("c02 · 2 Dec 2024 · 2.9 s"); @@ -284,6 +288,8 @@ test("opened at ?clip=&at=, the clock never jumps back there when the render's e await page.locator("[data-play-toggle]").click(); await expect.poll(() => tNow(page), { timeout: 20_000 }).toBeGreaterThan(1.3); expect(held).toEqual(expect.arrayContaining(["/api/report/cut-points", "/api/report/chrome/preview"])); + // The frames from here on are the ones the late data could pull back (the clock is past 1.3 s now). + const released = await page.evaluate(() => ((window as Window & { __clock?: number[] }).__clock ?? []).length); release(); await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); // On past the re-plan: the clock goes on from where it was. @@ -297,5 +303,8 @@ test("opened at ?clip=&at=, the clock never jumps back there when the render's e // frames either way); a jump back to the place it opened at is a second and more. const back = clock.slice(1).map((t, i) => clock[i] - t); expect(Math.max(...back), `the clock went back: ${JSON.stringify(clock.map((t) => Math.round(t * 100) / 100))}`).toBeLessThan(0.25); - expect(Math.min(...clock.slice(clock.length >> 1))).toBeGreaterThan(1.3); + // Never back to the place it opened at, once the late data arrived: every frame after the release. (Not "the second + // half of the frames": since the deck composes (A1, fitTallyLabel), the frames after it come slower, and half the + // count fell before the release.) + expect(Math.min(...clock.slice(released))).toBeGreaterThan(1.3); }); diff --git a/umtool/e2e/play-take-edit.spec.ts b/umtool/e2e/play-take-edit.spec.ts @@ -103,6 +103,14 @@ test("Edit on the draft's own parent with no edits goes straight on (307) to the const root = page.locator("[data-play-cut]"); await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); await page.locator('[data-play-row="t01c"]').press("Enter"); + // The state the page shows, not a time: t01c is the clip on screen before Edit is pressed. + await expect(root).toHaveAttribute("data-play-item", "t01c"); + // As under load: the open page's round-trip slower than Play's own URL write after the pause (150 ms), which once + // landed on top of the navigation and cancelled it (PlayCut editHere holds it now). + await page.route(/\/takes\/v2\/open\?/, async (route) => { + await new Promise((r) => setTimeout(r, 800)); + await route.continue(); + }); await page.locator("[data-play-edit]").click(); await expect(page.locator('[data-bench="t01c"]')).toBeVisible({ timeout: 20_000 }); await expect(page).toHaveURL(/\/projects\/reports\/play-take-edit-fixture\/clip\/t01c\?from=play/); diff --git a/umtool/e2e/play-walk.spec.ts b/umtool/e2e/play-walk.spec.ts @@ -196,6 +196,9 @@ test("Play → Edit → the bench in place → Back: the same clip, second and t const t0 = await tNow(page); const item = "c02"; const hist = await page.evaluate(() => history.length); + // The deck settled first (composed, or none): the check below is that it is not composed AGAIN. Since the + // fixture's "Seizures" composes (fitTallyLabel; before, its chrome was refused at once), composing takes a moment. + await expect(root(page)).not.toHaveAttribute("data-play-compose", "composing", { timeout: 60_000 }); const composed = (await root(page).getAttribute("data-play-compose"))!; await page.locator("[data-play-edit]").click(); // In place: Play hidden (kept), the bench on the clip, its address the bench's. diff --git a/umtool/e2e/post-narration.spec.ts b/umtool/e2e/post-narration.spec.ts @@ -79,6 +79,11 @@ test("Play plays the take over the attachment, muffled under the read, then open }); /** Over `ms` of wall time inside the page: how far the item's clock, its video and its voice moved, and how often the video seeked. */ +/** Playing for real before a speed is sampled: no "loading…" on the transport. (Not a wait on the post's clock: a + * sample that starts late runs past a short read's end, and the voice reads slow.) */ +const steadyPlay = async (page: Page, _id: string) => { + await expect(page.locator("[data-play-waiting]")).toHaveCount(0, { timeout: 15_000 }); +}; const sampleSpeed = (page: Page, id: string, ms: number) => page.evaluate(async ({ id, ms }) => { const p = document.querySelector(`[data-post-play="${id}"]`)!; @@ -97,6 +102,9 @@ test("FAST-FORWARD SPEEDS A POST ITEM UP (operator, 3 Nov: \"it's just skipping await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); await expect(root(page)).toHaveAttribute("data-play-item", "p-11"); + // The deck composed first, as the read's-rate test below waits: its frame mounts the player afresh, and a sample + // across that reads a player gone (the clock "moving" at 0.08x). + await expect(root(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); const player = page.locator('[data-post-play="p-11"]'); await expect(player).toHaveAttribute("data-post-step", "video"); await page.locator("[data-play-rate]").selectOption("2"); @@ -104,6 +112,8 @@ test("FAST-FORWARD SPEEDS A POST ITEM UP (operator, 3 Nov: \"it's just skipping await expect(player).toHaveAttribute("data-post-narration-playing", "1", { timeout: 15_000 }); await expect(page.locator("video[data-post-video]")).toHaveAttribute("data-post-video-rate", "2"); await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-rate", "2"); + // Sampled once it plays steadily: a window that opens on the media still loading measures the load, not the rate. + await steadyPlay(page, "p-11"); const r = await sampleSpeed(page, "p-11", 600); // The clock at ~2x wall time; the video and the voice moving with it (played, not jumped); no re-seek. expect(r.ds / r.dw).toBeGreaterThan(1.6); @@ -132,6 +142,8 @@ test("THE READ's RATE in Play: render.postNarration.rate 1.25 plays the voice at await expect(player).toHaveAttribute("data-post-narration-playing", "1", { timeout: 15_000 }); await expect(page.locator("[data-post-narration-audio]")).toHaveAttribute("data-post-narration-rate", "1.25"); await expect(page.locator("video[data-post-video]")).toHaveAttribute("data-post-video-rate", "1"); + // Sampled once it plays steadily: a window that opens on the media still loading measures the load, not the rate. + await steadyPlay(page, "p-11"); const r = await sampleSpeed(page, "p-11", 600); expect(r.ar).toBe(1.25); expect(r.vr).toBe(1); diff --git a/umtool/e2e/projects.spec.ts b/umtool/e2e/projects.spec.ts @@ -110,7 +110,9 @@ test("the two siteOrigin defects are BLOCKING, and nothing else is", async ({ re // siteOrigin (19 QR codes reading `undefined/?v=…`) and one pointing at // localhost (codes that resolve to nothing on a phone). const origins = items.filter((d) => d.kind === "manifest-invalid" && d.target === "provenance.siteOrigin"); + // (basic-no-origin-fixture is the same cut in basic mode: it draws no QR, so its missing origin is not a defect.) expect(origins.map((d) => d.project).sort()).toEqual(["reports/localhost-fixture", "reports/no-origin-fixture"]); + expect(items.some((d) => d.project === "reports/basic-no-origin-fixture" && d.target === "provenance.siteOrigin")).toBe(false); expect(origins.every((d) => d.severity === "blocking")).toBe(true); expect(origins.find((d) => d.project === "reports/no-origin-fixture")?.why).toContain("undefined"); expect(origins.find((d) => d.project === "reports/localhost-fixture")?.why).toContain("localhost"); diff --git a/umtool/e2e/recurring.spec.ts b/umtool/e2e/recurring.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, type APIRequestContext, type Page } from "@playwright/test"; +import { test, expect, type APIRequestContext, type Locator, type Page } from "@playwright/test"; import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; import path from "node:path"; @@ -6,6 +6,15 @@ import { fileURLToPath } from "node:url"; import * as urls from "./urls"; import { WARM_TIMEOUT, warm } from "./warm"; +/** A schedule write's click and its answer (POST /api/schedules): each runs the editor stub's real report-schedule + * action in a tsx child (editor-stub.mjs, spawnSync -- about 3.4 s on an idle machine, measured), longer than an + * expect's 5 s under load. The page is read once the answer is in. */ +const clickAnswered = async (page: Page, button: Locator) => { + const answered = page.waitForResponse((r) => new URL(r.url()).pathname.startsWith("/api/schedules") && r.request().method() !== "GET", { timeout: 60_000 }); + await button.click(); + await answered; +}; + // --------------------------------------------------------------------------- // RECURRING REPORTS (plans/umtool-redesign.md, R5) over the editor stub, which // runs the REAL report-schedule action and store over the fixture's article @@ -99,7 +108,7 @@ test("Create → A recurring report: a series, planned (first tick, model, cap), await expect(form.getByRole("combobox", { name: "cadence" })).toHaveValue("weekly"); await expect(form.getByRole("combobox", { name: "day of the week" })).toHaveValue("1"); await shoot(page, "create-recurring"); - await form.getByRole("button", { name: "Plan the schedule" }).click(); + await clickAnswered(page, form.getByRole("button", { name: "Plan the schedule" })); const plan = form.getByRole("region", { name: "plan recurring report" }); await expect(plan).toContainText("Series r5-cohost · weekly · Mon 06:00 · first tick Mon 06:00"); await expect(plan.locator("[data-plan-first-tick]")).toHaveAttribute("data-plan-first-tick", /T\d\d:00:00\.000Z$/); @@ -123,7 +132,7 @@ test("the series page: Tick now makes an edition over whole days; again at once, // Monday 2026-10-19, noon UTC (the same date on the stub's clock, whatever its zone). await clock(request, { now: "2026-10-19T12:00:00.000Z" }); await page.goto(urls.seriesHref("r5-cohost")); - await page.getByRole("button", { name: "Tick now" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Tick now" })); await expect(page.locator("[data-schedule-said]")).toContainText(/Tick queued — job stub-tick-\d+/); const done = page.locator("[data-edition='1']"); await expect(done).toHaveAttribute("data-edition-status", "done"); @@ -136,7 +145,7 @@ test("the series page: Tick now makes an edition over whole days; again at once, await expect(page.locator("[data-series-next]")).toHaveText(/^(Nothing to cover yet — the next edition starts 2026-10-19|next, Mon 06:00: 2026-10-19 … \d{4}-\d{2}-\d{2})$/); // At once again: no day is read twice -- no edition, $0, said plainly, no card. - await page.getByRole("button", { name: "Tick now" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Tick now" })); const ticks = page.getByRole("table", { name: "ticks" }); await expect(ticks.locator("tbody tr")).toHaveCount(2); await expect(ticks.locator("tbody tr").first()).toContainText("Nothing to cover yet — the next edition starts 2026-10-19"); @@ -144,7 +153,7 @@ test("the series page: Tick now makes an edition over whole days; again at once, // A week on, nothing in the window matches: a quiet edition, dimmed, no link. await clock(request, { now: "2026-10-26T12:00:00.000Z", quiet: true }); - await page.getByRole("button", { name: "Tick now" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Tick now" })); const quiet = page.locator("[data-edition='2']"); await expect(quiet).toHaveAttribute("data-edition-status", "quiet"); await expect(quiet).toHaveClass(/opacity-55/); @@ -160,15 +169,15 @@ test("the series page: Tick now makes an edition over whole days; again at once, await expect(page.locator("[data-series-spent]")).toHaveAttribute("data-series-spent", "0.37"); await shoot(page, "series-page"); - await page.getByRole("button", { name: "Pause schedule" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Pause schedule" })); await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · paused/); - await page.getByRole("button", { name: "Resume schedule" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Resume schedule" })); await expect(page.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/); await page.getByRole("button", { name: "Edit cadence" }).click(); const edit = page.getByRole("form", { name: "edit cadence" }); await edit.getByRole("combobox", { name: "cadence" }).selectOption("daily"); await edit.locator('input[aria-label="at"]').fill("07:30"); - await edit.getByRole("button", { name: "Save cadence" }).click(); + await clickAnswered(page, edit.getByRole("button", { name: "Save cadence" })); await expect(page.locator("[data-schedule-chip]")).toHaveText(/daily · next \w{3} 07:30/); expect(series("r5-cohost").cadence).toEqual({ kind: "daily", at: "07:30" }); expect(stubAsked("report-schedule").map((r) => r.action)).toEqual(expect.arrayContaining(["tick-now", "pause", "resume", "update"])); @@ -191,7 +200,10 @@ test("keys: the head's controls in Tab order; Edit cadence opens on its first fi await expect(edit).toHaveCount(0); await expect(page.getByRole("button", { name: "Edit cadence" })).toBeFocused(); await page.keyboard.press("Tab"); + // Enter on Delete schedule asks for the plan (a schedule write's round-trip, clickAnswered's): read once answered. + const planned = page.waitForResponse((r) => new URL(r.url()).pathname.startsWith("/api/schedules") && r.request().method() !== "GET", { timeout: 60_000 }); await page.keyboard.press("Enter"); + await planned; const plan = page.getByRole("region", { name: "delete schedule r5-cohost" }); await expect(plan.getByRole("button", { name: "Confirm delete" })).toBeFocused(); await page.keyboard.press("Escape"); @@ -252,13 +264,13 @@ test("a living report: Create makes it; its article carries the cadence chip wit await form.getByRole("textbox", { name: "topic" }).fill("R5 living"); await form.getByRole("textbox", { name: "find a channel" }).fill("site"); await form.getByRole("button", { name: /Site Channel/ }).click(); - await form.getByRole("button", { name: "Plan the schedule" }).click(); + await clickAnswered(page, form.getByRole("button", { name: "Plan the schedule" })); await expect(form.getByRole("region", { name: "plan recurring report" })).toContainText("a new article, r5-living: its first tick is its first sweep"); - await form.getByRole("button", { name: "Start the schedule" }).click(); + await clickAnswered(page, form.getByRole("button", { name: "Start the schedule" })); await page.waitForURL(/\/articles\/r5-living$/, { timeout: 20_000 }); const head = page.locator("[data-piece-schedule='r5-living']"); await expect(head.locator("[data-schedule-chip]")).toHaveText(/weekly · next Mon 06:00/); - await head.getByRole("button", { name: "Tick now" }).click(); + await clickAnswered(page, head.getByRole("button", { name: "Tick now" })); await expect(head.locator("[data-schedule-said]")).toContainText(/Tick queued/); // The first tick is the article's first sweep: an iteration, ready for review. await expect(page.locator("[data-testid='piece-tab-iterations']")).toContainText("1"); @@ -268,12 +280,12 @@ test("a living report: Create makes it; its article carries the cadence chip wit await page.goto("/articles/r5-living"); await page.getByRole("button", { name: "More" }).click(); - await page.getByRole("button", { name: "Delete schedule" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" })); const plan = page.getByRole("region", { name: "delete schedule r5-living" }); await expect(plan).toContainText("the schedule of r5-living"); await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("the article r5-living and its iterations"); await expect(plan.getByRole("button", { name: "Confirm delete" })).toBeFocused(); - await plan.getByRole("button", { name: "Confirm delete" }).click(); + await clickAnswered(page, plan.getByRole("button", { name: "Confirm delete" })); await expect(page.locator("[data-piece-schedule]")).toHaveCount(0); expect(existsSync(path.join(ARTICLES, "r5-living", "schedule.json"))).toBe(false); expect(existsSync(path.join(ARTICLES, "r5-living", "iterations", "1", "iteration.json"))).toBe(true); @@ -281,7 +293,7 @@ test("a living report: Create makes it; its article carries the cadence chip wit test("delete a series: the plan says the editions stay as articles; Keep it writes nothing; Confirm delete goes to the recurring list", async ({ page }) => { await page.goto(urls.seriesHref("r5-cohost")); - await page.getByRole("button", { name: "Delete schedule" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" })); const plan = page.getByRole("region", { name: "delete schedule r5-cohost" }); await expect(plan).toContainText("the series r5-cohost"); await expect(plan.getByRole("list", { name: "what is kept" })).toContainText("1 edition article, as articles: r5-cohost-"); @@ -289,8 +301,8 @@ test("delete a series: the plan says the editions stay as articles; Keep it writ await expect(plan).toHaveCount(0); await expect(page.getByRole("button", { name: "Delete schedule" })).toBeFocused(); expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost", "series.json"))).toBe(true); - await page.getByRole("button", { name: "Delete schedule" }).click(); - await page.getByRole("region", { name: "delete schedule r5-cohost" }).getByRole("button", { name: "Confirm delete" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Delete schedule" })); + await clickAnswered(page, page.getByRole("region", { name: "delete schedule r5-cohost" }).getByRole("button", { name: "Confirm delete" })); await page.waitForURL(/\/work\?recurring=1$/, { timeout: 20_000 }); expect(existsSync(path.join(ARTICLES, ".series", "r5-cohost"))).toBe(false); // The edition is an article in its own right now. diff --git a/umtool/e2e/review-pass.spec.ts b/umtool/e2e/review-pass.spec.ts @@ -247,6 +247,23 @@ test("a version's review pass is read-only: watched and noted, never marked -- O expect(res.headers()["location"]).toBe(urls.versionReviewHref(P, "v1")); }); +test("a version's address that selects the + (present mode keeps the inspector mounted) shows no adder: read-only", async ({ page }) => { + await page.goto(urls.workspaceHref(P, { mode: "present", take: "v1", block: "+" })); + await expect(page.locator("[data-workspace]")).toHaveAttribute("data-ws-read-only", "", { timeout: 20_000 }); + await expect(page.locator("[data-ws-add-read-only]")).toHaveCount(1); + await expect(page.locator("[data-ws-add]")).toHaveCount(0); +}); + +test("the draft's review pass moves nothing: a block does not drag", async ({ page }) => { + await page.goto(urls.workspaceHref(P, { mode: "review" })); + await expect(pass(page)).toHaveAttribute("data-review-pass", "draft", { timeout: 20_000 }); + const before = readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); + await expect(page.locator('[data-ws-block="c01"]')).toHaveAttribute("draggable", "false"); + await page.locator('[data-ws-block="c01"]').dragTo(page.locator('[data-ws-block="c02"]')); + await page.waitForTimeout(600); + expect(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).toBe(before); +}); + test("on a phone (390 px) the pass is a sheet under the viewer, its answers in reach", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); await page.goto(urls.workspaceHref(P, { mode: "review" })); @@ -264,6 +281,10 @@ test("a mark is of what was reviewed: c02's edge moved since its Fix -- \"change await page.goto(urls.workspaceHref(P, { mode: "review" })); await expect(pass(page)).toHaveAttribute("data-review-current", "c02", { timeout: 20_000 }); await expect(page.locator("[data-review-changed]")).toHaveText("changed since reviewed"); + // What the stale Fix said is still shown, and the Fix form opens on it. + await expect(page.locator("[data-review-stale-fix]")).toHaveText("it needed work: trim the tail"); + await page.keyboard.press("f"); + await expect(page.locator("[data-review-fix-text]")).toHaveValue("trim the tail"); await expect(page.locator('[data-ws-block="c02"]')).toHaveAttribute("data-ws-block-review", ""); // The mark is still on disk, with what it was of: the answer is gone, not the record. expect(json("review-pass.json").marks.c02).toMatchObject({ mark: "fix", note: "trim the tail" }); diff --git a/umtool/e2e/thread-scenes.spec.ts b/umtool/e2e/thread-scenes.spec.ts @@ -74,6 +74,9 @@ test.beforeEach(() => { async function playAt(page: Page, id: string, at: number) { await page.goto(urls.playHref(PROJECT, { bare: true, clip: id, at })); + // The deck composed first (post-narration.spec waits the same): its frame mounts the player afresh, and a frame + // read across that is detached. + await expect(page.locator("[data-play-cut]")).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 }); const player = page.locator(`[data-post-play="${id}"]`); await expect(player).toBeVisible({ timeout: 15_000 }); const frame = page.frameLocator('[data-post-card-frame="read"]'); diff --git a/umtool/e2e/triage-first.spec.ts b/umtool/e2e/triage-first.spec.ts @@ -1,10 +1,19 @@ -import { test, expect, type Page } from "@playwright/test"; +import { test, expect, type Locator, type Page } from "@playwright/test"; import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; import { WARM_TIMEOUT, warm } from "./warm"; +/** A schedule write's click and its answer (POST /api/schedules): each runs the editor stub's real report-schedule + * action in a tsx child (editor-stub.mjs, spawnSync -- about 3.4 s on an idle machine, measured), longer than an + * expect's 5 s under load. The page is read once the answer is in. */ +const clickAnswered = async (page: Page, button: Locator) => { + const answered = page.waitForResponse((r) => new URL(r.url()).pathname.startsWith("/api/schedules") && r.request().method() !== "GET", { timeout: 60_000 }); + await button.click(); + await answered; +}; + // --------------------------------------------------------------------------- // TRIAGE FIRST (plans/umtool-redesign.md, R6) over the editor stub, which runs // the REAL report-schedule action, store and tick over the fixture's article @@ -96,7 +105,7 @@ test("Create → A recurring report → Watch: its terms, topics and threshold, await expect(form.getByRole("textbox", { name: "strong flags" })).toHaveValue("1"); await expect(form.getByRole("textbox", { name: "flags of any strength" })).toHaveValue("3"); await shoot(page, "create-watch"); - await form.getByRole("button", { name: "Plan the schedule" }).click(); + await clickAnswered(page, form.getByRole("button", { name: "Plan the schedule" })); const plan = form.getByRole("region", { name: "plan recurring report" }); await expect(plan).toContainText("Watch r6-watch · weekly · Mon 06:00"); await expect(plan.locator("[data-plan-triage]")).toContainText(/triage first on \S+ \(\$0\): escalates on 1 strong or 3 weak · at most \d+ escalations? a day; no article until one does/); @@ -160,7 +169,7 @@ test("R6.1: a partial triage is never quiet — the tick is partial (Your call: test("an escalating tick: the flagged ids swept as r6-watch-<date>; the tiers on the triage page (each flag and dismissal with its reason) and on the run page", async ({ page }) => { test.setTimeout(90_000); await page.goto(urls.seriesHref("r6-watch")); - await page.getByRole("button", { name: "Tick now" }).click(); + await clickAnswered(page, page.getByRole("button", { name: "Tick now" })); await expect(page.locator("[data-found]")).toHaveCount(1, { timeout: 30_000 }); const t = series("r6-watch").ticks.at(-1); expect(t).toMatchObject({ status: "done", iteration: 1, usd: 0.37, triage: { k: 1, flagged: 2, escalated: true, ids: ["sv1", "sv2"], usd: { tier1: 0, tier2: 0.37 } } }); diff --git a/umtool/e2e/usage.spec.ts b/umtool/e2e/usage.spec.ts @@ -114,6 +114,9 @@ test("confirming the drop writes it through", async ({ page, request }) => { test.skip(!hit, "no planned clip in the fixture"); await page.goto(`/sort?only=${encodeURIComponent(hit!.key)}`); + // The page knows the clip is in a build before it is judged: until its usage has arrived, a verdict writes with + // no question asked (the confirm the spec waits for never comes). The state the page shows, as the test above. + await expect(page.getByText(new RegExp(`used in ${hit!.builds.length} builds?`))).toBeVisible(); const before = await (await request.get("/api/clips?mode=sort&limit=50")).json(); await page.locator('[data-verdict="0"]').click(); diff --git a/umtool/e2e/workspace.spec.ts b/umtool/e2e/workspace.spec.ts @@ -200,7 +200,10 @@ test("a write since the undo ends the redo: Redo is refused and the write is kep const r = await request.put("/api/report/window", { data: { project: P, clip: "c01", title: "Titled since the undo" } }); expect(r.ok(), await r.text()).toBe(true); const titled = manifestText(); + // The Redo's answer first (the page says nothing while it is out -- under load, longer than an expect's 5 s). + const answered = page.waitForResponse((r) => r.url().includes("/api/report/timeline") && r.request().method() === "POST", { timeout: 60_000 }); await page.locator("[data-ws-redo]").click(); + await answered; // Refused: on the page's token (the draft moved since it was read), never retried on a fresh one... await expect(page.locator("[data-ws-undo-said]")).toHaveAttribute("data-ws-undo-said", "error"); await expect(page.locator("[data-ws-undo-said]")).toContainText("changed since"); diff --git a/umtool/e2e/write-guard.spec.ts b/umtool/e2e/write-guard.spec.ts @@ -43,6 +43,10 @@ test("another site's write is refused by the proxy; a terminal's, a read and the r = await request.post("/api/projects/new", { data: JSON.stringify({ kind: "", pad: "x".repeat(12 * 1024 * 1024) }), headers: plain }); expect(r.status()).toBe(400); expect(await said(r)).toContain("unknown kind"); + // Over the cap: answered 413 with its sentence (writeGuard.mjs bodyRefusal), never handed to the route cut. + r = await request.post("/api/projects/new", { data: JSON.stringify({ kind: "", pad: "x".repeat(20 * 1024 * 1024) }), headers: plain }); + expect(r.status()).toBe(413); + expect(await said(r)).toContain("over the 16777216 (16 MB)"); // A read from anywhere is not the proxy's business. r = await request.get("/api/projects/new?from=", { headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site" } }); expect(r.status()).not.toBe(403); diff --git a/umtool/lib/analyse.mjs b/umtool/lib/analyse.mjs @@ -21,6 +21,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { MIX_CACHE, labelFor } from "./paths.mjs"; import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Analysis sample rate. 16 kHz resolves the whole band the ratio looks at. */ const ANALYSIS_SR = 16000; @@ -153,7 +154,7 @@ export async function analyseFile(abs, { st = undefined, cacheDir = MIX_CACHE } }; await mkdir(cacheDir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out)); await rename(tmp, file).catch(() => {}); return out; diff --git a/umtool/lib/annotations/store.mjs b/umtool/lib/annotations/store.mjs @@ -23,6 +23,7 @@ import { open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { NoteError, applyOp, emptyDoc, parseNotesDoc } from "./shape.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { NoteError }; export const LOCK_STALE_MS = 30_000; @@ -149,7 +150,7 @@ export async function writeOp(file, init, op, { by, token = null }) { }); return { doc: null, token: "absent", note }; } - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(/* turbopackIgnore: true */ tmp, file); return { doc, token: await notesToken(file), note }; diff --git a/umtool/lib/atomicFile-sweep.test.mjs b/umtool/lib/atomicFile-sweep.test.mjs @@ -0,0 +1,59 @@ +// THE TEMP-NAME SWEEP (umtool redesign E5 A2): a file written beside its target and renamed over it takes its temp +// name from ONE helper -- common/lib/atomicFile.mjs `tmpPathFor` (or its writers), and jsonFile-server.ts, its +// TypeScript twin. A name built by hand from the pid (`<file>.<pid>.tmp`) is one name for every write a process +// makes to that file, so two writes in flight at once share it and one rename takes the other's half-written file; +// a bare `<file>.tmp` is one name for every process. This fails on either, anywhere in umtool's or common's source. +// +// Run with: node --test umtool/lib/atomicFile-sweep.test.mjs +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; + +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const ROOTS = ["umtool", "common/lib"]; +const SKIP_DIRS = new Set(["node_modules", ".next", "e2e", "out", "test-results", ".e2e-song"]); +/** The helpers themselves: the only places a temp name is made. */ +const HELPERS = new Set(["common/lib/atomicFile.mjs", "common/lib/jsonFile-server.ts"]); +const SOURCE = /\.(mjs|js|ts|tsx)$/; +const TEST = /\.test\.(mjs|js|ts|tsx)$/; + +/** A temp name made by hand: the pid on the same line as `.tmp`, or a template literal ending `.tmp`. */ +const BY_HAND = [/process\.pid[^\n]*\.tmp/, /\.tmp[^\n]*process\.pid/, /\}\.tmp`/]; + +function* sources(dir) { + for (const d of readdirSync(dir, { withFileTypes: true })) { + if (d.isDirectory()) { + if (!SKIP_DIRS.has(d.name) && !d.name.startsWith(".")) yield* sources(path.join(dir, d.name)); + } else if (d.isFile() && SOURCE.test(d.name) && !TEST.test(d.name)) yield path.join(dir, d.name); + } +} + +test("no temp name is made by hand: every `<file>.<pid>.tmp` and `<file>.tmp` goes through atomicFile.mjs", () => { + const found = []; + let seen = 0; + for (const root of ROOTS) { + for (const file of sources(path.join(REPO, root))) { + const rel = path.relative(REPO, file); + if (HELPERS.has(rel)) continue; + seen += 1; + readFileSync(file, "utf8") + .split("\n") + .forEach((line, i) => { + if (BY_HAND.some((re) => re.test(line))) found.push(`${rel}:${i + 1}: ${line.trim()}`); + }); + } + } + assert.ok(seen > 500, `the sweep read ${seen} source files: a root moved?`); + assert.deepEqual(found, [], `a temp name made by hand -- use tmpPathFor / writeFileAtomic (common/lib/atomicFile.mjs):\n${found.join("\n")}`); +}); + +test("tmpPathFor: a name of its own per call, beside the file, keeping an extension", () => { + const a = tmpPathFor("/d/x.json"); + const b = tmpPathFor("/d/x.json"); + assert.notEqual(a, b); + assert.match(a, new RegExp(`^/d/x\\.json\\.tmp-${process.pid}-\\d+-[0-9a-f]{8}$`)); + assert.match(tmpPathFor("/d/.c01", { ext: ".mp4" }), /^\/d\/\.c01\.tmp-\d+-\d+-[0-9a-f]{8}\.mp4$/); +}); diff --git a/umtool/lib/bench-marks.mjs b/umtool/lib/bench-marks.mjs @@ -20,6 +20,7 @@ // Plain ESM: the unit test reads it the way the app does. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const BENCH_MARKS_FORMAT = "archilyzer-bench-marks"; export const BENCH_MARKS_VERSION = 1; @@ -110,7 +111,7 @@ export function setBenchMark(root, run, m) { doc.updatedAt = at; const file = benchMarksFile(root, run); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -583,7 +583,7 @@ export const GROUPS = [ ["`take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]`", "the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so"], ["`take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \\| --before <entry>] [--as <id>] [--dry-run] [--json]`", - "**items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\\|updated\\|unchanged\\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage**"], + "**items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\\|updated\\|unchanged\\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage**"], ["`take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \\| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]`", "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"], ["`take status <project> [--id <take>] [--json] [--log] [--tail N]`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -177,8 +177,8 @@ export const VERBS = Object.freeze([ takeOpt(), ], B(["clip"], { clip: "{id}" })), form("walk", "project", "the clip bench's walk: clips in walk order, verdicts, fetched", [project(), takeOpt({ help: "walk a take (a draft too)" }), bool("--all", "every fetched clip")]), - // The workspace's review pass (umtool redesign L7b, lib/report/reviewPass.mjs): a clip's Keep / Fix is its walk - // verdict (`window --verdict`); a post's or a card's lives in review-pass.json. + // The workspace's review pass (umtool redesign L7b, lib/report/reviewPass.mjs): a clip's Keep is its walk verdict + // (`window --verdict`); any block's Fix, and a post's or a card's Keep, live in review-pass.json. form("review-pass ls", "project", "the review pass: each block's answer, and where it resumes", [project()], { shape: "review-pass <project> ls" }), form("review-pass mark", "project", "a block's review-pass mark: keep (a post, a card), fix (needs work, saying what; any block) or clear", [ project(), arg("block", { help: "the block's id: a clip, a post item, a card" }), pick("mark", ["keep", "fix", "clear"], { required: true }), opt("--note", { type: "text", help: "a Fix: what needs work" }), diff --git a/umtool/lib/digestContextReview.mjs b/umtool/lib/digestContextReview.mjs @@ -29,6 +29,7 @@ import { createHash } from "node:crypto"; import { link, lstat, readFile, readdir, realpath, rename, unlink, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SUGGESTED = "digest-context.suggested.md"; export const ACTIVE = "digest-context.md"; @@ -235,7 +236,7 @@ export async function decideDigestContextNote({ channelsDir, slug, decision, sha await unlink(/* turbopackIgnore: true */ sugPath); } else { const rec = { by: "operator", at: now().toISOString(), sha256: want }; - const tmp = path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ at.dir, `.${REFUSED}`)); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(rec, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, /* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ at.dir, REFUSED)); } diff --git a/umtool/lib/inbox/refresh.ts b/umtool/lib/inbox/refresh.ts @@ -14,6 +14,7 @@ import { isMuted, type MutesRead } from "@/lib/mutes"; import { REPORTS_ROOT } from "@/lib/paths"; import type { Piece, PieceGraph } from "@/lib/pieces"; import { localDir, openSource } from "@/lib/research/sources"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // A REFRESH, SUGGESTED (plans/umtool-redesign.md, R4) -- two Inbox kinds: @@ -98,7 +99,7 @@ function saveCheck(entry: CheckEntry): Promise<void> { f.articles[entry.article] = entry; const file = CHECK_FILE(); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(f, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); }); diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs @@ -40,6 +40,7 @@ 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"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const USAGE_INDEX_FORMAT = "umtool-usage-index"; export const USAGE_INDEX_VERSION = 1; @@ -224,7 +225,7 @@ export async function readUsageIndex(file) { async function writeUsageIndex(file, index) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(index) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/lifecycle.mjs b/umtool/lib/lifecycle.mjs @@ -23,6 +23,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { isPieceId } from "./pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LIFECYCLE_STATES = ["active", "parked", "done"]; export const LIFECYCLE_FORMAT = "umtool-lifecycle"; @@ -110,7 +111,7 @@ async function write(reportsRoot, id, state, by, now) { pieces: Object.fromEntries(Object.entries({ ...read.pieces, [id]: entry }).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/loudness.ts b/umtool/lib/loudness.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { CACHE_DIR, labelFor } from "./paths"; import type { Loudness } from "./loudness-types"; import { pathCache } from "./pathCache.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export * from "./loudness-types"; @@ -163,7 +164,7 @@ export async function measureLoudness(abs: string): Promise<Loudness> { const c = await cacheFileFor(abs); if (c) { await mkdir(LOUD_CACHE, { recursive: true }); - const tmp = `${c.file}.tmp-${process.pid}`; + const tmp = tmpPathFor(c.file); await writeFile(tmp, JSON.stringify(out)); await rename(tmp, c.file).catch(() => {}); memo.set(abs, c.key, out); diff --git a/umtool/lib/mutes.mjs b/umtool/lib/mutes.mjs @@ -18,6 +18,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { isPieceId } from "./pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MUTES_FORMAT = "umtool-mutes"; export const MUTES_VERSION = 1; @@ -122,7 +123,7 @@ async function write(reportsRoot, piece, kind, muted, now) { mutes: sorted(Object.fromEntries(Object.entries(mutes).map(([p, kinds]) => [p, sorted(kinds)]))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/phrase-finder/cli.mjs b/umtool/lib/phrase-finder/cli.mjs @@ -16,6 +16,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { runPhraseScan } from "./scan.mjs"; import { summarisePhrase } from "./summary.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; function parse(args) { const o = { phrases: [], channels: [], prefer: null, exclude: null, mode: "auto", samples: 10, cache: true, json: false, full: false, spec: null, out: null, progress: false }; @@ -70,7 +71,7 @@ export async function phrasesCommand(args) { const answer = await runPhraseScan(spec, { ...(o.cache ? {} : { cacheDir: null }), onProgress }); if (o.out) { await mkdir(path.dirname(o.out), { recursive: true }); - const tmp = `${o.out}.${process.pid}.tmp`; + const tmp = tmpPathFor(o.out); await writeFile(tmp, JSON.stringify(answer), "utf8"); await rename(tmp, o.out); if (o.progress) console.log(JSON.stringify({ done: true, out: o.out, seconds: answer.seconds })); diff --git a/umtool/lib/phrase-finder/server.ts b/umtool/lib/phrase-finder/server.ts @@ -8,6 +8,7 @@ import { CHANNEL_RE, checkSpec } from "./scan.mjs"; import { summarisePhrase } from "./summary.mjs"; import { MONTAGE_KIND } from "../projects/create.mjs"; import type { PhraseChannel, PhraseFinderState, PhraseScanRowView, PhraseScanSpec, PhraseScanView, PhraseSuggestion } from "./types"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // --------------------------------------------------------------------------- // THE PHRASE FINDER's server half (release 34; the page is /tools/phrases). @@ -62,7 +63,7 @@ const runningScan = () => [...reg.jobs.values()].find((j) => j.state === "runnin async function writeAtomic(file: string, text: string) { await mkdir(path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, text, "utf8"); await rename(/* turbopackIgnore: true */ tmp, file); } diff --git a/umtool/lib/poster.ts b/umtool/lib/poster.ts @@ -6,6 +6,7 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { CACHE_DIR } from "./paths"; import { probeCached } from "./browse"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -60,7 +61,7 @@ export async function posterFrame(abs: string, width = DEFAULT_WIDTH): Promise<P const at = info.duration > 0 ? +(info.duration * POSTER_AT).toFixed(3) : 0; await mkdir(POSTER_CACHE, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}.jpg`; + const tmp = tmpPathFor(file, { ext: ".jpg" }); try { // -ss BEFORE -i is the fast seek: it jumps in the container rather than // decoding up to the mark, which on a 66 MB render is the difference diff --git a/umtool/lib/queue/store.mjs b/umtool/lib/queue/store.mjs @@ -56,6 +56,7 @@ import { mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } f import os from "node:os"; import path from "node:path"; import { firstErrorLine, procStartTime, processAlive, queueDirFor } from "../report/renderRecord.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const STEP_STATES = Object.freeze(["queued", "running", "done", "failed", "blocked", "cancelled"]); export const TERMINAL = new Set(["done", "failed", "cancelled"]); @@ -82,10 +83,8 @@ export const stepFile = (dir, qid) => path.join(stepsDir(dir), `${qid}.json`); export const logFileOf = (dir, qid, attempt = null) => path.join(dir, "logs", attempt ? `${qid}.${attempt}.log` : `${qid}.log`); const leaseFile = (dir) => path.join(dir, "runner.json"); -let tmpSeq = 0; async function writeJson(file, doc) { - tmpSeq += 1; - const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/basic-origin.test.mjs b/umtool/lib/report/basic-origin.test.mjs @@ -0,0 +1,34 @@ +// THE INBOX'S BLOCKING siteOrigin CARD and a basic-mode cut (operator ruling, 11 Nov, E5 A6): a cut that draws a QR +// built from a missing origin is blocked; the same cut in basic mode -- the footage alone, no QR (a quick clip on a +// channel no public site carries) -- is not. +// +// Run with: node --test umtool/lib/report/basic-origin.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { deadOriginQrsOf, originDeadFor } from "../projects/report.mjs"; + +const cut = (render) => ({ + slug: "q", + provenance: { siteOrigin: "", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, ...render }, + timeline: [{ type: "clip", id: "c01", channel: "chan", video: "v1", start: 41, end: 45, cite: 41 }], +}); + +test("a missing origin: blocking for a cut whose corner QR it builds, never for a basic-mode cut (no QR drawn)", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "basic-origin-")); + try { + const drawn = cut({}); + const qrs = await deadOriginQrsOf(dir, drawn); + assert.deepEqual(qrs.map((q) => q.where), ["timeline c01 (its corner QR)"]); + assert.equal(originDeadFor(drawn, qrs), true); + const basic = cut({ mode: "basic" }); + const none = await deadOriginQrsOf(dir, basic); + assert.deepEqual(none, []); + assert.equal(originDeadFor(basic, none), false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs @@ -56,6 +56,7 @@ import { clipsOf, readManifest } from "../projects/report.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { isTakeId } from "./takes.mjs"; import { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** An excerpt cut's resident set (234 MB, measured: a 2-minute 720p excerpt of a 1080p stream) plus the runner. */ export const PREP_ESTIMATE_MB = 400; @@ -233,7 +234,7 @@ export async function readPrepStatus(dir, take = null) { /** @param {string} dir @param {PrepStatus} st @param {string | null} [take] */ async function writePrepStatus(dir, st, take = null) { await mkdir(prepStateDirOf(dir, take), { recursive: true }); - const tmp = `${statusFile(dir, take)}.tmp-${process.pid}`; + const tmp = tmpPathFor(statusFile(dir, take)); await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`); await rename(tmp, statusFile(dir, take)); } diff --git a/umtool/lib/report/candidates.mjs b/umtool/lib/report/candidates.mjs @@ -40,6 +40,7 @@ import { readManifest } from "../projects/report.mjs"; import { groupModel } from "./claimGroups.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { sentenceBoundaries } from "./sentenceEdges.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CANDIDATES_FILE = "candidates.json"; export const CANDIDATES_FORMAT = "umtool-candidates"; @@ -361,7 +362,7 @@ function writeCandidates(dir, mutate) { candidates: doc.candidates.map(({ key: _k, ...r }) => ({ id: r.id, key: candidateKey(r), ...r })), }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/report/castAudition.mjs b/umtool/lib/report/castAudition.mjs @@ -24,6 +24,7 @@ import { cardText } from "umtool-report-to-video/post-item"; import { handleKey, voiceRefOf, voiceSpecOf } from "umtool-report-to-video/post-say"; import { ENGINE_WEIGHT, speakerFor } from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -187,7 +188,7 @@ export async function auditionPlan(dir, candidates, text, { relBase = AUDITION_D /** A sound brought to AUDITION_LUFS, 48 kHz mono (one loudnorm pass), `from` -> `to`; `from` removed when asked. */ export async function levelTo(from, to, { start = null, seconds = null } = {}) { - const tmp = `${to}.tmp-${process.pid}.wav`; + const tmp = tmpPathFor(to, { ext: ".wav" }); await execFileP(FFMPEG(), [ "-nostdin", "-v", "error", "-y", ...(start !== null ? ["-ss", String(start)] : []), "-i", from, ...(seconds !== null ? ["-t", String(seconds)] : []), "-vn", "-af", `loudnorm=I=${AUDITION_LUFS}:TP=-2:LRA=11`, "-ar", "48000", "-ac", "1", "-c:a", "pcm_s16le", tmp, @@ -354,7 +355,7 @@ export async function scoreAuditions(project, character, plan, { engineOpts = {} } const file = path.join(project.dir, ...AUDITION_SCORES.split("/")); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify({ version: 1, rows: scores.rows }, null, 1)}\n`); await rename(tmp, file); return { speaker: speaker.name, rows, reference, pieces: doc.speakers?.[0]?.kept ?? null }; diff --git a/umtool/lib/report/castStore.mjs b/umtool/lib/report/castStore.mjs @@ -17,6 +17,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { CAST_FORMAT, CAST_VERSION, emptyCast, validateCast } from "umtool-report-to-video/cast"; import { REPORTS_ROOT } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CAST_UNDO_KEEP = 50; @@ -96,7 +97,7 @@ export async function readCastUndo(file) { async function writeAtomic(file, text) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -55,6 +55,7 @@ import { ChromeRefused, addDeckChrome } from "./manifest.mjs"; import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"); const SCREENSHOT_MISSING = /no captured screenshot/; @@ -429,7 +430,7 @@ STEPS["draft-social"] = async (ctx) => { }; async function writeJson(file, value) { - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/clipSuggest.mjs b/umtool/lib/report/clipSuggest.mjs @@ -17,6 +17,7 @@ import { readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { readSuggestions, suggestionsState } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SUGGEST_TASK = "clips-suggest"; export const SUGGEST_JOB_FILE = ".clip-suggest-job.json"; @@ -82,7 +83,7 @@ export async function readSuggestJob(dir) { /** Remember the job a Suggest or an Ask started (tmp + rename). */ export async function writeSuggestJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/clipsLive.mjs b/umtool/lib/report/clipsLive.mjs @@ -51,6 +51,7 @@ import { SHADOW_CHANNELS } from "umtool-report-to-video/sources"; import { ClipsNewError } from "./clipsNew.mjs"; import { WORDS_FILE, proposeProject } from "./reactions.mjs"; import { LIVE_PROJECT_FILE, readLiveProject } from "./liveProject.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json"; export { LIVE_PROJECT_FILE, readLiveProject }; @@ -65,7 +66,7 @@ const readJson = (f) => readFile(f, "utf8").then(JSON.parse, () => null); async function writeWhole(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/cutPoints.mjs b/umtool/lib/report/cutPoints.mjs @@ -41,6 +41,7 @@ import { renderCut, snapKnobs } from "umtool-report-to-video/snap"; import { transitionStyleOf } from "umtool-report-to-video/transition"; import { CACHE_DIR } from "../paths.mjs"; import { channelsDirFor, cuesForSource, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bump when what is cached changes shape. */ const CACHE_VERSION = 1; @@ -77,7 +78,7 @@ async function cached(kind, key, make) { const value = await make(); try { await mkdir(/* turbopackIgnore: true */ cacheDir(), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify({ key, value })); await rename(/* turbopackIgnore: true */ tmp, file); } catch { diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -40,6 +40,7 @@ import path from "node:path"; import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps"; import { agentToken } from "../annotations/agentAuth.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const FETCH_RUNS_FILE = "fetch-runs.json"; export const MANIFEST_FILE = "video.manifest.json"; @@ -382,7 +383,7 @@ export async function readFetchRuns(projectDir) { async function writeRuns(projectDir, doc) { const file = path.join(projectDir, FETCH_RUNS_FILE); await mkdir(projectDir, { recursive: true }); - const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 1) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/groupProposals.mjs b/umtool/lib/report/groupProposals.mjs @@ -20,6 +20,7 @@ import { checkGroupProposals, markGroupProposals, readGroupProposals, writeGroup import { readManifest } from "../projects/report.mjs"; import { StaleToken, manifestToken, setGroup } from "./manifest.mjs"; import { assistJobView } from "./videoAssist.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const GROUPS_TASK = "propose-groups"; export const GROUPS_JOB_FILE = ".propose-groups-job.json"; @@ -60,7 +61,7 @@ export async function readGroupsJob(dir) { export async function writeGroupsJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/iterations.mjs b/umtool/lib/report/iterations.mjs @@ -27,6 +27,7 @@ import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { link, lstat, mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST_NAME = "video.manifest.json"; // Below this a segment is not worth a hash (a voice always is: it is small @@ -42,7 +43,7 @@ async function readJson(file) { // Replace `file` whole: a temp beside it, then a rename. async function writeJsonAtomic(file, value) { - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -31,6 +31,7 @@ import path from "node:path"; 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"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LINKS_FILE = "links.json"; export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); @@ -298,7 +299,7 @@ export async function runLinkCheck(dir, manifest, opts = {}) { const doc = await checkLinks(linksOf(manifest), { siteIdOf: await projectSiteIdOf(dir, manifest), ...opts }); const file = linksFile(dir); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); return doc; diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -100,6 +100,7 @@ import { import { DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // Its own write queue, not lib/state.ts's. // @@ -191,7 +192,7 @@ async function writeManifestAtomic(dir, manifest) { if (before) clearEditedDrafts(before, manifest); else pruneDrafted(manifest); await backupOnce(file); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, serialise(manifest), "utf8"); await rename(tmp, file); return manifestToken(dir); @@ -2127,6 +2128,8 @@ export function setUndoEveryMs(ms) { } /** The undo points kept: the newest this many `auto-before-*` snapshots (older ones are pruned). */ export const AUTO_SNAPSHOT_KEEP = 200; +/** The undone undo points kept (`undone-*`, what each Undo took back and a Redo can put back): the newest this many. */ +export const UNDONE_KEEP = 50; export const undoEveryMs = () => { const n = /** @type {any} */ (globalThis)[UNDO_EVERY_KEY]; return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : AUTO_SNAPSHOT_EVERY_MS; @@ -2156,21 +2159,23 @@ export async function autoSnapshot(dir, op, { now = Date.now(), every = undoEver * revisions/), removing the older ones and their draft-pointer sidecars * (versions.mjs openVersion) -- and, by the same rule, the newest `keep` of * `undo-saved` (with its `.redo.json` pairing and `.draft.json`) and of - * `redone-*`. Named snapshots and `undone-*` are never touched. Returns the - * names removed. + * `redone-*`; and the newest UNDONE_KEEP `undone-*` (a Redo further back than + * that is gone). Named snapshots are never touched. Returns the names removed. */ export async function pruneAutoSnapshots(dir, keep = AUTO_SNAPSHOT_KEEP) { const all = (await listSnapshots(dir)).filter((x) => !x.legacy); // Each kind the undo stack makes keeps its newest `keep`: the undo points, what an undo replaced (`undo-saved`, - // its redo pairing and draft pointer beside it), and what a redo used up (`redone-*`). + // its redo pairing and draft pointer beside it), and what a redo used up (`redone-*`); what an undo took back + // (`undone-*`, with its draft pointer) its newest UNDONE_KEEP. const kinds = [ - (x) => x.label?.startsWith(AUTO_SNAPSHOT_PREFIX), - (x) => x.label === "undo-saved", - (x) => x.label?.startsWith("redone-"), + [(x) => x.label?.startsWith(AUTO_SNAPSHOT_PREFIX), keep], + [(x) => x.label === "undo-saved", keep], + [(x) => x.label?.startsWith("redone-"), keep], + [(x) => x.label?.startsWith("undone-"), Math.min(keep, UNDONE_KEEP)], ]; const gone = []; - for (const kind of kinds) { - for (const x of all.filter(kind).slice(Math.max(0, keep))) { + for (const [kind, n] of kinds) { + for (const x of all.filter(kind).slice(Math.max(0, n))) { await rm(path.join(dir, x.rel), { force: true }); await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".draft.json")), { force: true }); await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".redo.json")), { force: true }); @@ -2559,7 +2564,7 @@ export async function readRemoved(dir) { async function recordRemoved(dir, row) { const rows = [...(await readRemoved(dir)), row]; const file = path.join(dir, REMOVED_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ removed: rows }, null, 2) + "\n"); await rename(tmp, file); } @@ -2597,9 +2602,12 @@ export async function removeWrongSpeaker(dir, id, { token = null, at = null, cor export async function rejectClip(dir, id, reason, { token = null, at = null, note = null, now = () => new Date() } = {}) { const r = rejectReasonOf(String(reason ?? "").trim()); const verdictPatch = rejectPatch(String(reason ?? "").trim(), note); + let cutChannel = null; const res = await structural(dir, r?.id === "wrong-speaker" ? "wrong-speaker" : "reject", token, (m) => { const entry = m.timeline[entryIndex(m.timeline, id, at)]; if (entry.type !== "clip") throw new Error(`${id} is a ${entry.type ?? "non-clip"} entry, not a clip`); + // Most clips name no channel of their own: the cut's (projects/report.mjs channelFor), on record with it. + cutChannel = typeof m.provenance?.channelSlug === "string" ? m.provenance.channelSlug : null; patchClipEntry(m, id, verdictPatch); return removeIn(m, id, at); }); @@ -2610,7 +2618,7 @@ export async function rejectClip(dir, id, reason, { token = null, at = null, not reason: r?.id ?? String(reason), correction: String(e.correction ?? "").trim() || null, ...(rejectNote ? { note: rejectNote } : {}), - channel: typeof e.channel === "string" ? e.channel : null, + channel: typeof e.channel === "string" ? e.channel : cutChannel, video: typeof e.video === "string" ? e.video : null, start: e.start ?? null, end: e.end ?? null, @@ -2644,6 +2652,23 @@ export function removedOutOfCut(rows, manifest) { } /** + * Where a removed clip came from, as the Removed list and `timeline <p> removed` say it: `<channel>/<video> @ s–e` + * -- its record's channel, else the cut's (`provenance.channelSlug`: a record from before removals carried it); + * with no channel to name, the video alone; with no video, "" (the clip's id says it). Never `?/`. + * + * @param {Record<string, any>} r a removed.json row + * @param {Record<string, any> | null} manifest + * @param {{ dash?: string, at?: string }} [o] the CLI's compact form: `{ dash: "-", at: "@" }` + */ +export function removedSourceOf(r, manifest, { dash = "–", at = " @ " } = {}) { + const channel = typeof r?.channel === "string" && r.channel ? r.channel : typeof manifest?.provenance?.channelSlug === "string" && manifest.provenance.channelSlug ? manifest.provenance.channelSlug : null; + const video = typeof r?.video === "string" && r.video ? r.video : null; + if (!video) return ""; + const span = Number.isFinite(r?.start) && Number.isFinite(r?.end) ? `${at}${r.start}${dash}${r.end}` : ""; + return `${channel ? `${channel}/` : ""}${video}${span}`; +} + +/** * 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. * @@ -4890,7 +4915,7 @@ export async function undoStructural(dir, { token = null } = {}) { // within the same second as another snapshot: the state is already kept } const file = manifestFile(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); const undone = target.rel.replace(`-${target.label}.manifest.json`, `-undone-${op}.manifest.json`); @@ -4908,7 +4933,7 @@ export async function undoStructural(dir, { token = null } = {}) { await writeFile(path.join(dir, saved.replace(/\.manifest\.json$/, ".draft.json")), JSON.stringify(now, null, 2) + "\n", "utf8").catch(() => {}); } if (side && typeof side === "object" && typeof side.from === "string" && side.from) { - const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmpD = tmpPathFor(draftFile); await writeFile(tmpD, JSON.stringify(side, null, 2) + "\n", "utf8"); await rename(tmpD, draftFile); draft = side; @@ -4976,6 +5001,10 @@ export async function redoStructural(dir, { token = null } = {}) { } const undone = pair && typeof pair.undone === "string" ? all.find((s) => s.rel === pair.undone && s.label?.startsWith("undone-")) : null; if (!head || !undone) throw new Error("nothing to redo: no undo since the last edit"); + // An undo point newer than that undo is an edit since it, whatever the draft hashes to now: a move and its + // move back leave the bytes as the undo left them, and the redo still ends there (E5 A3). + const headAt = all.indexOf(head); + if (all.slice(0, headAt).some((s) => s.label?.startsWith(AUTO_SNAPSHOT_PREFIX))) throw new Error("nothing to redo: an edit since the undo"); // The draft exactly as that undo left it, or no redo: whatever wrote it since -- a write that took no undo point // (a title, a terminal edit under the throttle, a saved version), the CLI, another process -- would be lost. if (typeof pair.after !== "string" || pair.after !== (await draftStateHash(dir))) throw new Error("the draft changed since the undo — nothing to redo"); @@ -4983,7 +5012,7 @@ export async function redoStructural(dir, { token = null } = {}) { const text = await readFile(path.join(dir, head.rel), "utf8"); JSON.parse(text); const file = manifestFile(dir); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); const side = (rel) => path.join(dir, rel.replace(/\.manifest\.json$/, ".draft.json")); @@ -4999,7 +5028,7 @@ export async function redoStructural(dir, { token = null } = {}) { if (pointer !== undefined) { const draftFile = path.join(dir, "takes", "draft.json"); if (pointer && typeof pointer === "object" && typeof pointer.from === "string" && pointer.from) { - const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmpD = tmpPathFor(draftFile); await writeFile(tmpD, JSON.stringify(pointer, null, 2) + "\n", "utf8"); await rename(tmpD, draftFile); draft = pointer; diff --git a/umtool/lib/report/montageRulings.mjs b/umtool/lib/report/montageRulings.mjs @@ -35,6 +35,7 @@ import { parseMontageRulings, rulingsLines, } from "umtool-report-to-video/montage-rulings"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const EDITS_FILE = "edits.json"; export const INSTANCES_FILE = "instances.json"; @@ -97,7 +98,7 @@ async function writeDoc(file, doc) { await mkdir(path.dirname(file), { recursive: true }); // Keys in order, so the file diffs as the deck walks. const rulings = Object.fromEntries(Object.entries(doc.rulings).sort(([a], [b]) => a.localeCompare(b))); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ version: RULINGS_VERSION, rulings }, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs @@ -23,6 +23,7 @@ // Plain ESM: the CLI runs it under bare node. import { readdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; @@ -125,7 +126,7 @@ export async function syncPatchMarkers(dir, before, after) { const notes = reanchorPatch(patch, anchors); if (!notes.length) continue; try { - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, file); out.push({ file: name, notes }); @@ -201,7 +202,7 @@ export async function fixStalePatchMarkers(dir, manifest, file) { } else left.push({ index, label, after }); }); if (notes.length) { - const tmp = `${full}.tmp-${process.pid}`; + const tmp = tmpPathFor(full); await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); await rename(tmp, full); } @@ -257,7 +258,7 @@ export async function syncSectionMarkers(dir, before, after) { const deck = doc.render.chrome.deck; if (Array.isArray(after) && after.length) deck.markers = JSON.parse(now); else delete deck.markers; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, indentOf(text)) + "\n", "utf8"); await rename(tmp, file); synced.push(name); diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -22,6 +22,7 @@ import { } from "umtool-report-to-video/post-say"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export class SayError extends Error { constructor(message) { @@ -76,7 +77,7 @@ async function readJson(file) { async function writeJsonAtomic(file, value) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 1)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/quoteCheck.mjs b/umtool/lib/report/quoteCheck.mjs @@ -31,6 +31,7 @@ import { resolveLocalSource } from "umtool-report-to-video/sources"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const QUOTE_CHECK_FILE = "quote-check.json"; /** Seconds either side of the cut that are transcribed: the 6 Nov offsets reached 13.6 s. */ @@ -78,7 +79,7 @@ export async function readQuoteCheck(dir) { async function writeQuoteCheck(dir, doc) { const file = path.join(dir, QUOTE_CHECK_FILE); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc, null, 1)}\n`); await rename(tmp, file); return file; diff --git a/umtool/lib/report/reactions.mjs b/umtool/lib/report/reactions.mjs @@ -58,6 +58,7 @@ import { SITES_DIR } from "../paths.mjs"; import { replaceManifest, manifestToken, StaleToken } from "./manifest.mjs"; import { REPO_ROOT } from "../paths.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { REACTIONS_FILE }; export const WORDS_FILE = "words.json"; @@ -149,7 +150,7 @@ const scanFile = (projectDir, channel, video, what) => path.join(/* turbopackIgn async function writeWhole(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(doc)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/recordSession.mjs b/umtool/lib/report/recordSession.mjs @@ -16,6 +16,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { postIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; import { RECORD_LABEL_RE, keepRecording } from "./postRecord.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** A part is at most this large (a minute of opus is well under 1 MB). */ export const SESSION_PART_MAX = 100 * 1024 * 1024; @@ -65,7 +66,7 @@ export async function savePart(projectDir, entry, { n, count, text, para, bytes, // A different split of the script (it was edited): the parts kept so far no longer line up. if (doc.count !== null && doc.count !== count) doc.parts = {}; const name = `p${String(n).padStart(2, "0")}.${extOf(type)}`; - const tmp = path.join(dir, `.${name}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${name}`)); await writeFile(tmp, bytes); const old = doc.parts[String(n)]; await rename(tmp, path.join(dir, name)); diff --git a/umtool/lib/report/reelHistory.mjs b/umtool/lib/report/reelHistory.mjs @@ -9,6 +9,7 @@ // diffReel is pure; the writer (trailerBeats.mjs beatsWrite, undo) appends. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const REEL_HISTORY_CAP = 200; const FIELDS = ["id", "start", "end", "gaps", "at", "dur", "label", "verdict"]; @@ -85,7 +86,7 @@ export async function appendReelHistory(dir, rel, { what, take = null, before, a const file = historyFileOf(dir, rel); const entries = [...(await readReelHistory(dir, rel)), entry].slice(-REEL_HISTORY_CAP); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ file: rel, entries }, null, 1) + "\n", "utf8"); await rename(tmp, file); return entry; diff --git a/umtool/lib/report/reject-reasons.test.mjs b/umtool/lib/report/reject-reasons.test.mjs @@ -123,7 +123,7 @@ test("rejectClip: rejected, taken out, re-anchored and on record with the reason const rec = (await readRemoved(dir)).at(-1); assert.deepEqual( { ...rec, reanchored: rec.reanchored.length }, - { id: "c02", reason: "repeats", correction: null, note: "covered by c01", channel: null, video: "v-c02", start: 10, end: 20, at: 1, reanchored: 0, when: "2026-10-30T12:00:00.000Z" }, + { id: "c02", reason: "repeats", correction: null, note: "covered by c01", channel: "chan", video: "v-c02", start: 10, end: 20, at: 1, reanchored: 0, when: "2026-10-30T12:00:00.000Z" }, ); await undoStructural(dir); const back = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); diff --git a/umtool/lib/report/renderRecord.mjs b/umtool/lib/report/renderRecord.mjs @@ -50,6 +50,7 @@ import { createWriteStream, readFileSync } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const RENDER_FILE = "render.json"; export const RENDER_LOG = "render.log"; @@ -206,10 +207,8 @@ export const WAITING_LINE = /^(queue-lock|heavy):.*\b(waiting|held for a render) /** A line that says it was let in. */ const ADMITTED_LINE = /^(queue-lock|heavy):.*\b(admitted|acquired|going on)\b/i; -let tmpSeq = 0; async function writeAtomic(file, doc) { - tmpSeq += 1; - const tmp = `${file}.${process.pid}.${tmpSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/restore-removed.test.mjs b/umtool/lib/report/restore-removed.test.mjs @@ -11,7 +11,7 @@ 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 { MANIFEST_NAME, readRemoved, rejectClip, removeEntry, removedOutOfCut, removedSourceOf, restoreRemoved, updateClip } = await import("./manifest.mjs"); const { timelineCommand } = await import("./timelineCli.mjs"); const C02 = { @@ -98,3 +98,15 @@ test("umtool timeline <p> removed | restore <id>: the list, then the clip back, assert.equal(await run("cli", "restore", "c02"), 1); assert.match(lines.at(-1), /c02 is in the cut already/); }); + +test("a removed clip names where it came from: its channel on record (the cut's when the clip names none), never `?/`", async () => { + const dir = await project("source"); + await rejectClip(dir, "c02", "irrelevant"); + const [row] = await readRemoved(dir); + assert.equal(row.channel, "chan", "the cut's channel, on record"); + assert.equal(removedSourceOf(row, await read(dir)), `chan/${C02.video} @ ${C02.start}–${C02.end}`); + // An older record with no channel: the cut's, at display; with none anywhere, the video alone. + assert.equal(removedSourceOf({ ...row, channel: null }, await read(dir)), `chan/${C02.video} @ ${C02.start}–${C02.end}`); + assert.equal(removedSourceOf({ ...row, channel: null }, { provenance: {} }, { dash: "-", at: "@" }), `${C02.video}@${C02.start}-${C02.end}`); + assert.equal(removedSourceOf({ id: "x" }, null), "", "no video: the id says it"); +}); diff --git a/umtool/lib/report/reviewPass.mjs b/umtool/lib/report/reviewPass.mjs @@ -29,6 +29,7 @@ export { blockAnswer, reviewBlocks, reviewProgress }; export const REVIEW_PASS_FILE = "review-pass.json"; export { REVIEW_MARKS } from "./reviewPassModel.mjs"; import { REVIEW_MARKS } from "./reviewPassModel.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** A Fix's note, at most (a correction is the bench's sixth field; this is its post-and-card twin). */ export const REVIEW_NOTE_LIMIT = 2000; @@ -98,7 +99,9 @@ export function entrySignature(e) { * @param {{ timeline?: Array<Record<string, any>> } | null} manifest */ export function marksAgainst(doc, manifest) { - const byId = new Map((manifest?.timeline ?? []).filter((e) => e && typeof e.id === "string").map((e) => [e.id, e])); + // A twin id (two entries sharing one) is judged by its FIRST entry, the one setReviewMark signs. + const byId = new Map(); + for (const e of manifest?.timeline ?? []) if (e && typeof e.id === "string" && !byId.has(e.id)) byId.set(e.id, e); return Object.fromEntries( Object.entries(doc.marks).map(([id, m]) => { const e = byId.get(id); @@ -111,8 +114,9 @@ export function marksAgainst(doc, manifest) { const MARKED_HERE = new Set(["clip", "post", "card", "teaser", "video"]); /** - * Set (or clear) one block's mark. Refused: a clip (its mark is its walk verdict), a block the timeline does not - * hold, a Fix with no note (say what needs fixing -- the rule the walk's `incorrect` has). + * Set (or clear) one block's mark -- any block's Fix, a post's or a card's Keep. Refused: a clip's Keep (its walk + * verdict, `umtool window --verdict confirmed`), a block the timeline does not hold, a Fix with no note (say what + * needs fixing -- the rule the walk's `incorrect` has). A twin id's mark is its first entry's. * * @param {string} dir * @param {{ timeline?: Array<Record<string, any>> } | null} manifest @@ -137,7 +141,7 @@ export async function setReviewMark(dir, manifest, block, mark, { note, now = ne if (mark === null) delete doc.marks[block]; else doc.marks[block] = { mark, ...(text ? { note: text } : {}), sig: entrySignature(e), at: now.toISOString() }; await mkdir(dir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); return { doc, mark: doc.marks[block] ?? null }; @@ -151,8 +155,9 @@ export const REVIEW_PASS_USAGE = [ ]; /** - * `umtool review-pass`: the pass's blocks with their answers and where it resumes (`ls`), or one post / card mark - * (`mark`). A clip's answer is its walk verdict -- `umtool window` writes it. + * `umtool review-pass`: the pass's blocks with their answers and where it resumes (`ls`), one block's mark (`mark`: + * any block's Fix, a post's or a card's Keep), or the draft's verdict (`verdict`). A clip's Keep is its walk + * verdict -- `umtool window` writes it. * * @param {string[]} args * @param {{ resolve?: (p: string) => Promise<{ id: string, dir: string } | null>, log?: Function, err?: Function }} [o] diff --git a/umtool/lib/report/reviewPass.test.mjs b/umtool/lib/report/reviewPass.test.mjs @@ -113,3 +113,20 @@ test("a mark is of what was reviewed: an edge moved, a post edited, an id reused rmSync(dir, { recursive: true, force: true }); } }); + +test("a twin id's mark is signed and judged on the same entry, its first: not stale for being a twin", async () => { + const dir = mkdtempSync(path.join(tmpdir(), "review-pass-twin-")); + try { + const tl = [ + { type: "card", id: "k1", heading: "First", seconds: 1.5 }, + { type: "card", id: "k1", heading: "Second", seconds: 2 }, + ]; + await setReviewMark(dir, { timeline: tl }, "k1", "keep"); + const doc = await readReviewPass(dir); + assert.equal(doc.marks.k1.sig, entrySignature(tl[0]), "signed on the first"); + assert.equal(marksAgainst(doc, { timeline: tl }).k1.stale, undefined, "and judged on the first"); + assert.equal(marksAgainst(doc, { timeline: [{ ...tl[0], heading: "Changed" }, tl[1]] }).k1.stale, true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/sourceBacklog.mjs b/umtool/lib/report/sourceBacklog.mjs @@ -29,6 +29,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { channelFor, clipsOf } from "../projects/report.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SOURCE_WATCH_FILE = "source-watch.json"; export const SOURCE_WATCH_FORMAT = "umtool-source-watch"; @@ -172,7 +173,7 @@ function writeSourceWatch(dir, mutate) { const result = mutate(doc); const out = { format: SOURCE_WATCH_FORMAT, version: 1, watch: doc.watch, ...(doc.last ? { last: doc.last } : {}) }; await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/report/speakerCheck.mjs b/umtool/lib/report/speakerCheck.mjs @@ -32,6 +32,7 @@ import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/rep import { REPO_ROOT } from "../paths.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; import { planClips, referenceRecordings } from "./voiceMatch.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const SPEAKERS_FILE = "speakers.json"; const NAME_RE = /^[^\s/=,][^/=,]{0,47}$/; @@ -80,7 +81,7 @@ export async function readSpeakers(dir) { export async function writeSpeakers(dir, speakers) { const list = normalizeSpeakers({ speakers }); const file = path.join(dir, SPEAKERS_FILE); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); const doc = { speakers: list.map((s) => ({ name: s.name, ...(s.clips.length ? { clips: s.clips } : {}), ...(s.videos.length ? { videos: s.videos } : {}), ...(s.channels.length ? { channels: s.channels } : {}) })) }; await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(tmp, file); diff --git a/umtool/lib/report/structure.test.mjs b/umtool/lib/report/structure.test.mjs @@ -5,7 +5,7 @@ // // Run with: pnpm test:scripts import assert from "node:assert/strict"; -import { mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; @@ -19,11 +19,13 @@ import { insertEntry, manifestToken, moveEntry, + pruneAutoSnapshots, removeEntry, removePost, redoStructural, updateClip, setUndoEveryMs, + UNDONE_KEEP, undoStructural, updateFactcheck, updateTeaser, @@ -267,6 +269,53 @@ test("redoStructural puts back what each undo took back, newest first, and an ed } }); +test("redo refuses when an undo point is newer than the undo -- a move and its move back leave the draft as the undo left it, and still end the redo", async () => { + const pause = () => new Promise((r) => setTimeout(r, 25)); + const dir = await project(); + setUndoEveryMs(0); + try { + await removeEntry(dir, "c01"); + await pause(); + await undoStructural(dir); + const undoneTo = await readRaw(dir); + await pause(); + // A move and its move back: two undo points since the undo, the manifest byte for byte as the undo left it. + await moveEntry(dir, "c03", 1); + await pause(); + await moveEntry(dir, "c03", 3); + assert.equal(await readRaw(dir), undoneTo); + await assert.rejects(redoStructural(dir), /nothing to redo/); + assert.equal(await readRaw(dir), undoneTo, "nothing restored"); + } finally { + setUndoEveryMs(null); + await rm(dir, { recursive: true }); + } +}); + +test("pruneAutoSnapshots keeps the newest 50 `undone-*` (UNDONE_KEEP); named snapshots are never touched", async () => { + const dir = await project(); + try { + await mkdir(path.join(dir, "revisions"), { recursive: true }); + const text = await readRaw(dir); + const t0 = Date.now() / 1000 - 1000; + for (let i = 0; i < 53; i += 1) { + const stamp = `20260101-0000${String(i).padStart(2, "0")}`; + const f = path.join(dir, "revisions", `${stamp}-undone-move.manifest.json`); + await writeFile(f, text); + await utimes(f, t0 + i, t0 + i); + } + await writeFile(path.join(dir, "revisions", "20250101-000000-before-launch.manifest.json"), text); + const gone = await pruneAutoSnapshots(dir); + assert.equal(UNDONE_KEEP, 50); + assert.deepEqual(gone.sort(), ["00", "01", "02"].map((n) => `20260101-0000${n}-undone-move.manifest.json`)); + const left = await revisions(dir); + assert.equal(left.filter((n) => n.includes("-undone-")).length, 50); + assert.ok(left.includes("20250101-000000-before-launch.manifest.json")); + } finally { + await rm(dir, { recursive: true }); + } +}); + test("redo refuses after ANY write since the undo -- one that took no undo point included -- and keeps it", async () => { const pause = () => new Promise((r) => setTimeout(r, 25)); // (a) every edit its own undo point: move, undo, a title (no undo point), redo -> refused, the title kept. diff --git a/umtool/lib/report/takeCancel.mjs b/umtool/lib/report/takeCancel.mjs @@ -31,6 +31,7 @@ import os from "node:os"; import path from "node:path"; import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs"; import { isTakeId, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CANCEL_FILE = ".cancel.json"; export const CANCELLED_FILE = "cancelled.json"; @@ -48,7 +49,7 @@ export class TakeCancelled extends Error { const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); async function writeJson(file, doc) { - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs @@ -286,7 +286,12 @@ export async function takeCommand(args, { reportsRoot = REPORTS_ROOT, log = cons const id = p.one("--id"); if (!id) throw new CliError("--id <id>: the take's directory name (lower-case letters, digits, dashes)"); if (p.has("--promote")) return await promote(project, id, p, log, err); - if (p.has("--import-item")) return await importItems(project, id, p, { reportsRoot, log, err }); + if (p.has("--import-item")) { + // A write into the take's patch (takeDeprecation.mjs): the draft's twin is `timeline <p> import-item`. + const { takeEditDeprecation } = await import("./takeDeprecation.mjs"); + err(takeEditDeprecation("take --import-item", { project: project.id, take: id, instead: `umtool timeline ${project.id} import-item <src>:<item>[,<item>…]` })); + return await importItems(project, id, p, { reportsRoot, log, err }); + } if (p.has("--preview") || p.has("--changes")) return await fastRender(project, id, p, out, { args, log, deps, renderMode }); const draft = p.has("--draft") || p.has("--no-render"); const prev = await readFile(path.join(takesDirOf(project.dir), id, TAKE_FILE), "utf8").then(JSON.parse, () => null); diff --git a/umtool/lib/report/takeDeprecation.mjs b/umtool/lib/report/takeDeprecation.mjs @@ -1,20 +1,21 @@ // 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 +// still write a take's patch -- `--in-take`, `timeline --take`, `window --take`, `take --import-item` -- 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`. + * The one line, for `what` (the flag or route as typed) on take `take` of project `project`; `instead`, the verb + * that does it in the draft when it is not the same command without the flag. * @param {string} what - * @param {{ project?: string | null, take?: string | null }} [o] + * @param {{ project?: string | null, take?: string | null, instead?: string | null }} [o] */ -export function takeEditDeprecation(what, { project = null, take = null } = {}) { +export function takeEditDeprecation(what, { project = null, take = null, instead = 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`; + return `umtool: ${what} is deprecated -- edits land in the draft now; open the take there first (umtool takes open ${p} ${t}) and ${instead ? `use ${instead}` : "edit without it"}`; } /** Say it on stderr (once per call). */ diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -52,6 +52,7 @@ import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { stampOf } from "./snapshots.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TAKE_REVISIONS_DIR = "revisions"; const AUTO = "auto-before-"; @@ -126,7 +127,7 @@ async function keepRevision(projectDir, id, text, label, now) { async function writeTakeAtomic(projectDir, id, doc) { const file = takeFileOf(projectDir, id); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, serialise(doc), "utf8"); await rename(tmp, file); return takeToken(projectDir, id); @@ -461,7 +462,7 @@ export async function undoTakeEdit(projectDir, id, { token = null, now = new Dat JSON.parse(restored); // a revision that does not parse is not restored over a take.json that does const saved = await keepRevision(projectDir, id, text, "undo-saved", now); const file = takeFileOf(projectDir, id); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, restored, "utf8"); await rename(tmp, file); const undone = target.name.replace(`-${target.label}.take.json`, `-undone-${op}.take.json`); diff --git a/umtool/lib/report/takeFrom.mjs b/umtool/lib/report/takeFrom.mjs @@ -69,6 +69,7 @@ import { makeLinker } from "umtool-report-to-video/link-or-copy"; import { KEEP_FRAMES_DIR, keptFramesDir } from "umtool-report-to-video/prune-frames"; import { seedLadderFit } from "umtool-report-to-video/variants"; import { takesDirOf } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Where a take keeps a layer aside: its `out/.keep-frames/<layer>-frames` (prune-frames.mjs). */ export { KEEP_FRAMES_DIR }; @@ -273,7 +274,7 @@ async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) const [theirMemo, ownMemo] = await Promise.all([memoOf(src), memoOf(dst)]); if (theirMemo?.v === 1 && theirMemo.h) { const merged = { v: 1, h: { ...theirMemo.h, ...(ownMemo?.v === 1 ? ownMemo.h : {}) } }; - const tmp = path.join(dst, `${HASH_MEMO_FILE}.${process.pid}.tmp`); + const tmp = path.join(dst, tmpPathFor(HASH_MEMO_FILE)); await writeFile(tmp, JSON.stringify(merged), "utf8"); await rename(tmp, path.join(dst, HASH_MEMO_FILE)); } @@ -282,7 +283,7 @@ async function linkVariant({ src, dst, kept, from, chunks: withChunks = true }) // named files) is found through this: build-video adopts it when this // take's segments are those very files (xfadeBatchKeyV1). if (await isDir(batchOut)) { - const tmp = path.join(batchOut, `${XFADE_FROM_FILE}.${process.pid}.tmp`); + const tmp = path.join(batchOut, tmpPathFor(XFADE_FROM_FILE)); await writeFile(tmp, JSON.stringify({ take: from, segments: path.resolve(segs) }) + "\n", "utf8"); await rename(tmp, path.join(batchOut, XFADE_FROM_FILE)); } diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -59,6 +59,7 @@ import { replaceManifest } from "./manifest.mjs"; import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { autoPickTake, frozenBaseText, isTakeId, isWorkingTake, listTakes, parseWindow, setTakePicked, takesDirOf, BASE_FILE, DRAFT_FILE, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MANIFEST = "video.manifest.json"; export const PREVIEW = "preview.mp4"; @@ -840,7 +841,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { } : {}), }; - const tmp = `${takeFile}.tmp-${process.pid}`; + const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); // A whole-cut take of the DRAFT as it is (not a frozen version re-rendered) is the draft's parent now (versions.mjs). @@ -933,7 +934,7 @@ export async function draftTake(projectDir, rawSpec, opts = {}) { baseHash: hashText(baseText), }; await mkdir(takeDir, { recursive: true }); - const tmp = `${takeFile}.tmp-${process.pid}`; + const tmp = tmpPathFor(takeFile); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, takeFile); const clips = manifest.timeline.filter((e) => isObj(e) && e.type === "clip").length; @@ -966,7 +967,7 @@ async function moveFile(from, to) { } catch (err) { if (/** @type {any} */ (err)?.code !== "EXDEV") throw err; const { copyFile, unlink } = await import("node:fs/promises"); - const tmp = `${to}.tmp-${process.pid}`; + const tmp = tmpPathFor(to); await copyFile(from, tmp); await rename(tmp, to); await unlink(from).catch(() => {}); diff --git a/umtool/lib/report/takeManifest.mjs b/umtool/lib/report/takeManifest.mjs @@ -26,6 +26,7 @@ import { readFile, stat, writeFile, rename } from "node:fs/promises"; import path from "node:path"; import { ALL_STYLES_RECIPE, MANIFEST, RECIPE_FILE, loadMontageStyles, mergePatch, parseRecipe } from "./takeMaker.mjs"; import { BASE_FILE, frozenBaseText, isTakeId, listTakes, parseTake, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { frozenBaseText }; @@ -211,12 +212,11 @@ export async function cachedTakeManifest(projectDir, id) { // 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}.${++playManifestSeq}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, "utf8"); await rename(tmp, file); return file; diff --git a/umtool/lib/report/takePreview.mjs b/umtool/lib/report/takePreview.mjs @@ -39,6 +39,7 @@ import { promisify } from "node:util"; import { applyMontageRulings, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { composeTake, checkSpec, estimatedSeconds, getPath, linkSharedOut, MANIFEST, mergePatch, QUICK_RENDER, sourcedEntries, windowManifest } from "./takeMaker.mjs"; import { takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -742,7 +743,7 @@ export async function changesTake(projectDir, id, opts = {}) { } const list = path.join(work, "pieces.txt"); await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n", "utf8"); - const tmp = p.changesMp4.replace(/\.mp4$/, `.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(p.changesMp4.replace(/\.mp4$/, ""), { ext: ".mp4" }); await execFileP(FFMPEG, ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", "-movflags", "+faststart", tmp], { maxBuffer: 1 << 26 }); await rename(tmp, p.changesMp4); await rm(work, { recursive: true, force: true }); @@ -777,7 +778,7 @@ export async function changesTake(projectDir, id, opts = {}) { async function writeAtomic(file, doc) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -91,6 +91,7 @@ import path from "node:path"; import { MEDIA_ROOT, REPORTS_ROOT, inside, mediaMirror } from "../paths.mjs"; import { namesProject, pipelineProcesses } from "./busy.mjs"; import { TAKES_DIR, isTakeId, parseTake, readVerdictsStrict, takesDirOf } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** The project's prune settings: `takes/prune.json`. */ export const POLICY_FILE = "prune.json"; @@ -280,7 +281,7 @@ export function lockIsLive(lock, { host = os.hostname(), alive = pidAlive } = {} export async function writeBuildLock(dir, info = {}, { now = () => new Date() } = {}) { const file = path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK); const doc = { pid: process.pid, host: os.hostname(), startedAt: now().toISOString(), ...info }; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc) + "\n", "utf8"); await rename(tmp, file); return file; @@ -969,7 +970,7 @@ async function appendPruneRecord(takeDir, entry) { const prev = await readJson(file); const prunes = Array.isArray(prev?.prunes) ? prev.prunes : []; const doc = { format: "umtool-pruned-work", version: 1, prunes: [...prunes, entry].slice(-PRUNE_RECORD_KEEP) }; - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/takeScope.test.mjs b/umtool/lib/report/takeScope.test.mjs @@ -235,6 +235,8 @@ test("--import-item: an item of another project cloned into the take with its na assert.deepEqual(doc.items[0].avatars, ["neighbour_one"]); r = await take("imp-dst", "--id", "t1", "--import-item", "imp-src:12", "--before", "p-3"); assert.equal(r.code, 0, r.err); + // A take-patch write, deprecated in one line on stderr that names the draft's verb. + assert.match(r.err, /^umtool: take --import-item is deprecated -- .*umtool takes open imp-dst t1\) and use umtool timeline imp-dst import-item <src>:<item>/m); assert.match(r.out, /p-12: added from imp-src:12 at 4, after p-2, before p-3/); const m = (await resolveTakeManifest(dst.dir, "t1")).manifest; assert.deepEqual(m.timeline.map((e) => e.id), ["p-1", "p-11", "p-10", "p-2", "p-12", "p-3"]); diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs @@ -19,6 +19,7 @@ import { mkdir, readdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { inside } from "../paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TAKES_DIR = "takes"; export const TAKE_FILE = "take.json"; @@ -359,7 +360,7 @@ async function readVerdictsForWrite(file) { async function writeVerdicts(file, map) { await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -75,6 +75,7 @@ import { rejectClip, readRemoved, removedOutOfCut, + removedSourceOf, restoreRemoved, sectionsOf, updateSection, @@ -609,7 +610,7 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } 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(`${String(r.id).padEnd(10)} ${removedSourceOf(r, manifest, { dash: "-", at: "@" }) || "-"} ${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; diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs @@ -44,6 +44,7 @@ import { indentOf } from "./patchMarkers.mjs"; import { appendReelHistory } from "./reelHistory.mjs"; import { sectionModel, sectionWords } from "./sectionEdit.mjs"; import { trailerCandidates } from "./trailerCandidates.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json"); /** The reel a caller that names none reads and writes: promo/trailer-beats.json. */ @@ -185,7 +186,7 @@ export async function readReelUndo(dir, { reel = DEFAULT_REEL } = {}) { async function writeUndo(dir, reel, points) { const file = undoFileOf(dir, reel); await mkdir(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify({ reel, file: reelFileOf(reel), points: points.slice(-REEL_UNDO_KEEP) }, null, 1) + "\n", "utf8"); await rename(tmp, file); } @@ -226,7 +227,7 @@ async function beatsWrite(dir, token, mutate, { reel = DEFAULT_REEL, what = "an if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {}); // The undo point: the file as it was, before this write. await writeUndo(dir, reel, [...(await readReelUndo(dir, { reel })), { at: new Date().toISOString(), what, text: read.exists ? read.text : null }]); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8"); await rename(tmp, file); // The history (reelHistory.mjs): what moved, old and new, by beat. @@ -253,7 +254,7 @@ export async function undoTrailerBeats(dir, { token = null, reel = DEFAULT_REEL const before = await readTrailerBeats(dir, { reel }).catch(() => null); if (last.text === null) await rm(file, { force: true }); else { - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, last.text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/variantFork.mjs b/umtool/lib/report/variantFork.mjs @@ -44,6 +44,7 @@ import { isSegment, walkProjects } from "../projects/walk.mjs"; import { renderHolds } from "./takeHousekeeping.mjs"; import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs"; import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const VARIANT_FILE = "variant.json"; /** Copied, never linked: what a variant may change of its own. */ @@ -55,7 +56,7 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); const exists = (p) => lstat(p).then(() => true, () => false); async function writeAtomic(file, text) { - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/lib/report/versions.mjs b/umtool/lib/report/versions.mjs @@ -37,6 +37,7 @@ import { applyStructural, manifestToken, replaceManifestLocked, StaleToken, with import { withEditNotes } from "./edit-guard.mjs"; import { BASE_FILE, DRAFT_FILE, frozenBaseText, isTakeId, listTakes, readDraftFile, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { readWorkingCut } from "./workingCut.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const MANIFEST = "video.manifest.json"; export const VERSION_RE = /^v(\d{1,6})$/; @@ -70,7 +71,7 @@ export async function writeDraft(projectDir, { from, hash = null, at = null, bas if (!isTakeId(from)) throw new Error(`"${from}" is not a take id`); await mkdir(path.dirname(file), { recursive: true }); const doc = { from, hash, at: at ?? new Date().toISOString(), ...(base ? { base } : {}) }; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); return doc; @@ -126,7 +127,7 @@ export async function claimVersionId(projectDir) { } async function writeAtomic(file, text) { - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } @@ -217,6 +218,7 @@ export function withoutReviewFields(m) { * it IS that version -- the parent is judged, nothing saved; * else (or no parent): the draft is saved as the next version (saveVersionLocked; at no edits at all that is * the parent again, nothing saved) and that version is judged. + * A clear (null) never saves: it clears the parent's when the draft is that version, else it is refused. * Returns `{ judged, saved, entry }`: which version took the verdict, and whether one was saved for it. * * @param {{ id: string, dir: string }} project @@ -237,6 +239,19 @@ export async function judgeDraft(project, verdict, { note, now = new Date() } = return { judged: working.parent.id, saved: false, entry: r.entry }; } } + // A clear has nothing to save for: a version is saved FOR a verdict, never for taking one away. The draft that + // is not its parent has no verdict to clear (re-review should-fix 3, 10 Nov). + if (verdict === null) { + if (working.parent && working.edits?.count === 0) { + const r = await setTakeVerdict(project.dir, working.parent.id, { verdict: null, ...(note !== undefined ? { note } : {}) }); + return { judged: working.parent.id, saved: false, entry: r.entry }; + } + throw new VersionRefused( + working.parent + ? `the draft has edits since ${working.parent.id}: it is not a version, so it has no verdict to clear (clear a version's with umtool takes verdict <p> <take> clear)` + : "the draft has never been saved as a version: it has no verdict to clear", + ); + } const s = await saveVersionLocked(project.dir, { now, why: "Saved for its verdict (the review pass)" }); const r = await setTakeVerdict(project.dir, s.id, { verdict, ...(note !== undefined ? { note } : {}) }); return { judged: s.id, saved: !!s.saved, entry: r.entry }; diff --git a/umtool/lib/report/versions.test.mjs b/umtool/lib/report/versions.test.mjs @@ -517,6 +517,30 @@ test("a project naming a PRESET: its latest legacy take with no edits opens as n } }); +test("judgeDraft: a clear never saves a version -- the parent's is cleared while the draft is that version; a draft with edits (or never saved) is refused, nothing written", async () => { + const { root, dir, proj } = await project(); + try { + // Never saved: nothing to clear, and no v1 made for it. + await assert.rejects(judgeDraft(proj, null), /never been saved as a version/); + assert.deepEqual((await listTakes(dir)).takes.filter((t) => t.version).map((t) => t.id), []); + await saveVersion(proj); + await judgeDraft(proj, "like"); + // The draft is v1 (a walk verdict only): the clear is v1's. + await updateClip(dir, "a", { verdict: "confirmed" }); + let r = await judgeDraft(proj, null); + assert.deepEqual([r.judged, r.saved], ["v1", false]); + assert.equal((await readVerdicts(dir)).v1?.verdict ?? null, null); + // An edge moved: the draft is not v1 -- refused, no v2. + await judgeDraft(proj, "like"); + await updateClip(dir, "c", { end: 48 }); + await assert.rejects(judgeDraft(proj, null), /edits since v1/); + assert.deepEqual((await listTakes(dir)).takes.filter((t) => t.version).map((t) => t.id), ["v1"]); + assert.equal((await readVerdicts(dir)).v1.verdict, "like", "v1's verdict untouched"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("judgeDraft: a draft that differs from its parent only by the walk's and the review pass's fields judges the PARENT and saves nothing; any other edit saves the next version and judges it", async () => { const { root, dir, proj } = await project(); try { diff --git a/umtool/lib/report/videoAssist.mjs b/umtool/lib/report/videoAssist.mjs @@ -28,6 +28,7 @@ import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp import { readManifest } from "../projects/report.mjs"; import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs"; import { runClipEditorOp } from "./clipEditor.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const ASSIST_TASK = "video-assist"; export const ASSIST_JOB_FILE = ".video-assist-job.json"; @@ -86,7 +87,7 @@ export async function readAssistJob(dir) { /** Remember the job an Ask started (tmp + rename). */ export async function writeAssistJob(dir, rec) { const file = jobFileOf(dir); - const tmp = `${file}.${process.pid}.tmp`; + const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } diff --git a/umtool/lib/report/writeGuard.mjs b/umtool/lib/report/writeGuard.mjs @@ -21,11 +21,35 @@ import { crossSiteRefusal } from "./sameOrigin.mjs"; // THE UPLOADS ARE OUTSIDE THE PROXY. For a request the proxy matches, Next holds the body twice in memory before // the proxy runs and hands the route a copy cut off at proxyClientMaxBodySize (next.config.ts, kept small so a // cross-site tab cannot make the server buffer gigabytes). A recording uploaded from a page is bigger than any such -// cap, so these routes stay out of the matcher. Each one refuses cross-site ITSELF, as the first thing its write -// handler does, before it reads the body (writeGuard.test.mjs checks the order in the source). +// cap, so these routes stay out of the matcher. Each one calls crossSiteRefusal ITSELF, as the first thing its write +// handler does, before it reads the body (writeGuard.test.mjs checks the order in the source) -- on EVERY request, +// not only a browser's as writeRefusal does: one naming a Host or X-Forwarded-Host that is not this machine (nor in +// UMTOOL_ALLOWED_HOSTS) is refused even from curl or the editor's server (`Host: umtool:3050` in docker), and so is +// a browser's from another site. export const EXEMPT = ["/api/report/voices", "/api/report/post-narration", "/api/report/post-narration/record"]; /** + * The proxy's body cap: next.config.ts `proxyClientMaxBodySize: "16mb"` (Next's bytes: 16 × 1024 × 1024), which + * writeGuard.test.mjs holds equal. A matched body over it reaches its route CUT at the cap, so it never parses. + */ +export const BODY_CAP = 16 * 1024 * 1024; + +/** + * The sentence to refuse a write with (413) when its declared length is over BODY_CAP, or null. A body with no + * `content-length` (chunked) is not judged here: the route sees it cut, and refuses it as it does any bad body. + * @param {string} method + * @param {string} pathname + * @param {{ get(name: string): string | null }} headers + */ +export function bodyRefusal(method, pathname, headers) { + if (!guardedPath(method, pathname)) return null; + const said = (headers.get("content-length") ?? "").trim(); + const n = /^\d+$/.test(said) ? Number(said) : NaN; + if (!(n > BODY_CAP)) return null; + return `the body is ${n} bytes, over the ${BODY_CAP} (16 MB) a write to umtool's API takes -- an upload goes to its own route (a voice, a narration recording)`; +} + +/** * The proxy's matcher: everything under /api/ except EXEMPT. umtool/proxy.ts must say exactly this string, because * Next reads a matcher at build time and it cannot be imported (the sweep test checks). */ diff --git a/umtool/lib/report/writeGuard.test.mjs b/umtool/lib/report/writeGuard.test.mjs @@ -5,7 +5,7 @@ import fs from "node:fs"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs"; +import { BODY_CAP, bodyRefusal, EXEMPT, GUARD_MATCHER, guardedPath, writeRefusal } from "./writeGuard.mjs"; const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const APP = path.join(UMTOOL, "app"); @@ -106,6 +106,7 @@ test("every route that exports a write is behind the proxy", () => { for (const p of EXEMPT) assert.ok(!matcherCovers(GUARD_MATCHER, p), `the matcher leaves out ${p}`); assert.match(proxySrc, /export function proxy\b/, "proxy.ts exports proxy"); assert.match(proxySrc, /writeRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)/, "proxy.ts asks writeRefusal"); + assert.match(proxySrc, /bodyRefusal\(request\.method, request\.nextUrl\.pathname, request\.headers\)[\s\S]*status: 413/, "proxy.ts asks bodyRefusal, 413"); assert.ok(!fs.existsSync(path.join(UMTOOL, "middleware.ts")), "no middleware.ts beside proxy.ts"); const all = routes(); @@ -137,3 +138,74 @@ test("every route that exports a write is behind the proxy", () => { assert.deepEqual(uncovered, [], "a write the proxy does not guard"); assert.deepEqual(exempt.sort(), EXEMPT.map((p) => `POST ${p}`).sort(), "every EXEMPT path is a POST route the sweep checked"); }); + +test("bodyRefusal: a write declaring a body over the proxy's cap is refused (413, a sentence); at the cap, a read, or no length passes -- and the cap is next.config.ts's", () => { + const cfg = fs.readFileSync(path.join(UMTOOL, "next.config.ts"), "utf8"); + const said = /proxyClientMaxBodySize:\s*"(\d+)mb"/.exec(cfg); + assert.ok(said, "next.config.ts names proxyClientMaxBodySize in mb"); + assert.equal(Number(said[1]) * 1024 * 1024, BODY_CAP, "BODY_CAP is next.config.ts's cap"); + const len = (n) => h({ "content-length": String(n) }); + assert.match(String(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP + 1))), /over the 16777216 \(16 MB\)/); + assert.match(String(bodyRefusal("PUT", "/api/report/window", len(20 * 1024 * 1024))), /20971520 bytes/); + assert.equal(bodyRefusal("POST", "/api/projects/new", len(BODY_CAP)), null, "at the cap"); + assert.equal(bodyRefusal("POST", "/api/projects/new", h({})), null, "no length (chunked): the route judges what it gets"); + assert.equal(bodyRefusal("POST", "/api/projects/new", h({ "content-length": "1e9" })), null, "not a length"); + assert.equal(bodyRefusal("GET", "/api/projects/new", len(BODY_CAP + 1)), null, "a read"); + assert.equal(bodyRefusal("POST", "/projects", len(BODY_CAP + 1)), null, "not under /api/"); +}); + +// THE READS WRITE NO MANIFEST (umtool redesign E5 A4): a GET or HEAD is what a tab, a prefetch, a crawler or a +// cross-site <img> may send without asking -- the proxy lets every read through -- so no GET/HEAD handler under +// app/api/ calls a writer of the project's manifest, its draft, its versions or its undo stack, nor writes a file +// itself, but for the cache writers named below with why each is only a cache. +const MANIFEST_WRITERS = [ + // lib/report/manifest.mjs + "updateClip", "updateClaim", "addLedgerRow", "updateLedgerRow", "removeLedgerRow", "updateOnscreen", "updateChrome", "updatePreset", + "addDeckChrome", "updateRenderKeys", "updateRender", "updatePosts", "updateStorage", "updateArticleLink", "updateLinkPolicy", + "updateClaimKnobs", "updateMarks", "updateVariants", "replaceManifest", "undoStructural", "redoStructural", "moveEntry", "removeEntry", + "insertEntry", "duplicateEntry", "upsertPost", "removePost", "updateFactcheck", "updateTeaser", "autoSnapshot", "pruneAutoSnapshots", + // lib/report/snapshots.mjs + "createSnapshot", "writeSnapshotRaw", + // lib/report/versions.mjs + "writeDraft", "saveVersion", "judgeDraft", "openVersion", "freezeTakes", + // lib/report/takeEdit.mjs, takes.mjs, takeManifest.mjs + "undoTakeEdit", "setTakeVerdict", "writePlayManifest", +]; +const FILE_WRITES = ["writeFile", "writeFileSync", "rename", "renameSync", "writeFileAtomic", "writeFileAtomicSync", "writeJsonAtomic", "ensureWindowFile"]; +/** `<route file> <method> <writer>` -> why it is only a cache. */ +const CACHE_ONLY_GET = { + "app/api/clip/[key]/audio/route.ts GET writeFile": "the clip's audio window, level-normalised, cached under the clip cache by its stamp", + "app/api/clip/[key]/audio/route.ts GET rename": "the same cache file put in place", + "app/api/clip/[key]/video/route.ts GET rename": "the clip's video window cut once into the clip cache", + "app/api/face/frame/route.ts GET rename": "one extracted frame, cached by its source and second", + "app/api/report/audio/route.ts GET ensureWindowFile": "a recording's excerpt cut into out/clips-raw (serve.mjs, a cache any read may make)", + "app/api/report/clip/route.ts GET ensureWindowFile": "the same excerpt, started early for the bench's player", + "app/api/report/peaks/route.ts GET ensureWindowFile": "the same excerpt, for its waveform", + "app/api/report/raw/route.ts GET ensureWindowFile": "the same excerpt, served", +}; + +test("no GET or HEAD handler under app/api/ writes a manifest (MANIFEST_WRITERS), nor a file but the named caches", () => { + const sources = ["manifest.mjs", "snapshots.mjs", "versions.mjs", "takeEdit.mjs", "takes.mjs", "takeManifest.mjs"].map((f) => + fs.readFileSync(path.join(UMTOOL, "lib", "report", f), "utf8"), + ); + for (const w of MANIFEST_WRITERS) { + assert.ok(sources.some((src) => new RegExp(`export (?:async )?function ${w}\\b`).test(src)), `${w} is still a writer lib/report exports`); + } + const found = []; + const allowedSeen = new Set(); + for (const file of routes().map((r) => r.file)) { + const src = fs.readFileSync(path.join(UMTOOL, file), "utf8"); + for (const m of ["GET", "HEAD"]) { + const body = handlerSource(src, m); + if (!body) continue; + for (const w of [...MANIFEST_WRITERS, ...FILE_WRITES]) { + if (!new RegExp(`\\b${w}\\(`).test(body)) continue; + const key = `${file} ${m} ${w}`; + if (!MANIFEST_WRITERS.includes(w) && CACHE_ONLY_GET[key]) allowedSeen.add(key); + else found.push(key); + } + } + } + assert.deepEqual(found, [], "a read that writes"); + assert.deepEqual([...allowedSeen].sort(), Object.keys(CACHE_ONLY_GET).sort(), "every cache-only GET writer named is still one (a stale entry is removed)"); +}); diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs @@ -30,6 +30,7 @@ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { PIECE_SEGMENT_RE, casePieceId } from "../pieces/ids.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CASE_FORMAT = "umtool-research-case"; export const CASE_VERSION = 1; @@ -331,7 +332,7 @@ function serialised(fn) { async function writeCase(reportsRoot, doc) { const file = caseFile(reportsRoot, doc.id); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/census.mjs b/umtool/lib/research/census.mjs @@ -19,6 +19,7 @@ import { createHash } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const CENSUS_FORMAT = "umtool-research-census"; export const CENSUS_VERSION = 1; @@ -90,7 +91,7 @@ export function writeCensus(reportsRoot, handle, identity, channels, { now } = { channels: Object.fromEntries(Object.entries(channels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/log.mjs b/umtool/lib/research/log.mjs @@ -16,6 +16,7 @@ // somebody fixes it; a read treats it as empty and says so in `error`). import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const LOG_FORMAT = "umtool-research-log"; export const LOG_VERSION = 1; @@ -135,7 +136,7 @@ async function write(reportsRoot, session, key, state, meta) { marks: Object.fromEntries(Object.entries(marks).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))), }; await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/research/triage-marks.mjs b/umtool/lib/research/triage-marks.mjs @@ -15,6 +15,7 @@ // Plain ESM: the unit test reads it the way the app does. import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const MARKS_FORMAT = "umtool-triage-marks"; export const MARKS_VERSION = 1; @@ -99,7 +100,7 @@ export function setMark(reportsRoot, schedule, m) { doc.updatedAt = at; const file = marksFile(reportsRoot, schedule); await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); - const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + const tmp = tmpPathFor(file); try { await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); await rename(/* turbopackIgnore: true */ tmp, file); diff --git a/umtool/lib/state.ts b/umtool/lib/state.ts @@ -2,6 +2,7 @@ import { readFile, writeFile, rename, mkdir } from "node:fs/promises"; import { existsSync } from "node:fs"; import path from "node:path"; import { stateFile, dataFile } from "./paths"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // The JSON state has TWO writers: this app and the CLI scripts (decode-um.mjs // applies paste-backs from the static page, which stays usable). A lost update @@ -24,7 +25,7 @@ export async function readJson<T>(file: string, fallback: T): Promise<T> { export async function writeJsonAtomic(file: string, value: unknown): Promise<void> { const dir = path.dirname(file); if (!existsSync(dir)) await mkdir(dir, { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(value, null, 1)); await rename(tmp, file); } 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/brandIcon.test.ts 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 components/projects/bench/*.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/proxy.ts b/umtool/proxy.ts @@ -1,17 +1,21 @@ import { NextResponse, type NextRequest } from "next/server"; -import { writeRefusal } from "@/lib/report/writeGuard.mjs"; +import { bodyRefusal, writeRefusal } from "@/lib/report/writeGuard.mjs"; // EVERY API WRITE IS REFUSED CROSS-SITE (umtool redesign E4): a POST/PUT/PATCH/DELETE under /api/ from another // site's page, a sibling site's, or a page whose name is not this machine (DNS rebinding) is answered 403 here, and // its route handler never runs (Next has already buffered the body, up to proxyClientMaxBodySize: next.config.ts). A // request no browser sent (curl, the CLI, an agent, the editor's server) passes, and so does every read. The rule is -// in lib/report/writeGuard.mjs, and its test sweeps every route file that exports a write. The matcher keeps the +// in lib/report/writeGuard.mjs, and its test sweeps every route file that exports a write. A write declaring a body +// over the cap is answered 413 with its sentence (bodyRefusal), not handed on cut. The matcher keeps the // proxy off pages, static assets and the uploads (EXEMPT, which refuse cross-site themselves). It must stay the // literal GUARD_MATCHER, because a matcher is read at build time and cannot be imported. export function proxy(request: NextRequest) { const refused = writeRefusal(request.method, request.nextUrl.pathname, request.headers); if (refused) return NextResponse.json({ error: refused }, { status: 403, headers: { "cache-control": "no-store" } }); + // A body over the cap would reach its route cut at it (next.config.ts proxyClientMaxBodySize): said here, 413. + const tooBig = bodyRefusal(request.method, request.nextUrl.pathname, request.headers); + if (tooBig) return NextResponse.json({ error: tooBig }, { status: 413, headers: { "cache-control": "no-store" } }); return NextResponse.next(); } diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs @@ -40,6 +40,7 @@ import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.m import { clipBlurOf } from "./clip-blur.mjs"; import { keptSpans, renderGaps } from "./gaps.mjs"; import { hasLocalMedia } from "./local-media.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const fin = (v) => typeof v === "number" && Number.isFinite(v); @@ -294,7 +295,7 @@ export async function renderBasic({ manifest, dirs, only = null, deps }) { emit("concat", { mode: "hardcut", n: files.length }); await mkdir(path.dirname(dirs.final), { recursive: true }); // Through a temporary name: a concat that fails never leaves a half file at the deliverable's path. - const finalTmp = `${dirs.final}.tmp-${process.pid}.mp4`; + const finalTmp = tmpPathFor(dirs.final, { ext: ".mp4" }); try { await exec(ffmpeg, concatArgs(list, finalTmp)); await rename(finalTmp, dirs.final); diff --git a/umtool/report-to-video/build-podcast.mjs b/umtool/report-to-video/build-podcast.mjs @@ -42,6 +42,7 @@ import { promisify } from "node:util"; import { deckOn, deckQrUrl, segmentSoundEdits, soundEdges, teaserTitle } from "./deck.mjs"; import { hasNarration, narrationsOf } from "./narration.mjs"; import { narrationDir, readCutDisclosure } from "./narration-store.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -372,7 +373,7 @@ export async function buildPodcast({ manifestPath, variant = "sourced", out = nu await writeFile(metaPath, podcastFfmeta(chapters, { title: manifest.title ?? null, disclosure: disclosure?.replace(/\n/g, " ") ?? null }), "utf8"); emit("podcast", { phase: "encode", m4a: path.basename(m4a), mp3: mp3 ? path.basename(mp3) : null }); const encode = async (file, codec) => { - const tmp = file.replace(/(\.[a-z0-9]+)$/, `.${process.pid}.tmp$1`); + const tmp = tmpPathFor(file.replace(/\.[a-z0-9]+$/, ""), { ext: /\.[a-z0-9]+$/.exec(file)?.[0] ?? "" }); try { await execFileP(FFMPEG(), [ "-nostdin", "-v", "error", "-y", "-i", work, "-i", metaPath, diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -863,6 +863,7 @@ export { WIN_EPS, cachedWindowsFor, findContainingWindow, listRawNames, rawWindowName, tightestContaining, windowContains, windowsFromNames, } from "./sources.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; // The yt-dlp argv for one clip window. The platform's fixed args come from // common's table (`platformArgsForUrl`) -- the same copy every editor spawn @@ -2239,7 +2240,7 @@ async function placeShort(seg, manifestDir, entry, render) { const dir = path.join(manifestDir, "shorts"); await mkdir(dir, { recursive: true }); const dest = path.join(dir, `${entry.id}.mp4`); - const tmp = `${dest}.tmp-${process.pid}`; + const tmp = tmpPathFor(dest); await writeFile(tmp, await readFile(seg)); await rename(tmp, dest); const rec = await readCutRecord(seg).catch(() => null); @@ -2699,7 +2700,7 @@ export async function detachSegmentFiles(segDir, id) { /** Write `text` to `file` through a rename: a link at `file` is replaced, never written through. */ async function replaceFile(file, text) { - const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(path.dirname(file), `.${path.basename(file)}`)); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } @@ -2856,7 +2857,7 @@ async function buildNarratedCardSegment(card, render, outDir, nodes, framing, re return seg; } const png = await renderCard(resolved, render, outDir, nodes); - const tmp = path.join(path.dirname(seg), `.${card.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(seg), `.${card.id}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, narratedCardEncodeArgs({ png, wav: narrationWavPath(dir, rec.key), seconds, vf, audio, render, outPath: tmp, @@ -2970,7 +2971,7 @@ export async function buildTeaserSegment(entry, { manifestPath, render, outDir, // on disk may be a hard link to another take's (linked in to re-lay chrome // over it), and a rename replaces this take's name without writing a byte of // the other take's file. - const tmp = path.join(path.dirname(seg), `.${entry.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(seg), `.${entry.id}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, teaserEncodeArgs({ framesDir: r.frames, seconds, render, audio, outPath: tmp }), { maxBuffer: 1 << 26 }); await rename(tmp, seg); @@ -3049,7 +3050,7 @@ async function buildVideoEntrySegment(entry, render, outDir, baseDir, D, timelin level = { measured, gain: loudnessGain(measured, target), target, basis }; } const graph = videoSegmentGraph({ entry, render, seconds, lead, hasAudio, gainDb: level?.gain ?? null, span }); - const tmp = `${seg}.tmp-${process.pid}.mp4`; + const tmp = tmpPathFor(seg, { ext: ".mp4" }); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-i", src.file, "-filter_complex", graph, "-map", "[v]", "-map", "[a]", diff --git a/umtool/report-to-video/chrome-deck.mjs b/umtool/report-to-video/chrome-deck.mjs @@ -43,7 +43,7 @@ import { } from "./deck.mjs"; import { contrast } from "./chrome-intro.mjs"; import { claimsCues, claimsMarkup } from "./chrome-claims.mjs"; -import { resolveFactcheck, TALLY_WRITTEN, tallyCues, tallyFinals, tallyKey, tallyLabelLines, tallyOf, tallyPopIns } from "./factcheck.mjs"; +import { fitTallyLabel, resolveFactcheck, TALLY_WRITTEN, tallyCues, tallyFinals, tallyKey, tallyOf, tallyPopIns } from "./factcheck.mjs"; import { resolveCounter } from "./counter.mjs"; import { SUBSECTION_SEPARATOR } from "./marker-limits.mjs"; @@ -841,14 +841,16 @@ export function deckHtml(schedule, render, opts = {}) { // will show stacked in one box (`n0` … `n<final>`), its label under it. const tb = lay.tally ?? null; const verdictSet = tb ? resolveFactcheck(render).verdicts : null; - // Each cell's words (factcheck.mjs tallyLabelLines): the cell's own short word, else the label (or its last - // words) that fits, capitalised -- never an ellipsis; AS WRITTEN (`counter.labels`), the label in up to two - // lines, its own case. Past 8 series the cells are narrower (design.mjs counterCell). + // Each cell's words (factcheck.mjs fitTallyLabel): the cell's own short word, else the label (or its last + // words) that fits, capitalised; AS WRITTEN (`counter.labels`), the label in up to two lines, its own case. One + // wider than its cell is drawn smaller (its own font-size, the one inline style), then cut with an ellipsis -- + // never a chrome refused. Past 8 series the cells are narrower (design.mjs counterCell). const written = counter.labels === "as-written"; const fontBold = render.fontBold ?? null; - const cellWords = tb - ? Object.fromEntries(tally.map((v) => [v, tallyLabelLines(verdictSet[v], { fontBold, n: tally.length, labels: counter.labels }) ?? [verdictSet[v].label]])) + const cellFit = tb + ? Object.fromEntries(tally.map((v) => [v, fitTallyLabel(verdictSet[v], { fontBold, n: tally.length, labels: counter.labels })])) : {}; + const cellWords = Object.fromEntries(Object.entries(cellFit).map(([v, f]) => [v, f.lines])); const labelLines = written ? Math.max(1, ...Object.values(cellWords).map((l) => l.length)) : 1; // As written in two lines, the count gives the second line its room. const countSize = tb ? Math.round(tb.height * (labelLines > 1 ? 0.36 : 0.42)) : 0; @@ -880,7 +882,7 @@ export function deckHtml(schedule, render, opts = {}) { ? `<div class="tshape" data-shape="${shapes[v]}" style="${shapeCss(shapes[v], 12, esc(color))}"></div>` : "") + // cellWords: its line, or (as written) its lines. - `<div class="tlabel">${cellWords[v].map(esc).join("<br>")}</div>` + + `<div class="tlabel"${cellFit[v].shortened ? ` style="font-size:${zs(cellFit[v].size)}px"` : ""}>${cellWords[v].map(esc).join("<br>")}</div>` + `<div class="tflash" data-k="${tallyKey(v, "flash")}"></div></div>` ); }) diff --git a/umtool/report-to-video/chunked-encode.mjs b/umtool/report-to-video/chunked-encode.mjs @@ -45,6 +45,7 @@ import { createHash } from "node:crypto"; import { readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bumped when what a chunk key covers changes: every chunk is encoded once more. */ export const CHUNK_KEY_VERSION = 1; @@ -239,8 +240,7 @@ export class HashMemo { async save() { if (!this.file || !this.dirty) return; // A tmp of its own per save: a build may save while another save of the same memo is in flight. - HashMemo.saves = (HashMemo.saves ?? 0) + 1; - const tmp = `${this.file}.${process.pid}.${HashMemo.saves}.tmp`; + const tmp = tmpPathFor(this.file); await writeFile(tmp, JSON.stringify({ v: 1, h: Object.fromEntries(this.map) }), "utf8"); await rename(tmp, this.file); this.dirty = false; diff --git a/umtool/report-to-video/compose-chrome.mjs b/umtool/report-to-video/compose-chrome.mjs @@ -48,6 +48,7 @@ import { FRAME_KEYS_FILE, SPARSE_FILE } from "./chunked-encode.mjs"; import { poolFor, poolFrame, poolFrameEvents, poolPutFrames } from "./render-pool.mjs"; import { regionCaching, regionModule } from "./modules/index.mjs"; import { stackedDeckWanted, verticalRender } from "./vertical.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const run = promisify(execFile); @@ -1076,7 +1077,7 @@ export { FRAME_KEYS_FILE }; const frameName = (n) => `frame_${String(n).padStart(6, "0")}.png`; async function writeFrameKeys(dir, fk) { - const tmp = path.join(dir, `${FRAME_KEYS_FILE}.${process.pid}.tmp`); + const tmp = path.join(dir, tmpPathFor(FRAME_KEYS_FILE)); await writeFile(tmp, fk.join("\n") + "\n", "utf8"); await rename(tmp, path.join(dir, FRAME_KEYS_FILE)); } diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs @@ -45,6 +45,7 @@ import path from "node:path"; import { draftedFields, fieldKey, isCodeDraft, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { narrationsOf } from "./narration.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const DRAFTS_REVIEW_FILE = "drafts.review.json"; /** Release 25's file, read unchanged; never written any more. */ @@ -369,7 +370,7 @@ export async function setDraftReview(manifestDir, address, patch) { } if (row.verdict === null && !row.note && !legacyHas) delete map[address]; else map[address] = row; - const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8"); await rename(tmp, file); const stored = row.verdict === null && !row.note ? null : row; diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs @@ -124,14 +124,14 @@ function unknownKeys(obj, allowed, where, errors) { } // --------------------------------------------------------------------------- -// The tally cell's label: it must fit, every time. +// The tally cell's label: fitted to its cell (fitTallyLabel), every time. // --------------------------------------------------------------------------- /** * The tally cell's label as chrome-deck.mjs sets it: 13 px capitals in the * deck's bold, letter-spaced 0.08 em, in the cell's width less 6 px a side - * (deck.mjs deckLayout's 124 px cell). The page ellipsizes what overruns, so - * a label is fitted HERE, before the page is written. + * (deck.mjs deckLayout's 124 px cell). A label is fitted HERE, before the + * page is written (fitTallyLabel: smaller, then cut with an ellipsis). */ export const TALLY_LABEL = Object.freeze({ size: 13, tracking: 0.08, width: COUNTER_CELL.cell - 2 * COUNTER_CELL.labelPad }); @@ -190,8 +190,8 @@ export function tallyLabelWidth(label, { fontBold = null, size = TALLY_LABEL.siz * * @returns {string|null} */ -export function tallyLabelOf(v, { fontBold = null, width = TALLY_LABEL.width } = {}) { - const fits = (s) => tallyLabelWidth(s, { fontBold }) <= width; +export function tallyLabelOf(v, { fontBold = null, width = TALLY_LABEL.width, size = TALLY_LABEL.size } = {}) { + const fits = (s) => tallyLabelWidth(s, { fontBold, size }) <= width; if (typeof v?.tallyLabel === "string" && v.tallyLabel.trim()) return fits(v.tallyLabel.trim()) ? v.tallyLabel.trim() : null; const label = String(v?.label ?? ""); if (fits(label)) return label; @@ -210,10 +210,10 @@ export function tallyLabelOf(v, { fontBold = null, width = TALLY_LABEL.width } = * * @returns {string[]|null} */ -export function writtenLabelLines(label, { fontBold = null, width = TALLY_LABEL.width } = {}) { +export function writtenLabelLines(label, { fontBold = null, width = TALLY_LABEL.width, size = TALLY_WRITTEN.size } = {}) { const words = String(label ?? "").trim().split(/\s+/).filter(Boolean); if (!words.length) return null; - const fits = (x) => tallyLabelWidth(x, { fontBold, size: TALLY_WRITTEN.size, caps: false }) <= width; + const fits = (x) => tallyLabelWidth(x, { fontBold, size, caps: false }) <= width; const lines = []; for (const w of words) { if (!fits(w)) return null; @@ -245,33 +245,106 @@ export function tallyLabelLines(v, { fontBold = null, n = 1, labels = "caps" } = return one === null ? null : [one]; } +/** The smallest a tally label is drawn (px at 1080): one that does not fit shrinks to this, then is cut (fitTallyLabel). */ +export const TALLY_LABEL_FLOOR = 10; + /** - * Why a counter series' words do not fit its tally cell (`deck.counter`, - * counter.mjs), as the verdicts' are held: its `tallyLabel` must fit, else - * its label or a run of its last words must -- in the cell a row of `n` gives - * it (design.mjs counterCell). As written (`labels: "as-written"`), its - * tallyLabel or label must fill at most two lines, no word wider than the - * cell. null when they fit. + * THE TALLY LABEL FITTED TO ITS CELL -- what the cell draws, never a refusal of the whole chrome (umtool redesign + * E5): the words tallyLabelLines picks at the label's own size; else the same pick a pixel smaller at a time, down to + * TALLY_LABEL_FLOOR; else, at the floor, its words cut with an ellipsis (capitalised: its tallyLabel, else its + * label's last word; as written: its words in up to two lines, a word or the second line cut). `shortened` is what + * the lint says (tallyLabelNotes): "shrunk", "cut", or null when it is drawn as it always was. + * + * @param {{ label?: string, tallyLabel?: string }} v + * @param {{ fontBold?: string | null, n?: number, labels?: string }} [opts] + * @returns {{ lines: string[], size: number, shortened: null | "shrunk" | "cut" }} + */ +export function fitTallyLabel(v, { fontBold = null, n = 1, labels = "caps" } = {}) { + const written = labels === "as-written"; + const base = written ? TALLY_WRITTEN.size : TALLY_LABEL.size; + const same = tallyLabelLines(v, { fontBold, n, labels }); + if (same) return { lines: same, size: base, shortened: null }; + const width = tallyLabelRoom(n); + const own = typeof v?.tallyLabel === "string" && v.tallyLabel.trim() ? v.tallyLabel.trim() : null; + const words = own ?? String(v?.label ?? "").trim(); + for (let size = base - 1; size >= TALLY_LABEL_FLOOR; size -= 1) { + const lines = written + ? writtenLabelLines(words, { fontBold, width, size }) + : (() => { + const one = tallyLabelOf(v, { fontBold, width, size }); + return one === null ? null : [one]; + })(); + if (lines) return { lines, size, shortened: "shrunk" }; + } + const size = TALLY_LABEL_FLOOR; + const fits = (x) => tallyLabelWidth(x, { fontBold, size, caps: !written }) <= width; + // The longest start of `x` that fits with an ellipsis after it. + const cut = (x) => { + let chars = [...x]; + while (chars.length && !fits(`${chars.join("").trimEnd()}…`)) chars = chars.slice(0, -1); + return `${chars.join("").trimEnd()}…`; + }; + if (!written) { + const last = own ?? words.split(/\s+/).filter(Boolean).at(-1) ?? ""; + return { lines: [fits(last) ? last : cut(last)], size, shortened: "cut" }; + } + const filled = []; + for (const w of words.split(/\s+/).filter(Boolean)) { + const joined = filled.length ? `${filled[filled.length - 1]} ${w}` : null; + if (joined !== null && fits(joined)) filled[filled.length - 1] = joined; + else filled.push(w); + } + const lines = filled.length > TALLY_WRITTEN.lines ? [filled[0], filled.slice(1).join(" ")] : filled; + return { lines: lines.map((l) => (fits(l) ? l : cut(l))), size, shortened: "cut" }; +} + +/** A cell fitted to nothing but an ellipsis: the one tally label that cannot be drawn at all. */ +const noRoomAtAll = (fit) => fit.lines.every((l) => l === "…"); + +/** + * Why a counter series' words cannot be drawn in its tally cell (`deck.counter`, counter.mjs) -- in the cell a row of + * `n` gives it (design.mjs counterCell). A label wider than the cell is no reason: it is fitted (fitTallyLabel: + * shrunk, then cut) and the lint says so. Only a cell with no room for a single letter is. null when it can be drawn. */ export function counterLabelProblem(s, w, { fontBold = null, n = 1, labels = "caps" } = {}) { const label = s.label ?? VERDICT_DEFAULTS[s.id]?.label ?? s.id; - const room = tallyLabelRoom(n); - const cells = room !== TALLY_LABEL.width ? ` (${n} cells in the row)` : ""; - if (labels === "as-written") { - const key = typeof s.tallyLabel === "string" ? "tallyLabel" : "label"; - const words = key === "tallyLabel" ? s.tallyLabel : label; - if (writtenLabelLines(words, { fontBold, width: room }) !== null) return null; - return `${w}.${key} "${String(words).trim()}" does not fit the tally's cell${cells} in two lines of ${room} px: set ${w}.tallyLabel to fewer or shorter words`; + if (!noRoomAtAll(fitTallyLabel({ ...s, label }, { fontBold, n, labels }))) return null; + return `${w}: the tally's cell (${n} in the row) has ${tallyLabelRoom(n)} px for its label, no room for a letter at ${TALLY_LABEL_FLOOR} px`; +} + +/** + * The lint's word on each tally label drawn shortened (fitTallyLabel): the fact-check's relabelled verdicts (one + * cell's room, as validateFactcheck measures them) and a counter's series (in their row). Notes, never refusals. + * + * @returns {string[]} + */ +export function tallyLabelNotes(render) { + const chrome = render?.chrome; + if (!isObj(chrome)) return []; + const fontBold = render.fontBold ?? null; + const out = []; + const say = (where, v, fit) => { + const words = typeof v.tallyLabel === "string" && v.tallyLabel.trim() ? `tallyLabel "${v.tallyLabel.trim()}"` : `label "${String(v.label ?? "").trim()}"`; + const how = fit.shortened === "shrunk" ? `drawn at ${fit.size} px` : `cut to "${fit.lines.join(" ")}" at ${fit.size} px`; + out.push(`${where}.${words} is wider than the tally's cell: ${how} (set ${where}.tallyLabel to a shorter word to draw it whole at its own size)`); + }; + const verdicts = isObj(chrome.factcheck?.verdicts) ? chrome.factcheck.verdicts : {}; + for (const [k, v] of Object.entries(verdicts)) { + if (!VERDICTS.includes(k) || !isObj(v) || (typeof v.label !== "string" && typeof v.tallyLabel !== "string")) continue; + const fit = fitTallyLabel({ label: v.label ?? VERDICT_DEFAULTS[k]?.label, tallyLabel: v.tallyLabel }, { fontBold }); + if (fit.shortened) say(`render.chrome.factcheck.verdicts.${k}`, v, fit); } - if (typeof s.tallyLabel === "string") { - const px = tallyLabelWidth(s.tallyLabel.trim(), { fontBold }); - return px > room - ? `${w}.tallyLabel "${s.tallyLabel.trim()}" is ${px} px wide in the tally's cell${cells}, which has ${room} px: shorten it` - : null; + const counter = isObj(chrome.deck) && isObj(chrome.deck.counter) ? chrome.deck.counter : null; + if (counter && Array.isArray(counter.series)) { + const labels = counter.labels === "as-written" ? "as-written" : "caps"; + counter.series.forEach((s, i) => { + if (!isObj(s)) return; + const v = { ...s, label: s.label ?? VERDICT_DEFAULTS[s.id]?.label ?? s.id }; + const fit = fitTallyLabel(v, { fontBold, n: counter.series.length, labels }); + if (fit.shortened) say(`render.chrome.deck.counter.series[${i}]`, v, fit); + }); } - if (tallyLabelOf({ label }, { fontBold, width: room }) !== null) return null; - const px = tallyLabelWidth(label, { fontBold }); - return `${w}.label "${String(label).trim()}" is ${px} px wide in the tally's cell${cells}, which has ${room} px, and no run of its last words fits: set ${w}.tallyLabel to a shorter word`; + return out; } /** @@ -328,16 +401,11 @@ export function validateFactcheck(f, where = "render.chrome.factcheck", { fontBo } else { errors.push(...verdictOverrideProblems(v, w)); } - // The tally cell never ellipsizes: its words fit, or the check says so. - if (isObj(v) && !errors.some((e) => e.startsWith(`${w}.`))) { - if (typeof v.tallyLabel === "string") { - const px = tallyLabelWidth(v.tallyLabel.trim(), { fontBold }); - if (px > TALLY_LABEL.width) { - errors.push(`${w}.tallyLabel "${v.tallyLabel.trim()}" is ${px} px wide in the tally's cell, which has ${TALLY_LABEL.width} px: shorten it`); - } - } else if (typeof v.label === "string" && tallyLabelOf(v, { fontBold }) === null) { - const px = tallyLabelWidth(v.label, { fontBold }); - errors.push(`${w}.label "${v.label.trim()}" is ${px} px wide in the tally's cell, which has ${TALLY_LABEL.width} px, and no run of its last words fits: set ${w}.tallyLabel to a shorter word`); + // A label wider than the tally's cell is fitted to it (fitTallyLabel) and said by the lint + // (tallyLabelNotes); only a cell with no room for a letter is refused. + if (isObj(v) && !errors.some((e) => e.startsWith(`${w}.`)) && (typeof v.tallyLabel === "string" || typeof v.label === "string")) { + if (noRoomAtAll(fitTallyLabel({ label: v.label ?? VERDICT_DEFAULTS[k]?.label, tallyLabel: v.tallyLabel }, { fontBold }))) { + errors.push(`${w}: the tally's cell has ${TALLY_LABEL.width} px for its label, no room for a letter at ${TALLY_LABEL_FLOOR} px`); } } } diff --git a/umtool/report-to-video/factcheck.test.mjs b/umtool/report-to-video/factcheck.test.mjs @@ -12,7 +12,7 @@ import test from "node:test"; import { claimOf, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, ledgerPinOf, marksOf, normalizeClaim, pinsLedgerRows, rawMarksOf, originalUrlAt, resolveFactcheck, roundStamps, STAMP_MOTION, stampSchedule, - TALLY_LABEL, TALLY_POP, tallyCues, tallyLabelOf, tallyLabelWidth, tallyOf, tallyPopIns, tallyShowAt, tallySteps, tallyVerdicts, validateClaims, validateFactcheck, VERDICTS, + fitTallyLabel, TALLY_LABEL, TALLY_LABEL_FLOOR, tallyLabelNotes, TALLY_POP, tallyCues, tallyLabelOf, tallyLabelWidth, tallyOf, tallyPopIns, tallyShowAt, tallySteps, tallyVerdicts, validateClaims, validateFactcheck, VERDICTS, } from "./factcheck.mjs"; import { VERDICT_DEFAULTS, VERDICT_LABEL_MAX, VERDICTS as COMMON_VERDICTS, @@ -498,7 +498,7 @@ for (let i = 1; i <= Math.round(dur * fps); i += 1) writeFileSync(out + "/frame_ } }); -test("the tally cell's label always fits: a tallyLabel, else the label, else its last words; refused by name when none fits", () => { +test("the tally cell's label: a tallyLabel, else the label, else its last words; one wider than its cell is fitted (shrunk, then cut) and said by the lint, never a refused chrome", () => { // The cell's width is deckLayout's cell less 6 px a side. assert.equal(TALLY_LABEL.width, deckLayout(RENDER, { tally: ["PARTLY"] }).tally.cell - 12); // Every stock label fits as it is (Fira Sans Bold and the brand's mono bold). @@ -516,11 +516,26 @@ test("the tally cell's label always fits: a tallyLabel, else the label, else its assert.equal(tallyLabelOf({ label: "Huck's Blend pitches", tallyLabel: " Pitches " }), "Pitches"); assert.deepEqual(validateFactcheck({ verdicts: { PARTLY: { label: "Huck's Blend pitches" } } }), []); assert.deepEqual(validateFactcheck({ verdicts: { PARTLY: { label: "Huck's Blend pitches", tallyLabel: "Pitches" } } }), []); - // A tallyLabel that does not fit, or a label no run of whose last words fits: refused by name. - assert.match(validateFactcheck({ verdicts: { PARTLY: { tallyLabel: "Blend pitches galore" } } })[0], - /^render\.chrome\.factcheck\.verdicts\.PARTLY\.tallyLabel "Blend pitches galore" is \d+ px wide in the tally's cell, which has 112 px: shorten it$/); - assert.match(validateFactcheck({ verdicts: { PARTLY: { label: "Misrepresentations" } } })[0], - /verdicts\.PARTLY\.label "Misrepresentations" is \d+ px wide .* set render\.chrome\.factcheck\.verdicts\.PARTLY\.tallyLabel/); + // What fits is drawn as it always was. + assert.deepEqual(fitTallyLabel({ label: "Huck's Blend pitches" }), { lines: ["Blend pitches"], size: 13, shortened: null }); + // Wider than its cell: no refusal -- shrunk a pixel at a time, then cut at the floor. + assert.deepEqual(validateFactcheck({ verdicts: { PARTLY: { tallyLabel: "Blend pitches galore" } } }), []); + assert.deepEqual(validateFactcheck({ verdicts: { PARTLY: { label: "Misrepresentations" } } }), []); + assert.deepEqual(fitTallyLabel({ label: "Uncorroborated" }), { lines: ["Uncorroborated"], size: 11, shortened: "shrunk" }); + assert.ok(tallyLabelWidth("Uncorroborated", { size: 11 }) <= TALLY_LABEL.width); + assert.deepEqual(fitTallyLabel({ label: "Misrepresentations" }), { lines: ["Misrepresentati…"], size: TALLY_LABEL_FLOOR, shortened: "cut" }); + const cut = fitTallyLabel({ tallyLabel: "Extraordinarily long misrepresentations" }); + assert.equal(cut.shortened, "cut"); + assert.equal(cut.size, TALLY_LABEL_FLOOR); + assert.equal(cut.lines[0], "Extraordinarily…"); + assert.ok(tallyLabelWidth(cut.lines[0], { size: TALLY_LABEL_FLOOR }) <= TALLY_LABEL.width); + // A face the table lacks (counted at 1.02 em, the e2e fixture's): "Seizures" is 117 px -- shrunk, and the chrome composes. + const other = { ...RENDER, fontBold: "/x/DejaVuSans-Bold.ttf", chrome: { ...CHROME, factcheck: { verdicts: { CORROBORATED: { label: "Seizures" } } } } }; + assert.ok(tallyLabelWidth("Seizures", { fontBold: other.fontBold }) > TALLY_LABEL.width); + assert.deepEqual(validateChrome(other.chrome, other), []); + // The lint names it (and nothing when every label fits). + assert.match(tallyLabelNotes(other).join("\n"), /^render\.chrome\.factcheck\.verdicts\.CORROBORATED\.label "Seizures" is wider than the tally's cell: drawn at \d+ px/); + assert.deepEqual(tallyLabelNotes({ ...RENDER, chrome: { ...CHROME, factcheck: { verdicts: { PARTLY: { label: "Huck's Blend pitches" } } } } }), []); assert.match(validateFactcheck({ verdicts: { PARTLY: { tallyLabel: "" } } })[0], /tallyLabel must be words/); // validateChrome measures in the render's own bold (here the brand's mono). const mono = { ...RENDER, fontBold: "/x/IBMPlexMono-Bold.ttf", chrome: { ...CHROME, factcheck: { verdicts: { PARTLY: { tallyLabel: "Pitches" } } } } }; @@ -536,4 +551,9 @@ test("the tally: a page whose labels fit is byte-for-byte what it was, a long on const longHtml = deckHtml(sched(long), long, {}); assert.match(longHtml, /<div class="tlabel">Coffee pitches<\/div>/); assert.doesNotMatch(longHtml, /class="tlabel">Huck/); + // Wider than its cell: drawn at its fitted size (the one inline style), never refused. + const wide = { ...RENDER, chrome: { ...CHROME, factcheck: { verdicts: { PARTLY: { label: "Uncorroborated" }, CONTRADICTED: { label: "Misrepresentations" } } } } }; + const wideHtml = deckHtml(sched(wide), wide, {}); + assert.match(wideHtml, /<div class="tlabel" style="font-size:11px">Uncorroborated<\/div>/); + assert.match(wideHtml, /<div class="tlabel" style="font-size:10px">Misrepresentati…<\/div>/); }); diff --git a/umtool/report-to-video/heavy-gate.test.mjs b/umtool/report-to-video/heavy-gate.test.mjs @@ -122,6 +122,8 @@ test("with no HEAVY_LOCK_FILE the lock is pinned to the checkout's git common di // ...and render mode's state module, which the gate imports. mkdirSync(path.join(repo, "common", "lib"), { recursive: true }); copyFileSync(path.join(checkoutRoot(), "common", "lib", "renderPriority.mjs"), path.join(repo, "common", "lib", "renderPriority.mjs")); + // ...and the temp-name helper it writes its state through. + copyFileSync(path.join(checkoutRoot(), "common", "lib", "atomicFile.mjs"), path.join(repo, "common", "lib", "atomicFile.mjs")); const lock = path.join(repo, ".git", "heavy-queue.lock"); const seen = await withEnv( { HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: undefined, HEAVY_MIN_FREE_MB: "0" }, diff --git a/umtool/report-to-video/intro.mjs b/umtool/report-to-video/intro.mjs @@ -70,6 +70,7 @@ import { INTRO_URL_PLACES, INTRO_URLS, introErrors, introOf, introSitePrefix, introUrlText, validateIntro, } from "yt-dlp-transcript-common/lib/report/intro.mjs"; import { SITES_DIR } from "../lib/paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { INTRO_BEATS, INTRO_BRAND_DEFAULT, INTRO_GROUNDS, INTRO_ID, INTRO_MARKS, INTRO_PROJECT_URL, INTRO_SECONDS, INTRO_SECONDS_MAX, @@ -426,7 +427,7 @@ export async function writeIntroPage(dir, entry, render, { file = "index.html", const at = html.lastIndexOf("</body>"); const page = !extraScript ? html : at < 0 ? html + extraScript : `${html.slice(0, at)}${extraScript}\n ${html.slice(at)}`; const out = path.join(/* turbopackIgnore: true */ dir, file); - const tmp = `${out}.${process.pid}.tmp`; + const tmp = tmpPathFor(out); await writeFile(/* turbopackIgnore: true */ tmp, page, "utf8"); await rename(tmp, out); return { file: out, html }; @@ -501,7 +502,7 @@ export async function renderIntro({ entry, render, encode, manifestDir = process seconds: entry.seconds, render, hasSound: !!sound, soundSeconds: sound ? await probeSeconds(sound) : null, }); await mkdir(cacheDir, { recursive: true }); - const tmp = path.join(/* turbopackIgnore: true */ cacheDir, `.${key}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ cacheDir, `.${key}`), { ext: ".mp4" }); try { await execFileP(FFMPEG, introEncodeArgs({ framesDir, sound, seconds: entry.seconds, render, encode, audio, outPath: tmp }), { maxBuffer: 1 << 26 }); await rename(tmp, cached); @@ -529,14 +530,14 @@ export async function buildIntroSegment(entry, { render, encode, outDir, manifes return seg; } await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), { recursive: true }); - const tmp = path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), `.${entry.id}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ seg), `.${entry.id}`), { ext: ".mp4" }); try { await copyFile(r.path, tmp); await rename(tmp, seg); } finally { await rm(tmp, { force: true }); } - const recTmp = `${recPath}.${process.pid}.tmp`; + const recTmp = tmpPathFor(recPath); await writeFile(/* turbopackIgnore: true */ recTmp, JSON.stringify({ key: r.key, style: entry.style, ground: entry.ground, mark: entry.mark, seconds: entry.seconds, ...(entry.site ? { site: entry.site.name, swap: entry.swap } : {}), cached: r.cached, diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -53,6 +53,9 @@ // and validateTeasers refuses it.) // - a QR under WARN_QR_PX_PER_MODULE_720P pixels per module at 720p: it // scans on a good screen with a steady hand, not reliably. +// - a tally label wider than its cell: drawn smaller, down to +// TALLY_LABEL_FLOOR, then cut with an ellipsis (factcheck.mjs +// fitTallyLabel) -- the chrome is never refused for it. // // THE QR ARITHMETIC. A QR's side is (17 + 4·version) modules plus its quiet // zone on each side (`render.qr.quiet`, 3 as qrencode is run here). The @@ -81,7 +84,7 @@ import { deckOn, deckQrUrl, estimateSchedule, postArchiveUrl, postNativeId, postQrUrl, resolveDeck, teaserLines, validateChrome, validateCutEdits, validateDeckMarkers, validatePosts, validateTeasers, deckClaimNotes, validateDeckClaims, } from "./deck.mjs"; -import { validateClaims } from "./factcheck.mjs"; +import { tallyLabelNotes, validateClaims } from "./factcheck.mjs"; import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateClipBlurEntries } from "./clip-blur.mjs"; import { validateGapEntries } from "./gaps.mjs"; @@ -98,6 +101,7 @@ import { validateStatsEntries } from "./stats.mjs"; import { validateChatEntries } from "./chat.mjs"; import { validateMontage } from "./montage.mjs"; import { validateAssist } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; +import { basicOn } from "yt-dlp-transcript-common/lib/report/look.mjs"; import { validateFxEntries } from "./fx.mjs"; import { validateTransitionStyle } from "./transition.mjs"; import { validateLook } from "./look.mjs"; @@ -176,6 +180,9 @@ export function qrsOf(manifest, { only = null, metaOf = null } = {}) { const provenance = manifest.provenance ?? {}; const timeline = (manifest.timeline ?? []).filter((e) => e && (!only || e.id === only)); const out = []; + // A basic-mode cut is the footage alone (basic.mjs): it draws no code, so none is measured -- nor counted as built + // from the origin (originQrsOf, the Inbox's Blocking siteOrigin card: a quick clip on no public site raises none). + if (basicOn(render)) return out; if (deckOn(render)) { const d = resolveDeck(render); if (d.qr?.show) { @@ -447,6 +454,8 @@ export function lintManifest(manifest, { // refusal); a twocrop clip's band drawn past ENLARGE_WARN times its source's pixels (a 16:9 source of the cut's // `maxHeightSource`, 1080 by default: the build says it again from the real one); a twocrop where no stacked deck plays it. if (!only) warnings.push(...stackedLeftOut(manifest)); + // A tally label wider than its cell, drawn smaller or cut (factcheck.mjs fitTallyLabel): said, never refused. + if (!only) warnings.push(...tallyLabelNotes(render)); warnings.push(...stackedLintWarnings(manifest, { only })); for (const { where, src } of imageSrcsOf(manifest, { only })) { diff --git a/umtool/report-to-video/lint.test.mjs b/umtool/report-to-video/lint.test.mjs @@ -13,7 +13,7 @@ import { fileURLToPath } from "node:url"; import { MIN_QR_PX_PER_MODULE_720P, TEASER_HOUSE_CHARS, WARN_QR_PX_PER_MODULE_720P, - imageSrcsOf, lintManifest, lintManifestFile, pxPerModuleAt720, qrModules, qrsOf, qrVersion, + imageSrcsOf, lintManifest, lintManifestFile, originQrsOf, pxPerModuleAt720, qrModules, qrsOf, qrVersion, } from "./lint.mjs"; import { buildVideo } from "./build-video.mjs"; @@ -270,3 +270,12 @@ test("a build refuses a lint error before it renders anything; --no-lint builds p.done(); } }); + +test("a basic-mode cut draws no code: none measured, none built from the origin -- a missing origin blocks nothing there", () => { + const timeline = [{ id: "c1", type: "clip", video: "v1", start: 12.7, end: 20 }, { id: "i1", type: "image", src: "a.png", citeUrl: "https://e.test/i1" }]; + const basic = { ...BASE, mode: "basic" }; + assert.deepEqual(qrsOf({ render: basic, provenance: PROV, timeline }), []); + assert.deepEqual(originQrsOf({ render: basic, provenance: { channelSlug: "chan" }, timeline }), []); + // The same cut drawn with its corner code: the clip's code is built from the origin. + assert.deepEqual(originQrsOf({ render: BASE, provenance: { channelSlug: "chan" }, timeline }).map((q) => q.where), ["timeline c1 (its corner QR)"]); +}); diff --git a/umtool/report-to-video/modules/counter.mjs b/umtool/report-to-video/modules/counter.mjs @@ -43,8 +43,8 @@ export default defineModule({ heading: "Counter", intro: "The deck's tally as named series (`render.chrome.deck.counter`). A clip's mark names the series it counts (`claim.verdict`, or its alias `claim.counter`); a deck claim's `tally` names one by id or label. Without `counter` the series are the fact-check verdicts with `factcheck.verdicts`' relabels and `factcheck.tally`'s settings, as ever; `umtool migrate <p>` writes those as a `counter` (the render is the same) and the two are not set together.", rows: [ - ["`deck.counter.series[]`", "1–12 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 (≤ 32 as written) and fitting the cell, as the verdicts' are. Up to 8 the cells are 124 px; past 8 they narrow into one row of 1040 px (9 → 108 px, 10 → 96, 12 → 79), so the title keeps a column of about 520 px, and a label must fit the narrower cell (refused by name, never cut)", "`umtool look <p> deck.counter='{\"series\":[{\"id\":\"seizures\",\"label\":\"Seizures\",\"color\":\"#e5534b\",\"stampLabel\":\"Seizure\"}]}'`"], - ["`deck.counter.labels`", "`caps` `as-written` · default `caps`: each cell's word capitalised on one line (its `tallyLabel`, else its label or the last words of it that fit). `as-written`: the label in its own case (\"close to MAGA\"), letter-spaced 0.02 em, broken between words into at most two lines, never cut to its last words -- a word wider than the cell, or a third line, is refused by name", "`umtool look <p> deck.counter.labels=as-written`"], + ["`deck.counter.series[]`", "1–12 `{id, label, color?, stampLabel?, tallyLabel?, showAt?, shape?, unit?}` -- an `id` a letter then letters, digits, `_` `-`; a verdict's id (`CORROBORATED` …) takes its default label, colour and shape; `label` ≤ 24 (≤ 32 as written), fitted to the cell as the verdicts' are. Up to 8 the cells are 124 px; past 8 they narrow into one row of 1040 px (9 → 108 px, 10 → 96, 12 → 79), so the title keeps a column of about 520 px, and a label wider than its cell is drawn smaller (down to 10 px), then cut with an ellipsis -- never a refused chrome; the lint names it", "`umtool look <p> deck.counter='{\"series\":[{\"id\":\"seizures\",\"label\":\"Seizures\",\"color\":\"#e5534b\",\"stampLabel\":\"Seizure\"}]}'`"], + ["`deck.counter.labels`", "`caps` `as-written` · default `caps`: each cell's word capitalised on one line (its `tallyLabel`, else its label or the last words of it that fit). `as-written`: the label in its own case (\"close to MAGA\"), letter-spaced 0.02 em, broken between words into at most two lines, never cut to its last words -- one that does not fit is drawn smaller (down to 10 px), then a word or its second line is cut with an ellipsis; the lint names it", "`umtool look <p> deck.counter.labels=as-written`"], ["`deck.counter.series[].shape`", "`circle` `diamond` `square` `triangle` `ring` · default by place (a verdict's own)", "same"], ["`deck.counter.series[].unit`", "≤ 24 · the noun a count claim's number reads (default its label, lower-cased)", "same"], ["`deck.counter.show`, `.position`, `.showAt`", "bool · `right` `left` · `always` `first` (a series' own `showAt` wins) · defaults `true`, `right`, `always`. A series that SAYS `always` (its own `showAt`, else the counter's) is a cell from the first frame, dim at 0, whether or not a mark ever counts it (\"Left 0\"); one with no `showAt` said, or `first`, is a cell once it is counted, so one never counted is not drawn. The cells show once the cut counts anything", "same"], diff --git a/umtool/report-to-video/modules/counter.test.mjs b/umtool/report-to-video/modules/counter.test.mjs @@ -5,7 +5,7 @@ import assert from "node:assert/strict"; import { counterOrder, resolveCounter, validateCounter, VERDICT_SHAPES } from "../counter.mjs"; import { - claimOf, counterLabelProblem, marksOf, normalizeClaim, resolveFactcheck, tallyAlways, tallyCells, tallyCellsFrom, tallyCues, tallyFinals, tallyLabelLines, + claimOf, counterLabelProblem, fitTallyLabel, tallyLabelNotes, marksOf, normalizeClaim, resolveFactcheck, tallyAlways, tallyCells, tallyCellsFrom, tallyCues, tallyFinals, tallyLabelLines, tallyOf, tallyShowAt, validateClaims, writtenLabelLines, } from "../factcheck.mjs"; import { deckLayout, estimateSchedule, validateChrome } from "../deck.mjs"; @@ -63,9 +63,10 @@ test("validateCounter: every shape refused in a sentence; one home for the serie assert.match(validateCounter({ series: [{ id: "a", label: "A", shape: "star" }] })[0], /shape must be one of/); assert.match(validateCounter({ series: SERIES, colour: 1 })[0], /colour is not a counter setting/); assert.match(validateCounter({ series: SERIES }, { factcheck: { verdicts: {} } })[0], /replaces render.chrome.factcheck.verdicts/); - // Through the deck's validator: the cell's fit, as the verdicts' labels are held. - const long = validateChrome(render({ counter: { series: [{ id: "a", label: "Extraordinarilylong" }] } }).chrome, render()); - assert.match(long.join("\n"), /no run of its last words fits: set render.chrome.deck.counter.series\[0\].tallyLabel/); + // Through the deck's validator: a label wider than its cell is fitted, never refused -- the lint says so. + const wide = render({ counter: { series: [{ id: "a", label: "Extraordinarilylong" }] } }); + assert.deepEqual(validateChrome(wide.chrome, render()), []); + assert.match(tallyLabelNotes(wide).join("\n"), /^render\.chrome\.deck\.counter\.series\[0\]\.label "Extraordinarilylong" is wider than the tally's cell: (drawn at|cut to)/); assert.deepEqual(validateChrome(render({ counter: { series: SERIES } }).chrome, render()), []); }); @@ -178,9 +179,12 @@ test("past 8 series the cells narrow into one row (up to 12); as written, a labe // Capitalised (the default), the one line it always was -- in a 9-cell row's narrower room. assert.deepEqual(tallyLabelLines({ label: "Seizures" }, { n: 4 }), ["Seizures"]); assert.deepEqual(tallyLabelLines({ label: "Moderate center right" }, { n: 10 }), ["right"]); - // Its fit check, in the row it stands in: a word wider than a 12-cell row's room is refused by name. + // Its fit check, in the row it stands in: a word wider than a 12-cell row's room is fitted (drawn smaller), never refused. assert.equal(counterLabelProblem({ id: "a", label: "slightly more conservative" }, "w", { n: 10, labels: "as-written" }), null); - assert.match(counterLabelProblem({ id: "a", label: "conservative" }, "w", { n: 12, labels: "as-written" }) ?? "", /does not fit the tally's cell \(12 cells in the row\) in two lines of 67 px/); + assert.equal(counterLabelProblem({ id: "a", label: "conservative" }, "w", { n: 12, labels: "as-written" }), null); + const fit = fitTallyLabel({ label: "conservative" }, { n: 12, labels: "as-written" }); + assert.deepEqual([fit.lines, fit.shortened], [["conservative"], "shrunk"]); + assert.ok(fit.size < 13); // Through the deck's validator: 10 phrases as written, a written label to 32 characters, a stamp word still 24. const PHRASES = ["moderate", "moderate conservative", "centrist", "moderate right", "centered conservative", "slightly more conservative", "moderate center right", "socially moderate", "conservative", "close to MAGA"]; const series = PHRASES.map((label, i) => ({ id: `p${i}`, label })); diff --git a/umtool/report-to-video/modules/design.mjs b/umtool/report-to-video/modules/design.mjs @@ -25,8 +25,8 @@ export const COUNTER_CELL = Object.freeze({ cell: 124, gap: 10, labelPad: 6 }); * THE DENSE COUNTER (lane leaflit-labels): past 8 series (up to 12, counter.mjs * COUNTER_LIMITS) the cells share `budget` px -- the room 8 cells took less a * cell, so the deck's title keeps a column -- `gap` apart. 9 cells are 99 px, - * 12 are 72; a label that does not fit its narrower cell is refused by the - * counter's fit check, never cut. + * 12 are 72; a label that does not fit its narrower cell is drawn smaller, + * then cut (factcheck.mjs fitTallyLabel). */ export const COUNTER_DENSE = Object.freeze({ budget: 1040, gap: 8, from: 9 }); diff --git a/umtool/report-to-video/narration-store.mjs b/umtool/report-to-video/narration-store.mjs @@ -20,6 +20,7 @@ import { promisify } from "node:util"; import { disclosureLine, disclosureLines, narrationsOf } from "./narration.mjs"; import { postNarrationDisclosure } from "./post-narration.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -90,7 +91,7 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { } await mkdir(dir, { recursive: true }); const wav = narrationWavPath(dir, n.key); - const tmp = path.join(dir, `.${n.key}.${process.pid}.tmp.wav`); + const tmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".wav" }); try { await copyFile(result.wav, tmp); await rename(tmp, wav); @@ -129,7 +130,7 @@ export async function keepNarration(dir, n, result, { jobId = null } = {}) { : disclosureLine(engine, voice), createdAt: new Date().toISOString(), }; - const recTmp = path.join(dir, `.${n.key}.${process.pid}.tmp.json`); + const recTmp = tmpPathFor(path.join(dir, `.${n.key}`), { ext: ".json" }); await writeFile(recTmp, JSON.stringify(record, null, 2) + "\n", "utf8"); await rename(recTmp, narrationRecordPath(dir, n.key)); return record; diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs @@ -19,6 +19,7 @@ import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { COMBO_DEFAULTS, comboCounts, comboItems, comboKnobs, repeatGroups, tiersOf, xMediaIdOf } from "./post-combo.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); @@ -46,7 +47,7 @@ async function cached(file, sig, cacheDir, field, make) { rec[field] = await make(); if (cacheDir) { await mkdir(cacheDir, { recursive: true }).catch(() => {}); - const tmp = path.join(cacheDir, `.${key}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(cacheDir, `.${key}`)); await writeFile(tmp, JSON.stringify(rec), "utf8").then(() => rename(tmp, path.join(cacheDir, `${key}.json`)), () => {}); } } diff --git a/umtool/report-to-video/post-combo-render.mjs b/umtool/report-to-video/post-combo-render.mjs @@ -23,6 +23,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { COMBO_TIMING, comboBadgeHtml, comboFrame, comboPlace, comboStart, comboTransform } from "./post-combo.mjs"; import { panelEntry, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs"; import { LIMITED_RANGE } from "./color-range.mjs"; +import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); const r3 = (v) => Math.round(v * 1000) / 1000; @@ -204,8 +205,7 @@ export async function applyPostCombo(seg, entry, { combo, render, outDir, box, e await rename(tmp, seg); const out = sigOf(await stat(seg)); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(/* turbopackIgnore: true */ `${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); - await rename(`${record}.tmp`, record); + await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, out, count: combo.count, at: cp.at, media: combo.media, region: cp.place.region, sfx: sfx ? combo.knobs.sfx : "off" }, null, 2) + "\n", "utf8"); emit("note", { message: `${entry.id}: combo ×${combo.count} at ${cp.at.toFixed(2)} s${sfx ? ` (sfx ${combo.knobs.sfx})` : ""}` }); return seg; } diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -37,6 +37,7 @@ import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; import { WORD_ZOOM_DEFAULTS, findMatch, overlappingZooms, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomSpan, zoomTarget, zoompanExprs } from "./word-zoom.mjs"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; +import { writeFileAtomic } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const r3 = (v) => Math.round(v * 1000) / 1000; const num = (v) => String(r3(v)); @@ -1574,8 +1575,7 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box // The follow frames are in the segment now: a rebuild shoots them again (they are many, and the key decides). if (cards.follow) await rm(path.dirname(cards.follow.list), { recursive: true, force: true }); // Through a rename: a record `--from` linked in (another take's) is replaced, never written through. - await writeFile(`${record}.tmp`, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); - await rename(`${record}.tmp`, record); + await writeFileAtomic(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length, ...(zooms.length ? { zooms: zooms.map((z) => ({ i: z.i, at: z.t, source: z.source, span: z.span, region: z.region, word: z.word })) } : {}), ...(cards.captions?.length ? { captions: cards.captions.map((c) => ({ i: c.i, at: c.t, source: c.source, span: c.span, place: c.placed.place, rel: c.placed.rel, box: { x: c.placed.x, y: c.placed.y, width: c.placed.width, height: c.placed.height }, word: c.placed.word, covers: c.placed.covers, leader: c.placed.leader, ...(c.cutByPan ? { cutByPan: c.cutByPan } : {}) })) } : {}), ...(cards.slams?.length ? { slams: cards.slams.map((sl) => ({ i: sl.i, text: sl.fx.text, at: sl.t, end: sl.end, source: sl.source, landings: sl.landings, span: { t0: sl.span.t0, t2: sl.span.t2, t3: sl.span.t3 }, where: sl.layout.where, box: { x: sl.layout.x, y: sl.layout.y, width: sl.layout.width, height: sl.layout.height }, ...(sl.layout.bar ? { bar: { text: sl.fx.bar, style: sl.fx.barStyle, x: sl.layout.bar.x, y: sl.layout.bar.y, width: sl.layout.bar.width, height: sl.layout.bar.height } } : {}), size: sl.size, covers: sl.layout.covers, sfx: sl.fx.sfx, shots: sl.shots })) } : {}), ...(narration ? { narration: { take: take.file, ...plan.narration, gainDb: narration.gainDb, measured: narration.lufs, ...(bleeps ? { slurs: { mode: bleeps.mode, spans: bleeps.spans } } : {}) } } : {}), ...(cards.follow ? { follow: { blocks: plan.follow.blocks.length, shots: cards.follow.shots, frames: cards.follow.frames, pan: cards.follow.path.segments.length, max: cards.follow.path.max } } : {}), ...(Number.isFinite(cards.joinAnchor) ? { joinAnchor: cards.joinAnchor } : {}) }, null, 2) + "\n", "utf8"); if (pool) await poolPut(pool, "post", key, { "seg.mp4": seg, "post.json": record }); emit("note", { message: narration diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -33,6 +33,7 @@ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const PRUNED_RECORD = "pruned.json"; /** Where an out/ keeps its set-aside chrome sequences: `<out>/.keep-frames/`. */ @@ -50,7 +51,7 @@ export function keptFramesDir(outRoot, variant = "sourced") { export async function markKeepFrames(outRoot, { now = () => new Date(), by = "take --keep-frames" } = {}) { const dir = path.join(outRoot, KEEP_FRAMES_DIR); await mkdir(dir, { recursive: true }); - const tmp = path.join(dir, `.${KEEP_FRAMES_ASKED}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${KEEP_FRAMES_ASKED}`)); await writeFile(tmp, `${JSON.stringify({ at: now().toISOString(), by }, null, 2)}\n`, "utf8"); await rename(tmp, path.join(dir, KEEP_FRAMES_ASKED)); } @@ -112,7 +113,7 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date(), se } for (const name of [...sequences, ...work]) bytes += await dirBytes(path.join(chromeDir, name)); const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; - const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); if (setAside && sequences.length) { @@ -154,7 +155,7 @@ export async function recordPrunedSequences(chromeDir, names, { now = () => new } if (!recorded.length) return recorded; const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; - const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(chromeDir, `.${PRUNED_RECORD}`)); await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); return recorded; diff --git a/umtool/report-to-video/reframe.mjs b/umtool/report-to-video/reframe.mjs @@ -20,6 +20,7 @@ import { promisify } from "node:util"; import { postLayout } from "./post-item.mjs"; import { VERTICAL_HEIGHT, VERTICAL_WIDTH, safeArea, verticalKnobs } from "./vertical.mjs"; import { assColour, assTime, captionText } from "./look.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = process.env.FFMPEG ?? "ffmpeg"; @@ -52,7 +53,7 @@ export async function normalizeLoudness(input, output, target, { log = () => {} const spec = `I=${target}:TP=-1.5:LRA=11`; const { stderr } = await execFileP(FFMPEG, ["-nostdin", "-hide_banner", "-i", input, "-af", `loudnorm=${spec}:print_format=json`, "-f", "null", "-"], { maxBuffer: 1 << 26 }); const m = JSON.parse(stderr.slice(stderr.lastIndexOf("{"), stderr.lastIndexOf("}") + 1)); - const tmp = `${output}.tmp-${process.pid}.mp4`; + const tmp = tmpPathFor(output, { ext: ".mp4" }); await execFileP(FFMPEG, [ "-nostdin", "-v", "error", "-y", "-i", input, "-c:v", "copy", "-af", `loudnorm=${spec}:measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:measured_thresh=${m.input_thresh}:offset=${m.target_offset}:linear=true`, diff --git a/umtool/report-to-video/render-pool.mjs b/umtool/report-to-video/render-pool.mjs @@ -51,6 +51,7 @@ import { appendFile, link, lstat, mkdir, readdir, readFile, realpath, rename, rm import path from "node:path"; import { MEDIA_ROOT } from "../lib/paths.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** * The kinds, each with its renderer SALT: bumped when code changes what a @@ -167,7 +168,8 @@ export async function poolPut(pool, kind, key, files, extra = {}) { if ((await stat(path.join(dir, META)).catch(() => null))?.isFile()) return true; const shard = path.dirname(dir); await mkdir(shard, { recursive: true }); - const tmp = path.join(path.dirname(shard), `.tmp-${process.pid}-${randomBytes(4).toString("hex")}`); + // A hidden work dir of its own beside the shards (`<kind dir>/.tmp-<pid>-<seq>-<random>`). + const tmp = tmpPathFor(path.dirname(shard) + path.sep); await mkdir(tmp); try { const meta = { kind, key: String(key), salt: POOL_KINDS[kind].salt, at: new Date().toISOString(), files: {}, ...extra }; diff --git a/umtool/report-to-video/segment-cache.mjs b/umtool/report-to-video/segment-cache.mjs @@ -32,6 +32,7 @@ import { readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promise import path from "node:path"; import { poolFetch, poolFor, poolPut } from "./render-pool.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** Bumped when what the key covers changes: every segment is rebuilt once. */ export const SEGMENT_KEY_VERSION = 1; @@ -142,7 +143,7 @@ export async function segmentKey({ argv, record, outDir, ffmpeg }) { const cutRecordOf = (seg) => seg.replace(/\.mp4$/, ".cut.json"); async function replaceText(file, text) { - const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(path.dirname(file), `.${path.basename(file)}`)); await writeFile(tmp, text, "utf8"); await rename(tmp, file); } diff --git a/umtool/report-to-video/side-card.mjs b/umtool/report-to-video/side-card.mjs @@ -17,6 +17,7 @@ import { loadChromium } from "./post-render.mjs"; // The post as a side card shows it (vertical.mjs, pure: Play's route reads it too). import { sideCardEntry } from "./vertical.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export { sideCardEntry }; /** The key of a side card: what it draws, at what size, under which redaction. */ @@ -54,7 +55,7 @@ export async function renderSideCard(post, { width, height, render = {}, avatars await writeFile(htmlFile, html, "utf8"); await page.goto(pathToFileURL(htmlFile).href, { waitUntil: "load" }); await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 }); - const tmp = `${file}.tmp-${process.pid}.png`; + const tmp = tmpPathFor(file, { ext: ".png" }); await page.locator("[data-post-card]").first().screenshot({ path: tmp, omitBackground: true }); await rename(tmp, file); } finally { diff --git a/umtool/report-to-video/trailer.mjs b/umtool/report-to-video/trailer.mjs @@ -78,6 +78,7 @@ import { beatGapsOf, gapFilterParts, offsetIn, recordGaps, sourceAtOffset } from import { OUTRO_FADE, outroAdds, outroFilterParts, renderOutroCard } from "./outro.mjs"; import { outroBrand, reelIntroOf, renderReelIntro } from "./reel-intro.mjs"; import { SNAP_HARD_ROOM, SNAP_MAX_SHIFT, pauseSpans, snapEdge } from "./pauses.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -858,7 +859,7 @@ export async function makeTrailer({ }; let argv = null; // Written beside, then renamed: a half-made file never sits at the name. - const tmp = path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}.${process.pid}.tmp.mp4`); + const tmp = tmpPathFor(path.join(path.dirname(outPath), `.${path.basename(outPath, ".mp4")}`), { ext: ".mp4" }); let encodeSeconds = null; // Cancelled (the Trailer page's Cancel signals the job's process group): the // half-made file goes with it. Exits as the signal would when nothing else diff --git a/umtool/report-to-video/trailer.test.mjs b/umtool/report-to-video/trailer.test.mjs @@ -268,7 +268,7 @@ test("makeTrailer: the encode runs in the slot, the file lands by rename, the re }); assert.equal(slotted, 1); assert.equal(res.outPath, path.join(take, "out", "cut.trailer.mp4")); - assert.match(path.basename(ran.at(-1)), /^\.cut\.trailer\.\d+\.tmp\.mp4$/); + assert.match(path.basename(ran.at(-1)), /^\.cut\.trailer\.tmp-\d+-\d+-[0-9a-f]{8}\.mp4$/); assert.equal(await readFile(res.outPath, "utf8"), "trailer"); const rec = JSON.parse(await readFile(path.join(take, "out", "cut.trailer.json"), "utf8")); assert.equal(rec.kind, "trailer"); diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs @@ -53,6 +53,7 @@ import { ladderJobs, masterFromChunks, rungAudioArgs, rungAudioFile, rungAudioKey, rungChunkArgs, rungChunkFile, rungChunkKey, rungJoinArgs, runPool, } from "./ladder-chunks.mjs"; import { ffmpegIdentity } from "./segment-cache.mjs"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -297,7 +298,7 @@ async function openLadder({ outDir, src, work, slug, onLog }) { for (const f of await readdir(cdir).catch(() => [])) { if ((isLadderChunkFile(f) && !keep.has(f)) || /\.partial\.(mp4|m4a)$/.test(f)) await rm(path.join(cdir, f), { force: true }); } - const tmp = path.join(dir, `.${LADDER_RECORD}.${process.pid}.tmp`); + const tmp = tmpPathFor(path.join(dir, `.${LADDER_RECORD}`)); await writeFile(tmp, JSON.stringify(rec, null, 2) + "\n", "utf8"); await rename(tmp, recFile); }; diff --git a/umtool/song/asr-via-ops.mjs b/umtool/song/asr-via-ops.mjs @@ -36,6 +36,7 @@ import { execFileSync } from "node:child_process"; import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, writeSync } from "node:fs"; import path from "node:path"; import { SONG_DATA } from "./paths.mjs"; +import { writeFileAtomicSync } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const plans = process.argv.slice(2).filter((a) => a.endsWith(".json")); if (!plans.length || !process.env.WORKER_TOKEN) { @@ -134,8 +135,7 @@ for (const w of words) { for (const id of ready) { const file = path.join(ASR, `${id}.json`); const list = perId.get(id).sort((a, b) => a.start - b.start); - writeFileSync(`${file}.tmp`, JSON.stringify({ windows: windowsOf(spans.get(id)), words: list })); - renameSync(`${file}.tmp`, file); + writeFileAtomicSync(file, JSON.stringify({ windows: windowsOf(spans.get(id)), words: list })); } const counts = ready.map((id) => perId.get(id).length); console.log(`asr: ${ready.length} written (${counts.filter((n) => n === 0).length} with no words), ` + diff --git a/umtool/song/link-sources.mjs b/umtool/song/link-sources.mjs @@ -31,6 +31,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSyn import { execFileSync } from "node:child_process"; import path from "node:path"; import { SONG_DATA } from "./paths.mjs"; +import { writeFileAtomicSync } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const argv = process.argv.slice(2); const ci = argv.indexOf("--channel"); @@ -105,8 +106,7 @@ for (const id of ids) { "-of", "csv=p=0", wav]).toString().trim()); ledger[id] = { channel: CHANNEL, saved: file, bytes: statSync(file).size, seconds: +secs.toFixed(2), linkedAt: new Date().toISOString() }; - writeFileSync(`${LEDGER}.tmp`, JSON.stringify(ledger, null, 1) + "\n"); - renameSync(`${LEDGER}.tmp`, LEDGER); + writeFileAtomicSync(LEDGER, JSON.stringify(ledger, null, 1) + "\n"); console.log(`${id}: ${(secs / 60).toFixed(1)} min`); } console.log(`${ids.length} sources: ${linked} linked, ${wavs} wav48 written, ${already} already done, ${waiting} not saved yet`); diff --git a/umtool/song/spec.mjs b/umtool/song/spec.mjs @@ -29,6 +29,7 @@ import { readFileSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, mkdirSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const ROOT = process.env.VIDEO_ROOT ?? path.join(os.homedir(), "reports", "quartering-uh-song", "videos"); const argv = process.argv.slice(2); @@ -48,7 +49,7 @@ function read(song) { function write(song, spec) { const f = file(song); if (!existsSync(path.dirname(f))) throw new Error(`no such song directory: ${path.dirname(f)}`); - const tmp = `${f}.tmp-${process.pid}`; + const tmp = tmpPathFor(f); writeFileSync(tmp, JSON.stringify(spec, null, 1)); renameSync(tmp, f); } diff --git a/umtool/song/video-dir.mjs b/umtool/song/video-dir.mjs @@ -51,6 +51,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync, readdirSy import { execFileSync } from "node:child_process"; import os from "node:os"; import path from "node:path"; +import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; const ROOT = process.env.VIDEO_ROOT ?? path.join(os.homedir(), "reports", "quartering-uh-song", "videos"); const argv = process.argv.slice(2); @@ -79,7 +80,7 @@ function readBuild(song) { function writeBuild(song, value) { const file = buildFile(song); mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}`; + const tmp = tmpPathFor(file); writeFileSync(tmp, JSON.stringify(value, null, 1)); renameSync(tmp, file); }