Archilyzer · Source

archilyzer

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

commit c145be798dc16d2077778e36afc9a3e9c65226b6
parent abf350de2950c0840077d3f7f2e5137f762cb51d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 03:48:24 -0500

Merge lane/ui-ops: the sites a cut's links depend on with their deploy dates and a Publish <site> button; a per-project link policy the inserters and the check enforce; social channels' Sync runs fetch-posts; the render queue panel (who holds the heavy slot, waiting tickets) and a take's ETA from past renders; a speaker check on the walk over the voice match (cli.md: tighten and link-policy rows both kept)

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

Diffstat:
MCOMMANDS.md | 2+-
MENVIRONMENT.md | 1+
MWORKTREES.md | 7+++++--
Mcommon/lib/envVars.ts | 1+
Acommon/lib/heavyQueue.mjs | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/heavyQueue.test.ts | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/speakerCheck.mjs | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/montage/speakerCheck.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/renderPriority.mjs | 18+++++++++++++-----
Mcommon/package.json | 2++
Mcommon/views/channelRow.test.ts | 6++++++
Mcommon/views/channelRow.ts | 6+++++-
Meditor/CHANGELOG.md | 5+++++
Aeditor/app/api/ops/sync/route.test.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/sync/route.ts | 4+++-
Meditor/app/channels/[slug]/pipelineActions.ts | 20++++++++++++++++++++
Meditor/app/channels/components/ChannelSyncButton.tsx | 17+++++++++++++++--
Meditor/app/channels/components/channelColumns.tsx | 2+-
Meditor/app/components/dashboard/DashboardCockpit.tsx | 2+-
Meditor/e2e/social-channel.spec.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/playwright.config.ts | 1+
Mscripts/archilyzer-ops.mjs | 5++++-
Mscripts/queue-lock.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/queue-lock.test.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/render-queue/route.ts | 37+++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/link-policy/route.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/publish-site/route.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/speaker-check/route.ts | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 10++++++++++
Mumtool/components/projects/ClipBench.tsx | 3+++
Mumtool/components/projects/NewTakePanel.tsx | 2++
Aumtool/components/projects/RenderQueuePanel.tsx | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/SpeakerBadge.tsx | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/DecisionSettle.tsx | 21+++++++++++++++++----
Aumtool/components/projects/report/LinkPolicyPanel.tsx | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/OverviewTab.tsx | 5+++++
Aumtool/components/projects/report/ProjectSites.tsx | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 4+++-
Mumtool/docs/inbox.md | 2++
Mumtool/docs/knobs.md | 31+++++++++++++++++++++++++++++++
Mumtool/docs/report-video.md | 42+++++++++++++++++++++++++++++++++++++++++-
Mumtool/e2e/fixtures/editor-stub.mjs | 11+++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/ui-ops-fixture.mjs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/ui-ops.spec.ts | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/decisions.ts | 3++-
Mumtool/lib/inbox/groups.mjs | 2++
Mumtool/lib/inbox/what.mjs | 2++
Mumtool/lib/projects/report.mjs | 51++++++++++++++++++++++++++++++++++++++++++++++++++-
Aumtool/lib/report/linkPolicy.mjs | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/linksCli.mjs | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aumtool/lib/report/siteDeploys.mjs | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/speakerCheck.mjs | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takeEta.mjs | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/takeMaker.mjs | 18++++++++++++++++--
Mumtool/lib/report/takeMaker.test.mjs | 19+++++++++++++++++++
Aumtool/lib/report/ui-ops.test.mjs | 402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 5+++++
59 files changed, 3744 insertions(+), 31 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -128,7 +128,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | -| `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | +| `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. A social channel's sync is its post fetch (fetch-posts' new posts, its guards and refusals: for X a fresh cookie jar), never the video listing; "full" is refused there (fetch-posts "full": true re-walks the timeline). | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | | | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -263,6 +263,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_FIXTURE_MAX_LIFETIME_MS` | the watchdog's | How long a fake binary may live before its watchdog kills it. | editor/e2e/fixtures/bin/_watchdog.mjs | | `E2E_OLLAMA_STUB_MODEL` | `qwen2.5:7b` | The model the ollama stub claims to serve. | editor/e2e/fixtures/ollama-stub.mjs | | `E2E_RACK_SHOTS` | off (spec skipped) | Runs the `/channels` rack screenshot audit. | editor/e2e/channels-rack-audit.spec.ts | +| `E2E_UI_OPS_SHOTS` | off (no screenshots) | A directory: the social Sync tests (UI notes #17) write their screenshots there, for a review. | editor/e2e/social-channel.spec.ts | | `E2E_TWO_ORIGIN_REBUILD` | off | `1` rebuilds the two-origin suite's cached hub bundle. | export/e2e-2origin/globalSetup.ts | | `E2E_REPORT_SITE_REUSE` | off (build again) | `1` serves the cited report-site suite's existing stage build (`.e2e-report-site/out`) instead of staging and building the fixture site again — for iterating on the specs alone; it does not see a change to the app. | export/playwright.report.config.ts | | `E2E_SHARDS` | min(max(2, cpus/2), 8) | How many containers `pnpm e2e:sharded` splits the editor suite across (`--shards N` wins). | scripts/run-sharded-e2e.mjs | diff --git a/WORKTREES.md b/WORKTREES.md @@ -267,8 +267,11 @@ The pieces sit in the git common dir: `heavy-queue.lock` (the slot — held SHAR admitted weighted job, EXCLUSIVELY by a job that runs alone, so an older checkout's copy of the gate, which always takes it exclusively, still waits for every new-style job and is never joined by one), `heavy-queue.lock.admit` (the line), `heavy-queue.lock.build` (the -build slot) and `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its -estimate and what it is; a ticket whose process is gone is dropped). The kernel releases +build slot), `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its +estimate and what it is; a ticket whose process is gone is dropped) and +`heavy-queue.lock.waiting/<pid>.json` (one per job waiting for the slot, with where it waits: +`render`, `line`, `slot`, `memory`, `build`, `exclusive`; dropped once it is admitted). umtool's +take panel reads them all as its **Render queue** (`common/lib/heavyQueue.mjs`). The kernel releases every lock when its holder's fd closes. A machine whose MemTotal is under the floor is told so and runs one job at a time; with no usable `flock` the gate warns and runs on the floor alone — it is a safety net, not a correctness lock. diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -260,6 +260,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_FIXTURE_MAX_LIFETIME_MS", audience: "test", default: "the watchdog's", readBy: "editor/e2e/fixtures/bin/_watchdog.mjs", doc: "How long a fake binary may live before its watchdog kills it." }, { name: "E2E_OLLAMA_STUB_MODEL", audience: "test", default: "`qwen2.5:7b`", readBy: "editor/e2e/fixtures/ollama-stub.mjs", doc: "The model the ollama stub claims to serve." }, { name: "E2E_RACK_SHOTS", audience: "test", default: "off (spec skipped)", readBy: "editor/e2e/channels-rack-audit.spec.ts", doc: "Runs the `/channels` rack screenshot audit." }, + { name: "E2E_UI_OPS_SHOTS", audience: "test", default: "off (no screenshots)", readBy: "editor/e2e/social-channel.spec.ts", doc: "A directory: the social Sync tests (UI notes #17) write their screenshots there, for a review." }, { name: "E2E_TWO_ORIGIN_REBUILD", audience: "test", default: "off", readBy: "export/e2e-2origin/globalSetup.ts", doc: "`1` rebuilds the two-origin suite's cached hub bundle." }, { name: "E2E_REPORT_SITE_REUSE", audience: "test", default: "off (build again)", readBy: "export/playwright.report.config.ts", doc: "`1` serves the cited report-site suite's existing stage build (`.e2e-report-site/out`) instead of staging and building the fixture site again — for iterating on the specs alone; it does not see a change to the app." }, { name: "E2E_SHARDS", audience: "test", default: "min(max(2, cpus/2), 8)", readBy: "scripts/run-sharded-e2e.mjs", doc: "How many containers `pnpm e2e:sharded` splits the editor suite across (`--shards N` wins)." }, diff --git a/common/lib/heavyQueue.mjs b/common/lib/heavyQueue.mjs @@ -0,0 +1,178 @@ +// THE HEAVY SLOT, AS IT STANDS (UI notes 2026-10-30, #18: the render queue +// panel). Read from the slot's own files beside its lock (scripts/queue-lock.mjs, +// WORKTREES.md "The heavy slot") -- nothing here is guessed: +// +// heavy-queue.lock.jobs/<pid>.json one ticket per job RUNNING in the slot: +// its estimate, whether it builds or runs +// alone, its command, since when +// heavy-queue.lock.waiting/<pid>.json one ticket per job WAITING: the same, +// and its stage (render, line, slot, +// memory, build, exclusive, serial) +// heavy-queue.lock.admit.holder.json the job at the head of the line +// heavy-queue.lock.build.holder.json the build slot's holder (one next build at a time) +// heavy-queue.lock.render.json render mode (renderPriority.mjs) +// <name>-queue.lock.holder.json each e2e suite's own queue +// +// A ticket whose process is gone (or whose pid was reused) is not counted; +// this module never removes one -- queue-lock does that. Plain ESM: umtool's +// route and the CLI read it under bare node. +import fs from "node:fs"; +import path from "node:path"; +import { describeRenderPriority, holderAlive, readRenderPriority, renderPriorityFile } from "./renderPriority.mjs"; + +/** What a waiting job waits for, in words. */ +export const STAGE_WORDS = Object.freeze({ + door: "arriving", + render: "waiting for the render (render mode)", + line: "in line behind the job at the head", + slot: "at the head of the line, for the slot", + memory: "at the head of the line, for memory", + build: "for the build slot (one next build at a time)", + exclusive: "for a job that runs alone", + serial: "one job at a time (this machine is under the floor)", +}); + +/** A ticket's process is alive and is the one that wrote it. */ +const alive = (t, isAlive) => Number.isInteger(t?.pid) && isAlive({ pid: t.pid, pidStart: t.pidStart ?? null }); + +function readDir(dir, isAlive) { + let names = []; + try { + names = fs.readdirSync(/* turbopackIgnore: true */ dir).filter((n) => n.endsWith(".json")); + } catch { + return []; + } + const out = []; + for (const n of names) { + try { + const t = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ path.join(dir, n), "utf8")); + if (alive(t, isAlive)) out.push(t); + } catch { + /* half-written by queue-lock: skipped this time */ + } + } + return out; +} + +function readHolder(file, isAlive) { + try { + const h = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8")); + return alive(h, isAlive) ? h : null; + } catch { + return null; + } +} + +/** + * What a command is: a render (build-video.mjs; its project directory and take + * read from the manifest path it is given), an e2e suite, a next build, the + * encode ladder, or the command itself. + * @param {string} cmd + * @returns {{ kind: "render" | "e2e" | "build" | "ladder" | "other", label: string, projectDir?: string | null, take?: string | null }} + */ +export function classifyCommand(cmd) { + const c = String(cmd ?? ""); + if (/build-video\.mjs/.test(c)) { + // A take's render: `build-video.mjs <project>/.take-<id>.render.json --out <project>/takes/<id>/out` + // (umtool/lib/report/takeRender.mjs); a project build: `build-video.mjs <project>/video.manifest.json`. + const after = c.slice(c.indexOf("build-video.mjs") + "build-video.mjs".length).trim(); + const man = after.split(/\s+/)[0] ?? ""; + const take = /(?:^|\/)\.take-([a-z0-9][a-z0-9-]*)\.render\.json$/.exec(man)?.[1] ?? /\/takes\/([a-z0-9][a-z0-9-]*)\/out(?:\s|$)/.exec(after)?.[1] ?? null; + const projectDir = man.includes("/") ? man.slice(0, man.lastIndexOf("/")) : null; + const name = projectDir ? projectDir.split("/").slice(-2).join("/") : null; + return { kind: "render", label: take ? `render of ${take}${name ? ` (${name})` : ""}` : `render${name ? ` of ${name}` : ""}`, projectDir, take }; + } + if (/variants|ladder/.test(c) && /umtool/.test(c)) return { kind: "ladder", label: "the encode ladder (variants)" }; + if (/playwright|run-sharded-e2e|\be2e\b/.test(c)) { + const suite = /--name (e2e-[a-z0-9-]+)/.exec(c)?.[1] ?? /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null; + return { kind: "e2e", label: suite ? `e2e suite ${suite}` : "an e2e suite" }; + } + if (/next build/.test(c)) { + const pkg = /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null; + return { kind: "build", label: pkg ? `next build (${pkg})` : "a next build" }; + } + return { kind: "other", label: c.length > 90 ? `${c.slice(0, 90)}…` : c }; +} + +const shape = (t, now) => { + const what = classifyCommand(t.cmd); + const started = Date.parse(t.since ?? t.startedAt ?? ""); + return { + pid: t.pid, + what: what.label, + kind: what.kind, + ...(what.projectDir ? { projectDir: what.projectDir } : {}), + ...(what.take ? { take: what.take } : {}), + estimateMb: Number.isFinite(t.estimateMb) ? t.estimateMb : null, + build: Boolean(t.build), + alone: Boolean(t.exclusive), + worktree: t.worktree ? path.basename(String(t.worktree)) : null, + branch: t.branch ?? null, + cmd: String(t.cmd ?? ""), + since: Number.isFinite(started) ? new Date(started).toISOString() : null, + forSeconds: Number.isFinite(started) ? Math.max(0, Math.round((now - started) / 1000)) : null, + }; +}; + +/** + * The slot now. + * @param {{ heavyLock: string, renderFile?: string, env?: Record<string, string | undefined>, now?: number, isAlive?: (h: { pid: number, pidStart: string | null }) => boolean, meminfo?: string }} o + */ +export function readHeavyQueue({ heavyLock, renderFile, env = process.env, now = Date.now(), isAlive = holderAlive, meminfo = "/proc/meminfo" }) { + const running = readDir(`${heavyLock}.jobs`, isAlive).map((t) => shape(t, now)).sort((a, b) => String(a.since).localeCompare(String(b.since))); + const waiting = readDir(`${heavyLock}.waiting`, isAlive) + .map((t) => ({ + ...shape(t, now), + stage: String(t.stage ?? "door"), + stageWords: STAGE_WORDS[/** @type {keyof typeof STAGE_WORDS} */ (t.stage)] ?? String(t.stage ?? ""), + })) + // The head of the line first, then by arrival. + .sort((a, b) => Number(b.stage !== "line" && b.stage !== "render" && b.stage !== "door") - Number(a.stage !== "line" && a.stage !== "render" && a.stage !== "door") || String(a.since).localeCompare(String(b.since))); + const head = readHolder(`${heavyLock}.admit.holder.json`, isAlive); + const build = readHolder(`${heavyLock}.build.holder.json`, isAlive); + // An older copy of queue-lock writes no ticket, only the slot's holder file. + const holder = running.length ? null : readHolder(`${heavyLock}.holder.json`, isAlive); + const dir = path.dirname(heavyLock); + const suites = []; + try { + for (const n of fs.readdirSync(/* turbopackIgnore: true */ dir)) { + const m = /^(e2e(?:-[a-z0-9-]+)?)-queue\.lock\.holder\.json$/.exec(n); + if (!m) continue; + const h = readHolder(path.join(dir, n), isAlive); + if (h) suites.push({ suite: m[1], ...shape(h, now) }); + } + } catch { + /* no lock dir yet */ + } + // An e2e suite's slot ticket names only its command ("playwright test"): its + // name is the suite queue its process holds. + for (const r of [...running, ...waiting]) { + if (r.kind !== "e2e") continue; + const names = suites.filter((x) => x.pid === r.pid).map((x) => x.suite); + if (names.length) r.what = `e2e suite ${names[0]}${names.length > 1 ? ` (and ${names.slice(1).join(", ")})` : ""}`; + } + const rp = readRenderPriority(renderFile ?? renderPriorityFile(env, { heavyLock })); + let mem = null; + try { + const text = fs.readFileSync(/* turbopackIgnore: true */ meminfo, "utf8"); + const kb = (k) => Number(new RegExp(`^${k}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? NaN); + const a = kb("MemAvailable"); + const t = kb("MemTotal"); + if (Number.isFinite(a)) mem = { availableMb: Math.round(a / 1024), totalMb: Number.isFinite(t) ? Math.round(t / 1024) : null }; + } catch { + mem = null; + } + const floor = Number(env.HEAVY_MIN_FREE_MB ?? 6000); + const promised = running.reduce((n, r) => n + (r.estimateMb ?? 0), 0); + return { + heavyLock, + running: holder && !running.length ? [shape(holder, now)] : running, + waiting, + head: head ? shape(head, now) : null, + build: build ? shape(build, now) : null, + suites: suites.sort((a, b) => a.suite.localeCompare(b.suite)), + render: rp.held && rp.state ? { held: true, what: describeRenderPriority(rp.state), since: rp.state.since ?? null, until: rp.state.until ?? null } : { held: false }, + memory: mem ? { ...mem, floorMb: Number.isFinite(floor) ? floor : 6000, promisedMb: promised } : null, + heldBy: running.length ? running.map((r) => r.what).join("; ") : holder ? classifyCommand(holder.cmd).label : null, + }; +} diff --git a/common/lib/heavyQueue.test.ts b/common/lib/heavyQueue.test.ts @@ -0,0 +1,82 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { classifyCommand, readHeavyQueue } from "./heavyQueue.mjs"; + +// The render queue panel's reader (UI notes 2026-10-30, #18): the heavy slot +// as its own files say, never guessed. A live ticket is this process's pid; a +// dead one a pid nothing runs as. + +function slot() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "heavy-queue-")); + const lock = path.join(dir, "heavy-queue.lock"); + const put = (file: string, doc: unknown) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(doc)); + }; + return { dir, lock, put, done: () => fs.rmSync(dir, { recursive: true, force: true }) }; +} + +const LIVE = process.pid; +const DEAD = 2 ** 22 + 12345; +const isAlive = (h: { pid: number }) => h.pid === LIVE || h.pid === LIVE + 1 || h.pid === LIVE + 2; + +test("classifyCommand: a take's render names its take and project; a suite, a build", () => { + assert.deepEqual( + classifyCommand("node /x/umtool/report-to-video/build-video.mjs /r/reports/ember/cut/.take-draft-3.render.json --out /r/reports/ember/cut/takes/draft-3/out --progress ndjson"), + { kind: "render", label: "render of draft-3 (ember/cut)", projectDir: "/r/reports/ember/cut", take: "draft-3" }, + ); + assert.equal(classifyCommand("node build-video.mjs /r/p/video.manifest.json").label, "render of r/p"); + assert.equal(classifyCommand("playwright test a.spec.ts").kind, "e2e"); + assert.equal(classifyCommand("systemd-run --user --scope -p MemoryMax=5G pnpm --filter export exec next build").label, "next build (export)"); +}); + +test("readHeavyQueue: running and waiting tickets (the dead ones not), the head of the line, the suites, render mode, memory", () => { + const s = slot(); + try { + const at = (min: number) => new Date(Date.parse("2026-11-02T10:00:00Z") + min * 60_000).toISOString(); + s.put(`${s.lock}.jobs/${LIVE}.json`, { pid: LIVE, estimateMb: 1500, build: false, exclusive: false, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: at(0) }); + s.put(`${s.lock}.jobs/${DEAD}.json`, { pid: DEAD, estimateMb: 5000, cmd: "next build", startedAt: at(0) }); + s.put(`${s.lock}.waiting/${LIVE + 1}.json`, { pid: LIVE + 1, estimateMb: 6020, cmd: "node build-video.mjs /r/reports/ember/cut/.take-draft-9.render.json --out /r/reports/ember/cut/takes/draft-9/out", since: at(2), stage: "memory" }); + s.put(`${s.lock}.waiting/${LIVE + 2}.json`, { pid: LIVE + 2, estimateMb: 5120, build: true, cmd: "pnpm --filter editor exec next build", since: at(1), stage: "line" }); + s.put(`${s.lock}.admit.holder.json`, { pid: LIVE + 1, cmd: "node build-video.mjs …", startedAt: at(2) }); + s.put(path.join(s.dir, "e2e-umtool-queue.lock.holder.json"), { pid: LIVE, cmd: "playwright test", startedAt: at(-1) }); + s.put(path.join(s.dir, "e2e-editor-queue.lock.holder.json"), { pid: DEAD, cmd: "playwright test", startedAt: at(-1) }); + const mem = path.join(s.dir, "meminfo"); + fs.writeFileSync(mem, "MemTotal: 16282624 kB\nMemAvailable: 8388608 kB\n"); + const q = readHeavyQueue({ heavyLock: s.lock, renderFile: path.join(s.dir, "none.json"), env: {}, now: Date.parse(at(3)), isAlive, meminfo: mem }); + assert.deepEqual(q.running.map((r) => [r.pid, r.what, r.estimateMb, r.worktree, r.forSeconds]), [[LIVE, "e2e suite e2e-umtool", 1500, "lane-a", 180]]); + // The head of the line first (it waits for memory), then the one behind it. + assert.deepEqual(q.waiting.map((w) => [w.pid, w.stage, w.what]), [ + [LIVE + 1, "memory", "render of draft-9 (ember/cut)"], + [LIVE + 2, "line", "next build (editor)"], + ]); + assert.equal(q.waiting[0].stageWords, "at the head of the line, for memory"); + assert.equal(q.waiting[0].take, "draft-9"); + assert.equal(q.head?.pid, LIVE + 1); + assert.deepEqual(q.suites.map((x) => x.suite), ["e2e-umtool"]); + assert.deepEqual(q.render, { held: false }); + assert.deepEqual(q.memory, { availableMb: 8192, totalMb: 15901, floorMb: 6000, promisedMb: 1500 }); + assert.equal(q.heldBy, "e2e suite e2e-umtool"); + // Nothing was removed: queue-lock owns the files. + assert.ok(fs.existsSync(`${s.lock}.jobs/${DEAD}.json`)); + } finally { + s.done(); + } +}); + +test("readHeavyQueue: an empty slot, and render mode holding the machine", () => { + const s = slot(); + try { + const renderFile = path.join(s.dir, "heavy-queue.lock.render.json"); + s.put(renderFile, { token: "t", since: "2026-11-02T10:00:00.000Z", until: "2099-01-01T00:00:00.000Z", by: "umtool take", holder: { pid: LIVE, cmd: "umtool take", project: "ember/cut", take: "draft-9" }, lanesHeld: [] }); + const q = readHeavyQueue({ heavyLock: s.lock, renderFile, env: {}, isAlive, meminfo: path.join(s.dir, "no-meminfo") }); + assert.deepEqual([q.running, q.waiting, q.head, q.build, q.suites, q.memory, q.heldBy], [[], [], null, null, [], null, null]); + assert.equal(q.render.held, true); + assert.match(String((q.render as { what?: string }).what), /^umtool take, since /); + } finally { + s.done(); + } +}); diff --git a/common/lib/montage/speakerCheck.mjs b/common/lib/montage/speakerCheck.mjs @@ -0,0 +1,206 @@ +// THE SPEAKER CHECK (UI notes 2026-10-30, #15): which of SEVERAL named voices +// a clip is -- "Speaker: matches Ember 0.93 / Kirsche 0.83" -- where the voice +// match (voiceMatch.mjs, release 34) scores every clip against ONE voice, the +// host's. Panel shows (Side Scrollers, Kirsche) were attributed this way by +// hand in scratch projects; this is the same arithmetic as a project's own +// file. +// +// The pieces are voiceMatch.mjs's, unchanged: a span decoded at 16 kHz mono on +// the window's own clock, the voiced-frames gate (a fallback span when the +// phrase holds too little speech), ONE embedding process for every clip and +// every reference piece (TitaNet-small through sherpa-onnx, or the test kit's +// fake embedder), a robust centroid per voice, the cosine to it. Each named +// reference set ("speaker") is clips of the cut, or reference pieces of +// recordings; a clip that is itself in a speaker's set is scored against the +// rest of that set (leave-one-out). Deterministic for a given model and input; +// no network; nothing rules -- the verification is still a person listening. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + DEFAULT_THRESHOLDS, + FALLBACK_SPEECH_S, + MIN_SPEECH_S, + SAMPLE_RATE, + VOICE_MATCH_MODEL, + decodeSpan, + embedWavs, + encodeWav16, + robustCentroid, + scoreAgainst, + voicedSamples, +} from "./voiceMatch.mjs"; + +export const SPEAKER_CHECK_FILE = "speaker-check.json"; +export const SPEAKER_CHECK_VERSION = 1; +/** A best voice this far ahead of the next is a match; closer is unsure. */ +export const SPEAKER_MARGIN = 0.05; + +const round = (x, n = 3) => Math.round(x * 10 ** n) / 10 ** n; + +/** + * A clip's verdict from its scores (best first): `matches` (the best at or + * over `likely` and SPEAKER_MARGIN ahead of the next), `none` (every voice + * under `unlikely`: someone the reference sets do not hold), else `unsure`. + * @param {{ name: string, score: number }[]} scores + */ +export function speakerVerdict(scores, t = DEFAULT_THRESHOLDS) { + const [a, b] = scores; + if (!a) return { label: /** @type {const} */ ("unsure"), best: null, margin: null }; + const margin = b ? round(a.score - b.score) : null; + if (a.score < t.unlikely) return { label: /** @type {const} */ ("none"), best: a.name, margin }; + if (a.score >= t.likely && (margin === null || margin >= SPEAKER_MARGIN)) return { label: /** @type {const} */ ("matches"), best: a.name, margin }; + return { label: /** @type {const} */ ("unsure"), best: a.name, margin }; +} + +/** + * Score `clips` against every named voice in `speakers`. + * + * @param {{ + * clips: Array<{ key: string, id?: string | null, file: string | null, start: number, dur: number, fallback?: { start: number, dur: number } | null, missing?: string }>, + * check?: string[], the keys to score (default every clip); the rest are only reference + * speakers: Array<{ name: string, clipKeys?: string[], items?: Array<{ key: string, file: string, start: number, dur: number, label?: string }>, recordings?: unknown[] }>, + * engine: { python: string, script: string, model: string, threads?: number }, + * scratch: string, + * thresholds?: { likely: number, unlikely: number }, + * ffmpeg?: string, + * now?: () => Date, + * onProgress?: (e: { event: string, n?: number, of?: number, items?: number }) => void, + * }} o + */ +export async function runSpeakerCheck(o) { + const t = o.thresholds ?? DEFAULT_THRESHOLDS; + const emit = o.onProgress ?? (() => {}); + const scratch = o.scratch; + await rm(scratch, { recursive: true, force: true }); + await mkdir(scratch, { recursive: true }); + const check = new Set(o.check ?? o.clips.map((c) => c.key)); + const refClipKeys = new Set(o.speakers.flatMap((s) => s.clipKeys ?? [])); + + /** @type {Map<string, { seconds: number, wav: string | null, why?: string, fallback?: boolean }>} */ + const prepared = new Map(); + const voiced = async (file, start, dur) => voicedSamples(await decodeSpan(file, start, dur, { ffmpeg: o.ffmpeg })); + const prepare = async (id, file, start, dur, fallback = null) => { + let v; + let usedFallback = false; + try { + v = await voiced(file, start, dur); + if (fallback && v.seconds < FALLBACK_SPEECH_S) { + const w = await voiced(file, fallback.start, fallback.dur); + if (w.seconds > v.seconds) { + v = w; + usedFallback = true; + } + } + } catch (e) { + prepared.set(id, { seconds: 0, wav: null, why: `decode failed: ${e instanceof Error ? e.message : String(e)}` }); + return; + } + if (v.seconds < MIN_SPEECH_S) { + prepared.set(id, { seconds: v.seconds, wav: null, why: "too little speech", fallback: usedFallback }); + return; + } + const wav = path.join(scratch, `${prepared.size.toString().padStart(4, "0")}.wav`); + await writeFile(wav, encodeWav16(v.samples)); + prepared.set(id, { seconds: v.seconds, wav, fallback: usedFallback }); + }; + const wanted = o.clips.filter((c) => check.has(c.key) || refClipKeys.has(c.key)); + let k = 0; + for (const c of wanted) { + k += 1; + if (c.file) await prepare(`clip:${c.key}`, c.file, c.start, c.dur, c.fallback ?? null); + emit({ event: "decode", n: k, of: wanted.length }); + } + for (const s of o.speakers) for (const r of s.items ?? []) await prepare(`ref:${s.name}:${r.key}`, r.file, r.start, r.dur); + + const batch = [...prepared].filter(([, p]) => p.wav).map(([id, p]) => ({ id, wav: /** @type {string} */ (p.wav) })); + emit({ event: "embed", items: batch.length }); + const emb = batch.length ? await embedWavs(batch, o.engine, scratch) : { model: path.basename(o.engine.model), version: null, dim: 0, items: new Map() }; + const vec = (id) => emb.items.get(id)?.embedding ?? null; + + // Each voice: its pieces, the outliers out. + const voices = o.speakers.map((s) => { + const all = [ + ...(s.clipKeys ?? []).map((key) => ({ key: `clip:${key}`, clipKey: key, vector: vec(`clip:${key}`) })), + ...(s.items ?? []).map((r) => ({ key: `ref:${s.name}:${r.key}`, clipKey: null, vector: vec(`ref:${s.name}:${r.key}`) })), + ].filter((r) => r.vector); + const robust = robustCentroid(all.map((r) => /** @type {number[]} */ (r.vector))); + const kept = robust.kept.map((i) => all[i]); + return { + name: s.name, + kept, + doc: { + name: s.name, + clips: [...(s.clipKeys ?? [])], + recordings: s.recordings ?? [], + pieces: (s.clipKeys?.length ?? 0) + (s.items?.length ?? 0), + embedded: all.length, + kept: kept.length, + dropped: robust.dropped.map((i) => all[i].clipKey ?? all[i].key.replace(/^ref:[^:]*:/, "")), + }, + }; + }); + + /** @type {Record<string, Record<string, unknown>>} */ + const clips = {}; + for (const c of o.clips) { + if (!check.has(c.key)) continue; + const p = prepared.get(`clip:${c.key}`); + const v = vec(`clip:${c.key}`); + /** @type {Record<string, unknown>} */ + const row = { speechSeconds: round(p?.seconds ?? 0, 2), scores: [] }; + if (c.id) row.id = c.id; + if (p?.fallback) row.fallback = true; + if (!c.file) row.why = c.missing ?? "no window"; + else if (!p?.wav) row.why = p?.why ?? "not decoded"; + else if (!v) row.why = emb.items.get(`clip:${c.key}`)?.error ?? "not embedded"; + else { + const scores = []; + for (const voice of voices) { + const s = scoreAgainst(v, voice.kept.map((r) => ({ key: r.key, vector: /** @type {number[]} */ (r.vector) })), { selfKey: `clip:${c.key}` }); + if (s.score == null) continue; + scores.push({ name: voice.name, score: s.score, best: s.best, ...(voice.kept.some((r) => r.clipKey === c.key) ? { inReference: true } : {}) }); + } + scores.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)); + row.scores = scores; + if (!scores.length) row.why = "no reference voice has pieces to compare with"; + else Object.assign(row, speakerVerdict(scores, t)); + } + clips[c.key] = row; + } + await rm(scratch, { recursive: true, force: true }); + return { + version: SPEAKER_CHECK_VERSION, + model: VOICE_MATCH_MODEL, + engine: { file: emb.model, sherpaOnnx: emb.version, dim: emb.dim, sampleRate: SAMPLE_RATE }, + madeAt: (o.now ? o.now() : new Date()).toISOString(), + thresholds: { likely: t.likely, unlikely: t.unlikely, margin: SPEAKER_MARGIN }, + speakers: voices.map((v) => v.doc), + clips, + }; +} + +/** `<project>/speaker-check.json`, or null. */ +export async function readSpeakerCheck(dir) { + try { + const doc = JSON.parse(await readFile(path.join(dir, SPEAKER_CHECK_FILE), "utf8")); + return doc && doc.version === SPEAKER_CHECK_VERSION && doc.clips && typeof doc.clips === "object" ? doc : null; + } catch { + return null; + } +} + +/** + * Written whole (tmp + rename), MERGED into the file there: a check of one + * clip keeps the other clips' rows -- when they were scored against the same + * voices (by name and pieces); a change of the reference sets starts over. + */ +export async function writeSpeakerCheck(dir, doc) { + const file = path.join(dir, SPEAKER_CHECK_FILE); + 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`; + await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`); + await rename(tmp, file); + return { file, doc: merged }; +} diff --git a/common/lib/montage/speakerCheck.test.ts b/common/lib/montage/speakerCheck.test.ts @@ -0,0 +1,75 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { encodeWav16 } from "./voiceMatch.mjs"; +import { SPEAKER_CHECK_FILE, readSpeakerCheck, runSpeakerCheck, speakerVerdict, writeSpeakerCheck } from "./speakerCheck.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice } from "../../testing/audio/syntheticVoice.mjs"; +import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs"; + +// The speaker check (UI notes 2026-10-30, #15): which of several named voices +// a clip is. Two synthetic voices the test kit's fake embedder tells apart; +// no python, no model. + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FAKE = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const FAKE_ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx", threads: 1 }; +const tmp = () => mkdtempSync(path.join(os.tmpdir(), "speaker-check-")); +const wav = (dir: string, name: string, x: Float32Array) => { + const f = path.join(dir, name); + writeFileSync(f, encodeWav16(x)); + return f; +}; + +test("speakerVerdict: matches when the best is over the bar and ahead by the margin; none under the floor; else unsure", () => { + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.93 }, { name: "Kirsche", score: 0.83 }]), { label: "matches", best: "Ember", margin: 0.1 }); + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.62 }, { name: "Kirsche", score: 0.6 }]), { label: "unsure", best: "Ember", margin: 0.02 }); + assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.2 }]), { label: "none", best: "Ember", margin: null }); + assert.deepEqual(speakerVerdict([]), { label: "unsure", best: null, margin: null }); +}); + +test("runSpeakerCheck: each clip against every named voice, best first; a voice's own clip is scored against the rest of it", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => { + const dir = tmp(); + try { + const a = [0.4, 1.1, 2.2].map((ph, i) => wav(dir, `a${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: ph }))); + const b = [0.7, 1.9].map((ph, i) => wav(dir, `b${i}.wav`, syntheticVoice({ ...VOICE_B, seconds: 2.5, phase: ph }))); + const probe = wav(dir, "probe.wav", syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: 3.3 })); + const clip = (key: string, file: string) => ({ key, id: key, file, start: 0, dur: 2.5 }); + const doc = await runSpeakerCheck({ + clips: [clip("a0", a[0]), clip("a1", a[1]), clip("p", probe)], + check: ["p", "a0"], + speakers: [ + { name: "Host", clipKeys: ["a0", "a1"], items: [{ key: "r2", file: a[2], start: 0, dur: 2.5 }] }, + { name: "Guest", items: b.map((f, i) => ({ key: `g${i}`, file: f, start: 0, dur: 2.5 })) }, + ], + engine: FAKE_ENGINE, + scratch: path.join(dir, "scratch"), + now: () => new Date("2026-11-02T10:00:00Z"), + }); + const p = doc.clips.p as { scores: { name: string; score: number }[]; label: string; best: string }; + assert.deepEqual(p.scores.map((s) => s.name), ["Host", "Guest"]); + assert.equal(p.label, "matches"); + assert.equal(p.best, "Host"); + assert.ok(p.scores[0].score > p.scores[1].score + 0.05, JSON.stringify(p.scores)); + // a0 is in Host's set: scored against a1 and r2, and says so. + const a0 = doc.clips.a0 as { scores: { name: string; inReference?: boolean }[]; label: string }; + assert.equal(a0.scores[0].name, "Host"); + assert.equal(a0.scores[0].inReference, true); + assert.equal("a1" in doc.clips, false, "a reference clip not asked for is not a row"); + assert.deepEqual(doc.speakers.map((s: { name: string; pieces: number; kept: number }) => [s.name, s.pieces, s.kept]), [["Host", 3, 3], ["Guest", 2, 2]]); + // The file merges a later check of one clip into the rows there. + await writeSpeakerCheck(dir, doc); + const again = { ...doc, clips: { p: { ...p, label: "unsure" } } }; + const { doc: merged } = await writeSpeakerCheck(dir, again); + assert.deepEqual(Object.keys(merged.clips).sort(), ["a0", "p"]); + assert.equal((await readSpeakerCheck(dir))?.clips.p && (merged.clips.p as { label: string }).label, "unsure"); + // New reference sets start the file over. + const { doc: fresh } = await writeSpeakerCheck(dir, { ...again, speakers: [{ ...doc.speakers[0], name: "Renamed" }] }); + assert.deepEqual(Object.keys(fresh.clips), ["p"]); + assert.ok(SPEAKER_CHECK_FILE.endsWith(".json")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs @@ -100,11 +100,19 @@ function gitCommonDir(cwd) { */ export function renderPriorityFile(env = process.env, { heavyLock = null, root = process.cwd() } = {}) { if (env.RENDER_PRIORITY_FILE) return env.RENDER_PRIORITY_FILE; - const lock = - heavyLock ?? - env.HEAVY_LOCK_FILE ?? - path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME); - return `${lock}${STATE_SUFFIX}`; + return `${heavyLock ?? heavyLockFile(env, { root })}${STATE_SUFFIX}`; +} + +/** + * The heavy slot's lock, as queue-lock.mjs finds it: HEAVY_LOCK_FILE, else + * `heavy-queue.lock` in the git common dir of `root` (one for every + * worktree), a tmpdir outside a git checkout. Its running and waiting + * tickets sit beside it (common/lib/heavyQueue.mjs reads them). + * @param {Record<string, string | undefined>} [env] + * @param {{ root?: string }} [opts] + */ +export function heavyLockFile(env = process.env, { root = process.cwd() } = {}) { + return env.HEAVY_LOCK_FILE ?? path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME); } /** The file's JSON, or null (missing, half-written, not ours). */ diff --git a/common/package.json b/common/package.json @@ -47,8 +47,10 @@ "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs", "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs", "./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs", + "./lib/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs", "./lib/ports.mjs": "./lib/ports.mjs", "./lib/renderPriority.mjs": "./lib/renderPriority.mjs", + "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", "./lib/report/look.mjs": "./lib/report/look.mjs", "./lib/report/intro.mjs": "./lib/report/intro.mjs", diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts @@ -114,6 +114,12 @@ test("the view carries no config, only the fields a cell draws", () => { assert.equal(bare.lastSyncedAt, null); }); +test("social: a posts channel's row says so, so its Sync button runs fetch-posts (UI notes #17)", () => { + assert.equal(buildChannelRowView(input()).social, false); + const x = buildChannelRowView(input({ config: { handling: "youtube", url: "https://x.com/someone", sourceKind: "social" } as ChannelConfig })); + assert.equal(x.social, true); +}); + test("media: in-place is dropped; the label is the volume's unless overridden", () => { const inPlace = buildChannelRowView( input({ media: { status: "in-place", target: "/x", detail: "" } }), diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts @@ -1,5 +1,5 @@ import { channelDownloadsAreManual } from "../lib/manualDownloads"; -import type { ChannelConfig } from "../lib/channelConfig"; +import { isSocialChannel, type ChannelConfig } from "../lib/channelConfig"; import type { ChannelSnapshot } from "../controller/channelSnapshot"; import type { ChannelMediaLocation } from "../lib/channelMedia"; import { mediaHoldText } from "../lib/channelMediaHold"; @@ -82,6 +82,9 @@ export type ChannelRowView = { handling: ChannelConfig["handling"]; // Whether the channel has a URL — Sync and Download need one. hasUrl: boolean; + // A social (posts) channel: its Sync runs fetch-posts, never the yt-dlp + // listing (UI notes 2026-10-30, #17), and the button says so. + social: boolean; excludeFromBuild: boolean; lastSyncedAt: string | null; // The playlist file's line count; null when there is no playlist file. @@ -195,6 +198,7 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView { name: i.config.name ?? "", handling: i.config.handling, hasUrl: Boolean(i.config.url), + social: isSocialChannel(i.config), excludeFromBuild: i.config.excludeFromBuild === true, lastSyncedAt: i.config.lastSyncedAt ?? null, playlistCount: i.playlistCount, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog ## [Unreleased] +- **Sync on an X, Bluesky or forum channel fetches its posts.** The Sync button on a social channel ran yt-dlp's video listing against the profile and failed. Every Sync — the channel rows', the dashboard's, a group's, Sync all, `pnpm ops sync`, a sync job's Retry — now runs the channel's post fetch (the same job as the channel page's Fetch posts: on the platform's queue, paced, and for X only on a fresh cookie jar), and a refusal is its own sentence beside the button. A full sweep is the video listing's, so a Sync never starts a social channel's whole re-walk; that is still Fetch posts → Re-fetch full history. +- **A report video's project page names the sites its links depend on, and says when one is behind.** Each site a clip's QR opens is listed with its deploy's date (its `corpus.json`, read by Check links) and the cited videos newer than it — uploaded or transcribed after it, and not found on it — and the check's new `site-deploy-behind` row offers **Publish <site>**, which asks the editor to build and deploy it. +- **A per-project link policy: cite via one site, these channels direct.** The Ember cut's citeUrls were rewritten by hand twice to send two channels to anilyzer and one to YouTube. A project's **Link policy** (Overview, or `umtool link-policy <p> --via <site> --direct a,b`) now says it once: new clips are written by it, and every clip that breaks it is a check row with a one-press fix (`umtool link-policy <p> --fix` for all). +- **The take panel shows the render queue and how long a take will take.** What runs in the machine's heavy slot and what waits there — e2e suites, builds, renders, and what each waits for — read from the slot's own files ("held by e2e suite e2e-editor"), and an ETA for a whole-cut take of the project, fresh and made from the newest take, from how long its past renders took. A take now records its render's own time (`renderSeconds`). +- **The walk checks who is speaking against several named voices.** The clip bench's verdict bar shows *Speaker: matches Ember 0.93 / Kirsche 0.83* with the reference sets it used, and **Check speaker** scores the clip (TitaNet-small, local, as a job through the heavy slot); the voices are the project's `speakers.json` (**Add to a voice**, or `umtool speaker-check <p> --set 'Ember=e01,e07'`). - **X has a cookie banner like Rumble's, and says how fresh its jar is.** X's banner used to go up only when X answered a fetch with a challenge, so an X fetch on an old jar was simply refused with a sentence the operator saw only in a job's error. Now the fresh-jar rule's refusal (`social.x.maxCookieAgeMinutes`, an hour by default) puts an **X needs fresh cookies** banner on the dashboard — "press Refresh cookies (or Connect X account) on /settings — with the browser login, open x.com in firefox" — with the jar's age under it, read from disk: the exported jar's time, or, with the browser login, when Firefox last sent its x.com `auth_token` (read by the cookie's name from a private copy of Firefox's cookie store; its value is never read). An X fetch refused at its start is offered under **Re-run stopped jobs** once the jar is fresh. Recheck re-reads the age and asks X nothing; the banner clears by itself as soon as an X job passes the rule on a fresh jar. This banner does not itself refuse X jobs (the rule does); a real challenge or login failure from X replaces it with the one that does. gallery-dl's own words are now read more carefully: its "AuthRequired: authenticated cookies needed to access this timeline" (what X answers a logged-out timeline with), "Could not authenticate you", a 401 and an API 403 count as a **login failure** (worded so on the banner and in the refusal), a 429 or "rate limit" is pacing and never raises the banner, and a protected or blocking account, an NSFW or protected tweet and a 403 on a twimg.com media file are about that one account or file — those used to raise X's banner and stop every X job. `pnpm ops get services` now always carries `x` (the jar's source, age, limit and whether an X job could start on it). Needs a restart of the editor. - **Rumble's cookies are checked on a timer, so the banner goes up before a sync fails.** Until now a stale Cloudflare clearance was noticed only when a Rumble sync or clip fetch failed on it. Every 3 hours (stretched a little at random, never shortened) the editor now looks by itself: when Rumble has been idle that long, it asks Rumble once for the last video it answered cleanly — a refusal is checked once more on the previous, different video a minute or more later, because a removed video refuses too, and two different videos refused put the banner up; every banner already up is rechecked once, as its Recheck button does, so it clears by itself after rumble.com was opened in Firefox; and X's jar age is re-read from disk (X jobs queued on an old jar put X's banner up before their start refuses them). Nothing is asked while a job is queued or running on Rumble's queues (its answer is the check), while Rumble is cooling down or held, or while a recheck runs, and a failed check is never retried — it waits for the next tick or a click. Each check is a **Recheck service cookies** job on /jobs. `settings.serviceCookies.recheckIntervalMinutes` (180; 30–1440; 0 turns it off) and `probeServices` (`["rumble"]`; YouTube and Odysee may be added), set with `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`; `pnpm ops get services` shows the timer's last tick under `timer`. Not on an idle boot. Needs a restart of the editor. - **A channel can download only the videos you add.** The operator wanted Harmful Opinions downloaded by hand, with its title filter gone, and nothing said that: `syncIntervalMinutes: 0` stops the listing but the download lane still works the backlog it has — and dropping a filter re-decides every video it had settled, so the whole channel would come down — while a `paused` tier stops every lane, transcription too. Configure → Advanced → **Downloads**: Manual (`downloadMode: "manual"` in config.json; `pnpm ops channel-config --json '{"slug":"<slug>","patch":{"downloadMode":"manual"}}'`, `""` sets it back to Automatic). On a manual channel the download lane skips the channel (its backlog, retries, metadata scan and chat backlog); a sync reads only the newest page of the listing and a full sweep still refreshes the playlist and the maybe-missing set, and neither downloads the new uploads it finds; Download from playlist, Download videos (`download-missing`) and the bucket retries refuse with a notice. What you ask for still downloads — Import, `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows, a whole-recording fetch — and the videos on disk are still transcribed. The channel's report keeps the listed videos it lacks as **Listed, not requested** (`manualNotRequestedIds`) rather than undownloaded work, so no lane, rack figure, dashboard count or group Download button counts them, and a video that leaves the listing unfetched is not raised as never fetched; the channel page says "Manual downloads — only videos you add are downloaded" at the top and the rack row carries a **manual dl** chip. An import still passes the channel's download filter, so set the mode first and then clear the filter. Needs a restart of the editor. diff --git a/editor/app/api/ops/sync/route.test.ts b/editor/app/api/ops/sync/route.test.ts @@ -0,0 +1,76 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/sync/route.test.ts" +// +// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): Sync on +// an X channel ran yt-dlp against the profile and failed. Every case here is a +// refusal answered before any job, from a temp corpus: the X channel has no +// cookie jar, so fetch-posts' own guard refuses it in its own sentence — which +// is how this knows the sync went to fetch-posts and not the video listing — +// and nothing reaches X. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "sync-route-")); +// Set before the route (and getPaths, which caches) is first imported. +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const channel = async (slug: string, config: Record<string, unknown>) => { + await mkdir(path.join(ROOT, "channels", slug), { recursive: true }); + await writeFile(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config)); +}; +await channel("demo-x", { + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "x-gallery-dl", + socialHandle: "example_user", + name: "Example (X)", + url: "https://x.com/example_user", +}); +await channel("demo-pages", { + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + name: "Example pages", + url: "https://web.archive.org/web/2020/https://example.test/", +}); +const { POST } = await import("./route"); +const { WAYBACK_PAGES_NOT_FETCHED } = await import("yt-dlp-transcript-common/controller/fetchPosts"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +async function post(body: Record<string, unknown>): Promise<{ status: number; error: string }> { + const res = await POST( + new Request("http://localhost/api/ops/sync", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, error: ((await res.json()) as { error?: string }).error ?? "" }; +} + +const jobs = () => readdir(path.join(ROOT, ".jobs")).catch(() => []); + +test("an X channel's sync is fetch-posts: refused on no cookie jar, in the post fetch's own words, before any job", async () => { + const res = await post({ slug: "demo-x" }); + assert.notEqual(res.status, 200); + assert.match(res.error, /^No X cookie jar has been exported: press Connect X account on \/settings, then fetch again\.$/); + assert.deepEqual(await jobs(), []); +}); + +test("a Wayback pages channel's sync is its post fetch too, which says such a channel is never fetched", async () => { + const res = await post({ slug: "demo-pages" }); + assert.equal(res.error, WAYBACK_PAGES_NOT_FETCHED); + assert.deepEqual(await jobs(), []); +}); + +test("a full sweep is the video listing's: a social channel's sync says where its whole re-walk is", async () => { + const res = await post({ slug: "demo-x", full: true }); + assert.match(res.error, /^A social channel's Sync fetches its new posts; a full re-walk of its timeline is Fetch posts → Re-fetch full history/); + assert.deepEqual(await jobs(), []); +}); diff --git a/editor/app/api/ops/sync/route.ts b/editor/app/api/ops/sync/route.ts @@ -6,7 +6,9 @@ export const dynamic = "force-dynamic"; // POST { slug: string, full?: boolean, queueKey?: string } -> { ok: true, jobId } // // `full` forces the periodic whole-listing sweep now; without it the job -// decides for itself from the configured cadence. +// decides for itself from the configured cadence. A social channel's sync is +// its post fetch (syncAction → fetch-posts, UI notes #17), and `full` is +// refused there. export async function POST(request: Request) { return ops(request, ["slug", "full", "queueKey"], async (body) => jobResponse( diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -1,6 +1,8 @@ "use server"; import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads"; +import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; +import { fetchPostsAction } from "./socialActions"; import path from "node:path"; import { safeRevalidate } from "../../lib/safeRevalidate"; import { @@ -394,11 +396,29 @@ export async function downloadMissingAction( // the periodic full sweep (see common/jobs/deepSync.ts). Pass fullSweep to force // one now — the sweep is still a single `sync` job: one row, one log, one // Cancel, and the same per-platform serialization. +// +// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17). An X, +// Bluesky, forum-thread or Wayback-pages channel holds posts, not a video +// listing: Sync on one ran yt-dlp against the profile URL and failed. Every +// Sync — the channel rows', the dashboard's, a group's, Sync all, `pnpm ops +// sync`, a Retry of a sync job — now runs fetch-posts (socialActions.ts +// fetchPostsAction, the same job the channel page's Fetch posts runs: the +// platform's queue, paced, and for X a fresh cookie jar and no raised alert, +// refused in its own sentence otherwise), never the yt-dlp listing. A full +// sweep is the video listing's; a social channel's whole re-walk is +// fetch-posts' `full`, asked for by name, so a Sync never starts one. +const SOCIAL_FULL_SWEEP_REFUSAL = + "A social channel's Sync fetches its new posts; a full re-walk of its timeline is Fetch posts → Re-fetch full history (fetch-posts \"full\": true)."; + export async function syncAction( slug: string, queueKey?: string, fullSweep?: boolean, ): Promise<StreamActionResult> { + if (isSocialChannel(await readChannelConfig(getPaths(), slug))) { + if (fullSweep) return { ok: false, info: true, error: SOCIAL_FULL_SWEEP_REFUSAL }; + return fetchPostsAction(slug, queueKey); + } return runPipelineAction(slug, "sync", "sync", queueKey, { forceFullSweep: fullSweep, spec: { kind: "sync", slug, params: { queueKey, fullSweep } }, diff --git a/editor/app/channels/components/ChannelSyncButton.tsx b/editor/app/channels/components/ChannelSyncButton.tsx @@ -9,12 +9,19 @@ type Status = | { kind: "done"; jobId: string } | { kind: "error"; message: string }; +// A SOCIAL channel's Sync is its post fetch (UI notes 2026-10-30, #17): +// syncAction runs fetch-posts for it — the channel page's Fetch posts job, +// paced on the platform's queue, and for X refused on a stale cookie jar in +// its own sentence, which shows here — never the yt-dlp listing. `social` +// only changes the words. export function ChannelSyncButton({ slug, disabled, + social = false, }: { slug: string; disabled?: boolean; + social?: boolean; }) { const [status, setStatus] = useState<Status>({ kind: "idle" }); @@ -48,6 +55,12 @@ export function ChannelSyncButton({ onClick={handleClick} disabled={running || disabled} aria-label={`sync ${slug}`} + data-sync-runs={social ? "fetch-posts" : "sync"} + title={ + social + ? "Fetches this account's new posts (fetch-posts, on its platform's queue) — a social channel has no video listing" + : "Lists the channel and downloads what is new" + } className="px-2 py-1 rounded-md bg-primary text-primary-foreground text-xs font-medium hover:opacity-90 disabled:opacity-50" > {running ? "Syncing…" : "Sync"} @@ -66,7 +79,7 @@ export function ChannelSyncButton({ aria-label={`sync ${slug} job`} className="text-xs text-muted-foreground font-mono" > - job {status.jobId} + {social ? "fetching posts · " : ""}job {status.jobId} </span> )} {status.kind === "done" && ( @@ -74,7 +87,7 @@ export function ChannelSyncButton({ aria-label={`sync ${slug} done`} className="text-xs text-muted-foreground" > - done (job {status.jobId}) + {social ? "posts fetched" : "done"} (job {status.jobId}) </span> )} </div> diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx @@ -342,7 +342,7 @@ export const CHANNEL_COLUMNS: Record< className: "whitespace-nowrap", content: ctx.extras?.actions ?? ( <div className="flex items-center gap-2"> - <ChannelSyncButton slug={c.slug} disabled={!c.hasUrl} /> + <ChannelSyncButton slug={c.slug} disabled={!c.hasUrl} social={c.social} /> <ChannelAvailabilityButton slug={c.slug} disabled={!c.hasUrl} /> <InlineActionButton variant={{ kind: "refreshReport", slug: c.slug }} /> </div> diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx @@ -132,7 +132,7 @@ function DashboardChannels({ <div className="flex flex-wrap items-center gap-1.5"> {c.hasUrl ? ( <> - <ChannelSyncButton slug={c.slug} /> + <ChannelSyncButton slug={c.slug} social={c.social} /> {c.work.undownloaded > 0 && ( <InlineActionButton variant={{ kind: "downloadMissing", slug: c.slug }} diff --git a/editor/e2e/social-channel.spec.ts b/editor/e2e/social-channel.spec.ts @@ -264,3 +264,75 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in ) .toEqual(["xenforo 21", "xenforo 22", "xenforo 23"]); }); + +// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): the +// Sync button on the /channels rack ran yt-dlp's listing against an X profile +// and failed. It runs fetch-posts now (the fake gallery-dl here), and a +// refusal is the post fetch's own sentence beside the button. +const UI_OPS_SHOTS = process.env.E2E_UI_OPS_SHOTS ?? ""; +const shot = async (page: import("@playwright/test").Page, name: string) => { + if (!UI_OPS_SHOTS) return; + await mkdir(UI_OPS_SHOTS, { recursive: true }); + await page.screenshot({ path: path.join(UI_OPS_SHOTS, `${name}.png`), fullPage: false }); +}; + +test("Sync on a social channel runs fetch-posts, never the video listing", async ({ page }) => { + await resetData("empty"); + await generateReport(page, "new"); + await page.goto("/channels/new"); + await page.locator('input[name="url"]').fill(X_URL); + await page.locator('input[name="name"]').fill("Fake Tester"); + await page.locator('input[name="slug"]').fill("faketester"); + await page.locator('input[name="fetchPostsNow"]').uncheck(); + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + const config = `${testPaths().transcriptsDir}/channels/faketester/config.json`; + await expect.poll(() => pathExists(config), { timeout: 15_000 }).toBe(true); + await generateReport(page, "faketester"); + + await page.goto("/channels"); + const sync = page.getByRole("button", { name: "sync faketester" }); + await expect(sync).toHaveAttribute("data-sync-runs", "fetch-posts"); + await expect(sync).toHaveAttribute("title", /fetch-posts/); + await sync.click(); + // The fake gallery-dl's three tweets: the post fetch ran, not yt-dlp. + const archive = `${testPaths().transcriptsDir}/channels/faketester/posts-archive`; + await expect + .poll(async () => ((await pathExists(archive)) ? (await readFile(resolvePath(archive), "utf8")).split("\n").filter(Boolean).length : 0), { + timeout: 30_000, + }) + .toBe(3); + await expect(page.getByLabel("sync faketester done")).toContainText(/posts fetched \(job /, { timeout: 30_000 }); + await sync.scrollIntoViewIfNeeded(); + await shot(page, "17-social-sync-fetch-posts"); + // The job it ran is a fetch-posts job (its record beside its log). + const jobId = ((await page.getByLabel("sync faketester done").textContent()) ?? "").match(/job ([^)\s]+)/)?.[1] ?? ""; + expect(jobId).not.toBe(""); + const meta = await readJson<{ kind: string; channelSlug?: string }>(`${testPaths().transcriptsDir}/.jobs/${jobId}.meta.json`); + expect(meta.kind).toBe("fetch-posts"); + expect(meta.channelSlug).toBe("faketester"); +}); + +test("a social channel whose post fetch refuses: the Sync button shows the refusal's sentence", async ({ page }) => { + await resetData("empty"); + const dir = resolvePath(`${testPaths().transcriptsDir}/channels/waypages`); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + name: "Wayback pages", + url: "https://web.archive.org/web/2020/https://example.test/", + }), + ); + await generateReport(page, "waypages"); + await page.goto("/channels"); + const sync = page.getByRole("button", { name: "sync waypages" }); + await expect(sync).toHaveAttribute("data-sync-runs", "fetch-posts"); + await sync.click(); + await expect(page.getByLabel("sync waypages error")).toHaveText( + "A Wayback pages channel is not fetched: import its captures (import-page, the channel page's Import a capture).", + ); + await shot(page, "17-social-sync-refusal"); +}); diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -91,6 +91,7 @@ import { currentSlot } from "./e2e/testPaths"; // E2E_SERIAL_LAST set below by the runner for its workers: whether // the @serial project runs last (a whole run) // E2E_RACK_SHOTS=1 run the /channels rack screenshot audit +// E2E_UI_OPS_SHOTS=<dir> social-channel.spec's Sync screenshots (UI notes #17) go there // E2E_FAKE_YTDLP_AUDIO_CHECK_MODE, E2E_FAKE_YTDLP_CHUNK_DELAY_MS, // E2E_FAKE_YTDLP_CORRUPT_AFTER_CHUNK, E2E_FAKE_YTDLP_CORRUPT_RUNS, // E2E_FAKE_YTDLP_DETERMINISTIC_CORRUPT, E2E_FAKE_YTDLP_RECOVER_ON_RESUME, diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1264,7 +1264,10 @@ export function usage() { 'sync lists a channel and downloads what is new, as its Sync button does:', ' {"slug"}. "full": true runs the periodic whole-listing sweep now (else', ' the configured cadence decides); "queueKey" picks another queue. On the', - " channel's platform queue, paced like its downloads.", + " channel's platform queue, paced like its downloads. A social channel's", + " sync is its post fetch (fetch-posts' new posts, its guards and refusals:", + ' for X a fresh cookie jar), never the video listing; "full" is refused', + ' there (fetch-posts "full": true re-walks the timeline).', "", 'download-missing downloads every listed video the channel does not hold:', ' {"slug"}. "ignoreArchive": true drops the download archive so listed', diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -869,6 +869,15 @@ function buildLockFor(heavyLock) { function jobsDirFor(heavyLock) { return `${heavyLock}.jobs`; } +// One ticket per job WAITING for the slot, `<pid>.json` (the render queue +// panel's "waiting", UI notes #18): what it is, since when, and where it waits +// -- `render` (at the door while render mode holds the machine), `line` (behind +// the job at the head of the line), `slot` (at the head, for the slot's lock), +// or the admission's own wait (`memory`, `build`, `exclusive`, `serial`). +// Dropped once it is admitted (its running ticket replaces it) or exits. +export function waitingDirFor(heavyLock) { + return `${heavyLock}.waiting`; +} // `systemd-run … -p MemoryMax=5G …` → 5120; none → null. export function memoryCapMb(cmd = []) { @@ -1108,6 +1117,63 @@ function writeTicket(dir, job, cmd) { }; } +/** + * The waiting ticket of this process: written now (stage `door`), its stage + * moved by `stage(name)`, removed by `drop()` (idempotent) and at exit. + * Informational, like the running tickets: a missing one never blocks. + */ +function writeWaitingTicket(dir, job, cmd) { + const file = path.join(dir, `${process.pid}.json`); + const since = new Date().toISOString(); + let dropped = false; + const put = (stage) => { + if (dropped) return; + const info = { + pid: process.pid, + pidStart: pidStartTime(process.pid), + estimateMb: job.estimateMb, + build: Boolean(job.build), + exclusive: Boolean(job.exclusive), + worktree: gitOut(["rev-parse", "--show-toplevel"]) ?? process.cwd(), + branch: gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "?", + cmd: cmd.join(" "), + since, + stage, + stageSince: new Date().toISOString(), + }; + try { + fs.mkdirSync(dir, { recursive: true }); + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`); + fs.renameSync(tmp, file); + } catch { + /* informational only */ + } + }; + const drop = () => { + if (dropped) return; + dropped = true; + process.off("exit", drop); + try { + fs.rmSync(file, { force: true }); + } catch { + /* best effort */ + } + }; + process.on("exit", drop); + let last = null; + put("door"); + return { + stage: (name) => { + if (name !== last) { + last = name; + put(name); + } + }, + drop, + }; +} + function describeTicket(t) { const where = t.worktree ? path.basename(t.worktree) : "?"; const age = t.startedAt ? ` for ${humanAge(Date.parse(t.startedAt))}` : ""; @@ -1147,6 +1213,8 @@ export async function waitForAdmission({ log = (line) => process.stderr.write(line), now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), + // Told what the job waits for each time that changes (its waiting ticket's stage). + onWait = () => {}, }) { const t0 = now(); let lastTick = t0; @@ -1174,6 +1242,7 @@ export async function waitForAdmission({ } if (d.wait !== lastWait) { lastWait = d.wait; + onWait(d.wait); log(waitLine(d, mem, minMb, describe)); } else if (now() - lastTick >= tickMs) { lastTick = now(); @@ -1340,13 +1409,17 @@ export async function withHeavy(opts, fn) { const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0; const remaining = () => (deadline ? Math.max(1000, deadline - Date.now()) : 0); const releases = []; + // Seen by the render queue panel until it is admitted (waitingDirFor). + const waiting = writeWaitingTicket(waitingDirFor(heavyLock), job, cmd); try { let releaseLine = null; // RENDER MODE first, outside the line: a job waiting for the render must // not hold the line the render is admitted through. Looked at again once in // line — a render that went on meanwhile sends this job back to wait. for (;;) { + if (renderPriorityBlocks(readRender(), process.env, { urgent: opts.urgent === true })) waiting.stage("render"); await renderGateOrExit(readRender, { urgent: opts.urgent === true, timeoutMs: remaining() }); + waiting.stage("line"); try { releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, remaining(), { ...HEAVY_LOCK, @@ -1360,6 +1433,7 @@ export async function withHeavy(opts, fn) { `heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`, ); await memoryFloorOrExit(timeoutMs); + waiting.drop(); process.env[HEAVY_HELD_ENV] = "1"; return await fn(); } @@ -1368,6 +1442,7 @@ export async function withHeavy(opts, fn) { releaseLine = null; } try { + waiting.stage("slot"); const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) }; if (job.exclusive) { releases.push(await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait)); @@ -1383,16 +1458,19 @@ export async function withHeavy(opts, fn) { describe: () => describeSlot(heavyLock), tryBuild: () => holdLock(buildLockFor(heavyLock), "heavy-build", cmd, 0, BUILD_LOCK, { nonblock: true }), + onWait: (w) => waiting.stage(w), }); if (releaseBuild) releases.push(releaseBuild); } releases.push(writeTicket(jobsDirFor(heavyLock), job, cmd)); + waiting.drop(); } finally { await releaseLine(); } process.env[HEAVY_HELD_ENV] = job.build ? "build" : "1"; return await fn(); } finally { + waiting.drop(); delete process.env[HEAVY_HELD_ENV]; for (const release of releases.reverse()) await release(); } diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -1088,3 +1088,52 @@ test("render mode: the render (its token) is admitted at once, on the floor 4000 }); assert.match(own.stdout, /floor=1000/); }); + +// THE WAITING TICKETS (UI notes #18): the render queue panel reads who waits +// at the slot, and for what, from the slot's own files. +test("a job waiting for the slot has a waiting ticket naming its stage; admitted, it is a running ticket instead", async () => { + const dir = tmpDir(); + const log = path.join(dir, "order.log"); + const env = heavyEnv(dir); + const gate = path.join(dir, "gate"); + const first = startLock(["--heavy", "--", ...gateCmd(log, "1", gate)], env); + await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`)); + const second = startLock(["--heavy", "--estimate", "700", "--", ...markerCmd(log, "2", 50)], env); + await second.waitFor(/waiting for/); + const waitingDir = `${env.HEAVY_LOCK_FILE}.waiting`; + await until(() => readTickets(waitingDir).some((t) => t.pid === second.child.pid && t.stage !== "door" && t.stage !== "line")); + const [w] = readTickets(waitingDir).filter((t) => t.pid === second.child.pid); + // Behind a job that runs alone: at the head of the line, for the slot. + assert.ok(["slot", "exclusive"].includes(w.stage), w.stage); + assert.equal(w.estimateMb, 700); + assert.match(w.cmd, /appendFileSync/); + assert.ok(Date.parse(w.since) <= Date.now()); + // The one running: its ticket, not a waiting one. + assert.deepEqual(readTickets(`${env.HEAVY_LOCK_FILE}.jobs`).map((t) => t.pid), [first.child.pid]); + assert.equal(readTickets(waitingDir).some((t) => t.pid === first.child.pid), false); + openGate(gate); + assert.equal((await first.done).code, 0); + assert.equal((await second.done).code, 0); + assert.deepEqual(readTickets(waitingDir), []); +}); + +test("waitForAdmission tells onWait what the job waits for, each time it changes", async () => { + let clock = 0; + const waits = []; + const sets = [[{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }, { estimateMb: 1500 }], []]; + await waitForAdmission({ + minMb: 6000, + pollMs: 1000, + tickMs: 60_000, + log: () => {}, + now: () => clock, + sleep: async (ms) => { + clock += ms; + }, + job: { estimateMb: 1500, build: false, exclusive: false }, + read: () => ({ availableMb: 8000, totalMb: 16_000 }), + tickets: () => sets.shift() ?? [], + onWait: (w) => waits.push(w), + }); + assert.deepEqual(waits, ["memory"]); +}); diff --git a/umtool/app/api/render-queue/route.ts b/umtool/app/api/render-queue/route.ts @@ -0,0 +1,37 @@ +import { realpath } from "node:fs/promises"; +import { readHeavyQueue } from "yt-dlp-transcript-common/lib/heavyQueue.mjs"; +import { heavyLockFile, renderPriorityFile } from "yt-dlp-transcript-common/lib/renderPriority.mjs"; +import { REPO_ROOT } from "@/lib/paths.mjs"; +import { projectRef } from "@/lib/projects"; +import { projectEtas } from "@/lib/report/takeEta.mjs"; + +export const dynamic = "force-dynamic"; + +// THE RENDER QUEUE (UI notes 2026-10-30, #18), for the take panel: what runs +// in the machine's heavy slot and what waits at it, and for what -- read from +// the slot's own files beside its lock (common/lib/heavyQueue.mjs: +// heavy-queue.lock.jobs/, .waiting/, the line's and the build slot's holders, +// the e2e suites' queues, render mode), never guessed -- and, with a project, +// how long a take of it renders, from its past renders (lib/report/takeEta.mjs). +// Read only: render mode is turned on by "Give renders the machine" (a take's +// --priority) or `umtool render-mode on`. +// +// GET ?project=<id> -> { queue, etas, mine } `mine`: the running and waiting renders of this project +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const queue = readHeavyQueue({ + heavyLock: heavyLockFile(process.env, { root: REPO_ROOT }), + renderFile: renderPriorityFile(process.env, { root: REPO_ROOT }), + }); + const id = url.searchParams.get("project"); + const project = id ? await projectRef(id) : null; + if (!project) return Response.json({ queue, etas: null, mine: [] }, { headers: noStore }); + const dir = await realpath(project.dir).catch(() => project.dir); + const same = async (d: string | undefined) => !!d && ((await realpath(d).catch(() => d)) === dir || d === project.dir); + const mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[] = []; + for (const r of queue.running) if (r.kind === "render" && (await same(r.projectDir))) mine.push({ pid: r.pid, take: r.take ?? null, state: "running", forSeconds: r.forSeconds }); + for (const w of queue.waiting) if (w.kind === "render" && (await same(w.projectDir))) mine.push({ pid: w.pid, take: w.take ?? null, state: "waiting", forSeconds: w.forSeconds, stage: w.stageWords }); + return Response.json({ queue, etas: await projectEtas(project.dir), mine }, { headers: noStore }); +} diff --git a/umtool/app/api/report/link-policy/route.ts b/umtool/app/api/report/link-policy/route.ts @@ -0,0 +1,71 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken, updateLinkPolicy } from "@/lib/report/manifest.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { linkPolicyOf } from "@/lib/report/linkPolicy.mjs"; +import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs"; +import { SITES_DIR } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10; lib/report/linkPolicy.mjs): +// "cite via site X; these channels direct", `provenance.linkPolicy`. +// +// GET ?project=<id> the policy, the cut's channels (with their clip counts), +// the sites a policy may cite via (SITES_DIR, each with a +// siteUrl), provenance.siteOrigin, the token +// PUT { project, token, policy: { via?, direct? } | null } set it (null clears) +// +// Setting it rewrites no clip: what breaks it is the check's clip-link-policy +// rows, each with its one-press fix through the window writer; new clips are +// written by it (the inserters). `umtool link-policy <p> …` is the same writer. +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { provenance?: Record<string, unknown>; timeline?: { type?: string; channel?: string }[] }; + const counts = new Map<string, number>(); + const fallback = typeof m.provenance?.channelSlug === "string" ? m.provenance.channelSlug : null; + for (const e of m.timeline ?? []) { + if (e?.type !== "clip") continue; + const c = e.channel ?? fallback; + if (c) counts.set(c, (counts.get(c) ?? 0) + 1); + } + return Response.json( + { + policy: linkPolicyOf(m), + siteOrigin: typeof m.provenance?.siteOrigin === "string" ? m.provenance.siteOrigin : null, + channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)), + sites: [...sitesByOrigin(SITES_DIR)].map(([origin, s]) => ({ origin, siteId: s.siteId, title: s.title })), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/link-policy"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + if (!("policy" in body)) return Response.json({ error: "policy is required — { via?, direct? }, or null to clear it" }, { status: 400 }); + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const { result, editNotes } = await withEditNotes(r.project, () => + updateLinkPolicy(r.project.dir, body.policy ?? null, { token: typeof body.token === "string" ? body.token : null }), + ); + return Response.json({ ok: true, ...result, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) { + return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); + } + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/publish-site/route.ts b/umtool/app/api/report/publish-site/route.ts @@ -0,0 +1,65 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { askEditor, EditorError } from "@/lib/articles/generation"; +import { refuseCaller } from "@/lib/report/caller"; +import { readLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { projectSites, sitesByOrigin } from "@/lib/report/siteDeploys.mjs"; +import { SITES_DIR } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// PUBLISH A SITE THE CUT CITES (UI notes 2026-10-30, #8 and #9): the +// project page's "Publish <site>" beside a site whose deploy is older than +// videos the cut cites there. UMTOOL BUILDS AND DEPLOYS NOTHING: it asks the +// editor (POST /api/ops/build-deploy {siteId}, the shared WORKER_TOKEN), whose +// publish queue runs the build and then the deploy, one stage at a time, each +// through the heavy slot -- so in render mode it waits for the render. The +// editor's refusal (a private site, no Pages project, the publish lane held) +// is answered in its own words. +// +// GET ?project=<id> the sites the cut's links depend on (siteDeploys.mjs) +// POST { project, siteId } -> { ok, siteId, jobId }: only a site the cut's links open +const headers = { "cache-control": "no-store" }; + +async function sitesOf(dir: string) { + const m = await readManifest(dir); + return projectSites(m ?? {}, await readLinkCheck(dir), { sites: sitesByOrigin(SITES_DIR) }); +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + return Response.json({ sites: await sitesOf(project.dir) }, { headers }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/publish-site"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as { project?: unknown; siteId?: unknown } | null; + if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "publishing a cited site is a report video's" }, { status: 400, headers }); + const siteId = String(b.siteId ?? ""); + const sites = await sitesOf(project.dir); + if (!sites.some((s) => s.siteId && s.siteId === siteId)) { + const named = sites.map((s) => s.siteId).filter(Boolean); + return Response.json( + { error: `"${siteId}" is not a site this cut's links open${named.length ? ` (they open ${named.join(", ")})` : ""}` }, + { status: 400, headers }, + ); + } + try { + const r = await askEditor<{ jobId?: string; jobs?: { siteId: string; jobId: string }[] }>("/api/ops/build-deploy", { + method: "POST", + body: { siteId }, + }); + const jobId = r.jobs?.find((j) => j.siteId === siteId)?.jobId ?? r.jobId ?? null; + return Response.json({ ok: true, siteId, jobId }, { headers }); + } catch (e) { + const status = e instanceof EditorError ? e.status : 500; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/app/api/report/speaker-check/route.ts b/umtool/app/api/report/speaker-check/route.ts @@ -0,0 +1,84 @@ +import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { addClipToSpeaker, speakerBadge, speakerCheckSteps } from "@/lib/report/speakerCheck.mjs"; + +export const dynamic = "force-dynamic"; + +// THE SPEAKER CHECK ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches +// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against +// (lib/report/speakerCheck.mjs; the voices are <project>/speakers.json). +// "Check speaker" is ONE job on the app's runner (lib/jobs.ts: a log, the +// NDJSON events, Cancel) running `umtool speaker-check <p> --clip <id>` +// through the machine's heavy slot (queue-lock --heavy with its estimate: +// beside other jobs by memory, after a render the operator is waiting for). +// Local: TitaNet-small; no network, no LLM. +// +// GET ?project=<id>&clip=<id> the clip's row, the voices, and the check running, if any +// GET ?job=<id>[&since=&sinceEvent=] that job +// POST { project, clip } check that clip's speaker (a job) +// POST { project, clip, addTo: "<name>" } put the clip in that voice's reference set (made when new) +const headers = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const id = url.searchParams.get("job"); + if (id) { + const job = getJob(id); + if (!job) return Response.json({ error: "no such job" }, { status: 404 }); + return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); + } + const project = await projectRef(String(url.searchParams.get("project") ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const clip = String(url.searchParams.get("clip") ?? ""); + const m = await readManifest(project.dir); + const running = runningJob(); + try { + return Response.json( + { + ...(await speakerBadge(project.dir, m ?? {}, clip)), + running: running && running.project === project.id && running.kind.startsWith("speaker-check ") ? jobView(running) : null, + }, + { headers }, + ); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} + +export async function POST(request: Request) { + const url = new URL(request.url); + const cancel = url.searchParams.get("cancel"); + if (cancel) { + const { cancelJob } = await import("@/lib/jobs"); + return Response.json({ cancelled: cancelJob(cancel) }); + } + const refused = refuseCaller(request, "/api/report/speaker-check"); + if (refused) return refused; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "speakers are checked for a report video" }, { status: 400 }); + const clip = typeof body.clip === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(body.clip) ? body.clip : null; + if (!clip) return Response.json({ error: "which clip?" }, { status: 400 }); + if (typeof body.addTo === "string") { + try { + const speakers = await addClipToSpeaker(project.dir, body.addTo, clip); + return Response.json({ ok: true, speakers }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + } + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + const plan = speakerCheckSteps(project, { clip }); + try { + const job = startJob(plan.kind, plan.steps, { project: project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -15,6 +15,8 @@ // umtool show <project> [--json] // umtool check [<project> | --all] [--json] exit 1 on anything blocking // umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json) +// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json) +// umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct // umtool decisions [--json] // umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them // umtool schedule list | show <id> [--json] the recurring reports (R5), read-only @@ -834,6 +836,10 @@ function usage() { " umtool check [<project>] [--json] exit 1 on anything blocking", " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage", " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead", + " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each", + " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list", + " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy", + " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it", " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a", " clip not in the cut; --fix gives each the after of the cut's marker of the same label", " umtool decisions [--json]", @@ -1059,6 +1065,10 @@ const COMMANDS = { trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))), + // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs. + "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))), + // The project's link policy (UI notes #10): lib/report/linksCli.mjs. + "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))), // A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs. "patch-markers": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).patchMarkersCommand(argv.slice(argv.indexOf("patch-markers") + 1))), // Tight windows: each clip to its sentence and its pauses (UI notes item 4): lib/report/tightCli.mjs. diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -19,6 +19,7 @@ import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane"; import { citationText } from "@/lib/research/facets.mjs"; import { cn } from "@/lib/utils"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; +import SpeakerBadge from "./SpeakerBadge"; import CopyCitation from "./bench/CopyCitation"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport"; import EdgeStrip from "./bench/EdgeStrip"; @@ -2750,6 +2751,8 @@ export default function ClipBench({ > {verdictLabel(clip)} </span> + {/* Which named voice it is (UI notes #15): the speaker check's row, and Check speaker. */} + <SpeakerBadge project={data.project} clip={clip.id} /> </VerdictBar> ); diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx @@ -6,6 +6,7 @@ import { buttonVariants } from "@/components/ui/button"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import { JobProgress, type JobStepState } from "@/components/ui/job-progress"; import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner"; +import RenderQueuePanel from "./RenderQueuePanel"; // New take, Make all styles -- and the job either starts (or a card's Rebuild // starts), watched here until it ends, then the page re-reads the takes. @@ -162,6 +163,7 @@ export default function NewTakePanel({ return ( <section data-new-take="" className="space-y-2"> <RenderModeBanner /> + <RenderQueuePanel project={project} /> <details className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]"> <summary data-action="new-take-open" className="cursor-pointer px-3 py-2 text-[12.5px] text-text"> New take diff --git a/umtool/components/projects/RenderQueuePanel.tsx b/umtool/components/projects/RenderQueuePanel.tsx @@ -0,0 +1,194 @@ +"use client"; + +import { useEffect, useState } from "react"; + +// THE RENDER QUEUE on the take panel (UI notes 2026-10-30, #18): what runs in +// the machine's heavy slot and what waits at it -- e2e suites, next builds, +// renders -- read from the slot's own files (GET /api/render-queue, +// common/lib/heavyQueue.mjs), and how long a take of this project renders, +// from its past renders (lib/report/takeEta.mjs). "Give renders the machine" +// beside it (RenderModeBanner) is what sends the others to wait at the door. + +type Row = { + pid: number; + what: string; + kind: string; + estimateMb: number | null; + build: boolean; + alone: boolean; + worktree: string | null; + branch: string | null; + since: string | null; + forSeconds: number | null; + stage?: string; + stageWords?: string; + take?: string; +}; +type Eta = { etaSeconds: number; rate: number; basis: { id: string; seconds: number; renderSeconds: number; how: string }[]; note: string | null }; +type View = { + queue: { + running: Row[]; + waiting: Row[]; + head: Row | null; + suites: (Row & { suite: string })[]; + render: { held: boolean; what?: string }; + memory: { availableMb: number; totalMb: number | null; floorMb: number; promisedMb: number } | null; + heldBy: string | null; + }; + etas: { seconds: number | null; newest: string | null; fresh: Eta | null; reuse: Eta | null; past: unknown[] } | null; + mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[]; +}; + +const dur = (s: number | null | undefined) => { + if (s == null || !Number.isFinite(s)) return "—"; + if (s < 90) return `${Math.round(s)} s`; + const m = Math.round(s / 60); + return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`; +}; +const gb = (mb: number) => `${(mb / 1000).toFixed(1)} GB`; +const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, "0")}`; + +function RowLine({ r, waiting }: { r: Row; waiting?: boolean }) { + return ( + <li + data-queue-row={r.kind} + data-queue-state={waiting ? "waiting" : "running"} + data-queue-pid={r.pid} + className="flex flex-wrap items-baseline gap-x-2 border-b border-seam py-1 text-[12px]" + > + <span className="text-text">{r.what}</span> + {r.worktree && ( + <span className="font-mono text-[11px] text-muted"> + {r.worktree} + {r.branch && r.branch !== r.worktree ? ` (${r.branch})` : ""} + </span> + )} + <span className="font-mono text-[11px] text-meter"> + {r.estimateMb ? `${gb(r.estimateMb)}` : r.alone ? "alone" : "no estimate"} + {r.build ? " · a build" : ""} + </span> + {waiting && r.stageWords && <span className="text-[11.5px] text-doubt-text">{r.stageWords}</span>} + <span className="ml-auto font-mono text-[11px] text-muted">{waiting ? "waiting " : ""}{dur(r.forSeconds)}</span> + </li> + ); +} + +export default function RenderQueuePanel({ project }: { project: string }) { + const [view, setView] = useState<View | null>(null); + const [error, setError] = useState<string | null>(null); + + useEffect(() => { + let alive = true; + const look = () => + fetch(`/api/render-queue?project=${encodeURIComponent(project)}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))) + .then((j: View) => { + if (!alive) return; + setView(j); + setError(null); + }) + .catch((e: unknown) => alive && setError(e instanceof Error ? e.message : String(e))); + void look(); + const t = setInterval(look, 5000); + return () => { + alive = false; + clearInterval(t); + }; + }, [project]); + + if (!view) { + return error ? ( + <p data-render-queue-error="" className="text-[12px] text-muted"> + The render queue could not be read: {error} + </p> + ) : null; + } + const { queue, etas, mine } = view; + const busy = queue.running.length > 0 || queue.waiting.length > 0; + return ( + <section data-render-queue={busy ? "busy" : "idle"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <div className="flex flex-wrap items-baseline gap-2"> + <h2 className="micro">Render queue</h2> + <span data-render-queue-held-by="" className="text-[12px] text-text-2"> + {queue.render.held + ? `held for a render: ${queue.render.what}` + : queue.heldBy + ? `held by ${queue.heldBy}` + : "the heavy slot is free"} + </span> + {queue.memory && ( + <span className="ml-auto font-mono text-[11px] text-muted" title="MemAvailable, the floor a job is admitted above, and what the running jobs declared"> + {gb(queue.memory.availableMb)} available · floor {gb(queue.memory.floorMb)} + {queue.memory.promisedMb ? ` · ${gb(queue.memory.promisedMb)} promised` : ""} + </span> + )} + </div> + {queue.running.length > 0 && ( + <ul data-render-queue-running={queue.running.length} className="mt-1"> + {queue.running.map((r) => ( + <RowLine key={`r${r.pid}`} r={r} /> + ))} + </ul> + )} + {queue.waiting.length > 0 && ( + <ul data-render-queue-waiting={queue.waiting.length} className="mt-1"> + {queue.waiting.map((r) => ( + <RowLine key={`w${r.pid}`} r={r} waiting /> + ))} + </ul> + )} + {queue.suites.filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid)).length > 0 && ( + <p className="mt-1 text-[11.5px] text-muted"> + e2e queues held:{" "} + {queue.suites + .filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid)) + .map((s) => `${s.suite} (${s.worktree ?? "?"}, building or about to ask for the slot)`) + .join(", ")} + </p> + )} + {mine.length > 0 && ( + <p data-render-queue-mine="" className="mt-1 text-[12px] text-text-2"> + {mine + .map((m) => `${m.take ?? "this project's render"}: ${m.state === "running" ? `rendering for ${dur(m.forSeconds)}` : `waiting ${dur(m.forSeconds)} — ${m.stage}`}`) + .join(" · ")} + </p> + )} + <div data-take-eta={etas?.fresh || etas?.reuse ? "known" : "unknown"} className="mt-1.5 text-[12px] text-text-2"> + {etas?.seconds && (etas.fresh || etas.reuse) ? ( + <> + <span> + A whole-cut take ({clock(etas.seconds)} of video):{" "} + {etas.reuse && ( + <span data-take-eta-reuse={etas.reuse.etaSeconds}> + ~{dur(etas.reuse.etaSeconds)} made from {etas.newest} (reuse) + </span> + )} + {etas.reuse && etas.fresh ? " · " : ""} + {etas.fresh && <span data-take-eta-fresh={etas.fresh.etaSeconds}>~{dur(etas.fresh.etaSeconds)} fresh</span>} + </span> + <details className="mt-0.5"> + <summary className="cursor-pointer text-[11.5px] text-muted"> + from {new Set([...(etas.reuse?.basis ?? []), ...(etas.fresh?.basis ?? [])].map((b) => b.id)).size} past render(s) of this project + </summary> + <ul className="mt-0.5 font-mono text-[11px] text-muted"> + {[...(etas.reuse?.basis.map((b) => ({ ...b, k: "reuse" })) ?? []), ...(etas.fresh?.basis.map((b) => ({ ...b, k: "fresh" })) ?? [])].map((b) => ( + <li key={`${b.k}-${b.id}`}> + {b.id} ({b.k}): {clock(b.seconds)} of video in {dur(b.renderSeconds)} + {b.how === "files" ? " (from its files' times)" : ""} + </li> + ))} + </ul> + {[etas.reuse?.note, etas.fresh?.note].filter(Boolean).map((n) => ( + <p key={n} className="text-[11px] text-muted"> + {n} + </p> + ))} + </details> + </> + ) : ( + <span className="text-muted">No ETA yet: no past render of this project says how long it took.</span> + )} + </div> + </section> + ); +} diff --git a/umtool/components/projects/SpeakerBadge.tsx b/umtool/components/projects/SpeakerBadge.tsx @@ -0,0 +1,180 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// THE SPEAKER BADGE ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches +// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against, +// and "Check speaker", which queues `umtool speaker-check <p> --clip <id>` as +// a job through the machine's heavy slot (POST /api/report/speaker-check). The +// voices are the project's speakers.json; "Add to a voice" puts this clip in +// one. An aid to the ear: the verdict is still the walk's. + +type Score = { name: string; score: number; best: number | null; inReference?: boolean }; +type Badge = { + speakers: { name: string; clips: string[]; videos: string[]; channels: string[]; inReference: boolean }[]; + result: null | { scores: Score[]; label?: "matches" | "unsure" | "none"; best?: string; margin?: number | null; why?: string; line: string; madeAt: string | null; speechSeconds?: number }; + reference: null | { name: string; pieces: number; kept: number; clips: string[]; recordings: { channel: string; video: string }[] }[]; + running: null | { id: string; state: string }; + error?: string; +}; +type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[] }; + +export default function SpeakerBadge({ project, clip }: { project: string; clip: string }) { + const [badge, setBadge] = useState<Badge | null>(null); + const [job, setJob] = useState<JobPoll | null>(null); + const [err, setErr] = useState<string | null>(null); + const [voice, setVoice] = useState(""); + const [adding, setAdding] = useState(false); + const timer = useRef<ReturnType<typeof setTimeout> | null>(null); + + const load = useCallback(async () => { + const r = await fetch(`/api/report/speaker-check?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as Badge | null; + if (!r.ok || !j) { + setErr(j?.error ?? `HTTP ${r.status}`); + return; + } + setBadge(j); + }, [project, clip]); + + useEffect(() => { + void load(); + return () => { + if (timer.current) clearTimeout(timer.current); + }; + }, [load]); + + const follow = useCallback( + (id: string) => { + const tick = async () => { + const r = await fetch(`/api/report/speaker-check?job=${encodeURIComponent(id)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as JobPoll | null; + if (!j) return; + setJob(j); + if (j.state === "running") timer.current = setTimeout(() => void tick(), 1000); + else void load(); + }; + void tick(); + }, + [load], + ); + + const check = async () => { + setErr(null); + const r = await fetch("/api/report/speaker-check", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip }), + }); + const j = (await r.json().catch(() => ({}))) as { job?: { id: string }; error?: string }; + if (!r.ok || !j.job) { + setErr(j.error ?? `HTTP ${r.status}`); + return; + } + follow(j.job.id); + }; + + const addTo = async () => { + const name = voice.trim(); + if (!name) return; + setErr(null); + const r = await fetch("/api/report/speaker-check", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip, addTo: name }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string }; + if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`); + setVoice(""); + setAdding(false); + void load(); + }; + + if (!badge) return err ? <span data-speaker-badge="error" className="text-[11.5px] text-doubt-text">{err}</span> : null; + const res = badge.result; + const running = job?.state === "running" || (!!badge.running && !job); + const label = res?.label ?? (res ? "unscored" : "unchecked"); + const tone = label === "matches" ? "text-[var(--color-good)]" : label === "none" ? "text-[var(--color-dirty)]" : "text-text-2"; + const mine = badge.speakers.find((s) => s.inReference); + const refWords = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length, kept: 0, clips: s.clips, recordings: [] }))) + .map((s) => `${s.name}: ${s.pieces} piece${s.pieces === 1 ? "" : "s"}${s.kept ? ` (${s.kept} kept)` : ""}`) + .join(" · "); + + // Compact: one line in the verdict bar (the bench is a one-screen layout at + // 1366×768 -- clip-bench.spec), the voice box only when asked for. + const refShort = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length }))) + .map((s) => `${s.name} ${s.pieces}`) + .join(" · "); + return ( + <span data-speaker-badge={label} className="inline-flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"> + <span data-speaker-line="" className={tone} title={refWords ? `measured against: ${refWords}` : undefined}> + Speaker: {res ? res.line : badge.speakers.length ? "not checked" : "no voices named"} + </span> + {res && ( + <span + data-speaker-reference="" + className="text-[11px] text-muted" + title={`measured against: ${refWords}${res.madeAt ? ` · ${res.madeAt.slice(0, 16).replace("T", " ")}` : ""}`} + > + vs {refShort || "—"} + </span> + )} + {mine && <span className="text-[11px] text-muted">in {mine.name}&rsquo;s voice</span>} + <button + type="button" + data-speaker-check="" + disabled={running || !badge.speakers.length} + onClick={() => void check()} + className={buttonVariants({ variant: "quiet", size: "sm" })} + title={ + badge.speakers.length + ? "scores this clip's voice against each named voice (TitaNet-small, local) as a job through the heavy slot" + : "name the voices first: + voice, or umtool speaker-check <p> --set 'Name=…'" + } + > + {running ? "Checking…" : "Check speaker"} + </button> + {adding ? ( + <span className="inline-flex items-center gap-1"> + <input + data-speaker-voice="" + list={`voices-${clip}`} + value={voice} + autoFocus + onChange={(e) => setVoice(e.target.value)} + onKeyDown={(e) => { + e.stopPropagation(); + if (e.key === "Enter") void addTo(); + if (e.key === "Escape") setAdding(false); + }} + placeholder="voice name" + className="w-[7.5rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px]" + /> + <datalist id={`voices-${clip}`}> + {badge.speakers.map((s) => ( + <option key={s.name} value={s.name} /> + ))} + </datalist> + <button type="button" data-speaker-add="" disabled={!voice.trim()} onClick={() => void addTo()} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is that voice: it joins the voice's reference set (speakers.json)"> + Add + </button> + </span> + ) : ( + <button type="button" data-speaker-add-open="" onClick={() => setAdding(true)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is a known voice: add it to that voice's reference set (speakers.json)"> + + voice + </button> + )} + {job?.state === "failed" && ( + <span data-speaker-error="" className="text-[11.5px] text-doubt-text"> + {job.error ?? job.log.at(-1) ?? "the check failed"} + </span> + )} + {err && ( + <span data-speaker-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/report/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx @@ -42,7 +42,13 @@ export default function DecisionSettle({ headers: { "content-type": "application/json" }, body: JSON.stringify({ project, file: settle.file }), }) - : await fetch("/api/report/links", { + : settle.kind === "publish-site" + ? await fetch("/api/report/publish-site", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, siteId: settle.siteId }), + }) + : await fetch("/api/report/links", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...(settle.fix ? { fix: true } : {}) }), @@ -53,6 +59,7 @@ export default function DecisionSettle({ fixed?: { clip: string }[]; notes?: string[]; left?: { label: string | null; after: string }[]; + jobId?: string | null; }; if (!r.ok) { setErr(j.error ?? `HTTP ${r.status}`); @@ -68,6 +75,10 @@ export default function DecisionSettle({ `${moved} marker${moved === 1 ? "" : "s"} moved` + (left.length ? ` · left by hand: ${left.map((l) => `${l.label ? `"${l.label}"` : "a marker"} after ${l.after}`).join(", ")}` : ""), ); + } else if (settle.kind === "publish-site") { + // The editor's publish queue runs it; nothing here changes until the deploy lands and a check reads it. + setSaid(`queued on the editor's publish queue${j.jobId ? ` (job ${j.jobId})` : ""} — Check links once it is deployed`); + return; } else setSaid("saved"); router.refresh(); } catch (e) { @@ -81,7 +92,7 @@ export default function DecisionSettle({ <span className="inline-flex items-center gap-2" data-settle={settle.kind}> <button type="button" - data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : "links"} + data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : settle.kind === "publish-site" ? `publish-${settle.siteId}` : "links"} disabled={busy} onClick={() => void run()} className={buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size: "sm" })} @@ -90,10 +101,12 @@ export default function DecisionSettle({ ? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer` : settle.kind === "patch-markers" ? `each marker of ${settle.file} after a clip that is gone takes the cut's marker of the same label` - : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host" + : settle.kind === "publish-site" + ? `asks the editor to build and deploy ${settle.siteId} (its publish queue, through the heavy slot)` + : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host" } > - {busy ? (settle.kind === "check-links" ? "Checking…" : "Saving…") : settle.label} + {busy ? (settle.kind === "check-links" ? "Checking…" : settle.kind === "publish-site" ? "Asking the editor…" : "Saving…") : settle.label} </button> {said && !err && ( <span data-settle-said="" className="text-[11.5px] text-text-2"> diff --git a/umtool/components/projects/report/LinkPolicyPanel.tsx b/umtool/components/projects/report/LinkPolicyPanel.tsx @@ -0,0 +1,149 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; + +// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10): "cite via site X; +// these channels direct" -- `provenance.linkPolicy`, through the one writer +// (PUT /api/report/link-policy; `umtool link-policy <p>` from a terminal). +// New clips are written by it; the clips already in the cut that break it are +// the check's clip-link-policy rows, each with its one-press fix. + +type View = { + policy: { via: string | null; direct: string[] } | null; + siteOrigin: string | null; + channels: { slug: string; clips: number }[]; + sites: { origin: string; siteId: string; title: string | null }[]; + token: string | null; +}; + +const DEFAULT = ""; + +export default function LinkPolicyPanel({ project }: { project: string }) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [via, setVia] = useState(DEFAULT); + const [direct, setDirect] = useState<string[]>([]); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<string | null>(null); + const [err, setErr] = useState<string | null>(null); + + const load = useCallback(async () => { + const r = await fetch(`/api/report/link-policy?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => null)) as View | null; + if (!r.ok || !j) return; + setView(j); + setVia(j.policy?.via ?? DEFAULT); + setDirect(j.policy?.direct ?? []); + }, [project]); + + useEffect(() => { + void load(); + }, [load]); + + if (!view || !view.channels.length) return null; + const options = [...view.sites]; + if (view.policy?.via && !options.some((s) => s.origin === view.policy?.via)) { + options.push({ origin: view.policy.via, siteId: new URL(view.policy.via).host, title: null }); + } + const dirty = via !== (view.policy?.via ?? DEFAULT) || direct.join(",") !== (view.policy?.direct ?? []).join(","); + + const save = async () => { + setBusy(true); + setErr(null); + setSaid(null); + try { + const policy = via || direct.length ? { ...(via ? { via } : {}), ...(direct.length ? { direct } : {}) } : null; + const r = await fetch("/api/report/link-policy", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, token: view.token, policy }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; changed?: boolean }; + if (!r.ok) { + setErr(j.error ?? `HTTP ${r.status}`); + return; + } + setSaid(j.changed ? "saved — the check names every clip that breaks it" : "unchanged"); + await load(); + router.refresh(); + } catch (e) { + setErr(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const defaultHost = (() => { + try { + return view.siteOrigin ? new URL(view.siteOrigin).host : null; + } catch { + return view.siteOrigin; + } + })(); + + return ( + <section data-link-policy={view.policy ? "set" : "none"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> + <h2 className="micro mb-1.5">Link policy</h2> + <label className="flex flex-wrap items-center gap-2 text-[12.5px] text-text-2"> + Cite via + <select + data-link-policy-via="" + value={via} + onChange={(e) => setVia(e.target.value)} + className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12.5px]" + > + <option value={DEFAULT}>{defaultHost ? `the cut's site origin (${defaultHost})` : "the cut's site origin"}</option> + {options.map((s) => ( + <option key={s.origin} value={s.origin}> + {s.siteId} — {new URL(s.origin).host} + </option> + ))} + </select> + </label> + <p className="mt-1.5 text-[12px] text-muted">These channels link their platform&rsquo;s own page directly:</p> + <ul className="mt-1 flex flex-wrap gap-x-4 gap-y-1"> + {view.channels.map((c) => ( + <li key={c.slug}> + <label className="flex items-center gap-1.5 text-[12.5px]"> + <input + type="checkbox" + data-link-policy-direct={c.slug} + checked={direct.includes(c.slug)} + onChange={(e) => setDirect((d) => (e.target.checked ? [...d, c.slug].sort() : d.filter((x) => x !== c.slug)))} + /> + <span className="font-mono text-[12px]">{c.slug}</span> + <span className="text-[11.5px] text-muted"> + {c.clips} clip{c.clips === 1 ? "" : "s"} + </span> + </label> + </li> + ))} + </ul> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <button + type="button" + data-link-policy-save="" + disabled={busy || !dirty} + onClick={() => void save()} + className={buttonVariants({ variant: "outline", size: "sm" })} + title="writes provenance.linkPolicy; new clips take its links, and the check names the clips that break it" + > + {busy ? "Saving…" : "Save link policy"} + </button> + <span className="font-mono text-[11px] text-muted">umtool link-policy {project} --via &lt;site&gt; --direct a,b</span> + {said && !err && ( + <span data-link-policy-said="" className="text-[11.5px] text-text-2"> + {said} + </span> + )} + {err && ( + <span data-link-policy-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </div> + </section> + ); +} diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx @@ -15,6 +15,8 @@ import type { Decision } from "@/lib/decisions"; import type { PieceFrame } from "@/lib/pieces/frame"; import { TONE, hms, type ReportTabProps } from "./shared"; import DecisionSettle from "./DecisionSettle"; +import ProjectSites from "./ProjectSites"; +import LinkPolicyPanel from "./LinkPolicyPanel"; import { manifestToken } from "@/lib/report/manifest.mjs"; // The Overview tab (canvas "Piece · Overview"): the Next card, then the @@ -117,6 +119,9 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP </ul> </section> + <ProjectSites project={project} detail={detail} /> + <LinkPolicyPanel project={project.id} /> + {frame.board && ( <section data-piece-board={frame.board.id}> <h2 className="micro mb-1.5">Research board</h2> diff --git a/umtool/components/projects/report/ProjectSites.tsx b/umtool/components/projects/report/ProjectSites.tsx @@ -0,0 +1,84 @@ +import { stat } from "node:fs/promises"; +import { readLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { dayOf, projectSites, sitesByOrigin } from "@/lib/report/siteDeploys.mjs"; +import { SITES_DIR } from "@/lib/paths.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +import DecisionSettle from "./DecisionSettle"; +import type { ClipDetail } from "./shared"; + +// THE SITES THIS CUT'S LINKS DEPEND ON (UI notes 2026-10-30, #9), on the +// piece's Overview: each site a clip QR opens, named from its site.json, with +// its deploy's date -- the corpus.json `generatedAt` the last link check read +// (out/links.json; this never fetches) -- and the cited videos newer than that +// deploy. "Publish <site>" asks the editor to build and deploy it; "Check +// links" reads every site again. The same answer is the check's +// `site-deploy-behind` row (lib/report/siteDeploys.mjs). + +const STATE: Record<string, string> = { + ok: "", + unreachable: "couldn't reach it at the last check", + "no-corpus": "it publishes no corpus.json", + unchecked: "not checked yet", +}; + +export default async function ProjectSites({ project, detail }: { project: ProjectRef; detail: ClipDetail }) { + const m = detail.manifest as Record<string, unknown>; + const doc = await readLinkCheck(project.dir); + const records = new Map<string, { uploadDate: string | null; landedAt: string | null }>(); + for (const e of detail.entries) { + if (e.kind !== "clip") continue; + const cueFile = (e as { cueFile?: string | null }).cueFile; + const st = cueFile ? await stat(cueFile).catch(() => null) : null; + records.set(e.id, { + uploadDate: (e as { uploadDate?: string | null }).uploadDate ?? null, + landedAt: st ? new Date(st.mtimeMs).toISOString() : null, + }); + } + const sites = projectSites(m, doc, { sites: sitesByOrigin(SITES_DIR), recordOf: (id: string) => records.get(id) ?? null }); + if (!sites.length) return null; + return ( + <section data-project-sites={sites.length}> + <h2 className="micro mb-1.5">Sites the links depend on</h2> + <ul className="space-y-1.5"> + {sites.map((s) => ( + <li + key={s.origin} + data-link-site={s.host} + data-link-site-id={s.siteId ?? undefined} + data-link-site-deployed={dayOf(s.deployedAt) ?? undefined} + data-link-site-newer={s.newer.length} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 text-[12.5px]" + > + <div className="flex flex-wrap items-baseline gap-2"> + <a href={s.origin} target="_blank" rel="noreferrer" className="ink-link font-mono text-[12px]"> + {s.host} + </a> + {s.siteId && <span className="text-text-2">{s.siteId}</span>} + <span className="ml-auto font-mono text-[11.5px] text-meter"> + {s.links} link{s.links === 1 ? "" : "s"} · {s.clips.length} clip{s.clips.length === 1 ? "" : "s"} + </span> + </div> + <p className="text-[12px] text-muted" data-link-site-deploy=""> + {s.deployedAt ? `deployed ${dayOf(s.deployedAt)} (its corpus.json)` : "deploy date unknown"} + {STATE[s.state] ? ` · ${STATE[s.state]}` : ""} + {doc?.checkedAt ? ` · checked ${doc.checkedAt.slice(0, 16).replace("T", " ")}` : ""} + </p> + {s.newer.length > 0 && ( + <p className="text-[12px] text-doubt-text" data-link-site-warning=""> + {s.newer.length} cited video{s.newer.length === 1 ? " is" : "s are"} newer than this deploy:{" "} + {s.newer.slice(0, 6).map((n) => `${n.clip} (${n.why})`).join(", ")} + {s.newer.length > 6 ? ` and ${s.newer.length - 6} more` : ""} + </p> + )} + <div className="mt-1 flex flex-wrap items-center gap-2"> + {s.siteId && s.newer.length > 0 && ( + <DecisionSettle project={project.id} settle={{ kind: "publish-site", siteId: s.siteId, label: `Publish ${s.siteId}` }} /> + )} + <DecisionSettle project={project.id} settle={{ kind: "check-links", label: doc ? "Check links again" : "Check links" }} /> + </div> + </li> + ))} + </ul> + </section> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -27,7 +27,8 @@ Inbox cannot disagree about what is wrong with one. | `window <project> <clip> --verdict confirmed\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]` | what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said)) | | `window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>` | what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip)) | | `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) | -| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)) | +| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) | +| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) | | `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) | | `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) | | `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at | @@ -69,6 +70,7 @@ Inbox cannot disagree about what is wrong with one. | `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | +| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -70,6 +70,8 @@ on (`decisionTab`, `songTabOfSection`). | `link-dead` | blocking | the recorded link check (`umtool links`, out/links.json) found clip QRs that don't open on their site — one row per site, the clips and the first reason | Fix the links | | `links-unverified` | info | the link check could not reach a site (offline, a timeout, no corpus.json) | Check links again | | `links-unchecked` | info | archive links never checked, or changed since the check | Check links | +| `site-deploy-behind` | open | a site the QRs open whose deploy (its recorded corpus.json `generatedAt`) is older than cited videos whose links the check did not find open — one row per site ([knobs.md](knobs.md#the-sites-the-links-depend-on)) | Publish &lt;site&gt; | +| `clip-link-policy` | open | a clip whose QR breaks the project's link policy (`provenance.linkPolicy`): a direct channel's clip opening an archive, or another clip not opening the policy's site ([knobs.md](knobs.md#the-link-policy)) | Link it by the policy | | `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows | | `clip-cue-gap` | open | the cue file ends before a clip does (`cues end 880 s · c03 needs 897 s`), one row per source | Fix the window | | `claim-unadjudicated` | blocking | a `ledger[]` entry missing any of the six adjudication fields — one row per entry | Adjudicate claim | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -112,6 +112,37 @@ site: *12 of 124 QR links don't open on anilyzer.pages.dev (deployed 2026-10-09) the site serves as `v<id>`, and only a link still exactly what the check saw — through the window writer, then checks again. A platform link (YouTube's own page) is not an archive link and is not checked. +### The sites the links depend on + +The project page's Overview names every site a clip QR opens (**Sites the links depend on**): the site +whose `site.json` `siteUrl` is that origin, how many links and clips it carries, and its deploy's date +— the `corpus.json` `generatedAt` the last link check read (`out/links.json`; the page never fetches; +**Check links** reads them again). A cited video **newer than that deploy** — uploaded after it, or +transcribed here after it — whose link the check did not find open is named under it, and is the +check's `site-deploy-behind` row (open, one per site): *anilyzer's deploy is from 2026-10-09; 3 cited +videos are newer: …*. Its **Publish anilyzer** asks the editor to build and deploy that site (`POST +/api/report/publish-site {project, siteId}` → the editor's ops `build-deploy`, its publish queue, each +stage through the heavy slot); from a terminal, `pnpm ops build-deploy --json '{"siteId":"anilyzer"}'`. +A link the check opened is on the site, whatever its dates say. + +## The link policy + +"Cite via site X; these channels direct." `provenance.linkPolicy` — `{via?, direct?}`: `via` the archive +every clip's QR opens (an origin; absent: `provenance.siteOrigin`), `direct` the channel slugs whose +clips link the platform's own page at the cite (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble +`start=<s>`, from the record's `webpage_url`). Set on the project page's Overview (**Link policy**: +**Cite via**, a box per channel the cut cites, **Save link policy**), `umtool link-policy <p> --via +<site id | https://…> --direct a,b` (`''` clears one, `--clear` the policy), or `PUT +/api/report/link-policy {project, token, policy}`. Saving rewrites no clip. **New clips are written +by it**: every inserter (`addClip` — the strip's selection, the clip finder, a live share — and +`insertEntry` — `umtool timeline insert`, the Cut tab) gives a new clip the policy's link when its own +would break it (a neighbour's copied citeUrl included). The clips already in the cut that break it are +the check's `clip-link-policy` rows (open, one per clip), each with its one press — **Link via +site.test** / **Link its YouTube page**, the citeUrl through the window writer — and its terminal twin +(`umtool window <p> <clip> --cite-url '…'`); `umtool link-policy <p> --fix` does them all. A direct +clip whose record names no `webpage_url` is a row without a fix. A clip with its own media (`src`) is +not judged. + ## Gaps inside a clip A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -945,7 +945,8 @@ them and records the verdicts. ``` takes/<id>/take.json id (== dir, [a-z0-9-]), group, order, label, kind reference|similar|different, preview; - optional summary, changes[], seconds, builtAt + optional summary, changes[], seconds, builtAt, + renderSeconds (the render's own time: the next take's ETA) takes/<id>/preview.mp4 whatever `preview` names, inside the take dir takes/<id>/out/<slug>.mp4 the take maker's render again, a hard link of preview.mp4 (what `umtool variants --take` and Deliver encode) @@ -1167,6 +1168,19 @@ take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `u it at once, and the editor's heartbeat releases its lanes. Close Firefox and other heavy apps while it renders. +**The render queue and a take's ETA.** Under the banner, **Render queue** says what the heavy +slot is doing, read from its own files (`common/lib/heavyQueue.mjs`; `GET /api/render-queue`): +each job running in it (an e2e suite by its queue's name, a `next build`, a render by its take +and project) with its worktree, its declared memory and for how long; each job **waiting** at +it and for what — the render (render mode), the line, the slot, memory, the build slot — from +the waiting tickets queue-lock keeps (`heavy-queue.lock.waiting/<pid>.json`); "held by …"; +MemAvailable against the floor. Beside it, **the ETA of a whole-cut take** of this project, +made from the newest take and fresh: the median seconds of render per second of video over the +project's past renders of that kind (`lib/report/takeEta.mjs`) — the `renderSeconds` a take +records (from the build's first event, so a wait at the slot is not counted), else the take's +own files (its `video.manifest.json`, written as the render starts, to `builtAt`), less any +wait its `<take>.log` reports. With no render of a kind it says it used the others. + ### A take's work files, and pruning them A take's build leaves behind what makes the NEXT build fast: its clip segments, the chrome @@ -1537,6 +1551,32 @@ fallback?, inReference?, why?}}}` — keyed by the source moment, as the rulings are, so a re-seed keeps it. A clip with no window on disk, or no speech in it, has `score: null` and says why. +### The speaker check on the walk: which of several voices + +The voice match scores every clip against one voice, the host's. A panel show needs more: which of +**several named voices** a clip is. `umtool speaker-check <project> [--clip <id> …]` scores each clip +the same way (TitaNet-small through sherpa-onnx, local; the phrase ± 1 s, voiced frames only) against +each voice in `<project>/speakers.json` — + +```json +{ "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] }, + { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] } +``` + +— a voice's **clips** of this cut, **videos** of that voice alone (the first 60 s of speech, in +pieces), or **channels** whose solo recordings it is (the voice match's heuristic). A clip in a voice's +set is scored against the rest of it. The answer is `<project>/speaker-check.json` (a check of one clip +keeps the others' rows; new reference sets start it over): per clip, every voice's score best first, +and `matches` (the best ≥ 0.42 and 0.05 ahead of the next), `none` (every one under 0.30: a voice the +sets do not hold) or `unsure`. + +On the clip bench's walk the verdict bar says **Speaker: matches Ember 0.93 / Kirsche 0.83**, with the +reference sets it was measured against; **Check speaker** queues the check of that clip as a job +through the machine's heavy slot (`queue-lock --heavy --estimate 800`: beside other jobs by memory, +after a render in render mode), and **Add to a voice** puts the clip in a voice's set (made when new). +From a terminal: `umtool speaker-check <p> --set 'Ember=e01,e07' --set 'Kirsche=kirsche/abc123,channel:kirsche'`, +`--remove <name>`, `--list`. An aid to the ear: it rules on nothing. + ## Highlights: the clip finder A long recording cut down to its best moments — a stream, a podcast, a host diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -975,6 +975,17 @@ function generationRoute(req, res, url, auth) { req.resume(); return json(res, 200, { ok: true, key: "autoQueue", value: lanes }); } + // "Publish <site>" (umtool's /api/report/publish-site, UI notes #9): the + // editor's build-deploy alias. Recorded; a site named "refused" is refused + // the way the editor refuses a private one. + if (req.method === "POST" && url.pathname === "/api/ops/build-deploy") { + return readBody(req, (body) => { + requests.push({ route: "build-deploy", ...(body ?? {}), authorization: auth }); + record(); + if (body?.siteId === "refused") return json(res, 400, { ok: false, error: "refused is private: it never deploys" }); + return json(res, 200, { ok: true, jobId: `deploy-${nextJob}`, jobs: [{ siteId: body?.siteId, jobId: `deploy-${nextJob++}` }], skipped: [] }); + }); + } if (req.method === "POST" && url.pathname === "/api/ops/lane") { return readBody(req, (body) => { requests.push({ route: "lane", ...(body ?? {}), authorization: auth }); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -36,6 +36,7 @@ import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; import { makeBenchShellFixture } from "./bench-shell-fixture.mjs"; import { makeTakeWalkFixture } from "./take-walk-fixture.mjs"; import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; +import { makeUiOpsFixture } from "./ui-ops-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeDigestContextFixture } from "./digest-context-fixture.mjs"; @@ -1874,6 +1875,8 @@ makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out" makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Cut integrity (UI notes 2026-10-30): the cite following the edge, repeatOf, ★ and walk notes, take patch markers, the QR link check (cut-integrity.spec.ts). makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// ui-ops.spec's own project and channels (UI notes #9 #10 #15 #18). +makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff }); // Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts). diff --git a/umtool/e2e/fixtures/ui-ops-fixture.mjs b/umtool/e2e/fixtures/ui-ops-fixture.mjs @@ -0,0 +1,109 @@ +// What ui-ops.spec.ts acts on (UI notes 2026-10-30, #9 #10 #15 #18): its own +// project and its own two channels, written by that spec alone. +// +// channels/uiopschan/ u1 (uploaded 2025-01-01, transcribed here long ago) +// u2 (uploaded 2026-10-20: newer than the site's deploy) +// channels/uiopsdirect/ d1, a YouTube upload (webpageUrl) -- the channel the +// link policy links direct +// reports/ui-ops-fixture/ +// video.manifest.json o01 u1, o02 u2, o03 d1; every QR on the spec's own +// site (a local server; SITE_PLACEHOLDER is replaced +// with its origin before a page opens) +// takes/draft-0..2 three past renders of the whole cut (take.json +// seconds + renderSeconds), and draft-2 made `from` +// draft-1: the ETA's records +// draft-0.log an older render's log line ("take draft-0: done (…)"), +// the ETA's other source +// out/clips-raw/ u1 0.00-9.00, so the speaker check has a window +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, utimesSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const UI_OPS = "ui-ops-fixture"; +export const UI_OPS_SITE_PLACEHOLDER = "http://127.0.0.1:9"; +export const UI_OPS_SPEAKER = "ui-ops-speaker-fixture"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n"); +}; + +const LONG_AGO = new Date("2025-01-02T00:00:00Z"); + +function source(channels, slug, id, { uploadDate, webpageUrl, old = true }) { + const dir = path.join(channels, slug, "data", id); + const cues = Array.from({ length: 30 }, (_, i) => ({ start: i * 2, end: i * 2 + 2, text: `Line ${i} of ${id}.` })); + write(dir, "transcript.cues.json", { title: `UI ops source ${id}`, uploadDate, channel: "UI Ops", webpageUrl, duration: 60, cues }); + if (old) utimesSync(path.join(dir, "transcript.cues.json"), LONG_AGO, LONG_AGO); +} + +/** The fixture's manifest, its QRs on `site`. Exported so the spec writes the same thing with its server's origin. */ +export function uiOpsManifest(manifest, site) { + const link = (chan, id, t) => `${site}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`; + const clip = (id, channel, video, start, end) => ({ + type: "clip", id, channel, video, start, end, cite: start, citeUrl: link(channel, video, start), lock: true, section: 0, quote: `Line of ${video}.`, + }); + const doc = manifest(UI_OPS, "The UI Ops Fixture", { siteOrigin: "https://archive.example", channelSlug: "uiopschan" }, [ + clip("o01", "uiopschan", "u1", 2, 6), + clip("o02", "uiopschan", "u2", 4, 8), + clip("o03", "uiopsdirect", "d1", 10, 14), + ]); + doc.render.fetchPad = 0; + return doc; +} + +/** + * @param {{ reports: string, channels: string, manifest: Function, cachedWindow: string, ff: (args: string[]) => void }} o + */ +export function makeUiOpsFixture({ reports, channels, manifest, cachedWindow, ff }) { + source(channels, "uiopschan", "u1", { uploadDate: "20250101", webpageUrl: "https://example.invalid/watch?v=u1" }); + source(channels, "uiopschan", "u2", { uploadDate: "20261020", webpageUrl: "https://example.invalid/watch?v=u2" }); + source(channels, "uiopsdirect", "d1", { uploadDate: "20250301", webpageUrl: "https://www.youtube.com/watch?v=d1" }); + write(path.join(channels, "uiopsdirect"), "config.json", { name: "UI Ops Direct", url: "https://www.youtube.com/@uiopsdirect", platform: "youtube" }); + const dir = path.join(reports, UI_OPS); + write(dir, "video.manifest.json", uiOpsManifest(manifest, UI_OPS_SITE_PLACEHOLDER)); + // Three past renders of the whole cut (30 s of video each): draft-0 known only + // by its files (its manifest 11 min before builtAt) and its log's 1 min wait + // at the slot -- 600 s; draft-1 recorded 600 s; draft-2, made from draft-1, 240 s. + const take = (id, order, extra) => ({ id, group: "takes", order, label: id.replace("-", " "), kind: "reference", preview: "preview.mp4", seconds: 30, window: "full", ...extra }); + write(path.join(dir, "takes", "draft-0"), "take.json", take("draft-0", 0, { builtAt: "2026-10-29T10:11:00.000Z" })); + write(path.join(dir, "takes", "draft-0"), "video.manifest.json", "{}\n"); + const at0 = new Date("2026-10-29T10:00:00.000Z"); + utimesSync(path.join(dir, "takes", "draft-0", "video.manifest.json"), at0, at0); + write(dir, "draft-0.log", "heavy: waiting for memory — 2917 MB available, the floor is 6000 MB\nheavy: 8879 MB available after 1m00s — admitted\ntake draft-0: done (30 s)\n"); + write(path.join(dir, "takes", "draft-1"), "take.json", take("draft-1", 1, { builtAt: "2026-10-30T10:10:00.000Z", renderSeconds: 600 })); + write(path.join(dir, "takes", "draft-2"), "take.json", take("draft-2", 2, { builtAt: "2026-10-31T10:04:00.000Z", renderSeconds: 240, from: "draft-1" })); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "u1_0.00-9.00.mp4")); + makeSpeakerProject({ reports, channels, manifest, ff }); + return dir; +} + +// THE SPEAKER CHECK'S PROJECT (#15): four clips, each window already in the +// corpus under its own channel -- three of one "voice" (a 150 Hz tone and its +// octave), one of another (1.1 kHz) -- and speakers.json naming Host (k01, k02) +// and Guest (k03). k04 is the clip the walk checks. The app's job runs the test +// kit's fake embedder (VOICE_MATCH_* in playwright.config.ts). +function makeSpeakerProject({ reports, channels, manifest, ff }) { + const chan = "uiopsvoice"; + const voices = { host: "0.3*sin(2*PI*150*t)+0.15*sin(2*PI*300*t)", guest: "0.3*sin(2*PI*1100*t)+0.1*sin(2*PI*2300*t)" }; + const timeline = []; + for (const [id, who] of [["k01", "host"], ["k02", "host"], ["k03", "guest"], ["k04", "host"]]) { + const vid = `voice-${id}`; + const vdir = path.join(channels, chan, "data", vid); + mkdirSync(path.join(vdir, "clips"), { recursive: true }); + write(vdir, "transcript.cues.json", { title: `Voice ${vid}`, uploadDate: "20250101", channel: "UI Ops Voices", webpageUrl: `https://example.invalid/watch?v=${vid}`, duration: 20, cues: [{ start: 2, end: 4.5, text: "slow news day." }] }); + ff([ + "-f", "lavfi", "-i", "color=c=gray:size=160x90:rate=15:duration=6", + "-f", "lavfi", "-i", `aevalsrc=${voices[who]}:s=48000:d=6`, + "-map", "0:v", "-map", "1:a", "-t", "6", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", + path.join(vdir, "clips", "0.00-6.00.mp4"), + ]); + timeline.push({ type: "clip", id, channel: chan, video: vid, start: 0.5, end: 5.5, cutStart: 2, cutEnd: 4.5, cite: 2, section: 0, lock: true, quote: "slow news day." }); + } + const dir = path.join(reports, UI_OPS_SPEAKER); + write(dir, "video.manifest.json", manifest(UI_OPS_SPEAKER, "The Speaker Check Fixture", { siteOrigin: "https://archive.example", channelSlug: chan }, timeline)); + write(dir, "speakers.json", { speakers: [{ name: "Host", clips: ["k01", "k02"] }, { name: "Guest", clips: ["k03"] }] }); +} diff --git a/umtool/e2e/ui-ops.spec.ts b/umtool/e2e/ui-ops.spec.ts @@ -0,0 +1,218 @@ +import { test, expect, type Page } from "@playwright/test"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; +import { UI_OPS, UI_OPS_SITE_PLACEHOLDER, UI_OPS_SPEAKER } from "./fixtures/ui-ops-fixture.mjs"; + +// --------------------------------------------------------------------------- +// OPERATIONS UI (UI notes 2026-10-30), each through the app: +// +// #9 the sites the cut's links depend on, each with its deploy's date, and +// the warning when cited videos are newer than it; Publish <site> asks +// the editor (its stub records build-deploy) +// #10 the link policy: "these channels direct" saved through its writer, +// the check's clip-link-policy row and its one-press fix, and a new +// clip written by the policy +// #18 the render queue panel, read from the slot's own files (the +// fixture's: HEAVY_LOCK_FILE), and a take's ETA from past renders +// #15 the walk's speaker badge and Check speaker (the fake embedder) +// +// Fixture: fixtures/ui-ops-fixture.mjs, written for this file alone. Serial: +// each test leaves what the next reads. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const PROJECT = `reports/${UI_OPS}`; +const SPEAKERS = `reports/${UI_OPS_SPEAKER}`; +const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song"); +const DIR = path.join(FIXTURE, "reports", UI_OPS); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const SITE_DIR = path.join(FIXTURE, "sites", "ui-ops-site"); +const HEAVY = path.join(FIXTURE, "heavy"); +const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json"); +type Entry = { id: string; type: string; citeUrl?: string; channel?: string; video?: string }; +const entries = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline; +const entry = (id: string) => entries().find((e) => e.id === id); +// Screenshots for the morning review, when asked for (UI_OPS_SHOTS=<dir>). +const SHOTS = process.env.UI_OPS_SHOTS ?? ""; +const shot = async (page: Page, name: string, el?: ReturnType<Page["locator"]>) => { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + if (el) await el.screenshot({ path: path.join(SHOTS, `${name}.png`) }); + else await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +}; + +// The site the QRs link: built 9 Oct, with uiopschan's u1 only -- no u2 +// (uploaded the 20th), no uiopsdirect. +let server: Server; +let origin = ""; +const startSite = () => + new Promise<void>((resolve) => { + server = createServer((req, res) => { + const p = new URL(req.url ?? "/", "http://x").pathname; + const json = (doc: unknown) => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(doc)); + }; + if (p === "/corpus.json") { + return json({ + spec: 5, + generatedAt: "2026-10-09T10:00:00.000Z", + site: { title: "UI ops archive" }, + channels: [{ slug: "uiopschan", manifests: { transcripts: `${origin}/transcripts/uiopschan/manifest.json` } }], + }); + } + if (p === "/transcripts/uiopschan/manifest.json") return json({ pageCount: 1, slugToPage: { u1: 0 } }); + if (p === "/transcripts/uiopschan/page-0000.json") return json([{ id: "u1" }]); + res.writeHead(404); + res.end(); + }); + server.listen(0, "127.0.0.1", () => { + origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + resolve(); + }); + }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await startSite(); + writeFileSync(MANIFEST, readFileSync(MANIFEST, "utf8").split(UI_OPS_SITE_PLACEHOLDER).join(origin)); + // The site the QRs open, as transcripts/sites/<id>/site.json names it. + mkdirSync(SITE_DIR, { recursive: true }); + writeFileSync(path.join(SITE_DIR, "site.json"), JSON.stringify({ siteId: "ui-ops-site", siteTitle: "UI Ops Site", siteUrl: origin, channels: [{ slug: "uiopschan", order: 0 }] })); + await warm(playwright, [urls.projectHref(PROJECT), urls.takesHref(PROJECT), urls.clipBenchHref(SPEAKERS, "k04")]); +}); +test.afterAll(() => { + server?.close(); + rmSync(SITE_DIR, { recursive: true, force: true }); + rmSync(HEAVY, { recursive: true, force: true }); +}); + +const row = (page: Page, kind: string, target: string) => page.locator(`[data-decision="${kind}"][data-target="${target}"]`); + +test("#9 the sites the links depend on: the deploy's date, the cited videos newer than it, and Publish <site>", async ({ page }) => { + const host = new URL(origin).host; + await page.goto(urls.projectHref(PROJECT)); + const site = page.locator(`[data-link-site="${host}"]`); + await expect(site).toHaveAttribute("data-link-site-id", "ui-ops-site"); + await expect(site.locator("[data-link-site-deploy]")).toContainText("deploy date unknown · not checked yet"); + // Check links reads every site's corpus.json; its date is the deploy's. + await site.locator('[data-settle-button="links"]').click(); + await expect(site).toHaveAttribute("data-link-site-deployed", "2026-10-09", { timeout: 30_000 }); + await expect(site.locator("[data-link-site-deploy]")).toContainText("deployed 2026-10-09 (its corpus.json)"); + await expect(site).toHaveAttribute("data-link-site-newer", "1"); + await expect(site.locator("[data-link-site-warning]")).toHaveText("1 cited video is newer than this deploy: o02 (uploaded 2026-10-20)"); + const behind = row(page, "site-deploy-behind", host); + await expect(behind).toContainText("ui-ops-site's deploy is from 2026-10-09; 1 cited video is newer: o02 (uploaded 2026-10-20)"); + await expect(behind.locator("[data-fix]")).toHaveAttribute("data-fix", `pnpm ops build-deploy --json '{"siteId":"ui-ops-site"}'`); + await shot(page, "9-site-deploy-warning"); + await shot(page, "9-site-deploy-warning-panel", site); + // Publish asks the editor's build-deploy (the stub records it). + await site.locator('[data-settle-button="publish-ui-ops-site"]').click(); + await expect(site.locator('[data-settle="publish-site"] [data-settle-said]')).toContainText(/queued on the editor's publish queue \(job deploy-\d+\)/); + const asked = (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; siteId?: string; authorization?: string }[]).filter((r) => r.route === "build-deploy"); + expect(asked.at(-1)).toMatchObject({ siteId: "ui-ops-site", authorization: "Bearer umtool-e2e-token" }); +}); + +test("#10 the link policy: cite via ui-ops-site, uiopsdirect direct; the check's row and its fix; a new clip is written by it", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + const panel = page.locator("[data-link-policy]"); + await expect(panel).toHaveAttribute("data-link-policy", "none"); + // "Cite via ui-ops-site; uiopsdirect direct." + await panel.locator("[data-link-policy-via]").selectOption(origin); + await panel.locator('[data-link-policy-direct="uiopsdirect"]').check(); + await panel.locator("[data-link-policy-save]").click(); + await expect(panel.locator("[data-link-policy-said]")).toContainText("saved"); + await expect(panel).toHaveAttribute("data-link-policy", "set"); + expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { provenance: { linkPolicy?: unknown } }).provenance.linkPolicy).toEqual({ via: origin, direct: ["uiopsdirect"] }); + // Only o03 breaks it: o01 and o02 already open ui-ops-site. + await expect(page.locator('[data-decision="clip-link-policy"]')).toHaveCount(1); + const policyRow = row(page, "clip-link-policy", "o03"); + await expect(policyRow).toContainText(`uiopsdirect links direct by the project's link policy, but its QR opens ${new URL(origin).host}`); + await expect(policyRow.locator('[data-settle-button="o03"]')).toHaveText("Link its YouTube page"); + await expect(policyRow.locator("[data-fix]")).toHaveAttribute("data-fix", `umtool window ${PROJECT} o03 --cite-url 'https://www.youtube.com/watch?v=d1&t=10s'`); + await shot(page, "10-link-policy-row"); + await shot(page, "10-link-policy-panel", panel); + await policyRow.locator('[data-settle-button="o03"]').click(); + await expect(row(page, "clip-link-policy", "o03")).toHaveCount(0); + expect(entry("o03")?.citeUrl).toBe("https://www.youtube.com/watch?v=d1&t=10s"); + await shot(page, "10-link-policy-fixed"); + // A new clip of the direct channel: the inserter writes its YouTube page. + const r = await page.request.post("/api/report/timeline", { + data: { project: PROJECT, op: "insert", afterId: "o03", entry: { type: "clip", channel: "uiopsdirect", video: "d1", start: 20, end: 24, citeUrl: `${origin}/?v=uiopsdirect%2Fd1&t=20` } }, + }); + expect(r.ok()).toBe(true); + const added = entries().find((e) => e.type === "clip" && e.video === "d1" && e.id !== "o03"); + expect(added?.citeUrl).toBe("https://www.youtube.com/watch?v=d1&t=20s"); +}); + +test("#18 the render queue: what runs and waits at the heavy slot, from its files, and a take's ETA from past renders", async ({ page }) => { + // The slot's own files, as queue-lock writes them (the fixture's slot): an + // e2e suite running, a render of this project waiting for memory. Both name + // live pids (this worker and its parent), so they count. + const lock = path.join(HEAVY, "heavy-queue.lock"); + const put = (file: string, doc: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(doc)); + }; + const now = Date.now(); + put(`${lock}.jobs/${process.pid}.json`, { pid: process.pid, estimateMb: 1500, build: false, exclusive: false, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: new Date(now - 12 * 60_000).toISOString() }); + put(path.join(HEAVY, "e2e-editor-queue.lock.holder.json"), { name: "e2e-editor", pid: process.pid, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: new Date(now - 13 * 60_000).toISOString() }); + put(`${lock}.waiting/${process.ppid}.json`, { + pid: process.ppid, estimateMb: 6020, build: false, exclusive: false, worktree: "/w/main", branch: "main", + cmd: `node /repo/umtool/report-to-video/build-video.mjs ${DIR}/.take-draft-3.render.json --out ${DIR}/takes/draft-3/out --progress ndjson`, + since: new Date(now - 3 * 60_000).toISOString(), stage: "memory", stageSince: new Date(now - 2 * 60_000).toISOString(), + }); + await page.goto(urls.takesHref(PROJECT)); + const q = page.locator("[data-render-queue]"); + await expect(q).toHaveAttribute("data-render-queue", "busy", { timeout: 15_000 }); + await expect(q.locator("[data-render-queue-held-by]")).toHaveText("held by e2e suite e2e-editor"); + const running = q.locator('[data-queue-state="running"]'); + await expect(running).toHaveCount(1); + await expect(running).toContainText("e2e suite e2e-editor"); + await expect(running).toContainText("lane-a (lane/a)"); + await expect(running).toContainText("12 min"); + const waiting = q.locator('[data-queue-state="waiting"]'); + await expect(waiting).toContainText("render of draft-3"); + await expect(waiting).toContainText("at the head of the line, for memory"); + await expect(q.locator("[data-render-queue-mine]")).toContainText("draft-3: waiting 3 min — at the head of the line, for memory"); + // The ETA: draft-2 (from draft-1) 240 s for 30 s; draft-0 and draft-1 600 s fresh. + const eta = q.locator("[data-take-eta]"); + await expect(eta).toHaveAttribute("data-take-eta", "known"); + await expect(eta.locator("[data-take-eta-reuse]")).toHaveText("~4 min made from draft-2 (reuse)"); + await expect(eta.locator("[data-take-eta-fresh]")).toHaveText("~10 min fresh"); + await eta.locator("summary").click(); + await expect(eta).toContainText("draft-0 (fresh): 0:30 of video in 10 min (from its files' times)"); + await shot(page, "18-render-queue-eta", q); + await shot(page, "18-render-queue-page"); + // The job lets go: its ticket is gone and the panel says so. + rmSync(HEAVY, { recursive: true, force: true }); + await expect(q).toHaveAttribute("data-render-queue", "idle", { timeout: 15_000 }); + await expect(q.locator("[data-render-queue-held-by]")).toHaveText("the heavy slot is free"); +}); + +test("#15 the walk's speaker badge: Check speaker scores the clip against the named voices", async ({ page }) => { + await page.goto(urls.clipBenchHref(SPEAKERS, "k04")); + const badge = page.locator("[data-speaker-badge]"); + await expect(badge).toHaveAttribute("data-speaker-badge", "unchecked"); + await expect(badge.locator("[data-speaker-line]")).toHaveText("Speaker: not checked"); + await badge.locator("[data-speaker-check]").click(); + await expect(badge).toHaveAttribute("data-speaker-badge", "matches", { timeout: 60_000 }); + await expect(badge.locator("[data-speaker-line]")).toHaveText(/^Speaker: matches Host \d\.\d\d \/ Guest 0\.\d\d$/); + await expect(badge.locator("[data-speaker-reference]")).toHaveText("vs Host 2 · Guest 1"); + await expect(badge.locator("[data-speaker-reference]")).toHaveAttribute("title", /^measured against: Host: 2 pieces \(2 kept\) · Guest: 1 piece \(1 kept\) · \d{4}-\d\d-\d\d \d\d:\d\d$/); + await shot(page, "15-speaker-badge", page.locator("[data-verdict-bar]").first()); + await shot(page, "15-speaker-badge-page"); + // This clip is Host's: it joins Host's reference set. + await badge.locator("[data-speaker-add-open]").click(); + await badge.locator("[data-speaker-voice]").fill("Host"); + await badge.locator("[data-speaker-add]").click(); + await expect(badge).toContainText("in Host’s voice"); + const speakers = JSON.parse(readFileSync(path.join(FIXTURE, "reports", UI_OPS_SPEAKER, "speakers.json"), "utf8")) as { speakers: { name: string; clips?: string[] }[] }; + expect(speakers.speakers.find((s) => s.name === "Host")?.clips).toEqual(["k01", "k02", "k04"]); +}); diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -89,7 +89,8 @@ export type Decision = { settle?: | { kind: "patch"; clip: string; patch: Record<string, unknown>; label: string } | { kind: "check-links"; label: string; fix?: boolean } - | { kind: "patch-markers"; file: string; label: string }; + | { kind: "patch-markers"; file: string; label: string } + | { kind: "publish-site"; siteId: string; label: string }; /** The clips a project-wide row is about (a site's dead links). */ clips?: string[]; diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -133,6 +133,8 @@ const ACTION_LABEL = { "link-dead": "Fix the links", "links-unverified": "Check links again", "links-unchecked": "Check links", + "site-deploy-behind": (d) => (d.settle?.kind === "publish-site" ? d.settle.label : "Publish the site"), + "clip-link-policy": "Link it by the policy", "no-punctuation": "Check the windows", "manifest-invalid": "Fix the manifest", "stale-build": "Rebuild the video", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -38,6 +38,8 @@ export const WHAT = { "link-dead": "QR links that don't open", "links-unverified": "links not verified", "links-unchecked": "links not checked", + "site-deploy-behind": "a cited site's deploy is behind the cut", + "clip-link-policy": "QR links that break the link policy", "no-punctuation": "windows without punctuation", "manifest-invalid": "manifest invalid", "stale-build": "video out of date", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -18,7 +18,7 @@ import { rawCacheOf } from "../report/raw-cache.mjs"; import { rejectionOf } from "../report/rejectReasons.mjs"; import { resolveVideoDirSync } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { deliverablesState, finishCommand, outDirState, leftoversOf } from "../report/storage.mjs"; -import { CHANNELS_DIR, inside, resolveInRoots } from "../paths.mjs"; +import { CHANNELS_DIR, SITES_DIR, inside, resolveInRoots } from "../paths.mjs"; import { channelName, cleanTitle } from "umtool-report-to-video/attribution"; import { archiveMomentUrl } from "umtool-report-to-video/site-links"; import { deckOn, resolveDeck, teaserTitle } from "umtool-report-to-video/deck"; @@ -46,6 +46,8 @@ import { fileSig, pathCache } from "../pathCache.mjs"; import { citeOffsets } from "../report/citeFollow.mjs"; import { PATCH_FILE_RE, stalePatchMarkers } from "../report/patchMarkers.mjs"; import { linkVerdicts, linksFile, readLinkCheck } from "../report/linkCheck.mjs"; +import { deployBehindWhy, projectSites, sitesByOrigin } from "../report/siteDeploys.mjs"; +import { policyBreaks, policyFixLabel } from "../report/linkPolicy.mjs"; // widen() and the cache's window naming are IMPORTED, never reimplemented. The // bench's "extend to sentence end" has to be the same function the CLI runs, or @@ -1071,6 +1073,14 @@ export const REPORT_DECISION_KINDS = [ "links-unverified", // Links never checked, or changed since the check. `info`, with Check links. "links-unchecked", + // A site the QRs open whose deploy (its recorded corpus.json generatedAt) + // is older than videos the cut cites there, and the check did not find + // those open (siteDeploys.mjs). `open`, with Publish <site>. + "site-deploy-behind", + // A clip whose QR breaks the project's link policy (provenance.linkPolicy, + // linkPolicy.mjs): a direct channel's clip opening an archive, or another + // clip not opening the policy's site. `open`, with the policy's link. + "clip-link-policy", ]; /** @@ -1225,6 +1235,8 @@ export async function reportDecisions(ctx, summary) { } const unpunctuated = []; + /** @type {Map<string, { uploadDate: string | null, landedAt: string | null, webpageUrl: string | null }>} */ + const recordByClip = new Map(); for (const [key, list] of byVideo) { const file = cuePathFor(m, list[0], channelsDir); const doc = file ? await readCues(file) : null; @@ -1248,6 +1260,12 @@ export async function reportDecisions(ctx, summary) { } if (doc.punctuationRate < 0.1) unpunctuated.push(key); + // What the site-deploy row reads (siteDeploys.mjs): the recording's upload + // date and when its transcript landed here. + { + const st = await stat0(file); + for (const e of list) recordByClip.set(e.id, { uploadDate: doc.uploadDate ?? null, landedAt: st ? new Date(st.mtimeMs).toISOString() : null, webpageUrl: doc.webpageUrl ?? null }); + } for (const e of list) { // The standing rule, mechanised. One 14-clip cut shipped with 8 clips @@ -1618,6 +1636,37 @@ export async function reportDecisions(ctx, summary) { } } + // --- the project's link policy (linkPolicy.mjs) -------------------------- + // "Cite via site X; these channels direct": one row per clip whose QR + // breaks it, the fix the window writer's citeUrl. + for (const b of policyBreaks(m, { webpageOf: (e) => recordByClip.get(e.id)?.webpageUrl ?? null })) { + add("clip-link-policy", b.clip, b.why, "open", { + href: clipHref(b.clip), + ...(b.fix + ? { + fix: `umtool window ${id} ${b.clip} --cite-url '${b.fix}'`, + settle: { kind: "patch", clip: b.clip, patch: { citeUrl: b.fix }, label: policyFixLabel(b) }, + } + : {}), + }); + } + + // --- is each site's deploy recent enough? (siteDeploys.mjs) -------------- + // From the same recorded check: the deploy's date is its corpus.json's + // generatedAt. A cited video newer than it, whose link the check did not + // find open, is not on the site yet. + { + const doc = await readLinkCheck(dir); + for (const site of projectSites(m, doc, { sites: sitesByOrigin(SITES_DIR), recordOf: (cid) => recordByClip.get(cid) ?? null })) { + if (!site.newer.length) continue; + add("site-deploy-behind", site.host, deployBehindWhy(site), "open", { + fix: site.siteId ? `pnpm ops build-deploy --json '{"siteId":"${site.siteId}"}'` : `umtool links ${id}`, + ...(site.siteId ? { settle: { kind: "publish-site", siteId: site.siteId, label: `Publish ${site.siteId}` } } : {}), + clips: site.newer.map((n) => n.clip), + }); + } + } + // --- the build ----------------------------------------------------------- if (s.build.stale) { add( diff --git a/umtool/lib/report/linkPolicy.mjs b/umtool/lib/report/linkPolicy.mjs @@ -0,0 +1,211 @@ +// A project's LINK POLICY (UI notes 2026-10-30, #10): "cite via site X; these +// channels direct". On the Ember cut Ember's and Side Scrollers' clips linked +// anilyzer while Harmful Opinions' linked YouTube, and the citeUrls were +// rewritten by hand twice. The policy lives in the manifest, beside the other +// link setting it qualifies (`provenance.siteOrigin`): +// +// provenance.linkPolicy = { via?: "<origin>", direct?: ["<channel slug>", …] } +// +// via the archive every clip's QR opens (default: provenance.siteOrigin) +// direct the channels whose clips link the platform's own page at the cite +// (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble `start=<s>` -- +// common/lib/clips/assist.mjs watchUrlAt over the record's webpage_url) +// +// Enforced in two places, both through the existing writers: +// +// - THE INSERTERS (manifest.mjs addClip: the strip's selection, the clip +// finder, a live share; `umtool timeline insert`): the citeUrl a new clip +// is written with is the policy's (`policyCiteUrl`), never a neighbour's +// link that breaks it. +// - THE CHECK (lib/projects/report.mjs): `clip-link-policy`, one row per clip +// whose QR breaks the policy, its settle the window writer's citeUrl patch +// ("Link via site.test" / "Link its YouTube page"). +// +// A clip with its own media (`src`) is not judged. Plain ESM: the CLI runs it +// under bare node. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { archiveMomentUrl } from "umtool-report-to-video/site-links"; +import { archiveLinkOf } from "./linkCheck.mjs"; +import { originOf } from "./siteDeploys.mjs"; + +export const LINK_POLICY_KEY = "linkPolicy"; +const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i; + +/** + * A policy as written, checked and normalised: `{ via, direct }` (via an + * origin or null, direct sorted and unique), or null for "no policy". Throws + * on a policy the check could not apply. + * @param {unknown} raw + * @returns {{ via: string | null, direct: string[] } | null} + */ +export function normalizeLinkPolicy(raw) { + if (raw == null) return null; + if (typeof raw !== "object" || Array.isArray(raw)) throw new Error("provenance.linkPolicy is { via?, direct? }"); + const r = /** @type {Record<string, unknown>} */ (raw); + for (const k of Object.keys(r)) if (k !== "via" && k !== "direct") throw new Error(`provenance.linkPolicy has no key "${k}" (via, direct)`); + let via = null; + if (r.via != null && String(r.via).trim() !== "") { + via = originOf(String(r.via).trim()); + if (!via) throw new Error(`linkPolicy.via is a site's http(s) address, not ${JSON.stringify(r.via)}`); + } + const list = r.direct == null ? [] : Array.isArray(r.direct) ? r.direct : String(r.direct).split(","); + const direct = [...new Set(list.map((s) => String(s).trim()).filter(Boolean))].sort(); + for (const s of direct) if (!SLUG_RE.test(s)) throw new Error(`linkPolicy.direct names channel slugs, not ${JSON.stringify(s)}`); + return via || direct.length ? { via, direct } : null; +} + +/** The manifest's policy, or null (none, or one that does not read). */ +export function linkPolicyOf(m) { + try { + return normalizeLinkPolicy(m?.provenance?.[LINK_POLICY_KEY]); + } catch { + return null; + } +} + +const chanOf = (m, e) => e?.channel ?? m?.provenance?.channelSlug ?? null; +const citeOf = (e) => Math.floor(Number(e?.cite ?? e?.cutStart ?? e?.start ?? 0) || 0); + +/** + * Where a clip's QR points now -- build-video's rule (lib/projects/report.mjs + * citeUrlFor): its own citeUrl, else its moment on the provenance's origin. + */ +export function currentLinkOf(m, e) { + if (typeof e?.citeUrl === "string" && e.citeUrl) return e.citeUrl; + return archiveMomentUrl({ ...e, channel: chanOf(m, e) }, m?.provenance, e?.start ?? 0, { origin: m?.provenance?.siteOrigin ?? "" }); +} + +/** + * What the policy wants of one clip: `{ want: "direct" | "via", url }`, the + * url null when it cannot be built (a direct clip whose record names no + * webpage_url, a via policy with no origin). Null when the policy has nothing + * to say about the clip. + * @param {Record<string, any>} m + * @param {Record<string, any>} e + * @param {{ webpageUrl?: string | null, policy?: ReturnType<typeof linkPolicyOf> }} [o] + */ +export function policyLinkFor(m, e, { webpageUrl = null, policy = linkPolicyOf(m) } = {}) { + if (!policy || e?.type !== "clip" || e.src != null) return null; + const chan = chanOf(m, e); + const cite = citeOf(e); + if (chan && policy.direct.includes(chan)) return { want: /** @type {const} */ ("direct"), url: watchUrlAt(webpageUrl, cite) }; + const via = policy.via ?? originOf(m?.provenance?.siteOrigin); + if (!via) return null; + return { want: /** @type {const} */ ("via"), url: archiveMomentUrl({ ...e, channel: chan }, m?.provenance, cite, { origin: via }), via }; +} + +/** + * Whether the clip's QR keeps the policy: a direct channel's is not an + * archive link; any other's is an archive link on `via`. `null` when the + * policy says nothing about the clip. + */ +export function keepsPolicy(m, e, o = {}) { + const want = policyLinkFor(m, e, o); + if (!want) return null; + const a = archiveLinkOf(currentLinkOf(m, e)); + if (want.want === "direct") return !a; + return !!a && a.origin === /** @type {any} */ (want).via; +} + +/** + * Every clip whose QR breaks the policy, with the citeUrl that keeps it (null + * when it cannot be built). Pure over `webpageOf` (the record's webpage_url). + * @param {Record<string, any>} m + * @param {{ webpageOf?: (e: Record<string, any>) => string | null }} [o] + */ +export function policyBreaks(m, { webpageOf = () => null } = {}) { + const policy = linkPolicyOf(m); + if (!policy) return []; + const out = []; + for (const e of m?.timeline ?? []) { + if (e?.type !== "clip" || e.src != null) continue; + const webpageUrl = webpageOf(e); + const want = policyLinkFor(m, e, { webpageUrl, policy }); + if (!want || keepsPolicy(m, e, { webpageUrl, policy }) !== false) continue; + const current = currentLinkOf(m, e); + let host = ""; + try { + host = new URL(current).host; + } catch { + host = current; + } + out.push({ + clip: e.id, + channel: chanOf(m, e), + current, + want: want.want, + fix: want.url, + why: + want.want === "direct" + ? `${chanOf(m, e)} links direct by the project's link policy, but its QR opens ${host}${want.url ? "" : " — and its record names no platform page to link (no webpage_url)"}` + : `the project's link policy cites via ${new URL(/** @type {any} */ (want).via).host}, but its QR opens ${host}`, + }); + } + return out; +} + +/** The settle button's words for a fix. */ +export function policyFixLabel(b) { + if (b.want === "direct") { + let host = "the platform"; + try { + host = new URL(String(b.fix)).hostname.replace(/^(?:www|m)\./, ""); + } catch { + /* keep the generic word */ + } + const name = /youtu/.test(host) ? "YouTube" : /twitch/.test(host) ? "Twitch" : /rumble/.test(host) ? "Rumble" : host; + return `Link its ${name} page`; + } + try { + return `Link via ${new URL(String(b.fix)).host}`; + } catch { + return "Link via the site"; + } +} + +/** + * The record's webpage_url, read once per recording: the cue file's + * `webpageUrl`, else metadata.info.json's `webpage_url`. Null when neither + * says (or there is no channels dir). + * @param {string | null} channelsDir + */ +export function webpageReader(channelsDir) { + const memo = new Map(); + return async (slug, video) => { + if (!channelsDir || !slug || !video) return null; + const key = `${slug}/${video}`; + if (!memo.has(key)) { + memo.set(key, (async () => { + const dir = await resolveVideoDir(channelsDir, slug, video).catch(() => path.join(channelsDir, slug, "data", video)); + const read = (name) => readFile(path.join(/* turbopackIgnore: true */ dir, name), "utf8").then(JSON.parse, () => null); + const cues = await read("transcript.cues.json"); + if (typeof cues?.webpageUrl === "string" && cues.webpageUrl) return cues.webpageUrl; + const meta = await read("metadata.info.json"); + return typeof meta?.webpage_url === "string" && meta.webpage_url ? meta.webpage_url : null; + })()); + } + return memo.get(key); + }; +} + +/** + * The citeUrl an inserter writes a NEW clip with under the policy: the + * policy's link when the clip's link would break it (a neighbour's copied + * citeUrl, or the default origin when `via` is another site), `undefined` + * when the clip keeps it as it is (so nothing is written), `null` when the + * link the policy wants cannot be built (the clip's citeUrl is dropped so the + * check names it, rather than a copied link that breaks the policy). + * @param {Record<string, any>} m + * @param {Record<string, any>} entry + * @param {string | null} webpageUrl + */ +export function policyCiteUrl(m, entry, webpageUrl) { + const policy = linkPolicyOf(m); + const want = policyLinkFor(m, entry, { webpageUrl, policy }); + if (!want) return undefined; + if (keepsPolicy(m, entry, { webpageUrl, policy }) === true) return undefined; + return want.url; +} diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -159,3 +159,111 @@ export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s) return e instanceof CliError ? 2 : 1; } } + +export const LINK_POLICY_USAGE = [ + "usage: umtool link-policy <project> [--via <site id | https://…>] [--direct <slug,slug…>] [--clear] [--fix] [--json]", + "", + "The project's link policy, provenance.linkPolicy: \"cite via site X; these channels direct\". --via names the", + "archive every clip's QR opens (a site id from transcripts/sites, or its address; '' goes back to", + "provenance.siteOrigin); --direct the channels whose clips link the platform's own page at the cite ('' none);", + "--clear removes the policy. New clips are written by it (the inserters); the clips already in the cut that", + "break it are `umtool check`'s clip-link-policy rows. --fix rewrites each of them that has a fix through the", + "window writer. With no flag, prints the policy and what breaks it. Exit 1 when a clip still breaks it.", +].join("\n"); + +/** + * `umtool link-policy …` + * @param {string[]} args the words after `link-policy` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [opts] + * @returns {Promise<number>} + */ +export async function linkPolicyCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) { + try { + const { linkPolicyOf, normalizeLinkPolicy, policyBreaks, webpageReader } = await import("./linkPolicy.mjs"); + const { sitesByOrigin } = await import("./siteDeploys.mjs"); + const { updateLinkPolicy } = await import("./manifest.mjs"); + const { channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs"); + const { SITES_DIR } = await import("../paths.mjs"); + const words = []; + /** @type {Map<string, string | true>} */ + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--via" || a === "--direct") { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value ('' clears it)`); + flags.set(a, args[++i]); + } else if (["--clear", "--fix", "--json", "--help"].includes(a)) flags.set(a, true); + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(LINK_POLICY_USAGE); + return flags.has("--help") ? 0 : 2; + } + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); + let m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const notes = []; + if (flags.has("--clear") || flags.has("--via") || flags.has("--direct")) { + if (flags.has("--clear") && (flags.has("--via") || flags.has("--direct"))) throw new CliError("--clear takes no --via or --direct"); + let next = null; + if (!flags.has("--clear")) { + const was = linkPolicyOf(m) ?? { via: null, direct: [] }; + let via = was.via; + if (flags.has("--via")) { + const v = String(flags.get("--via")).trim(); + if (!v) via = null; + else if (/^https?:\/\//i.test(v)) via = v; + else { + const hit = [...sitesByOrigin(sitesDir ?? SITES_DIR)].find(([, s]) => s.siteId === v); + if (!hit) throw new CliError(`--via ${v}: no site of that id has a siteUrl (transcripts/sites/<id>/site.json); pass its address`); + via = hit[0]; + } + } + const direct = flags.has("--direct") ? String(flags.get("--direct")) : was.direct; + next = normalizeLinkPolicy({ via, direct }); + } + const res = await withEditNotes(project, () => updateLinkPolicy(project.dir, next)); + notes.push(res.result.changed ? "link policy saved" : "link policy unchanged"); + m = await readManifest(project.dir); + } + const shadowExists = await hasShadowChannels(project.dir); + const read = webpageReader(channelsDirFor(project.dir, m, { shadowExists })); + const web = new Map(); + for (const e of m.timeline ?? []) { + if (e?.type === "clip") web.set(e.id, await read(e.channel ?? m.provenance?.channelSlug, e.video)); + } + let breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null }); + const fixed = []; + if (flags.has("--fix")) { + for (const b of breaks) { + if (!b.fix) continue; + await withEditNotes(project, () => updateClip(project.dir, b.clip, { citeUrl: b.fix })); + fixed.push({ clip: b.clip, from: b.current, to: b.fix }); + } + if (fixed.length) { + m = await readManifest(project.dir); + breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null }); + } + } + const policy = linkPolicyOf(m); + if (flags.has("--json")) { + out(JSON.stringify({ ok: breaks.length === 0, project: project.id, policy, breaks, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); + return breaks.length ? 1 : 0; + } + for (const n of notes) out(n); + for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`); + if (!policy) out(`${project.id}: no link policy (every QR opens provenance.siteOrigin, or the clip's own citeUrl)`); + else out(`${project.id}: cite via ${policy.via ?? `provenance.siteOrigin (${m.provenance?.siteOrigin ?? "unset"})`}; direct: ${policy.direct.length ? policy.direct.join(", ") : "none"}`); + for (const b of breaks) out(`BREAKS ${b.clip} ${b.why}${b.fix ? `\n fix: ${b.fix}` : ""}`); + if (policy && !breaks.length) out("every clip's QR keeps it"); + return breaks.length ? 1 : 0; + } catch (e) { + err(`umtool link-policy: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -58,6 +58,9 @@ import { } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; import { parseMuteFrom } from "./playback.mjs"; +import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs"; +import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources"; +import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs"; import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; @@ -1076,7 +1079,7 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null * @param {{ token?: string | null, now?: string | null }} [opts] */ export async function addClip(dir, spec, { token = null, now = null } = {}) { - return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m) => { + return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m, webpageUrl) => { if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }"); if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id"); const num = (k, v) => { @@ -1097,6 +1100,8 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) { if (quote) entry.quote = quote.slice(0, 2000); const title = typeof spec.title === "string" ? spec.title.trim() : ""; if (title) entry.title = title.slice(0, 300); + // The project's link policy (linkPolicy.mjs): the QR a new clip gets is the policy's. + applyPolicyLink(m, entry, webpageUrl); const stamp = now ?? new Date().toISOString(); entry.assist = { by: "operator", @@ -1115,7 +1120,7 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) { } m.timeline.splice(at, 0, entry); return { id: entry.id, at, entry }; - })); + }, { prepare: (m) => policyWebpage(dir, m, spec) })); } @@ -2081,13 +2086,16 @@ export function reanchorAfterRemove(m, removed, i) { * One structural write: token, read, `mutate` (which throws to refuse), the * build's checks, the auto snapshot of the file as it still is, then the write. */ -async function structural(dir, op, token, mutate, { snapshotEvery = undefined } = {}) { +async function structural(dir, op, token, mutate, { snapshotEvery = undefined, prepare = null } = {}) { return withManifestLock(async () => { const current = await manifestToken(dir); if (token !== null && current !== token) throw new StaleToken(token, current); const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); const timelineBefore = Array.isArray(manifest.timeline) ? [...manifest.timeline] : []; - const result = applyStructural(manifest, mutate); + // What a write must read before it mutates (an inserter's link policy: + // the record's webpage_url), inside the lock, after the token is checked. + const prepared = prepare ? await prepare(manifest) : undefined; + const result = applyStructural(manifest, (m) => mutate(m, prepared)); const snapshot = await autoSnapshot(dir, op, snapshotEvery === undefined ? {} : { every: snapshotEvery }); const nextToken = await writeManifestAtomic(dir, manifest); // The project's take patches follow a removal as the manifest's markers @@ -2280,12 +2288,70 @@ function clipEntry(timeline, e) { * @param {{ token?: string | null, at?: number | null }} [opts] `at` is afterId's index */ export async function insertEntry(dir, afterId, spec, { token = null, at = null } = {}) { - return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m) => { + return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m, webpageUrl) => { const i = afterId ? entryIndex(m.timeline, afterId, at) + 1 : 0; const entry = entryFromSpec(m.timeline, spec); + // A clip's QR is the project's link policy's (linkPolicy.mjs), not a copied link that breaks it. + if (entry.type === "clip") applyPolicyLink(m, entry, webpageUrl); m.timeline.splice(i, 0, entry); return { id: entry.id, at: i, entry }; - })); + }, { prepare: (m) => policyWebpage(dir, m, typeof spec === "string" ? parseClipSpec(spec) : spec) })); +} + +// ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) ----------- + +/** + * The record's webpage_url when the project's link policy links `spec`'s + * channel direct, else null: read inside the write's lock (structural's + * `prepare`), so the inserters write the platform link in the same write. + * @param {string} dir + * @param {Record<string, any>} m the manifest as the write read it + * @param {{ channel?: string, video?: string } | null | undefined} spec + */ +async function policyWebpage(dir, m, spec) { + const policy = linkPolicyOf(m); + if (!policy?.direct.length || !spec || typeof spec !== "object") return null; + const chan = typeof spec.channel === "string" && spec.channel ? spec.channel : m.provenance?.channelSlug; + if (!chan || !policy.direct.includes(chan) || typeof spec.video !== "string") return null; + const shadowExists = await stat(path.join(dir, POLICY_SHADOW)).then((st) => st.isDirectory(), () => false); + const channelsDir = policyChannelsDirFor(dir, m, { shadowExists, fallback: POLICY_CHANNELS_DIR }); + return webpageReader(channelsDir)(chan, spec.video); +} + +/** Write the policy's citeUrl on a new clip: its link when the clip's breaks it; a copied one it cannot replace is dropped. */ +function applyPolicyLink(m, entry, webpageUrl) { + const cu = policyCiteUrl(m, entry, webpageUrl); + if (typeof cu === "string" && cu) entry.citeUrl = cu; + else if (cu === null) delete entry.citeUrl; +} + +/** + * Set (or with null, clear) the project's link policy, + * `provenance.linkPolicy = { via?, direct? }` (linkPolicy.mjs + * normalizeLinkPolicy: `via` an origin, `direct` channel slugs). A no-op + * writes nothing. The clips already in the cut are not rewritten here: what + * breaks the policy is the check's `clip-link-policy` rows, each with its fix. + * + * @param {string} dir + * @param {unknown} policy + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ linkPolicy: { via: string | null, direct: string[] } | null, token: string | null, changed: boolean }>} + */ +export async function updateLinkPolicy(dir, policy, { token = null } = {}) { + const next = normalizeLinkPolicy(policy); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const was = manifest.provenance?.[LINK_POLICY_KEY] ?? null; + const written = next ? { ...(next.via ? { via: next.via } : {}), ...(next.direct.length ? { direct: next.direct } : {}) } : null; + if (JSON.stringify(was) === JSON.stringify(written)) return { linkPolicy: next, token: current, changed: false }; + if (!isObj(manifest.provenance)) manifest.provenance = {}; + if (written) manifest.provenance[LINK_POLICY_KEY] = written; + else delete manifest.provenance[LINK_POLICY_KEY]; + const nextToken = await writeManifestAtomic(dir, manifest); + return { linkPolicy: next, token: nextToken, changed: true }; + }); } // ---- sections, edited as sections (UI notes 2026-10-30, item 1) ----------- diff --git a/umtool/lib/report/siteDeploys.mjs b/umtool/lib/report/siteDeploys.mjs @@ -0,0 +1,155 @@ +// Which sites does this cut's QR links depend on, and is each one's deploy +// recent enough to hold what the cut cites? (UI notes 2026-10-30, #9) +// +// On the Ember cut anilyzer's publish policy was "build" only: nothing said +// the video being made cited a site that had not been deployed since 9 Oct. +// The link check (linkCheck.mjs, #8) already reads each site's corpus.json and +// records its `generatedAt` -- the day the deployed bundle's data was built -- +// in out/links.json. This module reads that record (it never fetches): +// +// - the SITES: every origin a clip QR the cut draws opens (linksOf), each +// named by the site whose site.json `siteUrl` it is (SITES_DIR, read only) +// and dated by the recorded corpus.json; +// - the cited videos NEWER than that deploy: a clip on that site whose +// recording was uploaded after it, or whose transcript landed here after +// it, and whose link the check did not find open (a link the check opened +// is on the site, whatever its dates say). +// +// The check row `site-deploy-behind` (lib/projects/report.mjs) is one per site +// with such clips, its settle "Publish <site>" asking the editor to build and +// deploy that site (POST /api/report/publish-site -> the editor's ops +// build-deploy). Plain ESM: the CLI runs it under bare node. +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { archiveLinkOf, linksOf } from "./linkCheck.mjs"; + +/** `https://x.pages.dev/` -> `https://x.pages.dev`; null for anything not http(s). */ +export function originOf(url) { + try { + const u = new URL(String(url)); + return u.protocol === "http:" || u.protocol === "https:" ? u.origin : null; + } catch { + return null; + } +} + +/** + * Every site with a `siteUrl`, by its origin: `{ siteId, title }`. Read once + * per call (a handful of small files); a site.json that does not parse is + * skipped. + * @param {string} sitesDir + * @returns {Map<string, { siteId: string, title: string | null }>} + */ +export function sitesByOrigin(sitesDir) { + const out = new Map(); + let ids = []; + try { + ids = readdirSync(/* turbopackIgnore: true */ sitesDir); + } catch { + return out; + } + for (const id of ids.sort()) { + let doc; + try { + doc = JSON.parse(readFileSync(/* turbopackIgnore: true */ path.join(sitesDir, id, "site.json"), "utf8")); + } catch { + continue; + } + const origin = originOf(doc?.siteUrl); + if (!origin || out.has(origin)) continue; + out.set(origin, { siteId: id, title: typeof doc?.siteTitle === "string" ? doc.siteTitle : typeof doc?.title === "string" ? doc.title : null }); + } + return out; +} + +/** `20261020` / `2026-10-20` / an ISO time -> `2026-10-20`, else null. */ +export function dayOf(v) { + const s = String(v ?? "").trim(); + if (/^\d{8}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`; + const m = /^(\d{4}-\d{2}-\d{2})/.exec(s); + return m ? m[1] : null; +} + +/** + * The sites the cut's links depend on, with each one's deploy and the cited + * videos newer than it. Pure over its inputs. + * + * @param {Record<string, any>} m the manifest + * @param {{ origins?: Record<string, any>, links?: Array<{ clip: string, url: string, state: string }>, checkedAt?: string } | null} linkDoc out/links.json + * @param {{ sites?: Map<string, { siteId: string, title: string | null }>, recordOf?: (clipId: string) => { uploadDate?: string | null, landedAt?: string | null } | null }} [opts] + * `recordOf`: what is known of the clip's recording here -- its upload date + * and when its transcript landed (the cue file's mtime, ISO). + * @returns {Array<{ + * origin: string, host: string, siteId: string | null, title: string | null, + * deployedAt: string | null, state: "ok" | "unreachable" | "no-corpus" | "unchecked", + * clips: string[], links: number, + * newer: Array<{ clip: string, why: string, day: string }>, + * }>} + */ +export function projectSites(m, linkDoc, { sites = new Map(), recordOf = () => null } = {}) { + /** @type {Map<string, { clips: Set<string>, links: Array<{ clip: string, url: string }> }>} */ + const by = new Map(); + for (const l of linksOf(m)) { + const a = archiveLinkOf(l.url); + if (!a) continue; + if (!by.has(a.origin)) by.set(a.origin, { clips: new Set(), links: [] }); + const g = /** @type {{ clips: Set<string>, links: Array<{ clip: string, url: string }> }} */ (by.get(a.origin)); + g.clips.add(l.clip); + g.links.push(l); + } + const checked = new Map((linkDoc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l.state])); + const out = []; + for (const [origin, g] of by) { + const o = linkDoc?.origins?.[origin] ?? null; + const deployedAt = typeof o?.generatedAt === "string" ? o.generatedAt : null; + const deployDay = dayOf(deployedAt); + const site = sites.get(origin) ?? null; + const newer = []; + if (deployDay) { + const seen = new Set(); + for (const l of g.links) { + if (seen.has(l.clip)) continue; + // The check opened it: the record is on the site. + if (checked.get(`${l.clip}\u0000${l.url}`) === "ok") continue; + const r = recordOf(l.clip) ?? {}; + const up = dayOf(r.uploadDate); + const landed = dayOf(r.landedAt); + if (up && up > deployDay) { + seen.add(l.clip); + newer.push({ clip: l.clip, why: `uploaded ${up}`, day: up }); + } else if (landed && landed > deployDay) { + seen.add(l.clip); + newer.push({ clip: l.clip, why: `transcribed here ${landed}`, day: landed }); + } + } + } + let host = origin; + try { + host = new URL(origin).host; + } catch { + /* the origin as written */ + } + out.push({ + origin, + host, + siteId: site?.siteId ?? null, + title: site?.title ?? (typeof o?.title === "string" ? o.title : null), + deployedAt, + state: o ? o.state : "unchecked", + clips: [...g.clips], + links: g.links.length, + newer, + }); + } + return out.sort((a, b) => b.links - a.links || a.host.localeCompare(b.host)); +} + +/** The check row's sentence for one site with newer videos. */ +export function deployBehindWhy(s) { + const list = s.newer.slice(0, 6).map((n) => `${n.clip} (${n.why})`).join(", "); + const more = s.newer.length > 6 ? ` and ${s.newer.length - 6} more` : ""; + return ( + `${s.siteId ?? s.host}'s deploy is from ${dayOf(s.deployedAt)}; ${s.newer.length} cited video${s.newer.length === 1 ? " is" : "s are"} newer: ${list}${more}` + + ` — publish the site before the video ships, or link elsewhere` + ); +} diff --git a/umtool/lib/report/speakerCheck.mjs b/umtool/lib/report/speakerCheck.mjs @@ -0,0 +1,321 @@ +// `umtool speaker-check <project>` (UI notes 2026-10-30, #15): which of the +// project's named voices a clip is -- "Speaker: matches Ember 0.93 / Kirsche +// 0.83" on the walk -- with the reference sets it was measured against. +// +// The scorer is common's (lib/montage/speakerCheck.mjs, over the voice match's +// pieces: TitaNet-small through sherpa-onnx, local). This module is umtool's +// half, the voice match's (voiceMatch.mjs) again: which seconds of which file +// each clip is (planClips), and the reference sets, `<project>/speakers.json`: +// +// { "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] }, +// { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] } +// +// clips clips of this cut known to be that voice (a confirmed clip; the +// walk's "Add to <name>'s voice") +// videos recordings of that voice alone (`<channel>/<id>`): the first +// REFERENCE_SECONDS of speech, in pieces, as the voice match reads them +// channels channels whose solo recordings are that voice (the voice +// match's heuristic picks them) +// +// The app's "Check speaker" runs this command as a job (speakerCheckSteps) +// through the machine's heavy slot -- light, but a render the operator is +// waiting for comes first (render mode). Nothing here calls a model but the +// local speaker-embedding one; nothing touches the network. +import { existsSync } from "node:fs"; +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_THRESHOLDS, PHRASE_PAD_S, REFERENCE_VIDEOS, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { readSpeakerCheck, runSpeakerCheck, writeSpeakerCheck } from "yt-dlp-transcript-common/lib/montage/speakerCheck.mjs"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; +import { REPO_ROOT } from "../paths.mjs"; +import { UMTOOL_DIR } from "./driver.mjs"; +import { planClips, referenceRecordings } from "./voiceMatch.mjs"; + +export const SPEAKERS_FILE = "speakers.json"; +const NAME_RE = /^[^\s/=,][^/=,]{0,47}$/; +const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; +const VIDEO_RE = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9_.-]+$/i; + +class CliError extends Error {} + +/** + * The reference sets, checked: `[{ name, clips, videos, channels }]` ([] with + * no file). Throws on a file that does not read as one. + * @param {unknown} raw + */ +export function normalizeSpeakers(raw) { + const list = raw && typeof raw === "object" && Array.isArray(/** @type {any} */ (raw).speakers) ? /** @type {any} */ (raw).speakers : null; + if (!list) throw new Error(`${SPEAKERS_FILE} is { "speakers": [ { "name", "clips"?, "videos"?, "channels"? } ] }`); + const seen = new Set(); + return list.map((s, i) => { + const name = String(s?.name ?? "").trim(); + if (!NAME_RE.test(name)) throw new Error(`speaker ${i + 1}: a name of 1–48 characters, no / = or comma (got ${JSON.stringify(s?.name)})`); + if (seen.has(name.toLowerCase())) throw new Error(`two speakers are named "${name}"`); + seen.add(name.toLowerCase()); + const strs = (k, re) => { + const v = s?.[k] ?? []; + if (!Array.isArray(v)) throw new Error(`${name}: ${k} is a list`); + const out = [...new Set(v.map((x) => String(x).trim()).filter(Boolean))]; + for (const x of out) if (!re.test(x)) throw new Error(`${name}: ${k} has ${JSON.stringify(x)}`); + return out; + }; + return { name, clips: strs("clips", ID_RE), videos: strs("videos", VIDEO_RE), channels: strs("channels", /^[a-z0-9][a-z0-9._-]*$/i) }; + }); +} + +/** The project's reference sets ([] when there is no speakers.json). */ +export async function readSpeakers(dir) { + let text; + try { + text = await readFile(path.join(dir, SPEAKERS_FILE), "utf8"); + } catch { + return []; + } + return normalizeSpeakers(JSON.parse(text)); +} + +/** Write the reference sets whole (tmp + rename). */ +export async function writeSpeakers(dir, speakers) { + const list = normalizeSpeakers({ speakers }); + const file = path.join(dir, SPEAKERS_FILE); + const tmp = `${file}.${process.pid}.tmp`; + 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); + return list; +} + +/** + * `Name=clip:e01,video:chan/id,channel:slug` (a bare word is a clip id, a + * `chan/id` a video) -> a speaker. + * @param {string} spec + */ +export function parseSpeakerSpec(spec) { + const i = String(spec).indexOf("="); + if (i <= 0) throw new CliError(`--set takes Name=<clip id | channel/id | channel:slug>,… (got ${JSON.stringify(spec)})`); + const name = spec.slice(0, i).trim(); + const s = { name, clips: [], videos: [], channels: [] }; + for (const raw of spec.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean)) { + const [k, v] = raw.includes(":") ? [raw.slice(0, raw.indexOf(":")), raw.slice(raw.indexOf(":") + 1)] : [raw.includes("/") ? "video" : "clip", raw]; + if (k === "clip") s.clips.push(v); + else if (k === "video") s.videos.push(v); + else if (k === "channel") s.channels.push(v); + else throw new CliError(`--set ${name}: "${raw}" is clip:<id>, video:<channel>/<id> or channel:<slug>`); + } + return s; +} + +/** Add one clip of the cut to a voice (made when it is new); a clip is in one voice at a time. */ +export async function addClipToSpeaker(dir, name, clipId) { + const list = await readSpeakers(dir); + const n = String(name ?? "").trim(); + let s = list.find((x) => x.name.toLowerCase() === n.toLowerCase()); + for (const x of list) x.clips = x.clips.filter((c) => c !== clipId); + if (!s) { + s = { name: n, clips: [], videos: [], channels: [] }; + list.push(s); + } + s.clips.push(String(clipId)); + return writeSpeakers(dir, list); +} + +/** + * The scorer's inputs for the project: the planned clips, the keys to check, + * the voices with their pieces. + */ +export async function planSpeakerCheck(dir, manifest, { clipIds = [], channelsDir, speakers }) { + const clips = await planClips(dir, manifest, { channelsDir, pad: PHRASE_PAD_S }); + const keyOf = new Map(clips.filter((c) => c.id).map((c) => [c.id, c.key])); + for (const id of clipIds) if (!keyOf.has(id)) throw new CliError(`no clip ${id} in the cut (or it has its own media)`); + const check = clipIds.length ? clipIds.map((id) => /** @type {string} */ (keyOf.get(id))) : clips.filter((c) => c.id).map((c) => c.key); + const voices = []; + const skipped = []; + for (const s of speakers) { + const clipKeys = s.clips.map((id) => keyOf.get(id)).filter(Boolean); + for (const id of s.clips) if (!keyOf.has(id)) skipped.push({ speaker: s.name, why: `clip ${id} is not in the cut` }); + let items = []; + let recordings = []; + if (s.videos.length || s.channels.length) { + const r = await referenceRecordings({ channelsDir, channels: s.channels, videos: s.videos, n: REFERENCE_VIDEOS }); + items = r.items.map((it) => ({ key: it.key, file: it.file, start: it.start, dur: it.dur })); + recordings = [...new Map(r.items.map((it) => [`${it.slug}/${it.video}`, { channel: it.slug, video: it.video, date: it.date ?? null, title: it.title ?? null }])).values()]; + for (const x of r.skipped) skipped.push({ speaker: s.name, why: `${x.channel}/${x.video}: ${x.why}` }); + } + voices.push({ name: s.name, clipKeys: /** @type {string[]} */ (clipKeys), items, recordings }); + } + return { clips, check, voices, skipped }; +} + +export const SPEAKER_CHECK_USAGE = [ + "usage: umtool speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]", + " umtool speaker-check <project> --list | --set 'Name=<clip id>,<channel>/<id>,channel:<slug>,…' | --remove Name", + "", + "Which of the project's named voices each clip is: TitaNet-small (sherpa-onnx, local) on the clip's phrase", + `± ${PHRASE_PAD_S} s, voiced frames only, against each voice's robust centroid -> ${"<project>"}/speaker-check.json (merged:`, + "a check of one clip keeps the others'). The voices are <project>/speakers.json: per name, clips of the cut,", + "recordings of that voice alone (<channel>/<id>), or channels whose solo recordings it is. A clip that is in a", + "voice's set is scored against the rest of it. An aid to the ear: it rules on nothing.", + "The engine: VOICE_MATCH_PYTHON / VOICE_MATCH_MODEL, else settings.diarization.python / .embModel, else .diarize/.", +].join("\n"); + +const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); + +/** + * `umtool speaker-check …` + * @param {string[]} args + * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, engine?: Record<string, unknown> }} [opts] + */ +export async function speakerCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) { + try { + const words = []; + /** @type {Record<string, string[]>} */ + const flags = {}; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (["--clip", "--set", "--remove", "--progress"].includes(a)) { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + (flags[a] ??= []).push(args[++i]); + } else if (["--json", "--list", "--help"].includes(a)) (flags[a] ??= []).push(""); + else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`); + else words.push(a); + } + if (flags["--help"] || !words.length) { + log(SPEAKER_CHECK_USAGE); + return flags["--help"] ? 0 : 2; + } + const r = await resolveProject(words[0], reportsRoot); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`); + const ndjson = flags["--progress"]?.at(-1) === "ndjson"; + const say = (line) => (ndjson ? err(line) : log(line)); + const emit = (ev) => { + if (ndjson) log(JSON.stringify({ ev: "speaker-check", ...ev })); + }; + + // The reference sets: edited, or listed. + if (flags["--set"] || flags["--remove"]) { + let list = await readSpeakers(project.dir); + for (const spec of flags["--set"] ?? []) { + const s = parseSpeakerSpec(spec); + list = [...list.filter((x) => x.name.toLowerCase() !== s.name.toLowerCase()), s]; + } + for (const name of flags["--remove"] ?? []) list = list.filter((x) => x.name.toLowerCase() !== name.trim().toLowerCase()); + await writeSpeakers(project.dir, list); + say(`${SPEAKERS_FILE}: ${list.length} voice(s)`); + } + const speakers = await readSpeakers(project.dir); + if (flags["--list"] || flags["--set"] || flags["--remove"]) { + if (flags["--json"]) log(JSON.stringify({ project: project.id, speakers }, null, 2)); + else for (const s of speakers) log(`${s.name}: ${[...s.clips.map((c) => `clip ${c}`), ...s.videos, ...s.channels.map((c) => `channel ${c}`)].join(", ") || "(nothing yet)"}`); + return 0; + } + if (!speakers.length) { + throw new CliError(`no voices to compare with: name them in ${SPEAKERS_FILE} (umtool speaker-check ${project.id} --set 'Name=<clip id>,<channel>/<id>,…'), or the walk's "Add to a voice"`); + } + + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError(`${project.id} has no manifest`); + const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); + if (!channelsDir) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from"); + emit({ phase: "plan" }); + const plan = await planSpeakerCheck(project.dir, manifest, { clipIds: flags["--clip"] ?? [], channelsDir, speakers }); + for (const s of plan.skipped) say(`${s.speaker}: ${s.why}`); + say(`${plan.check.length} clip(s) to check against ${plan.voices.map((v) => `${v.name} (${v.clipKeys.length + v.items.length} piece(s))`).join(", ")}`); + + let settings = null; + try { + settings = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")); + } catch { + settings = null; + } + const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts }); + const t0 = Date.now(); + const doc = await runSpeakerCheck({ + clips: plan.clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })), + check: plan.check, + speakers: plan.voices, + engine, + // Beside the project, never /tmp (a RAM tmpfs here); removed at the end. + scratch: path.join(/* turbopackIgnore: true */ project.dir, ".speaker-check-work"), + thresholds: DEFAULT_THRESHOLDS, + onProgress: (e) => emit({ phase: e.event, ...(e.n ? { n: e.n, of: e.of } : {}), ...(e.items ? { items: e.items } : {}) }), + }); + const { file, doc: merged } = await writeSpeakerCheck(project.dir, doc); + emit({ phase: "done", file, seconds: Math.round((Date.now() - t0) / 100) / 10 }); + if (flags["--json"]) log(JSON.stringify(merged, null, 1)); + else if (!ndjson) { + for (const key of plan.check) { + const row = /** @type {any} */ (doc.clips[key]); + if (!row) continue; + log(`${String(row.id ?? "-").padEnd(5)} ${speakerLine(row)}`); + } + log(`→ ${file}`); + } else say(`→ ${file}`); + return 0; + } catch (e) { + err(e instanceof CliError ? `umtool speaker-check: ${e.message}` : `umtool speaker-check: ${e instanceof Error ? e.stack ?? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; + } +} + +/** "matches Ember 0.93 / Kirsche 0.83", "unsure: Ember 0.51 / Kirsche 0.49", or why it was not scored. */ +export function speakerLine(row) { + if (!row || !Array.isArray(row.scores) || !row.scores.length) return row?.why ? `not scored — ${row.why}` : "not scored"; + const list = row.scores.map((s) => `${s.name} ${Number(s.score).toFixed(2)}`).join(" / "); + if (row.label === "matches") return `matches ${list}`; + if (row.label === "none") return `matches none of them: ${list}`; + return `unsure: ${list}`; +} + +/** The CLI path the app's job runs. */ +const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); + +/** The checkout's heavy-slot CLI (takeRender.mjs's rule), when this umtool sits in the checkout. */ +function queueLockScript() { + const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs"); + return existsSync(/* turbopackIgnore: true */ file) ? file : null; +} + +/** What a check declares to the heavy slot: TitaNet-small and ffmpeg on a few seconds a clip. */ +export const SPEAKER_CHECK_ESTIMATE_MB = 800; + +/** + * The walk's "Check speaker": ONE job step on lib/jobs.ts running this + * command through the machine's heavy slot (queue-lock --heavy, with its + * estimate: admitted beside other jobs by memory, and waiting at the door + * while render mode gives a render the machine), nice'd. + * @param {{ id: string }} project + * @param {{ clip?: string | null, queueLock?: string | null }} [req] + */ +export function speakerCheckSteps(project, { clip = null, queueLock = queueLockScript() } = {}) { + const cmd = ["nice", "-n", "10", process.execPath, umtoolCli(), "speaker-check", project.id, ...(clip ? ["--clip", clip] : []), "--progress", "ndjson"]; + return { + kind: `speaker-check ${project.id}`, + steps: [{ + label: clip ? `check ${clip}'s speaker` : "check each clip's speaker", + argv: queueLock ? [process.execPath, queueLock, "--heavy", "--estimate", String(SPEAKER_CHECK_ESTIMATE_MB), "--", ...cmd] : cmd, + cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), + env: {}, + ndjson: /** @type {const} */ (true), + timeoutMs: 20 * 60 * 1000, + }], + }; +} + +/** The walk's badge for one clip: its row in speaker-check.json, and the voices it was measured against. */ +export async function speakerBadge(dir, manifest, clipId) { + const [doc, speakers] = await Promise.all([readSpeakerCheck(dir), readSpeakers(dir).catch(() => [])]); + let row = null; + if (doc) { + row = Object.values(doc.clips).find((r) => /** @type {any} */ (r)?.id === clipId) ?? null; + } + return { + speakers: speakers.map((s) => ({ name: s.name, clips: s.clips, videos: s.videos, channels: s.channels, inReference: s.clips.includes(clipId) })), + result: row ? { ...row, line: speakerLine(row), madeAt: doc?.madeAt ?? null } : null, + reference: doc ? doc.speakers : null, + }; +} diff --git a/umtool/lib/report/takeEta.mjs b/umtool/lib/report/takeEta.mjs @@ -0,0 +1,160 @@ +// HOW LONG WILL THIS TAKE RENDER? (UI notes 2026-10-30, #18) -- from the +// project's own past renders, never a constant. On the Ember cut every ETA was +// worked out by hand. +// +// A past render is a take (takes/<id>/take.json) whose render time is known: +// +// - `renderSeconds`, which the take maker records (takeMaker.mjs: from the +// build's first event to its end, so a wait at the heavy slot's door is +// not counted); +// - else the take's own files: from its video.manifest.json (written just +// before the render starts and renamed into place unchanged) to its +// take.json `builtAt`, less any wait at the slot its log says it had (a +// `<take>.log` beside the project or in the take, the heavy gate's +// `admitted after …` / `the render let go after …` lines). +// +// The ETA is the median seconds of render per second of video, over the past +// renders of the same kind -- made `from` another take (its segments, frames +// and chunks reused) or fresh, the whole cut or a window -- times the take's +// length; with none of its kind it says it used the others. Plain ESM: the CLI +// and the route read it under bare node. +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; + +const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/; +const num = (v) => typeof v === "number" && Number.isFinite(v); + +/** `35s`, `2m10s`, `1h02m` (queue-lock's humanDuration) -> seconds, else null. */ +export function parseDuration(s) { + const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(String(s ?? "").trim()); + if (!m || (!m[1] && !m[2] && !m[3])) return null; + return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0); +} + +/** The seconds a render's log says it waited at the heavy slot (its door, its line, memory). */ +export function slotWaitOf(text) { + let s = 0; + for (const m of String(text ?? "").matchAll(/(?:heavy: .* after |queue-lock: the render let go after )(\d+h)?(\d+m)?(\d+s)?(?: — admitted| — going on)/g)) { + s += parseDuration(`${m[1] ?? ""}${m[2] ?? ""}${m[3] ?? ""}`) ?? 0; + } + return s; +} + +/** + * Every past render of the project with its render time and length. + * @param {string} projectDir + * @returns {Promise<Array<{ id: string, seconds: number, renderSeconds: number, how: "recorded" | "files", window: "full" | "window", from: string | null, quick: boolean, builtAt: string | null }>>} + */ +export async function pastRenders(projectDir) { + const takesDir = path.join(projectDir, "takes"); + const names = await readdir(takesDir).catch(() => []); + const out = []; + for (const id of names) { + if (!TAKE_ID.test(id)) continue; + const dir = path.join(takesDir, id); + let t; + try { + t = JSON.parse(await readFile(path.join(dir, "take.json"), "utf8")); + } catch { + continue; + } + if (t?.draft === true || !num(t?.seconds) || t.seconds <= 0) continue; + let renderSeconds = num(t.renderSeconds) && t.renderSeconds > 0 ? t.renderSeconds : null; + let how = /** @type {"recorded" | "files"} */ ("recorded"); + if (renderSeconds === null && typeof t.builtAt === "string") { + const st = await stat(path.join(dir, "video.manifest.json")).catch(() => null); + const end = Date.parse(t.builtAt); + if (st && Number.isFinite(end)) { + let wait = 0; + for (const log of [path.join(projectDir, `${id}.log`), path.join(dir, `${id}.log`), path.join(dir, "take.log")]) { + const text = await readFile(log, "utf8").catch(() => null); + if (text) { + wait = slotWaitOf(text); + break; + } + } + const s = (end - st.mtimeMs) / 1000 - wait; + // A manifest older than a day before its build is a take rebuilt in + // place long after: its files say nothing about the render. + if (s > 0 && s < 86_400) { + renderSeconds = Math.round(s * 10) / 10; + how = "files"; + } + } + } + if (renderSeconds === null) continue; + out.push({ + id, + seconds: t.seconds, + renderSeconds, + how, + window: t.window && t.window !== "full" ? "window" : "full", + from: typeof t.from === "string" && t.from ? t.from : null, + quick: t.quick === true, + builtAt: typeof t.builtAt === "string" ? t.builtAt : null, + }); + } + return out.sort((a, b) => String(a.builtAt).localeCompare(String(b.builtAt))); +} + +const median = (xs) => { + const s = [...xs].sort((a, b) => a - b); + const n = s.length; + return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2; +}; + +/** + * The ETA of a take of `seconds` of video. Pure over `past`. + * @param {Awaited<ReturnType<typeof pastRenders>>} past + * @param {{ seconds: number, from?: boolean, window?: "full" | "window", quick?: boolean, last?: number }} want + * `from`: made from another take (reuse); `last`: at most this many of the newest renders count (default 6) + * @returns {null | { etaSeconds: number, rate: number, basis: Array<{ id: string, seconds: number, renderSeconds: number, how: string }>, kind: string, note: string | null }} + */ +export function takeEta(past, { seconds, from = false, window = "full", quick = false, last = 6 }) { + if (!num(seconds) || seconds <= 0 || !past.length) return null; + const kindOf = (p) => `${p.from ? "reuse" : "fresh"}/${p.window}${p.quick ? "/quick" : ""}`; + const want = `${from ? "reuse" : "fresh"}/${window}${quick ? "/quick" : ""}`; + let pool = past.filter((p) => kindOf(p) === want); + let note = null; + if (!pool.length) { + pool = past.filter((p) => p.window === window); + if (!pool.length) pool = past; + note = `no past ${from ? "take made from another" : "fresh take"}${window === "window" ? " of a window" : " of the whole cut"} — from the project's other renders`; + } + pool = pool.slice(-last); + const rate = median(pool.map((p) => p.renderSeconds / p.seconds)); + return { + etaSeconds: Math.round(rate * seconds), + rate: Math.round(rate * 100) / 100, + basis: pool.map((p) => ({ id: p.id, seconds: p.seconds, renderSeconds: p.renderSeconds, how: p.how })), + kind: want, + note, + }; +} + +/** `1 h 05 min` / `23 min` / `40 s`. */ +export function etaText(s) { + if (!num(s)) return "—"; + if (s < 90) return `${Math.round(s)} s`; + const m = Math.round(s / 60); + return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`; +} + +/** + * The project's ETAs for the take panel: a whole-cut take fresh and made from + * the newest take, at the length of the newest whole-cut take. + * @param {string} projectDir + */ +export async function projectEtas(projectDir) { + const past = await pastRenders(projectDir); + const fulls = past.filter((p) => p.window === "full"); + const newest = fulls.at(-1) ?? null; + const seconds = newest?.seconds ?? null; + return { + past, + seconds, + newest: newest?.id ?? null, + fresh: seconds ? takeEta(past, { seconds, from: false }) : null, + reuse: seconds ? takeEta(past, { seconds, from: true }) : null, + }; +} diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -480,7 +480,7 @@ export async function linkSharedOut(projectDir, takeOut) { * @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise<number | null>, * styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>, * emit?: (ev: Record<string, unknown>) => void, log?: (line: string) => void, - * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date, + * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date, clock?: () => number, * from?: string | null, keepFrames?: boolean }} [opts] * `from`: another take whose built segments, chrome renders and crossfade * batches are hard-linked in before the render (takeFrom.mjs), so the build @@ -670,6 +670,17 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0; emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null }); let file; + // How long the render itself took (UI notes #18: a take's ETA is read from + // the project's past renders, lib/report/takeEta.mjs): from the build's + // first event -- after the heavy slot admitted it, so a wait at the slot's + // door is not counted -- to its end. Recorded as take.json `renderSeconds`. + const clock = opts.clock ?? Date.now; + const renderStart = clock(); + let firstEventAt = null; + const timedEmit = (ev) => { + if (firstEventAt === null && ev?.ev !== "take") firstEventAt = clock(); + emit(ev); + }; try { // A cancel asked while the take was being set up: no render at all. if (opts.signal?.aborted) throw new Error(`${spec.id}: cancelled before its render started`); @@ -681,7 +692,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { full: spec.window === "full", xfade, keepFrames: opts.keepFrames === true, - emit, + emit: timedEmit, log, ...(opts.signal ? { signal: opts.signal } : {}), })); @@ -692,6 +703,7 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { } finally { await rm(renderPath, { force: true }); } + const renderSeconds = Math.round((clock() - (firstEventAt ?? renderStart)) / 100) / 10; await moveFile(file, preview); await keepBuildName(preview, file, (line) => log(`${spec.id}: ${line}`)); @@ -723,6 +735,8 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { baseHash: hashText(baseText), // The take it was built from: the pruner keeps a kept take's base (takePrune.mjs). ...(opts.from ? { from: opts.from } : {}), + // The render's own time, for the next take's ETA (takeEta.mjs). + renderSeconds, }; const tmp = `${takeFile}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -590,3 +590,22 @@ test("makeTake refuses a cut that still holds a clip ruled incorrect, by name an await rm(root, { recursive: true, force: true }); } }); + +test("makeTake records renderSeconds: from the build's first event (after any wait at the heavy slot) to its end (UI notes #18)", async () => { + const { root, dir } = await project(); + let t = 0; + const r = stubRender(); + const render = async (job) => { + t = 30_000; // 30 s waiting at the slot's door: not counted + job.emit({ ev: "phase", phase: "clips" }); + t = 30_000 + 95_400; + return r.render(job); + }; + try { + await makeTake(dir, { id: "timed", label: "Timed", group: "g", window: "full" }, opts(r, { render, clock: () => t })); + const doc = JSON.parse(await readFile(path.join(dir, "takes", "timed", "take.json"), "utf8")); + assert.equal(doc.renderSeconds, 95.4); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/ui-ops.test.mjs b/umtool/lib/report/ui-ops.test.mjs @@ -0,0 +1,402 @@ +// Operations UI (UI notes 2026-10-30, #9 #10 #15 #18): the sites a cut's +// links depend on and their deploys, the per-project link policy, the speaker +// check, the render queue and a take's ETA. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +// SITES_DIR is read when lib/paths.mjs loads: point it at this file's own +// sites before anything imports it. +const SITES = await mkdtemp(path.join(tmpdir(), "ui-ops-sites-")); +process.env.SITES_DIR = SITES; +await mkdir(path.join(SITES, "anilyzer"), { recursive: true }); +await writeFile(path.join(SITES, "anilyzer", "site.json"), JSON.stringify({ siteTitle: "Anilyzer", siteUrl: "https://site.test/" })); +await mkdir(path.join(SITES, "other"), { recursive: true }); +await writeFile(path.join(SITES, "other", "site.json"), JSON.stringify({ siteTitle: "Other", siteUrl: "https://other.test" })); +test.after(() => rm(SITES, { recursive: true, force: true })); + +const { dayOf, deployBehindWhy, originOf, projectSites, sitesByOrigin } = await import("./siteDeploys.mjs"); +const { runLinkCheck } = await import("./linkCheck.mjs"); +const { decisionsFor } = await import("../projects/core.mjs"); +const { walkProjects } = await import("../projects/walk.mjs"); + +const SITE = "https://site.test"; +const url = (chan, id, t, site = SITE) => `${site}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`; +const manifestOf = (timeline, extra = {}) => ({ + schemaVersion: 1, + slug: "cut", + title: "Cut", + provenance: { channelSlug: "c", siteOrigin: SITE }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline, + ...extra, +}); + +/** A fake archive: corpus.json generatedAt 2026-10-09, channel c holding `ids`. */ +function fakeSite(ids = ["v1"]) { + return async (u) => { + const p = new URL(String(u)).pathname; + const json = (doc) => ({ ok: true, status: 200, json: async () => doc }); + if (p === "/corpus.json") { + return json({ spec: 5, generatedAt: "2026-10-09T10:00:00.000Z", site: { title: "Site" }, channels: [{ slug: "c", manifests: { transcripts: `${SITE}/transcripts/c/manifest.json` } }] }); + } + if (p === "/transcripts/c/manifest.json") return json({ pageCount: 1, slugToPage: Object.fromEntries(ids.map((i) => [i, 0])) }); + if (p === "/transcripts/c/page-0000.json") return json(ids.map((id) => ({ id }))); + return { ok: false, status: 404, json: async () => ({}) }; + }; +} + +/** A project in a temp root: channel c's v1..v3, each with cues and an upload date. */ +async function project(timeline, { uploads = {}, landed = {}, extra = {} } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "ui-ops-")); + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + for (const v of ["v1", "v2", "v3"]) { + const vdir = path.join(channelsDir, "c", "data", v); + await mkdir(vdir, { recursive: true }); + const cues = Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })); + const file = path.join(vdir, "transcript.cues.json"); + await writeFile(file, JSON.stringify({ cues, uploadDate: uploads[v] ?? "20260901", webpageUrl: `https://www.youtube.com/watch?v=${v}` })); + const at = new Date(landed[v] ?? "2026-09-02T00:00:00Z"); + await utimes(file, at, at); + } + const dir = path.join(reportsRoot, "cut"); + await mkdir(dir, { recursive: true }); + const m = manifestOf(timeline.map((e) => ({ type: "clip", channel: "c", video: "v1", lock: true, ...e })), extra); + m.provenance.channelsDir = path.relative(dir, channelsDir); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + const decisions = async () => { + const [ref] = (await walkProjects(reportsRoot)).filter((p) => p.id === "cut"); + return decisionsFor(ref, reportsRoot); + }; + const manifest = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + return { root, reportsRoot, dir, channelsDir, decisions, manifest, done: () => rm(root, { recursive: true, force: true }) }; +} + +// ---- #9 the sites a cut's links depend on ----------------------------------- + +test("originOf, dayOf, sitesByOrigin: a site is named by the origin of its siteUrl", () => { + assert.equal(originOf("https://site.test/"), "https://site.test"); + assert.equal(originOf("mailto:x@y"), null); + assert.equal(dayOf("20261020"), "2026-10-20"); + assert.equal(dayOf("2026-10-09T10:00:00.000Z"), "2026-10-09"); + assert.equal(dayOf("soon"), null); + const s = sitesByOrigin(SITES); + assert.deepEqual(s.get("https://site.test"), { siteId: "anilyzer", title: "Anilyzer" }); + assert.equal(sitesByOrigin(path.join(SITES, "nope")).size, 0); +}); + +test("projectSites: each origin with its deploy; videos newer than it, unless the check opened their link", () => { + const m = manifestOf([ + { type: "clip", id: "a", video: "v1", start: 10, end: 20 }, + { type: "clip", id: "b", video: "v2", start: 10, end: 20 }, + { type: "clip", id: "c", video: "v3", start: 10, end: 20 }, + { type: "clip", id: "d", video: "v3", start: 30, end: 40, citeUrl: url("c", "v3", 30, "https://other.test") }, + { type: "clip", id: "y", video: "yt", start: 1, end: 2, citeUrl: "https://www.youtube.com/watch?v=yt&t=1s" }, + ]); + const doc = { + checkedAt: "2026-11-01T10:00:00.000Z", + origins: { [SITE]: { state: "ok", generatedAt: "2026-10-09T10:00:00.000Z" } }, + links: [ + { clip: "a", url: url("c", "v1", 10), state: "ok" }, + { clip: "b", url: url("c", "v2", 10), state: "dead" }, + ], + }; + const rec = { a: { uploadDate: "20261020" }, b: { uploadDate: "20261020" }, c: { uploadDate: "20260101", landedAt: "2026-10-21T08:00:00Z" }, d: { uploadDate: "20261030" } }; + const sites = projectSites(m, doc, { sites: sitesByOrigin(SITES), recordOf: (id) => rec[id] ?? null }); + assert.deepEqual( + sites.map((s) => [s.host, s.siteId, s.state, s.deployedAt, s.links, s.newer.map((n) => `${n.clip} ${n.why}`)]), + [ + // a was opened by the check: on the site, whatever its date says. + ["site.test", "anilyzer", "ok", "2026-10-09T10:00:00.000Z", 3, ["b uploaded 2026-10-20", "c transcribed here 2026-10-21"]], + // Never checked: no deploy date, so nothing can be newer than it. + ["other.test", "other", "unchecked", null, 1, []], + ], + ); + assert.equal( + deployBehindWhy(sites[0]), + "anilyzer's deploy is from 2026-10-09; 2 cited videos are newer: b (uploaded 2026-10-20), c (transcribed here 2026-10-21) — publish the site before the video ships, or link elsewhere", + ); +}); + +test("the check: site-deploy-behind, one row per site with newer videos, its settle Publish <site>", async () => { + const p = await project( + [{ id: "a", video: "v1", start: 10, end: 20, cite: 10 }, { id: "b", video: "v2", start: 10, end: 20, cite: 10 }], + { uploads: { v2: "20261020" } }, + ); + try { + // Never checked: no deploy date, no row. + assert.equal((await p.decisions()).filter((d) => d.kind === "site-deploy-behind").length, 0); + // The site has v1 only (built 9 Oct); v2 was uploaded on the 20th. + await runLinkCheck(p.dir, await p.manifest(), { fetchImpl: fakeSite(["v1"]), cacheDir: null, gapMs: 0 }); + const rows = (await p.decisions()).filter((d) => d.kind === "site-deploy-behind"); + assert.equal(rows.length, 1); + assert.equal(rows[0].severity, "open"); + assert.equal(rows[0].target, "site.test"); + assert.match(rows[0].why, /^anilyzer's deploy is from 2026-10-09; 1 cited video is newer: b \(uploaded 2026-10-20\)/); + assert.deepEqual(rows[0].settle, { kind: "publish-site", siteId: "anilyzer", label: "Publish anilyzer" }); + assert.equal(rows[0].fix, `pnpm ops build-deploy --json '{"siteId":"anilyzer"}'`); + assert.deepEqual(rows[0].clips, ["b"]); + // Redeployed with v2: the check opens it, and the row goes. + await runLinkCheck(p.dir, await p.manifest(), { fetchImpl: fakeSite(["v1", "v2"]), cacheDir: null, gapMs: 0 }); + assert.equal((await p.decisions()).filter((d) => d.kind === "site-deploy-behind").length, 0); + } finally { + await p.done(); + } +}); + +// ---- #10 the link policy ---------------------------------------------------- + +const { normalizeLinkPolicy, policyBreaks, policyCiteUrl, policyFixLabel } = await import("./linkPolicy.mjs"); +const { addClip, insertEntry, updateLinkPolicy } = await import("./manifest.mjs"); +const { linkPolicyCommand } = await import("./linksCli.mjs"); + +test("normalizeLinkPolicy: via an origin, direct slugs sorted; nothing is no policy; a stray key refuses", () => { + assert.deepEqual(normalizeLinkPolicy({ via: "https://site.test/x", direct: ["b", "a", "a"] }), { via: "https://site.test", direct: ["a", "b"] }); + assert.deepEqual(normalizeLinkPolicy({ direct: "ho, side" }), { via: null, direct: ["ho", "side"] }); + assert.equal(normalizeLinkPolicy({}), null); + assert.equal(normalizeLinkPolicy(null), null); + assert.throws(() => normalizeLinkPolicy({ via: "ftp://x" }), /a site's http\(s\) address/); + assert.throws(() => normalizeLinkPolicy({ sites: [] }), /has no key "sites"/); + assert.throws(() => normalizeLinkPolicy({ direct: ["no spaces"] }), /channel slugs/); +}); + +test("policyBreaks: a direct channel's archive link, another site's link, a platform link where the policy cites via; each with its fix", () => { + const m = manifestOf( + [ + { type: "clip", id: "e1", channel: "ember", video: "v1", start: 10, end: 20, cite: 12 }, + { type: "clip", id: "e2", channel: "ember", video: "v2", start: 10, end: 20, citeUrl: url("ember", "v2", 10, "https://other.test") }, + { type: "clip", id: "e3", channel: "ember", video: "v3", start: 10, end: 20, citeUrl: "https://www.youtube.com/watch?v=v3&t=10s" }, + { type: "clip", id: "h1", channel: "ho", video: "y1", start: 30, end: 40, cite: 31 }, + { type: "clip", id: "h2", channel: "ho", video: "y2", start: 30, end: 40, citeUrl: "https://www.youtube.com/watch?v=y2&t=30s" }, + { type: "clip", id: "h3", channel: "ho", video: "y3", start: 30, end: 40 }, + { type: "clip", id: "s1", src: "media/own.mp4", start: 0, end: 4 }, + ], + { provenance: { channelSlug: "ember", siteOrigin: SITE, linkPolicy: { direct: ["ho"] } } }, + ); + const web = { y1: "https://www.youtube.com/watch?v=y1", y2: "https://www.youtube.com/watch?v=y2" }; + const b = policyBreaks(m, { webpageOf: (e) => web[e.video] ?? null }); + assert.deepEqual(b.map((x) => [x.clip, x.want, x.fix]), [ + ["e2", "via", url("ember", "v2", 10)], + ["e3", "via", url("ember", "v3", 10)], + ["h1", "direct", "https://www.youtube.com/watch?v=y1&t=31s"], + ["h3", "direct", null], + ]); + assert.match(b[0].why, /^the project's link policy cites via site\.test, but its QR opens other\.test$/); + assert.match(b[3].why, /^ho links direct by the project's link policy, but its QR opens site\.test — and its record names no platform page to link/); + assert.equal(policyFixLabel(b[0]), "Link via site.test"); + assert.equal(policyFixLabel(b[2]), "Link its YouTube page"); + // With no policy nothing breaks. + assert.deepEqual(policyBreaks({ ...m, provenance: { siteOrigin: SITE } }), []); +}); + +test("policyCiteUrl: a new clip of a direct channel gets its platform page; via another site gets that site; one that keeps it is left alone", () => { + const m = manifestOf([], { provenance: { channelSlug: "c", siteOrigin: SITE, linkPolicy: { via: "https://other.test", direct: ["ho"] } } }); + assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9, cutStart: 6 }, "https://www.youtube.com/watch?v=y1"), "https://www.youtube.com/watch?v=y1&t=6s"); + assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9 }, null), null); + assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9 }, null), url("c", "v1", 5, "https://other.test")); + assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9, citeUrl: url("c", "v1", 5, "https://other.test") }, null), undefined); +}); + +test("the inserters write the policy's link; the check's clip-link-policy rows and their one-press fix; the CLI", async () => { + const p = await project([ + { id: "a", video: "v1", start: 10, end: 20, cite: 10 }, + { id: "b", video: "v2", start: 10, end: 20, cite: 12 }, + ]); + try { + // No policy: no rows. + assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0); + // "These channels direct": channel c links YouTube. + const res = await updateLinkPolicy(p.dir, { direct: ["c"] }); + assert.equal(res.changed, true); + assert.deepEqual((await p.manifest()).provenance.linkPolicy, { direct: ["c"] }); + assert.equal((await updateLinkPolicy(p.dir, { direct: ["c"] })).changed, false, "a no-op writes nothing"); + const rows = (await p.decisions()).filter((d) => d.kind === "clip-link-policy"); + assert.deepEqual(rows.map((d) => [d.target, d.severity]), [["a", "open"], ["b", "open"]]); + assert.deepEqual(rows[1].settle, { kind: "patch", clip: "b", patch: { citeUrl: "https://www.youtube.com/watch?v=v2&t=12s" }, label: "Link its YouTube page" }); + assert.equal(rows[1].fix, "umtool window cut b --cite-url 'https://www.youtube.com/watch?v=v2&t=12s'"); + // A new clip (the strip's selection, an insert) is written by the policy. + const added = await addClip(p.dir, { video: "v3", cutStart: 40, cutEnd: 44 }); + assert.equal(added.entry.citeUrl, "https://www.youtube.com/watch?v=v3&t=40s"); + const ins = await insertEntry(p.dir, "a", { type: "clip", video: "v1", start: 50, end: 55, citeUrl: url("c", "v1", 50) }); + assert.equal(ins.entry.citeUrl, "https://www.youtube.com/watch?v=v1&t=50s", "a copied archive link that breaks the policy is replaced"); + // The CLI: what breaks it, then --fix through the window writer. + const lines = []; + const code = await linkPolicyCommand(["cut"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 1); + assert.match(lines.join("\n"), /cut: cite via provenance\.siteOrigin \(https:\/\/site\.test\); direct: c/); + assert.match(lines.join("\n"), /BREAKS {2}a {2}c links direct/); + const fixed = []; + assert.equal(await linkPolicyCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => fixed.push(s), err: (s) => fixed.push(s) }), 0); + assert.match(fixed.join("\n"), /fixed a: https:\/\/site\.test\/\?v=c%2Fv1&t=10 -> https:\/\/www\.youtube\.com\/watch\?v=v1&t=10s/); + assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0); + // --via by site id; --clear. + assert.equal(await linkPolicyCommand(["cut", "--via", "other", "--direct", ""], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 1); + assert.deepEqual((await p.manifest()).provenance.linkPolicy, { via: "https://other.test" }); + assert.equal(await linkPolicyCommand(["cut", "--via", "nope"], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 2); + assert.equal(await linkPolicyCommand(["cut", "--clear"], { root: p.reportsRoot, out: () => {}, err: () => {} }), 0); + assert.equal("linkPolicy" in (await p.manifest()).provenance, false); + } finally { + await p.done(); + } +}); + +// ---- #18 a take's ETA from the project's past renders -------------------- + +const { etaText, parseDuration, pastRenders, projectEtas, slotWaitOf, takeEta } = await import("./takeEta.mjs"); + +test("parseDuration / slotWaitOf: the heavy gate's waits, read from a render's log", () => { + assert.equal(parseDuration("35s"), 35); + assert.equal(parseDuration("2m10s"), 130); + assert.equal(parseDuration("1h02m"), 3720); + assert.equal(parseDuration("soon"), null); + assert.equal(slotWaitOf("heavy: waiting for memory — …\nheavy: 8879 MB available after 35s — admitted\nqueue-lock: the render let go after 2m10s — going on\n"), 165); + assert.equal(slotWaitOf("take x: done (1413.3 s)"), 0, "a take's done line is the video's length, not a wait"); +}); + +test("pastRenders: recorded renderSeconds, else the take's files' times less its log's wait; a draft or a take with no length is not one", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-eta-")); + try { + const take = async (id, doc, { manifestAt = null, log = null } = {}) => { + const d = path.join(dir, "takes", id); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "reference", preview: "preview.mp4", ...doc })); + if (manifestAt) { + await writeFile(path.join(d, "video.manifest.json"), "{}"); + await utimes(path.join(d, "video.manifest.json"), new Date(manifestAt), new Date(manifestAt)); + } + if (log) await writeFile(path.join(dir, `${id}.log`), log); + }; + await take("d1", { seconds: 600, window: "full", builtAt: "2026-10-30T10:40:00.000Z" }, { manifestAt: "2026-10-30T10:00:00.000Z", log: "heavy: 9000 MB available after 4m00s — admitted\n" }); + await take("d2", { seconds: 600, window: "full", builtAt: "2026-10-31T10:00:00.000Z", renderSeconds: 900, from: "d1" }); + await take("d3", { seconds: 30, window: { at: 0, dur: 30 }, builtAt: "2026-10-31T11:00:00.000Z", renderSeconds: 90 }); + await take("dr", { seconds: null, draft: true, builtAt: null }); + const past = await pastRenders(dir); + assert.deepEqual(past.map((p) => [p.id, p.renderSeconds, p.how, p.window, p.from]), [ + ["d1", 2160, "files", "full", null], + ["d2", 900, "recorded", "full", "d1"], + ["d3", 90, "recorded", "window", null], + ]); + const e = await projectEtas(dir); + assert.equal(e.seconds, 600); + assert.equal(e.newest, "d2"); + assert.equal(e.fresh?.etaSeconds, 2160); + assert.equal(e.reuse?.etaSeconds, 900); + assert.equal(etaText(e.fresh?.etaSeconds), "36 min"); + assert.equal(etaText(4000), "1 h 07 min"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("takeEta: the median rate of the same kind, times the length; none of its kind says so and uses the others", () => { + const past = [ + { id: "a", seconds: 100, renderSeconds: 300, how: "recorded", window: "full", from: null, quick: false, builtAt: "1" }, + { id: "b", seconds: 100, renderSeconds: 500, how: "recorded", window: "full", from: null, quick: false, builtAt: "2" }, + { id: "c", seconds: 100, renderSeconds: 100, how: "recorded", window: "full", from: "b", quick: false, builtAt: "3" }, + ]; + const fresh = takeEta(past, { seconds: 200 }); + assert.deepEqual([fresh?.etaSeconds, fresh?.rate, fresh?.basis.map((b) => b.id), fresh?.note], [800, 4, ["a", "b"], null]); + const reuse = takeEta(past, { seconds: 200, from: true }); + assert.deepEqual([reuse?.etaSeconds, reuse?.basis.map((b) => b.id)], [200, ["c"]]); + const win = takeEta(past, { seconds: 60, window: "window" }); + assert.equal(win?.etaSeconds, 180); + assert.match(String(win?.note), /no past fresh take of a window — from the project's other renders/); + assert.equal(takeEta([], { seconds: 60 }), null); +}); + +// ---- #15 the speaker check ------------------------------------------------ + +const { execFileSync } = await import("node:child_process"); +const { fileURLToPath } = await import("node:url"); +const { encodeWav16 } = await import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"); +const { VOICE_A, VOICE_B, syntheticVoice, withSilence } = await import("yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"); +const { PROJECT_KINDS } = await import("../projects/kinds.mjs"); +const sc = await import("./speakerCheck.mjs"); + +const FAKE_EMBED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs"); +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +test("speakers.json: names checked, a spec parsed, a clip added to one voice at a time", async () => { + assert.deepEqual(sc.normalizeSpeakers({ speakers: [{ name: " Ember ", clips: ["e01", "e01"], videos: ["ember/abc"] }] }), [{ name: "Ember", clips: ["e01"], videos: ["ember/abc"], channels: [] }]); + assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "a/b" }] }), /no \/ = or comma/); + assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "X" }, { name: "x" }] }), /two speakers are named "x"/); + assert.throws(() => sc.normalizeSpeakers({}), /speakers\.json is/); + assert.deepEqual(sc.parseSpeakerSpec("Kirsche=k01,kirsche/v9,channel:kirsche"), { name: "Kirsche", clips: ["k01"], videos: ["kirsche/v9"], channels: ["kirsche"] }); + const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-speakers-")); + try { + assert.deepEqual(await sc.readSpeakers(dir), []); + await sc.addClipToSpeaker(dir, "Ember", "e01"); + await sc.addClipToSpeaker(dir, "Kirsche", "k01"); + await sc.addClipToSpeaker(dir, "Kirsche", "e01"); + assert.deepEqual((await sc.readSpeakers(dir)).map((s) => [s.name, s.clips]), [["Ember", []], ["Kirsche", ["k01", "e01"]]]); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("Check speaker is one job through the heavy slot, with its estimate", () => { + const plan = sc.speakerCheckSteps({ id: "reports/x" }, { clip: "k04", queueLock: "/repo/scripts/queue-lock.mjs" }); + assert.equal(plan.kind, "speaker-check reports/x"); + const argv = plan.steps[0].argv; + assert.deepEqual(argv.slice(1, 5), ["/repo/scripts/queue-lock.mjs", "--heavy", "--estimate", "800"]); + assert.deepEqual(argv.slice(argv.indexOf("speaker-check")), ["speaker-check", "reports/x", "--clip", "k04", "--progress", "ndjson"]); + assert.equal(sc.speakerCheckSteps({ id: "p" }, { queueLock: null }).steps[0].argv[0], "nice"); +}); + +test("umtool speaker-check: each clip against the named voices, over a synthetic corpus; the walk's badge reads the row", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => { + const root = await mkdtemp(path.join(tmpdir(), "ui-ops-speaker-")); + try { + const chans = path.join(root, "channels"); + const encode = async (x, out) => { + await writeFile(`${out}.wav`, encodeWav16(x)); + execFileSync("ffmpeg", ["-v", "error", "-y", "-i", `${out}.wav`, "-c:a", "aac", "-b:a", "96k", out]); + await rm(`${out}.wav`); + }; + const timeline = []; + for (const [id, voice, phase] of [["k01", VOICE_A, 0.3], ["k02", VOICE_A, 1.6], ["k03", VOICE_B, 0.8], ["k04", VOICE_A, 2.9]]) { + const d = path.join(chans, "chan", "data", `v${id}`); + await mkdir(path.join(d, "clips"), { recursive: true }); + await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify({ id: `v${id}`, cues: [{ start: 102.5, end: 104, text: "slow news day" }] })); + await encode(withSilence(syntheticVoice({ ...voice, seconds: 2.5, phase }), { before: 2, after: 3.5 }), path.join(d, "clips", "100.00-108.00.mp4")); + timeline.push({ type: "clip", id, channel: "chan", video: `v${id}`, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, quote: "slow news day" }); + } + const reportsRoot = path.join(root, "reports"); + const dir = path.join(reportsRoot, "cut"); + await mkdir(dir, { recursive: true }); + const manifest = { schemaVersion: 1, slug: "cut", title: "Cut", kind: PROJECT_KINDS.find((k) => k.makesTakes).id, provenance: { channelsDir: "../../channels", channelSlug: "chan" }, render: {}, timeline }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)); + const out = []; + const io = { reportsRoot, log: (s) => out.push(s), err: (s) => out.push(s), engine: { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx" } }; + // No voices yet: refused, saying how to name them. + assert.equal(await sc.speakerCheckCommand(["cut"], io), 2); + assert.match(out.join("\n"), /no voices to compare with: name them in speakers\.json/); + assert.equal(await sc.speakerCheckCommand(["cut", "--set", "Host=k01,k02", "--set", "Guest=k03"], io), 0); + out.length = 0; + assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "k04"], io), 0, out.join("\n")); + assert.match(out.join("\n"), /k04 {3}matches Host \d\.\d\d \/ Guest 0\.\d\d/); + const doc = JSON.parse(await readFile(path.join(dir, "speaker-check.json"), "utf8")); + assert.deepEqual(Object.keys(doc.clips), ["chan/vk04@102.50"]); + const badge = await sc.speakerBadge(dir, manifest, "k04"); + assert.equal(badge.result?.label, "matches"); + assert.match(badge.result?.line ?? "", /^matches Host \d\.\d\d \/ Guest 0\.\d\d$/); + assert.deepEqual(badge.reference?.map((s) => [s.name, s.pieces]), [["Host", 2], ["Guest", 1]]); + assert.deepEqual(badge.speakers.map((s) => s.name), ["Host", "Guest"]); + // A clip with no row yet. + assert.equal((await sc.speakerBadge(dir, manifest, "k02")).result, null); + assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "nope"], io), 2); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -221,6 +221,11 @@ export default defineConfig({ // so a take made here never joins — and the banner never shows — the // machine's render mode, and a --priority take holds the stub's lanes. `RENDER_PRIORITY_FILE=${FIXTURE}/render-priority.json ` + + // The heavy slot the render queue panel reads (common/lib/heavyQueue.mjs, + // UI notes #18): the fixture's own, so ui-ops.spec writes the tickets it + // asserts and never reads the machine's. A take made here still passes + // through the slot this suite holds (HEAVY_HELD), touching no lock. + `HEAVY_LOCK_FILE=${FIXTURE}/heavy/heavy-queue.lock ` + // Two seconds of pacing per CUT, so the deliver spec can press Stop in // the middle of a job and prove that cancelling abandons the rest while // the next run resumes. Read only by bin/cut-from-cache.mjs.