Archilyzer · Source

archilyzer

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

commit cfd2d911f7a0e1606af69b12253d1897ac434ab8
parent 3f5f084f814a9a3e425c1f1fd416efaf48ef35aa
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 00:13:46 -0400

umtool: cut integrity -- tests, the e2e spec, docs; the link check paced per host (>= 3 s, jittered)

- lib/report/cut-integrity.test.mjs: the cite follow (writer and row), walkNote/star, take patches re-anchored by a removal and the stale row, It's deliberate, the link check (open, dead channel, bare Twitch id and its fix, inconsistent shard, a cached shard read again once, offline, pacing), umtool links --fix, trailer candidates
- e2e/cut-integrity.spec.ts + its fixture: every surface through the UI, with its own local site for Check links
- REPORT_CACHE_DIR set for the e2e app server (the archive JSON cache stays in the fixture)
- docs: knobs.md (the cite follows the edge, take patches, do the QR links open, walkNote/star rows), clip-bench.md, cli.md, inbox.md, report-video.md

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

Diffstat:
Mumtool/docs/cli.md | 15+++++++++++++++
Mumtool/docs/clip-bench.md | 17+++++++++++++++++
Mumtool/docs/inbox.md | 7++++++-
Mumtool/docs/knobs.md | 45++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/docs/report-video.md | 17+++++++++++++++++
Aumtool/e2e/cut-integrity.spec.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/cut-integrity-fixture.mjs | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Mumtool/lib/projects/report.mjs | 2+-
Aumtool/lib/report/cut-integrity.test.mjs | 463+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/linkCheck.mjs | 23++++++++++++++++++++---
Mumtool/lib/report/linksCli.mjs | 14++++++++++----
Mumtool/playwright.config.ts | 4++++
13 files changed, 864 insertions(+), 10 deletions(-)

diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -24,6 +24,8 @@ Inbox cannot disagree about what is wrong with one. | `folders [--json]` · `kinds [--json]` | the tree, the registry | | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | | `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)) | +| `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)) | | `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 | | `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) | @@ -166,6 +168,19 @@ c01: 43.12–61.48 -> 43.12–61.48 `--gap-remove 51` takes out the gap holding that second; `--gaps ''` clears them all. +An edge move that leaves the clock (`cite`) more than 5 s before what plays — or past its end — +moves it with the edge, and the QR's `t=` with it when the citeUrl names this recording +([knobs.md](knobs.md#the-cite-follows-the-edge)); the CLI says so: + +``` +$ umtool window ferret-rescue c02 --start 1600 +c02: 1522.4–1620 -> 1600–1620 + cite followed the edge: 25:22 -> 26:40 + QR followed: https://archive.example/?v=ferrets%2Fabc123&t=1600 +``` + +`check` prints a row's terminal fix under it when it knows one (`fix: umtool window … --repeat-of …`). + ## `link` names the article a project is the video of An article links to a project its iterations made, to one whose manifest names it diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md @@ -347,6 +347,23 @@ differs from the stored window, <kbd>y</kbd> carries `start`/`end` (and clears a cut the new extent no longer contains) in the same patch as the verdict, so walking on never loses the window you just chose. +### ★ and the walk note — not a verdict, not a correction + +<kbd>s</kbd> (or **☆ Star** beside the answers; **☆ Star** in the phone's status line) stars the +clip: a favourite, written at once (`star: true`). A starred clip is a **trailer candidate** — the +Cut tab lists them under **★ trailer candidates**, and `umtool trailer <p> --candidates [--json]` +prints them as a trailer's `--beats-json`. The **walk note** field (beside `correction`) takes an +editorial note — *this is gold*, *wants a beat of silence*, *move it to sex appeal* — as `walkNote`. +Neither touches the verdict, and neither is a `correction`: that field says the REPORT got a fact +wrong and is read by the next report pass. From a terminal: `umtool window <p> <clip> --star` +(`--no-star`), `--walk-note "…"` (`''` clears). A clip that re-plays another on purpose shows +**repeats `<clip>`** in the header (`repeatOf`). + +A window you save that leaves the clip's `cite` (the clock) — or its citeUrl's `t=` — more than 5 s +before what plays, or past its end, moves it to the clip's first second, and the save says so +(*saved — the cite followed the edge: 25:22 → 26:40, and the QR with it*). See +[knobs.md](knobs.md#the-cite-follows-the-edge). + A note on a clip that is already **confirmed** is just a note — why its window moved, a caveat for the writers — and writing one there leaves the verdict alone — as it does on a clip rejected for a cut reason, whose facts are right. diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -64,7 +64,12 @@ on (`decisionTab`, `songTabOfSection`). | `clip-unfetchable` | blocking | the last preflight says the source is gone | Replace the source | | `clip-unchecked` | info | the last preflight could not ask: the platform refused a probe (403, 429, a bot check), so it and the platform's other sources were left `unchecked` | Re-check later | | `clip-mid-sentence` | open | the cut lands inside a cue that does not close a sentence, and `lockEnd` is unset | Trim to the sentence | -| `window-overlap` | open/info | two clips from one source overlap | Fix the windows | +| `window-overlap` | open/info | two clips from one source overlap; the row offers **It's deliberate: `<later>` repeats `<earlier>`** (`repeatOf` through the window writer) | Fix the windows | +| `clip-cite-off` | open | the clock (`cite`) or the QR's `t=` (a citeUrl naming this recording) more than 5 s before what the clip plays, or after it: "the clock and the QR point 78 s before the clip (cite 25:22, it plays 26:40–26:50)"; **Move to 26:40** | Move the cite to the clip | +| `patch-markers-stale` | open | a take patch beside the manifest (`*.patch.json`) whose deck markers name a clip not in the cut — a take made with it is refused | Fix the take patch | +| `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 | | `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 @@ -22,7 +22,10 @@ that generates it ([notes.md](notes.md)). | `claim.label` — this stamp's text (≤ 20; default the verdict's stamp word) | Marks, **label** | `claim.label="2 SEIZURES"` | same | | `claim.eventDate` — `YYYY-MM-DD`, the day the event this mark counts happened when it is not the clip's (a seizure he tells of on 8 Oct that was on 22 Sep): a deck claim's window dates the mark by it ([Claim checks](#claim-checks-on-the-rail)); the stamp lands where it always did | Marks, **happened** | `claim.eventDate=2026-09-22` (`--mark <id>` for another mark) | same | | marks — more than one stamp and count on a clip (≤ 8): see [Marks](#marks) | Marks: **Add mark at playhead** (Shift+M), a mark's verdict, **Remove**, **Clear** | `mark.add=Episodes@190.2` `mark.remove=<id>` `mark.verdict=Grift` `marks=<json>` | `POST /api/report/clip-editor {op: "marks", clip, add \| remove \| mark+verdict \| set}` | -| `repeatOf` — the id of the clip this one re-plays ON PURPOSE (a closing callback, a flash-forward cut out of a longer clip): the check's `window-overlap` row and the build's de-overlap leave that pair alone. Must name another clip of the cut; empty clears it | — | `umtool window <p> <clip> --repeat-of <other>` (`--repeat-of ''` clears) | `PUT /api/report/window {project, clip, repeatOf}` | +| `repeatOf` — the id of the clip this one re-plays ON PURPOSE (a closing callback, a flash-forward cut out of a longer clip): the check's `window-overlap` row and the build's de-overlap leave that pair alone. Must name another clip of the cut; empty clears it | the project page's `window-overlap` row: **It's deliberate: `<later>` repeats `<earlier>`**; shown as **repeats `<clip>`** on the Cut tab's row and the bench | `umtool window <p> <clip> --repeat-of <other>` (`--repeat-of ''` clears) | `PUT /api/report/window {project, clip, repeatOf}` | +| `cite` — the second the deck's clock prints (default the clip's start); **follows the edge**: a window or cut save that leaves it more than 5 s before what plays, or past its end, moves it to the first played second, and a citeUrl naming this recording moves its `t=` with it ([below](#the-cite-follows-the-edge)) | clip bench, **cite**; the project page's `clip-cite-off` row: **Move to m:ss** | `umtool window <p> <clip> --cite 1600` | `PUT /api/report/window {project, clip, cite}` | +| `walkNote` — an editorial note from the walk (*this is gold*, *wants a beat of silence*); not a `correction` (a fact error), never rendered; ≤ 2000 | clip bench, **walk note**; the Cut tab's row shows it | `umtool window <p> <clip> --walk-note "…"` (`''` clears) | `PUT /api/report/window {project, clip, walkNote}` | +| `star` — `true`: the walk's favourite, a **trailer candidate** (`lib/report/trailerCandidates.mjs`); not a verdict | clip bench, **☆ Star** (`s`); the Cut tab's **★ trailer candidates** | `umtool window <p> <clip> --star` (`--no-star` clears) · `umtool trailer <p> --candidates [--json]` lists them as beats | `PUT /api/report/window {project, clip, star}` | | `audio.offset` — ms, + = the sound later (−2000…2000) | clip editor, **Audio**: **sync**, the ±10/±40 nudges, **listen** (the 3 s around the playhead) | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio", clip, audio: {offset}}` | | `audio.gain` — dB (−20…20) | Audio, **gain** | `audio.gain=-3` | same | | `audio.fadeIn`, `audio.fadeOut` — seconds (0–5) | Audio, **fade in / fade out** | `audio.fadeIn=0.3` | same | @@ -41,6 +44,46 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +## The cite follows the edge + +A clip's `cite` is the second the clock prints and its `citeUrl`'s `t=` the second the QR opens; both +were written against the window the clip had when it was found. The window writer +(`lib/report/citeFollow.mjs`, through `patchClipEntry`, so the bench, Play the cut, a take's walk and +`umtool window` all get it) moves them when an edge move leaves them **more than 5 s before** what +plays (the cut when the clip has one, else the extent) **or past its end**: the cite to the first +played second (floored), the `t=` to the cite. Up to 5 s ahead is a lead-in and is kept. A citeUrl is +moved only when it names this recording (`?v=<channel>/<id>`, Twitch's `v<id>`, or the platform's own +`watch?v=` / `youtu.be/`) — a mirror's clock is not this one's. A patch that writes `cite` itself +moves only the QR, and only when it agreed with the old clock; one that writes `citeUrl` keeps what +it wrote. The CLI prints *cite followed the edge*, the route answers `citeFollowed`. What was left +before this existed is the check's `clip-cite-off` row (open): *the clock and the QR point 78 s before +the clip*, with **Move to m:ss** (`umtool window <p> <clip> --cite N`). + +## Take patches follow a removal + +A take patch beside the manifest (`*.patch.json`, the file `umtool take --patch` reads) that carries +`render.chrome.deck.markers` carries the whole list (a merge patch replaces arrays). Every structural +write — remove, reject, wrong speaker, merge — re-anchors those markers the way it re-anchors the +manifest's (`lib/report/patchMarkers.mjs`): a marker after a removed clip moves to the clip before it, +or is dropped when there is none; `umtool timeline` prints each change (`draft-1.patch.json: deck marker +1 ("Sex appeal") moved from after ow2b to after ow2`). A patch with a `timeline` of its own is left +alone. An **undo** restores the manifest, not the patches. Anything still naming a clip that is not in +the cut is the check's `patch-markers-stale` row (open: a take made with it is refused). + +## Do the QR links open? + +`umtool links <p> [--json] [--fix]`, or **Check links** on the project page's link rows, resolves every +clip QR the cut draws (the build's own rules, lint.mjs `qrsOf`) against the site it links: +`corpus.json` → the channel's transcripts manifest → `slugToPage[<id>]` → `page-<NNNN>.json` → the +record. One request at a time; `corpus.json` and the manifests are read fresh, a shard comes from the +cue cache (`REPORT_CACHE_DIR`, the same files the build reads) and is fetched again only when the record +it should hold is missing. A site that does not answer leaves its links **not verified**. The answer is +recorded in `out/links.json`; the check reads it and never fetches: `link-dead` (blocking, one row per +site: *12 of 124 QR links don't open on anilyzer.pages.dev (deployed 2026-10-09): …*), `links-unverified` +(info: *couldn't reach …*), `links-unchecked` (info: never checked, or a link changed since). `--fix` +rewrites the dead links it knows the fix for — a Twitch id the site serves as `v<id>` — through the +window writer. A platform link (YouTube's own page) is not an archive link and is not checked. + ## 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 @@ -112,6 +112,20 @@ Two are checked rather than trusted: - **`citeUrl`** must be `http(s)`. A QR encoding anything else is the same class of defect as the 19 codes that shipped reading `undefined/?v=…`. +**`cite` follows the edge.** A window or cut save that leaves the clock more than +5 s before what plays, or past its end, moves `cite` to the first played second, +and a citeUrl naming this recording moves its `t=` with it; an explicit `cite` +takes the QR along when the two agreed. What is left over is the check's +`clip-cite-off` row. Whether a QR opens at all is `umtool links`: [knobs.md](knobs.md#the-cite-follows-the-edge), +[Do the QR links open?](knobs.md#do-the-qr-links-open). + +### `walkNote` and `star` — what the walk said that is not a verdict + +`walkNote` is an editorial note from the walk (*this is gold*, *wants a beat of +silence*); `star: true` is a favourite, which makes the clip a trailer candidate +(the Cut tab's ★ list, `umtool trailer <p> --candidates`). Neither is rendered, +neither touches the verdict, and neither is a `correction`. + ### `correction` — what the REPORT got wrong Free text, written while watching the clip, **never rendered and never read by @@ -1277,6 +1291,9 @@ its log says so, rather than refused as emptied. pips and running tallies show the whole video's timeline, and a viewer can see the full version has more. Nothing is rendered again: it is one ffmpeg pass over the finished file. +The walk's ★ clips are the candidates: `umtool trailer <project> --candidates` lists them, +`--candidates --json` prints them as beats over what each plays, ready for `--beats-json`. + A beat is either: ``` diff --git a/umtool/e2e/cut-integrity.spec.ts b/umtool/e2e/cut-integrity.spec.ts @@ -0,0 +1,208 @@ +import { test, expect, type Page } from "@playwright/test"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdirSync, readFileSync, 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 { CUT_INTEGRITY, SITE_PLACEHOLDER } from "./fixtures/cut-integrity-fixture.mjs"; + +// --------------------------------------------------------------------------- +// CUT INTEGRITY (UI notes 2026-10-30): every surface through the window +// writer, each with its terminal twin. +// +// #3 a window-overlap row's "It's deliberate: c02 repeats c01" writes +// repeatOf; the Cut tab and the bench show "repeats c01" +// #5 a clip-cite-off row's "Move to 0:06" puts the clock AND the QR back +// on the clip +// #6 a take patch whose markers name a clip that is gone is a row; removing +// a clip re-anchors the patch's markers +// #7 ★ (s) and the walk note on the bench -- neither a verdict nor a +// correction; the Cut tab's ★ trailer candidates +// #8 Check links resolves every clip QR against the site's corpus.json +// contract (this spec's own server): one dead link blocks; a site that +// does not answer leaves them "not verified" +// +// Fixture (fixtures/cut-integrity-fixture.mjs), written by this file alone. +// The tests run in order, each leaving what the next reads. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const PROJECT = `reports/${CUT_INTEGRITY}`; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", CUT_INTEGRITY); +const MANIFEST = path.join(DIR, "video.manifest.json"); +type Entry = { id: string; cite?: number; citeUrl?: string; repeatOf?: string; star?: boolean; walkNote?: string; correction?: string; verdict?: 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 (CUT_INTEGRITY_SHOTS=<dir>). +const SHOTS = process.env.CUT_INTEGRITY_SHOTS ?? ""; +const shot = async (page: Page, name: string) => { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +}; + +// The site the QRs link: corpus.json -> testchan's manifest -> page-0000.json, +// holding vid1 and vid2 (not "nope"). +let server: Server; +let origin = ""; +const asked: string[] = []; +const startSite = () => + new Promise<void>((resolve) => { + server = createServer((req, res) => { + const p = new URL(req.url ?? "/", "http://x").pathname; + asked.push(p); + 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: "Fixture archive" }, + channels: [{ slug: "testchan", manifests: { transcripts: `${origin}/transcripts/testchan/manifest.json` } }], + }); + } + if (p === "/transcripts/testchan/manifest.json") return json({ pageCount: 1, slugToPage: { vid1: 0, vid2: 0 } }); + if (p === "/transcripts/testchan/page-0000.json") return json([{ id: "vid1" }, { id: "vid2" }]); + 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(); + // The QRs on this run's server: the placeholder origin, replaced. + writeFileSync(MANIFEST, readFileSync(MANIFEST, "utf8").split(SITE_PLACEHOLDER).join(origin)); + await warm(playwright, [urls.projectHref(PROJECT), urls.projectHref(PROJECT, { tab: "cut" }), urls.clipBenchHref(PROJECT, "c01")]); +}); +test.afterAll(() => { + server?.close(); +}); + +const row = (page: Page, kind: string, target: string) => page.locator(`[data-decision="${kind}"][data-target="${target}"]`); + +test("the check rows: an overlap, a clock and QR off the clip, a stale take patch, links never checked — each with its settle and its fix", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + const overlap = row(page, "window-overlap", "c01"); + await expect(overlap).toContainText("overlaps c02 by 2.0s"); + await expect(overlap.locator('[data-settle-button="c02"]')).toHaveText("It's deliberate: c02 repeats c01"); + await expect(overlap.locator("[data-fix]")).toHaveAttribute("data-fix", /^umtool window reports\/cut-integrity-fixture c02 --repeat-of c01/); + + const cite = row(page, "clip-cite-off", "c03"); + await expect(cite).toContainText("the clock and the QR point 6 s before the clip (cite 0:00, it plays 0:06–0:08)"); + await expect(cite.locator('[data-settle-button="c03"]')).toHaveText("Move to 0:06"); + await expect(cite.locator("[data-fix]")).toHaveAttribute("data-fix", "umtool window reports/cut-integrity-fixture c03 --cite 6"); + + const stale = row(page, "patch-markers-stale", "draft-1.patch.json"); + await expect(stale).toContainText('a deck marker names a clip not in the cut: "Hand-made" after gone'); + + await expect(row(page, "links-unchecked", "QR links")).toContainText("4 archive links never checked against the sites they open"); + await expect(row(page, "links-unchecked", "QR links").locator('[data-settle-button="links"]')).toHaveText("Check links"); + await shot(page, "3-5-6-8-check-rows"); +}); + +test("#3 It's deliberate: repeatOf through the writer, the row gone, the chip on the Cut tab and the bench", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "window-overlap", "c01").locator('[data-settle-button="c02"]').click(); + await expect(row(page, "window-overlap", "c01")).toHaveCount(0); + expect(entry("c02")?.repeatOf).toBe("c01"); + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await expect(page.locator('[data-entry="c02"] [data-repeat-of="c01"]')).toHaveText("repeats c01"); + await shot(page, "3-repeat-of-chip-cut-tab"); + await page.goto(urls.clipBenchHref(PROJECT, "c02")); + await expect(page.locator('[data-bench-repeat-of="c01"]')).toHaveText("repeats c01"); +}); + +test("#5 Move to 0:06: the clock and the QR back on the clip, and the row gone", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "clip-cite-off", "c03").locator('[data-settle-button="c03"]').click(); + await expect(row(page, "clip-cite-off", "c03")).toHaveCount(0); + expect(entry("c03")?.cite).toBe(6); + expect(entry("c03")?.citeUrl).toBe(`${origin}/?v=testchan%2Fvid1&t=6`); +}); + +test("#7 ★ (s) and the walk note on the bench: not a verdict, not a correction; the Cut tab's trailer candidates", async ({ page }) => { + await page.goto(urls.clipBenchHref(PROJECT, "c01")); + const star = page.locator("[data-verdict-star]"); + await expect(star).toHaveAttribute("data-verdict-star", "off"); + // The bench's keys answer once it has hydrated: `s` stars. + await expect(async () => { + await page.locator("body").press("s"); + await expect(star).toHaveAttribute("data-verdict-star", "on", { timeout: 1500 }); + }).toPass({ timeout: 15_000 }); + await expect.poll(() => entry("c01")?.star).toBe(true); + await expect(page.locator("[data-bench-star]")).toBeVisible(); + const note = page.locator('[data-attrib-field="walkNote"]'); + await note.fill("THIS IS GOLD"); + await note.press("Tab"); + await expect.poll(() => entry("c01")?.walkNote).toBe("THIS IS GOLD"); + expect(entry("c01")?.correction).toBeUndefined(); + expect(entry("c01")?.verdict).toBeUndefined(); + await shot(page, "7-star-walk-note-bench"); + + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await expect(page.locator('[data-entry="c01"] [data-star="c01"]')).toHaveText("★ trailer"); + await expect(page.locator('[data-walk-note-of="c01"]')).toContainText("THIS IS GOLD"); + const cands = page.locator("[data-trailer-candidates]"); + await expect(cands).toHaveAttribute("data-trailer-candidates", "1"); + await expect(cands.locator('[data-trailer-candidate="c01"]')).toContainText("0:01–0:05 (4.0 s)"); + await expect(cands).toContainText(`umtool trailer ${PROJECT} --candidates --json`); + await shot(page, "7-trailer-candidates-cut-tab"); + + // ☆ again clears it. + await page.goto(urls.clipBenchHref(PROJECT, "c01")); + await page.locator('[data-verdict-star="on"]').click(); + await expect.poll(() => entry("c01")?.star).toBeUndefined(); + await page.locator('[data-verdict-star="off"]').click(); + await expect.poll(() => entry("c01")?.star).toBe(true); +}); + +test("#8 Check links: one link dead on the site blocks, naming the clip and why; offline they are not verified", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT)); + await row(page, "links-unchecked", "QR links").locator('[data-settle-button="links"]').click(); + const host = new URL(origin).host; + const dead = row(page, "link-dead", host); + await expect(dead).toBeVisible({ timeout: 30_000 }); + await expect(dead).toHaveAttribute("data-severity", "blocking"); + await expect(dead).toContainText(`1 of 4 QR links don't open on ${host} (deployed 2026-10-09): c04 — c04: "nope" is not published in testchan on ${host}`); + await expect(row(page, "links-unchecked", "QR links")).toHaveCount(0); + // Polite: corpus.json, the channel's manifest, its one page -- each once. + expect(asked.filter((p) => p === "/corpus.json")).toHaveLength(1); + expect(asked.filter((p) => p.endsWith("/page-0000.json"))).toHaveLength(1); + const doc = JSON.parse(readFileSync(path.join(DIR, "out", "links.json"), "utf8")) as { links: { clip: string; state: string }[] }; + expect(doc.links.map((l) => [l.clip, l.state])).toEqual([["c01", "ok"], ["c03", "ok"], ["c02", "ok"], ["c04", "dead"]]); + await shot(page, "8-link-dead"); + + // The site goes away: a check now cannot verify, and says so -- it does not call them dead. + await new Promise<void>((r) => server.close(() => r())); + await dead.locator('[data-settle-button="links"]').click(); + const unverified = row(page, "links-unverified", host); + await expect(unverified).toBeVisible({ timeout: 30_000 }); + await expect(unverified).toHaveAttribute("data-severity", "info"); + await expect(unverified).toContainText(`4 links not verified`); + await expect(unverified).toContainText(`couldn't reach ${host}`); + await expect(row(page, "link-dead", host)).toHaveCount(0); + await shot(page, "8-links-unverified-offline"); +}); + +test("#6 removing a clip re-anchors the take patch's markers; the hand-made one is still a row", async ({ page }) => { + await page.goto(urls.projectHref(PROJECT, { tab: "cut" })); + await page.locator('[data-row-menu="c04"]').click(); + await page.locator('[data-entry="c04"] [data-row-action="remove"]').click(); + await expect.poll(() => entries().map((e) => e.id)).toEqual(["c01", "c03", "c02"]); + const patch = JSON.parse(readFileSync(path.join(DIR, "draft-1.patch.json"), "utf8")) as { render: { chrome: { deck: { markers: { after: string; label: string }[] } } } }; + expect(patch.render.chrome.deck.markers).toEqual([{ after: "c02", label: "After four" }, { after: "gone", label: "Hand-made" }]); + await page.goto(urls.projectHref(PROJECT)); + await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).toContainText('"Hand-made" after gone — a take made with --patch draft-1.patch.json is refused'); + await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).not.toContainText("After four"); + await shot(page, "6-patch-markers-stale"); +}); diff --git a/umtool/e2e/fixtures/cut-integrity-fixture.mjs b/umtool/e2e/fixtures/cut-integrity-fixture.mjs @@ -0,0 +1,56 @@ +// What cut-integrity.spec.ts acts on (UI notes 2026-10-30, #3 #5 #6 #7 #8): +// its own project, written by that spec alone. +// +// reports/cut-integrity-fixture/ +// video.manifest.json four clips of vid1 (the fixture corpus's cues): +// c01 1.0-5.0 cite 1 -- overlaps c02 (not next to it): window-overlap +// c03 6.8-8.6 cite 0.5, citeUrl t=0 -- the clock and the QR 6 s early: clip-cite-off +// c02 3.0-6.0 cite 3 +// c04 vid2 2.0-4.0 cite 2, citeUrl naming a record the site does not have +// draft-1.patch.json deck markers after c04 and after `gone` (a clip +// nobody has): patch-markers-stale; removing c04 +// re-anchors the first +// out/clips-raw/ vid1 0.00-9.00, which holds every clip +// +// The site the QRs link is the spec's own (a local HTTP server on a free +// port): the spec writes its origin into the manifest before it opens a page. +// +// Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const CUT_INTEGRITY = "cut-integrity-fixture"; +export const SITE_PLACEHOLDER = "http://127.0.0.1:9"; + +const write = (dir, name, doc) => { + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n"); +}; + +/** The fixture's manifest, its QRs on `site`. Exported so the spec writes the same thing with its server's origin. */ +export function cutIntegrityManifest(manifest, site) { + const link = (id, t) => `${site}/?v=${encodeURIComponent(`testchan/${id}`)}&t=${t}`; + const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid1", start, end, lock: true, section: 0, ...extra }); + const doc = manifest(CUT_INTEGRITY, "The Cut Integrity Fixture", { siteOrigin: site }, [ + clip("c01", 1.0, 5.0, { cite: 1, quote: "This is a complete sentence." }), + clip("c03", 6.8, 8.6, { cite: 0.5, citeUrl: link("vid1", 0), quote: "of that it finishes here." }), + clip("c02", 3.0, 6.0, { cite: 3, quote: "And this one runs on" }), + clip("c04", 2.0, 4.0, { video: "vid2", cite: 2, citeUrl: link("nope", 2), quote: "a record the site does not have" }), + ]); + doc.render.fetchPad = 0; + return doc; +} + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string }} o + */ +export function makeCutIntegrityFixture({ reports, manifest, cachedWindow }) { + const dir = path.join(reports, CUT_INTEGRITY); + write(dir, "video.manifest.json", cutIntegrityManifest(manifest, SITE_PLACEHOLDER)); + write(dir, "draft-1.patch.json", { + render: { chrome: { deck: { markers: [{ after: "c04", label: "After four" }, { after: "gone", label: "Hand-made" }] } } }, + }); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow))); + return dir; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -34,6 +34,7 @@ import { makeMontageOpsFixture } from "./montage-ops-fixture.mjs"; 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 { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; @@ -1849,6 +1850,8 @@ makeClipEditorFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out" makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // Walk a take: a draft take of sub-windows, walked on the bench (take-walk.spec.ts). 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") }); // 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/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -1324,7 +1324,7 @@ export async function reportDecisions(ctx, summary) { const words = (n) => (n < 0 ? `${Math.abs(n).toFixed(0)} s before the clip` : `${n.toFixed(0)} s after the clip ends`); const what = off.clockOff && off.qrOff && Math.sign(off.clockOff) === Math.sign(off.qrOff) - ? `the clock and the QR point ${words(Math.abs(off.clockOff) >= Math.abs(off.qrOff) ? off.clockOff : off.qrOff)}` + ? `the clock and the QR point ${words(off.clockOff)}` : [off.clockOff ? `the clock points ${words(off.clockOff)}` : null, off.qrOff ? `the QR points ${words(off.qrOff)}` : null].filter(Boolean).join("; "); const flags = [ off.patch.cite !== undefined ? `--cite ${off.patch.cite}` : null, diff --git a/umtool/lib/report/cut-integrity.test.mjs b/umtool/lib/report/cut-integrity.test.mjs @@ -0,0 +1,463 @@ +// Cut integrity (UI notes 2026-10-30, #3 #5 #6 #7 #8): the cite follows the +// edge, a take patch's markers follow a removal, repeatOf / ★ / walk notes +// through the writer, and the QR links resolved against the site's contract. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { citeFollow, citeOffsets, citeUrlSecond, offsetFrom, parseT, playedSpan, withT } from "./citeFollow.mjs"; +import { patchClipEntry, removeEntry, updateClip } from "./manifest.mjs"; +import { removedAnchors, reanchorPatch, stalePatchMarkers } from "./patchMarkers.mjs"; +import { archiveLinkOf, checkLinks, linkVerdicts, linksOf, runLinkCheck } from "./linkCheck.mjs"; +import { linksCommand } from "./linksCli.mjs"; +import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; +import { decisionsFor } from "../projects/core.mjs"; +import { walkProjects } from "../projects/walk.mjs"; + +const SITE = "https://site.test"; +const url = (chan, id, t) => `${SITE}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`; + +// ---- citeFollow.mjs --------------------------------------------------------- + +test("the span that plays, offsets against it, t= spellings, the same recording", () => { + assert.deepEqual(playedSpan({ start: 10, end: 20 }), { from: 10, to: 20 }); + assert.deepEqual(playedSpan({ start: 10, end: 20, cutStart: 12, cutEnd: 18 }), { from: 12, to: 18 }); + // A lead-in of up to 5 s is inside; more is N s before; past the end is N s after. + assert.equal(offsetFrom(5, { from: 10, to: 20 }), 0); + assert.equal(offsetFrom(4, { from: 10, to: 20 }), -6); + assert.equal(offsetFrom(21, { from: 10, to: 20 }), 1); + assert.equal(parseT("123"), 123); + assert.equal(parseT("123s"), 123); + assert.equal(parseT("1m2s"), 62); + assert.equal(parseT("1h0m5s"), 3605); + assert.equal(parseT("soon"), null); + assert.equal(withT("https://a.test/?v=c%2Fx&t=12", 40), "https://a.test/?v=c%2Fx&t=40"); + assert.equal(withT("https://www.youtube.com/watch?v=abc&t=12s", 40.9), "https://www.youtube.com/watch?v=abc&t=40s"); + assert.equal(withT("https://www.youtube.com/watch?t=1m2s&v=abc", 70), "https://www.youtube.com/watch?t=70&v=abc"); + // Twitch: the corpus id is bare, the site's record is v<id> -- the same recording either way. + assert.equal(citeUrlSecond({ channel: "tw", video: "290", citeUrl: url("tw", "v290", 14) }), 14); + assert.equal(citeUrlSecond({ channel: "tw", video: "290", citeUrl: url("tw", "290", 14) }), 14); + assert.equal(citeUrlSecond({ video: "abc", citeUrl: "https://www.youtube.com/watch?v=abc&t=9s" }), 9); + assert.equal(citeUrlSecond({ video: "abc", citeUrl: "https://youtu.be/abc?t=9" }), 9); + // A mirror: another recording, another clock -- never judged. + assert.equal(citeUrlSecond({ channel: "c", video: "abc", citeUrl: url("mirror", "zzz", 9) }), null); +}); + +test("citeFollow: an edge past the cite moves it (and a same-recording QR); a lead-in or a mirror stays", () => { + const e = { channel: "c", video: "v1", start: 1600, end: 1620, cite: 1523, citeUrl: url("c", "v1", 1523) }; + assert.deepEqual(citeFollow(e), { cite: { from: 1523, to: 1600 }, citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1600) } }); + assert.equal(citeFollow({ ...e, cite: 1596, citeUrl: url("c", "v1", 1596) }), null, "4 s ahead is a lead-in"); + assert.deepEqual(citeFollow({ ...e, citeUrl: url("mirror", "m1", 10) }), { cite: { from: 1523, to: 1600 } }); + // The cut is what plays. + assert.deepEqual(citeFollow({ start: 100, end: 200, cutStart: 150, cutEnd: 160, cite: 100 })?.cite, { from: 100, to: 150 }); + // After the end. + assert.deepEqual(citeFollow({ start: 100, end: 110, cite: 130 })?.cite, { from: 130, to: 100 }); +}); + +test("citeOffsets: the row's numbers and the patch that settles it", () => { + const e = { channel: "c", video: "v1", start: 1600, end: 1620, cite: 1522, citeUrl: url("c", "v1", 1522) }; + const off = citeOffsets(e); + assert.equal(off.clockOff, -78); + assert.equal(off.qrOff, -78); + // The writer moves the QR with an explicit cite when they agreed: the patch is the cite alone. + assert.deepEqual(off.patch, { cite: 1600 }); + // QR off alone: the citeUrl is the patch. + const q = citeOffsets({ ...e, cite: 1601 }); + assert.deepEqual(q.patch, { citeUrl: url("c", "v1", 1601) }); + assert.equal(citeOffsets({ ...e, cite: 1598, citeUrl: url("c", "v1", 1598) }), null); +}); + +// ---- the window writer -------------------------------------------------------- + +const manifestOf = (timeline, extra = {}) => ({ + schemaVersion: 1, + slug: "cut", + title: "Cut", + provenance: { channelSlug: "c", siteOrigin: SITE }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline, + ...extra, +}); + +test("the writer: an edge move carries the cite and the QR along; a lead-in is kept; an explicit cite takes the QR with it", () => { + const clip = () => ({ type: "clip", id: "a", channel: "c", video: "v1", start: 1500, end: 1620, cite: 1523, citeUrl: url("c", "v1", 1523) }); + let m = manifestOf([clip()]); + const r = patchClipEntry(m, "a", { start: 1601.2 }); + assert.equal(m.timeline[0].cite, 1601); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1601)); + assert.deepEqual(r.citeFollowed, { cite: { from: 1523, to: 1601 }, citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1601) } }); + + m = manifestOf([clip()]); + assert.equal(patchClipEntry(m, "a", { start: 1527 }).citeFollowed, null); + assert.equal(m.timeline[0].cite, 1523, "4 s of lead-in stays"); + + // A cut that moves past the cite carries it too. + m = manifestOf([clip()]); + patchClipEntry(m, "a", { cutStart: 1560, cutEnd: 1600 }); + assert.equal(m.timeline[0].cite, 1560); + + // An explicit cite: the QR follows because it agreed with the clock. + m = manifestOf([clip()]); + assert.deepEqual(patchClipEntry(m, "a", { cite: 1540 }).citeFollowed, { citeUrl: { from: url("c", "v1", 1523), to: url("c", "v1", 1540) } }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1540)); + // ...and not when it said something else. + m = manifestOf([{ ...clip(), citeUrl: url("c", "v1", 1510) }]); + patchClipEntry(m, "a", { cite: 1540 }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1510)); + + // A patch that writes citeUrl keeps exactly what it wrote; the cite still follows. + m = manifestOf([clip()]); + patchClipEntry(m, "a", { start: 1601, citeUrl: url("c", "v1", 1400) }); + assert.equal(m.timeline[0].citeUrl, url("c", "v1", 1400)); + assert.equal(m.timeline[0].cite, 1601); + + // No cite: the clock is the start already; a QR left behind still follows. + m = manifestOf([{ type: "clip", id: "b", channel: "c", video: "v2", start: 10, end: 90, citeUrl: url("c", "v2", 10) }]); + patchClipEntry(m, "b", { start: 40 }); + assert.equal("cite" in m.timeline[0], false); + assert.equal(m.timeline[0].citeUrl, url("c", "v2", 40)); +}); + +test("the writer: walkNote and star -- set, cleared, refused", () => { + const m = manifestOf([{ type: "clip", id: "a", video: "v1", start: 1, end: 9 }]); + patchClipEntry(m, "a", { walkNote: " THIS IS GOLD ", star: true }); + assert.equal(m.timeline[0].walkNote, "THIS IS GOLD"); + assert.equal(m.timeline[0].star, true); + assert.equal("correction" in m.timeline[0], false, "a walk note is not a correction"); + assert.equal("verdict" in m.timeline[0], false, "nor a verdict"); + patchClipEntry(m, "a", { walkNote: "", star: false }); + assert.equal("walkNote" in m.timeline[0], false); + assert.equal("star" in m.timeline[0], false); + patchClipEntry(m, "a", { star: "true" }); + assert.equal(m.timeline[0].star, true); + assert.throws(() => patchClipEntry(m, "a", { star: "maybe" }), /star must be true or false/); +}); + +// ---- take patches follow a removal ------------------------------------------ + +test("removedAnchors / reanchorPatch: the same boundary, or dropped; a patch with its own timeline is left", () => { + const before = [{ type: "clip", id: "a" }, { type: "card", id: "k" }, { type: "clip", id: "b" }, { type: "clip", id: "c" }]; + const after = [{ type: "clip", id: "a" }, { type: "card", id: "k" }, { type: "clip", id: "c" }]; + assert.deepEqual([...removedAnchors(before, after)], [["b", "a"]]); + assert.deepEqual([...removedAnchors(before, before.slice(1))], [["a", null]]); + const patch = { render: { chrome: { deck: { markers: [{ after: "b", label: "Sex appeal" }, { after: "c" }] } } } }; + assert.deepEqual(reanchorPatch(patch, new Map([["b", "a"]])), ['deck marker 0 ("Sex appeal") moved from after b to after a (the same boundary)']); + assert.equal(patch.render.chrome.deck.markers[0].after, "a"); + const own = { timeline: [], render: { chrome: { deck: { markers: [{ after: "b" }] } } } }; + assert.deepEqual(reanchorPatch(own, new Map([["b", "a"]])), []); +}); + +async function project(timeline, { files = {}, render = {} } = {}) { + const root = await mkdtemp(path.join(tmpdir(), "cut-integrity-")); + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + for (const v of ["v1", "v2"]) { + const vdir = path.join(channelsDir, "c", "data", v); + await mkdir(vdir, { recursive: true }); + const cues = Array.from({ length: 2000 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues })); + } + 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 })), + { render: { width: 1920, height: 1080, fps: 30, ...render } }, + ); + m.provenance.channelsDir = path.relative(dir, channelsDir); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + for (const [name, doc] of Object.entries(files)) await writeFile(path.join(dir, name), typeof doc === "string" ? doc : `${JSON.stringify(doc, null, 2)}\n`); + const decisions = async () => { + const [ref] = (await walkProjects(reportsRoot)).filter((p) => p.id === "cut"); + return decisionsFor(ref, reportsRoot); + }; + return { root, reportsRoot, dir, decisions, done: () => rm(root, { recursive: true, force: true }) }; +} + +const markersRender = (markers) => ({ chrome: { engine: "hyperframes", layout: "deck", deck: { markers } } }); + +test("removing a clip re-anchors the take patches beside the manifest; the check names what is still stale", async () => { + const p = await project( + [{ id: "a", start: 10, end: 20 }, { id: "b", start: 30, end: 40 }, { id: "c", start: 50, end: 60 }], + { + render: markersRender([{ after: "b", label: "Two" }]), + files: { + "draft-1.patch.json": { render: { chrome: { deck: { markers: [{ after: "b", label: "Two" }, { after: "c", label: "Three" }] } } } }, + "own.patch.json": { timeline: [{ type: "clip", id: "x", video: "v1", start: 1, end: 2 }], render: { chrome: { deck: { markers: [{ after: "b" }] } } } }, + "hand.patch.json": { render: { chrome: { deck: { markers: [{ after: "gone", label: "Hand" }] } } } }, + }, + }, + ); + try { + const res = await removeEntry(p.dir, "b"); + assert.deepEqual(res.patches, [{ file: "draft-1.patch.json", notes: ['deck marker 0 ("Two") moved from after b to after a (the same boundary)'] }]); + const patch = JSON.parse(await readFile(path.join(p.dir, "draft-1.patch.json"), "utf8")); + assert.deepEqual(patch.render.chrome.deck.markers, [{ after: "a", label: "Two" }, { after: "c", label: "Three" }]); + // A patch with a timeline of its own names its own clips: untouched. + const own = JSON.parse(await readFile(path.join(p.dir, "own.patch.json"), "utf8")); + assert.equal(own.render.chrome.deck.markers[0].after, "b"); + // The manifest's own markers moved the same way. + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(m.render.chrome.deck.markers[0].after, "a"); + // What is still stale: the hand-written one. + assert.deepEqual(await stalePatchMarkers(p.dir, m), [{ file: "hand.patch.json", markers: [{ index: 0, label: "Hand", after: "gone" }] }]); + const rows = (await p.decisions()).filter((d) => d.kind === "patch-markers-stale"); + assert.equal(rows.length, 1); + assert.equal(rows[0].target, "hand.patch.json"); + assert.equal(rows[0].severity, "open"); + assert.match(rows[0].why, /"Hand" after gone — a take made with --patch hand.patch.json is refused/); + } finally { + await p.done(); + } +}); + +// ---- the check rows ------------------------------------------------------------ + +test("clip-cite-off: the clock and the QR N s before the clip, with the settle and the fix", async () => { + const p = await project([ + { id: "ag0", start: 1600, end: 1610, cite: 1522, citeUrl: url("c", "v1", 1522) }, + { id: "ok1", video: "v2", start: 100, end: 110, cite: 97, citeUrl: url("c", "v2", 97) }, + ]); + try { + const rows = (await p.decisions()).filter((d) => d.kind === "clip-cite-off"); + assert.equal(rows.length, 1); + const [r] = rows; + assert.equal(r.target, "ag0"); + assert.equal(r.severity, "open"); + assert.equal(r.why, "the clock and the QR point 78 s before the clip (cite 25:22, it plays 26:40–26:50)"); + assert.deepEqual(r.settle, { kind: "patch", clip: "ag0", patch: { cite: 1600 }, label: "Move to 26:40" }); + assert.equal(r.fix, "umtool window cut ag0 --cite 1600"); + // Settling it through the writer clears the row, and the QR followed. + const res = await updateClip(p.dir, "ag0", r.settle.patch); + assert.equal(res.entry.citeUrl, url("c", "v1", 1600)); + assert.equal((await p.decisions()).filter((d) => d.kind === "clip-cite-off").length, 0); + } finally { + await p.done(); + } +}); + +test("window-overlap offers It's deliberate: the later clip repeats the earlier; the writer clears the row", async () => { + const p = await project([ + { id: "tr3", start: 100, end: 140, cite: 100 }, + { id: "x", video: "v2", start: 10, end: 20, cite: 10 }, + { id: "tr3z", start: 120, end: 130, cite: 120 }, + ]); + try { + const rows = (await p.decisions()).filter((d) => d.kind === "window-overlap"); + assert.equal(rows.length, 1); + assert.deepEqual(rows[0].settle, { kind: "patch", clip: "tr3z", patch: { repeatOf: "tr3" }, label: "It's deliberate: tr3z repeats tr3" }); + assert.match(rows[0].fix, /^umtool window cut tr3z --repeat-of tr3/); + await updateClip(p.dir, "tr3z", rows[0].settle.patch); + assert.equal((await p.decisions()).filter((d) => d.kind === "window-overlap").length, 0); + } finally { + await p.done(); + } +}); + +// ---- the link check -------------------------------------------------------------- + +/** A published site: corpus.json, one channel's manifest and pages, counting what is asked. */ +function fakeSite({ channels = { c: { v1: 0, v2: 1 }, tw: { v290: 0 } }, down = false, emptyPage = null } = {}) { + const asked = []; + const pages = {}; + for (const [chan, ids] of Object.entries(channels)) { + for (const [id, n] of Object.entries(ids)) (pages[`${chan}/${n}`] ??= []).push({ id, title: id }); + } + const fetchImpl = async (u) => { + asked.push(String(u)); + if (down) throw new TypeError("fetch failed", { cause: new Error("getaddrinfo ENOTFOUND site.test") }); + 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: Object.keys(channels).map((slug) => ({ slug, manifests: { transcripts: `${SITE}/transcripts/${slug}/manifest.json` } })), + }); + } + const m = /^\/transcripts\/([^/]+)\/(manifest\.json|page-(\d{4})\.json)$/.exec(p); + if (m && m[2] === "manifest.json") return json({ pageCount: 2, slugToPage: Object.fromEntries(Object.entries(channels[m[1]] ?? {})) }); + if (m && m[3]) { + const key = `${m[1]}/${Number(m[3])}`; + // A deploy whose shard lacks a record its slugToPage promises. + if (emptyPage === key) return json([]); + return json(pages[key] ?? []); + } + return { ok: false, status: 404, json: async () => ({}) }; + }; + return { fetchImpl, asked }; +} + +test("archiveLinkOf / linksOf: the build's own QR links; a platform link is not an archive link", () => { + assert.deepEqual(archiveLinkOf(url("tw", "v290", 14)), { origin: SITE, channel: "tw", id: "v290", t: "14" }); + assert.equal(archiveLinkOf("https://www.youtube.com/watch?v=abc&t=9s"), null); + const m = manifestOf([ + { type: "clip", id: "a", video: "v1", start: 10, end: 20 }, + { type: "clip", id: "b", video: "v2", start: 10, end: 20, citeUrl: "https://www.youtube.com/watch?v=v2&t=10s" }, + ]); + assert.deepEqual(linksOf(m), [ + { clip: "a", url: `${SITE}/?v=${encodeURIComponent("c/v1")}&t=10` }, + { clip: "b", url: "https://www.youtube.com/watch?v=v2&t=10s" }, + ]); +}); + +test("checkLinks: open, a channel not on the site, the bare Twitch id (with its fix), a stale cached shard, one request per URL", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const site = fakeSite(); + const links = [ + { clip: "a", url: url("c", "v1", 10) }, + { clip: "a2", url: url("c", "v1", 30) }, + { clip: "b", url: url("c", "v2", 10) }, + { clip: "q01", url: url("tw", "290", 14538) }, + { clip: "n1", url: url("nochan", "x", 1) }, + { clip: "gone", url: url("c", "v9", 1) }, + { clip: "yt", url: "https://www.youtube.com/watch?v=abc&t=9s" }, + ]; + const doc = await checkLinks(links, { fetchImpl: site.fetchImpl, cacheDir, now: () => new Date("2026-11-01T01:00:00Z"), gapMs: 0 }); + const by = Object.fromEntries(doc.links.map((l) => [l.clip, l])); + assert.equal(by.a.state, "ok"); + assert.equal(by.a2.state, "ok"); + assert.equal(by.b.state, "ok"); + assert.equal(by.q01.state, "dead"); + assert.equal(by.q01.why, `"290" is not a record on site.test; the site's record is "v290"`); + assert.equal(by.q01.fix, url("tw", "v290", 14538)); + assert.equal(by.n1.state, "dead"); + assert.match(by.n1.why, /the channel "nochan" is not on site\.test \(its deploy of 2026-10-09\)/); + assert.equal(by.gone.state, "dead"); + assert.match(by.gone.why, /"v9" is not published in c on site\.test \(deployed 2026-10-09\)/); + assert.equal(by.yt.state, "direct"); + assert.equal(doc.origins[SITE].state, "ok"); + // Polite: corpus.json once, each manifest once, each page once (+1 for the stale one). + const count = (s) => site.asked.filter((u) => u.endsWith(s)).length; + assert.equal(count("/corpus.json"), 1); + assert.equal(count("/c/manifest.json"), 1); + assert.equal(count("/c/page-0000.json"), 1); + assert.equal(count("/c/page-0001.json"), 1); + // A second check reads shards from the cache: only the contract is asked again. + const again = fakeSite(); + await checkLinks(links.slice(0, 3), { fetchImpl: again.fetchImpl, cacheDir, gapMs: 0 }); + assert.deepEqual(again.asked.map((u) => new URL(u).pathname), ["/corpus.json", "/transcripts/c/manifest.json"]); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks: a shard that lacks its record is inconsistent; a cached copy older than the deploy is read again, once", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const broken = fakeSite({ emptyPage: "c/1" }); + const one = await checkLinks([{ clip: "b", url: url("c", "v2", 10) }], { fetchImpl: broken.fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(one.links[0].state, "dead"); + assert.match(one.links[0].why, /slugToPage puts "v2" on page 1, but no record there has that id/); + // Fetched from the network this check: never asked twice in one check. + assert.equal(broken.asked.filter((u) => u.endsWith("/page-0001.json")).length, 1); + // Redeployed: the cached shard misses, so it is read again -- once. + const fixed = fakeSite(); + const two = await checkLinks([{ clip: "b", url: url("c", "v2", 10) }], { fetchImpl: fixed.fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(two.links[0].state, "ok"); + assert.deepEqual(fixed.asked.map((u) => new URL(u).pathname), ["/corpus.json", "/transcripts/c/manifest.json", "/transcripts/c/page-0001.json"]); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks offline: every link unverified, with couldn't reach; the rows say so, and a dead link blocks", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + const p = await project([ + { id: "a", start: 10, end: 20, cite: 10 }, + { id: "q01", start: 30, end: 40, cite: 30, citeUrl: url("tw", "290", 30) }, + ]); + try { + // Never checked. + let rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.deepEqual(rows.map((d) => [d.kind, d.severity, d.why]), [["links-unchecked", "info", "2 archive links never checked against the sites they open"]]); + assert.deepEqual(rows[0].settle, { kind: "check-links", label: "Check links" }); + assert.equal(rows[0].fix, "umtool links cut"); + + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + const off = await runLinkCheck(p.dir, m, { fetchImpl: fakeSite({ down: true }).fetchImpl, cacheDir, gapMs: 0 }); + assert.ok(off.links.every((l) => l.state === "unverified")); + assert.equal(off.origins[SITE].state, "unreachable"); + rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.equal(rows.length, 1); + assert.equal(rows[0].kind, "links-unverified"); + assert.equal(rows[0].severity, "info"); + assert.match(rows[0].why, /^2 links not verified on .* — couldn't reach site\.test \(fetch failed \(getaddrinfo ENOTFOUND site\.test\)\)$/); + + // Online: q01's bare Twitch id is dead, and that blocks. + await runLinkCheck(p.dir, m, { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 0 }); + rows = (await p.decisions()).filter((d) => d.kind.startsWith("link")); + assert.deepEqual(rows.map((d) => [d.kind, d.severity, d.target]), [["link-dead", "blocking", "site.test"]]); + assert.match(rows[0].why, /^1 of 2 QR links don't open on site\.test \(deployed 2026-10-09\): q01 — q01: "290" is not a record on site\.test; the site's record is "v290"\. Every clip with a fix: `umtool links cut --fix`$/); + assert.deepEqual(rows[0].clips, ["q01"]); + + // A link changed since the check is unchecked, not judged by the old answer. + await updateClip(p.dir, "a", { citeUrl: url("c", "v2", 10) }); + const v = linkVerdicts(JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")), JSON.parse(await readFile(path.join(p.dir, "out", "links.json"), "utf8"))); + assert.deepEqual(v.unchecked.map((l) => l.clip), ["a"]); + } finally { + await p.done(); + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("umtool links --fix: the dead link with a known fix rewritten through the writer, then checked again", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + const p = await project([{ id: "q01", start: 30, end: 40, cite: 30, citeUrl: url("tw", "290", 30) }]); + try { + const lines = []; + const code = await linksCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s), fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 0 }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines.find((l) => l.startsWith("fixed ")) ?? "", /^fixed q01: .*%2F290&t=30 -> .*%2Fv290&t=30$/); + const m = JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + assert.equal(m.timeline[0].citeUrl, url("tw", "v290", 30)); + assert.equal((await p.decisions()).filter((d) => d.kind.startsWith("link")).length, 0); + } finally { + await p.done(); + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("checkLinks paces one host: at least the gap between two requests, nothing waited on a cache hit", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "links-cache-")); + try { + const waits = []; + let clock = 0; + const realNow = Date.now; + Date.now = () => clock; + try { + const sleep = async (ms) => { + waits.push(ms); + clock += ms; + }; + await checkLinks([{ clip: "a", url: url("c", "v1", 10) }, { clip: "b", url: url("c", "v2", 10) }], { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 3000, sleep }); + // corpus, manifest, page 0, page 1: three gaps, each ≥ 3 s and < 3.75 s (upward jitter only). + assert.equal(waits.length, 3); + for (const w of waits) assert.ok(w >= 3000 && w < 3750, String(w)); + waits.length = 0; + await checkLinks([{ clip: "a", url: url("c", "v1", 10) }], { fetchImpl: fakeSite().fetchImpl, cacheDir, gapMs: 3000, sleep }); + assert.equal(waits.length, 1, "corpus.json and the manifest: one gap; the shard is a cache hit"); + } finally { + Date.now = realNow; + } + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +// ---- ★ trailer candidates ------------------------------------------------------- + +test("trailerCandidates: the starred clips in the cut's order, over what each plays; a rejected one is left out", () => { + const m = manifestOf([ + { type: "clip", id: "j01", video: "v", start: 3335.1, end: 3337.14, star: true, quote: "anime girl", walkNote: "GOLD" }, + { type: "clip", id: "b01", video: "v", start: 10, end: 30 }, + { type: "clip", id: "tr3", video: "v", start: 2980, end: 3020, cutStart: 2988.36, cutEnd: 3011.2, star: true }, + { type: "clip", id: "z", video: "v", start: 1, end: 2, star: true, verdict: "rejected", reason: "weak" }, + ]); + assert.deepEqual(trailerCandidates(m).map((b) => b.id), ["j01", "tr3"]); + assert.deepEqual(candidateBeats(m), [{ id: "j01", start: 3335.1, end: 3337.14 }, { id: "tr3", start: 2988.36, end: 3011.2 }]); + assert.equal(trailerCandidates(m)[0].walkNote, "GOLD"); +}); diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -12,7 +12,9 @@ // (report-to-video/cues.mjs walks the same contract for cues, through the same // on-disk JSON cache, so a shard the build already read is not fetched again.) // -// POLITE: one request at a time, each URL at most once per check. corpus.json +// POLITE: one request at a time per host, at least LINK_GAP_MS apart (jittered +// upward, common/lib/jitter.mjs -- the operator's "≥3 s between metadata +// requests, one stream per host"), each URL at most once per check. corpus.json // and the channel manifests are re-read every check (a deploy changes them); // a shard page is read from the cache, and fetched again only when the record // slugToPage promised is not in the cached copy. @@ -28,10 +30,13 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; +import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; export const LINKS_FILE = "links.json"; export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); const FETCH_TIMEOUT_MS = 20_000; +/** The floor between two requests to one host (a cache hit asks nothing and waits for nothing). */ +export const LINK_GAP_MS = 3000; /** * An archive viewer link's parts: `<origin>/?v=<channel>/<id>&t=…`, or null @@ -100,16 +105,28 @@ const errText = (e) => { * Resolve the links. Pure over `fetchImpl` (and the cache dir). * * @param {Array<{ clip: string, url: string }>} links - * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void }} [opts] + * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void, gapMs?: number, sleep?: (ms: number) => Promise<void> }} [opts] * @returns {Promise<{ * version: 1, checkedAt: string, fetched: number, * origins: Record<string, { state: "ok" | "unreachable" | "no-corpus", error?: string, generatedAt?: string | null, title?: string | null }>, * links: Array<{ clip: string, url: string, state: "ok" | "dead" | "unverified" | "direct", origin?: string, why?: string, fix?: string }>, * }>} */ -export async function checkLinks(links, { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {} } = {}) { +export async function checkLinks( + links, + { fetchImpl = globalThis.fetch, cacheDir = DEFAULT_CACHE_DIR, now = () => new Date(), log = () => {}, gapMs = LINK_GAP_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}, +) { let fetched = 0; + /** host -> when its last request was sent (ms) */ + const lastAt = new Map(); const counting = withTimeout(async (url, init) => { + const host = new URL(String(url)).host; + const last = lastAt.get(host); + if (last != null && gapMs > 0) { + const wait = last + jitterUp(gapMs) - Date.now(); + if (wait > 0) await sleep(wait); + } + lastAt.set(host, Date.now()); fetched += 1; return fetchImpl(url, init); }, FETCH_TIMEOUT_MS); diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -20,7 +20,8 @@ export const LINKS_USAGE = [ "usage: umtool links <project> [--json] [--fix]", "", "Resolves every clip QR the cut draws against the site it links: corpus.json -> the channel's", - "transcripts manifest -> slugToPage -> page-NNNN.json -> the record. One request at a time; shard", + "transcripts manifest -> slugToPage -> page-NNNN.json -> the record. One request at a time per host,", + "at least 3 s apart (jittered); shard", "pages from the cue cache, read again only on a miss. A site that does not answer leaves its links", "unverified (not dead). Writes out/links.json: `umtool check` reports link-dead (blocking),", "links-unverified and links-unchecked from it. --fix rewrites the dead links it knows the fix for", @@ -51,10 +52,10 @@ export function linksSummary(doc) { /** * @param {string[]} args the words after `links` - * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, cacheDir?: string | null }} [opts] + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, cacheDir?: string | null, gapMs?: number }} [opts] * @returns {Promise<number>} */ -export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir } = {}) { +export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir, gapMs } = {}) { try { const words = args.filter((a) => !a.startsWith("--")); const flags = new Set(args.filter((a) => a.startsWith("--"))); @@ -68,7 +69,12 @@ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => con 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 opts = { ...(fetchImpl ? { fetchImpl } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) }; + const opts = { + ...(fetchImpl ? { fetchImpl } : {}), + ...(cacheDir !== undefined ? { cacheDir } : {}), + ...(gapMs !== undefined ? { gapMs } : {}), + log: flags.has("--json") ? () => {} : (s) => err(` ${s}`), + }; let m = await readManifest(project.dir); if (!m) throw new CliError(`${project.id} has no video.manifest.json`); let doc = await runLinkCheck(project.dir, m, opts); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -181,6 +181,10 @@ export default defineConfig({ // SONG_DIR (release 17): its default is the user's ~/.cache, which a // suite must never write. The fixture's own, rebuilt with it every run. `UMTOOL_CACHE_DIR=${FIXTURE}/cache ` + + // The archive JSON cache (report-to-video/cues.mjs: the cue walk's, and the + // QR link check's, lib/report/linkCheck.mjs): the fixture's own, never the + // user's ~/.cache. + `REPORT_CACHE_DIR=${FIXTURE}/report-cache ` + // And never the media root: Playwright hands the app this shell's whole // environment, so a shell that exports UMTOOL_MEDIA_DIR would put every // fixture build's out/ on the real media drive. Empty is unset