Archilyzer · Source

archilyzer

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

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

umtool: cut integrity -- the cite follows the edge, take patches follow a removal, repeatOf/★/walk notes in the UI, QR links checked against the site

- the window writer moves `cite` (and a same-recording citeUrl's t=) when an edge move leaves it more than a 5 s lead-in before what plays, or past its end; an explicit cite moves the QR's t= when they agreed (lib/report/citeFollow.mjs); check row clip-cite-off with a one-press "Move to m:ss"
- structural writes re-anchor the project's *.patch.json deck markers the way the manifest's are (lib/report/patchMarkers.mjs); check row patch-markers-stale
- window-overlap rows offer "It's deliberate: b repeats a" (repeatOf through the writer); repeats/★ chips on the Cut tab and the bench
- the walk's `walkNote` (not a correction) and `star` (s on the bench): ★ clips are trailer candidates (Cut tab list, `umtool trailer <p> --candidates`)
- `umtool links <p> [--fix]` / POST /api/report/links: every clip QR resolved corpus.json -> slugToPage -> page-NNNN -> record, polite and cached, recorded in out/links.json; rows link-dead (blocking), links-unverified, links-unchecked

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

Diffstat:
Mumtool/app/api/report/clip/route.ts | 4++++
Aumtool/app/api/report/links/route.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/window/route.ts | 7++++++-
Mumtool/bin/umtool.mjs | 22++++++++++++++++++++++
Mumtool/components/projects/ClipBench.tsx | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/ClipBenchPage.tsx | 4++++
Mumtool/components/projects/report/CutTab.tsx | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/report/DecisionSettle.tsx | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/OverviewTab.tsx | 15++++++++++++---
Mumtool/lib/decisions.ts | 13+++++++++++++
Mumtool/lib/inbox/groups.mjs | 5+++++
Mumtool/lib/inbox/what.mjs | 5+++++
Mumtool/lib/projects/report.mjs | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Aumtool/lib/report/citeFollow.mjs | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/linkCheck.mjs | 279+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/linksCli.mjs | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Aumtool/lib/report/patchMarkers.mjs | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/timelineCli.mjs | 5+++++
Aumtool/lib/report/trailerCandidates.mjs | 39+++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/trailerCli.mjs | 27++++++++++++++++++++++++++-
21 files changed, 1342 insertions(+), 17 deletions(-)

diff --git a/umtool/app/api/report/clip/route.ts b/umtool/app/api/report/clip/route.ts @@ -69,6 +69,10 @@ export async function GET(request: Request) { muteFrom: clip.muteFrom ?? null, // Seconds cut out of its middle (gaps.mjs). gaps: Array.isArray(clip.gaps) ? clip.gaps : [], + // What the walk said that is not a verdict, and a deliberate repeat. + walkNote: typeof clip.walkNote === "string" ? clip.walkNote : null, + star: clip.star === true, + repeatOf: typeof clip.repeatOf === "string" ? clip.repeatOf : null, }, view, // `v`: the version of each window's bytes, for the media URLs -- a refetch diff --git a/umtool/app/api/report/links/route.ts b/umtool/app/api/report/links/route.ts @@ -0,0 +1,47 @@ +import { projectRef } from "@/lib/projects"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { linkVerdicts, readLinkCheck, runLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// DO THE QR LINKS OPEN (lib/report/linkCheck.mjs; UI notes #8): every clip QR +// the cut draws, resolved against the site it links -- corpus.json, the +// channel's manifest, slugToPage, the shard's record. One request at a time; +// a site that does not answer leaves its links unverified. The project page's +// Check links (the link-dead / links-unverified / links-unchecked rows), and +// `umtool links <project>`. +// +// GET ?project=<id> the recorded check (out/links.json) read against the manifest as it is now +// POST { project } check now, record it, and answer the same +const headers = { "cache-control": "no-store" }; + +async function answer(dir: string, doc: Awaited<ReturnType<typeof readLinkCheck>>) { + const m = await readManifest(dir); + const v = linkVerdicts(m ?? {}, doc); + return { doc, verdicts: { ...v, unchecked: v.unchecked.length } }; +} + +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(await answer(project.dir, await readLinkCheck(project.dir)), { headers }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/links"); + if (refused) return refused; + const b = (await request.json().catch(() => null)) as { project?: 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 }); + const m = await readManifest(project.dir); + if (!m) return Response.json({ error: "the project has no video.manifest.json" }, { status: 400, headers }); + try { + const doc = await runLinkCheck(project.dir, m); + return Response.json({ ok: true, ...(await answer(project.dir, doc)) }, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); + } +} diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -62,6 +62,10 @@ export async function PUT(request: Request) { // The clip this one re-plays on purpose (a callback, a flash-forward), so // their overlap is not flagged or trimmed; empty or null clears it. "repeatOf", + // What the walk said that is not a verdict: an editorial note (not a + // correction) and the ★ favourite, a trailer candidate. + "walkNote", + "star", // Seconds taken out of the clip's middle (gaps.mjs): the whole list // (`gaps`, empty clears), one span added (`gapAdd`: {from, to} or // "12.3-15.1"), or the gap holding a source second removed (`gapRemove`). @@ -109,7 +113,8 @@ export async function PUT(request: Request) { }), ); return Response.json( - { ok: true, entry: res.entry, before: res.before, token: res.token, editNotes }, + // `citeFollowed`: the cite / the QR's t= this edit moved with an edge (lib/report/citeFollow.mjs). + { ok: true, entry: res.entry, before: res.before, token: res.token, editNotes, ...(res.citeFollowed ? { citeFollowed: res.citeFollowed } : {}) }, { headers: { "cache-control": "no-store" } }, ); } catch (e) { diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -14,6 +14,7 @@ // [--q TEXT] [--sort name|recent] [--json] // 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 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 @@ -377,6 +378,8 @@ async function cmdCheck() { if (d.severity === "info" && !has("--all-severities")) continue; console.log(`${d.severity.toUpperCase().padEnd(8)} ${d.project} ${d.kind} ${d.target}`); console.log(` ${d.why}`); + // The command that settles it, when the row knows one (the UI's action's twin). + if (d.fix) console.log(` fix: ${d.fix}`); } const partial = refs.filter((p) => !decisionsAreComplete(p.kind)).length; console.log( @@ -761,6 +764,8 @@ function usage() { " [--q TEXT] [--sort name|recent] [--json]", " umtool show <project> [--json]", " 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 decisions [--json]", " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them", " (--all: the hidden ones on parked/done pieces, and the quiet group)", @@ -774,6 +779,10 @@ function usage() { " attribution too: --title, --date YYYY-MM-DD, --cite, --cite-url, --quote", " --repeat-of <clip> it re-plays that clip on purpose (a callback): their overlap is not flagged or trimmed", " --correction TEXT what the REPORT got wrong here (never rendered)", + " --walk-note TEXT an editorial note from the walk (not a correction; never rendered)", + " --star / --no-star the walk's favourite: a trailer candidate (umtool trailer <p> --candidates)", + " a window edit that leaves --cite (or the citeUrl's t=) more than 5 s before the clip, or", + " after it, moves it to the clip's first second; an explicit --cite moves the QR's t= with it", " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --reject <why> [--note TEXT] rejected on the walk, kept in place (`umtool timeline <p> reject`", " takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its", @@ -961,6 +970,8 @@ const COMMANDS = { // Render mode (2026-10-30): lib/report/renderMode.mjs. "render-mode": async () => process.exit(await (await import("../lib/report/renderMode.mjs")).renderModeCommand(argv.slice(argv.indexOf("render-mode") + 1))), 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))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. @@ -1050,6 +1061,8 @@ async function cmdWindow() { ["--lock-end", "lockEnd"], // The cut, pinned against the resolver. `lock` is about the EXTENT. ["--lock-cut", "lockCut"], + // The walk's favourite: a trailer candidate (lib/report/trailerCandidates.mjs). + ["--star", "star"], ]) { if (has(flag)) patch[key] = true; if (has(`--no-${flag.slice(2)}`)) patch[key] = false; @@ -1082,6 +1095,9 @@ async function cmdWindow() { ["--cite-url", "citeUrl"], ["--quote", "quote"], ["--correction", "correction"], + // Not attribution: an editorial note from the walk ("THIS IS GOLD") -- not + // a correction, which says the report got a fact wrong. + ["--walk-note", "walkNote"], // Not attribution: the clip this one re-plays on purpose (a callback, a // flash-forward), so its overlap with that clip is neither flagged nor trimmed. ["--repeat-of", "repeatOf"], @@ -1174,6 +1190,12 @@ async function cmdWindow() { if (patch.verdict !== undefined || patch.correction !== undefined) { console.log(` review: ${reviewWords(res.entry)}`); } + if (patch.walkNote !== undefined) console.log(res.entry.walkNote ? ` walk note: ${res.entry.walkNote}` : " walk note cleared"); + if (patch.star !== undefined) console.log(res.entry.star ? " ★ starred — a trailer candidate (umtool trailer <p> --candidates)" : " ★ cleared"); + // The cite follows the edge (lib/report/citeFollow.mjs): said, so a window + // edit that moved the clock or the QR is never silent. + if (res.citeFollowed?.cite) console.log(` cite followed the edge: ${hms(res.citeFollowed.cite.from)} -> ${hms(res.citeFollowed.cite.to)}`); + if (res.citeFollowed?.citeUrl) console.log(` QR followed: ${res.citeFollowed.citeUrl.to}`); if (reject !== undefined) { console.log(` still in the cut: umtool timeline ${p.id} reject ${clipId} ${String(reject).trim()} takes it out, on the record (removed.json)`); } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -147,6 +147,12 @@ type Clip = { gaps: Span[]; /** "confirmed" / "incorrect" / "rejected", or null for "nobody has looked at this yet". */ verdict: "confirmed" | "incorrect" | "rejected" | null; + /** An editorial note from the walk -- not a correction (a fact error). Never rendered. */ + walkNote: string | null; + /** The walk's favourite (★): a trailer candidate (lib/report/trailerCandidates.mjs). */ + star: boolean; + /** The clip this one re-plays on purpose (a callback, a flash-forward), or null. */ + repeatOf: string | null; /** Why it was rejected (lib/report/rejectReasons.mjs): wrong-speaker under incorrect, a cut reason under rejected. */ reason: string | null; /** The rejection's note (a cut reason's; a fact reason's note is the correction). */ @@ -197,6 +203,7 @@ const ATTRIB = [ ["citeUrl", "citeUrl", "Where the QR points. Empty derives it from the archive. Set it when the clip is cut from a mirror that reads better."], ["quote", "quote", "The words this clip exists for. Not drawn on screen — it is what the cut is checked against."], ["correction", "correction", "On an incorrect clip (rejected as doesn't match or wrong speaker): what the report got wrong — wrong speaker, wrong addressee, wrong date, read by the next report pass. On a confirmed or rejected-as-irrelevant one it is just a note: why the window moved, or something a reader should know. Never rendered."], + ["walkNote", "walk note", "An editorial note from the walk: this is gold, it wants a beat of silence, move it to another section. Not a correction — that says the report got a fact wrong. ★ (s) makes the clip a trailer candidate. Never rendered."], ] as const; type AttribKey = (typeof ATTRIB)[number][0]; @@ -235,6 +242,9 @@ const fromEntry = (prev: Clip, e: Record<string, unknown>): Clip => ({ muteFrom: e.muteFrom == null ? null : Number(e.muteFrom), gaps: Array.isArray(e.gaps) ? (e.gaps as Span[]) : [], verdict: e.verdict === "confirmed" || e.verdict === "incorrect" || e.verdict === "rejected" ? e.verdict : null, + walkNote: (e.walkNote as string) ?? null, + star: e.star === true, + repeatOf: (e.repeatOf as string) ?? null, reason: (e.reason as string) ?? null, rejectNote: (e.rejectNote as string) ?? null, onscreen: (e.onscreen as Onscreen | undefined) ?? null, @@ -1525,9 +1535,14 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { } // Re-sync only the fields this save carried, and from what the writer // actually stored -- which is trimmed, rounded, or gone. + // The cite and the QR follow a moved edge (lib/report/citeFollow.mjs): + // their boxes show what the writer stored, and the save says so. + const followed = j.citeFollowed as { cite?: { from: number; to: number }; citeUrl?: { to: string } } | undefined; setDraft((d) => { const out = { ...d }; for (const [k] of ATTRIB) if (patch[k] !== undefined) out[k] = attribValue(next, k); + if (followed?.cite) out.cite = attribValue(next, "cite"); + if (followed?.citeUrl) out.citeUrl = attribValue(next, "citeUrl"); return out; }); // The on-screen pair saves as one value. Each field goes back to what was @@ -1542,7 +1557,13 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { })); } token.current = String(j.token ?? ""); - setNote("saved"); + setNote( + followed?.cite + ? `saved — the cite followed the edge: ${hms(followed.cite.from)} → ${hms(followed.cite.to)}${followed.citeUrl ? ", and the QR with it" : ""}` + : followed?.citeUrl + ? "saved — the QR's t= followed the edge" + : "saved", + ); // The widener's opinion changes when the window does. void refresh(); return true; @@ -1751,6 +1772,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { router.push(to); }, [data.fromPlay, dirty, muteMoved, save, windowPatch, router]); + /** + * ★: the walk's favourite, a trailer candidate (lib/report/trailerCandidates.mjs). + * Not a verdict and not a note -- one key (`s`), written at once. + */ + const toggleStar = useCallback(() => { + const on = !clip.star; + void save({ star: on }).then((ok) => { + if (ok) setNote(on ? `★ ${clip.id} — a trailer candidate` : `★ cleared on ${clip.id}`); + }); + }, [clip.star, clip.id, save]); + /** Reject ▾: the reasons (RejectClip) -- on a phone in a sheet, keyboard up; on the desk where the answer sits. */ const rejectClip = useCallback(() => { if (isPhoneNow()) { @@ -2037,6 +2069,11 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { case "X": rejectClip(); break; + // ★ the clip: a favourite, a trailer candidate (not a verdict). + case "s": + case "S": + toggleStar(); + break; // How fast you listen, and whether a clip plays itself on arrival. case "-": case "_": @@ -2124,6 +2161,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { hrefOf, confirmClip, rejectClip, + toggleStar, choosePlayback, mute, mutePick, @@ -2641,6 +2679,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { > Reject ▾ <kbd>x</kbd> </button> + <button + type="button" + data-verdict-star={clip.star ? "on" : "off"} + aria-pressed={clip.star} + className={buttonVariants({ variant: clip.star ? "go" : "quiet", size: "md" })} + disabled={!!busy} + onClick={toggleStar} + title="a favourite: the clip becomes a trailer candidate (the Cut tab's ★ list, umtool trailer <p> --candidates). Not a verdict" + > + {clip.star ? "★ Starred" : "☆ Star"} <kbd>s</kbd> + </button> <span data-verdict-state="" className={ @@ -2929,6 +2978,16 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { Undo the extension </button> )} + <button + type="button" + data-walk-star={clip.star ? "on" : "off"} + aria-pressed={clip.star} + disabled={!!busy} + onClick={toggleStar} + className={cn(buttonVariants({ variant: clip.star ? "go" : "outline", size: "md" }), "h-11")} + > + {clip.star ? "★ Starred" : "☆ Star"} + </button> {busy && <span className="text-meter">{busy}</span>} {note && ( <span data-walk-said="" className="text-doubt-text"> @@ -3189,6 +3248,21 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { not fetched yet </span> )} + {/* A deliberate repeat (`repeatOf`): its overlap with that clip is the point. */} + {clip.repeatOf && ( + <span + data-bench-repeat-of={clip.repeatOf} + title={`re-plays ${clip.repeatOf} on purpose (a callback, a flash-forward): their overlap is neither flagged nor trimmed`} + className={cn(badgeVariants({ variant: "info", size: "sm" }), "max-md:order-[21] max-md:self-start")} + > + repeats {clip.repeatOf} + </span> + )} + {clip.star && ( + <span data-bench-star="" title="starred on the walk: a trailer candidate" className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")}> + ★ trailer + </span> + )} {/* The renderer's own line, live. It used to sit four hundred pixels down the page; it is the one string this bench exists to get right, so it heads the screen. */} @@ -4218,7 +4292,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { unsaved — was {attribValue(clip, k) || "(empty)"} </span> )} - {k === "quote" || k === "correction" ? ( + {k === "quote" || k === "correction" || k === "walkNote" ? ( <textarea data-attrib-field={k} name={k} @@ -4227,7 +4301,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { placeholder={ k === "correction" ? "what the report got wrong: speaker, addressee, date, wording…" - : "" + : k === "walkNote" + ? "an editorial note: gold, too long, wants a beat of silence, move it…" + : "" } onChange={(e) => setDraft((d) => ({ ...d, [k]: e.target.value }))} onBlur={() => commit(k)} diff --git a/umtool/components/projects/ClipBenchPage.tsx b/umtool/components/projects/ClipBenchPage.tsx @@ -114,6 +114,10 @@ export default async function ClipBenchPage({ ?.gaps ?? [], verdict: entry.verdict === "confirmed" || entry.verdict === "incorrect" || entry.verdict === "rejected" ? entry.verdict : null, + // What the walk said that is not a verdict, and a deliberate repeat. + walkNote: typeof entry.walkNote === "string" ? entry.walkNote : null, + star: entry.star === true, + repeatOf: typeof entry.repeatOf === "string" ? entry.repeatOf : null, // Why it was rejected (lib/report/rejectReasons.mjs), from the manifest's own entry. ...(() => { const own = ((manifest.timeline ?? []) as { id: string; reason?: unknown; rejectNote?: unknown }[]).find((e) => e.id === clipId); diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -20,6 +20,7 @@ import BenchPrepPanel from "./BenchPrepPanel"; import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. @@ -37,6 +38,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor verdict: "confirmed" | "incorrect" | "rejected" | "unreviewed"; }[]; const clips = entries.filter((e) => e.kind === "clip"); + // The walk's ★ clips, as trailer beats (lib/report/trailerCandidates.mjs). + const candidates = trailerCandidates(m); // How much of the cut has been walked. One definition, shared with the bench // header and `umtool corrections`. const review = reviewOf(m); @@ -302,6 +305,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {e.lock && <Pill>locked</Pill>} {!e.lock && e.lockStart && <Pill>start pinned</Pill>} {!e.lock && e.lockEnd && <Pill>end pinned</Pill>} + {/* The walk's favourite (a trailer candidate) and a deliberate repeat. */} + {e.star === true && ( + <span data-star={e.id} title="starred on the walk: a trailer candidate"> + <Pill tone={TONE.open}>★ trailer</Pill> + </span> + )} + {typeof e.repeatOf === "string" && e.repeatOf && ( + <span data-repeat-of={e.repeatOf} title={`re-plays ${e.repeatOf} on purpose: their overlap is neither flagged nor trimmed`}> + <Pill>repeats {e.repeatOf}</Pill> + </span> + )} {/* The PLAYER's question, and the walk's: is this clip watchable end to end right now. `data-cached` keeps the BUILD's -- the padded window it would fetch -- because @@ -367,6 +381,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor {String(e.quote).length > 240 ? "…" : ""}&rdquo; </p> )} + {typeof e.walkNote === "string" && e.walkNote && ( + <p data-walk-note-of={e.id} className="mt-1 text-[11px] leading-snug text-text-2"> + <span className="micro">walk note</span> {e.walkNote} + </p> + )} {midSentence && e.endCueText && ( <p className="num mt-1 text-[11px] text-text-2"> cut lands inside: &ldquo;…{String(e.endCueText).trim().slice(-64)}&rdquo; @@ -393,6 +412,36 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </div> </section> + {/* --- the walk's ★ clips: the trailer's candidates ------------------- */} + {candidates.length > 0 && ( + <section + data-trailer-candidates={candidates.length} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <h2 className="micro mb-1.5"> + ★ trailer candidates — {candidates.length} · {candidates.reduce((n, b) => n + b.end - b.start, 0).toFixed(1)} s + </h2> + <ul className="space-y-1"> + {candidates.map((b) => ( + <li key={b.id} data-trailer-candidate={b.id} className="flex flex-wrap items-baseline gap-2 text-[12px] leading-snug"> + <Link href={clipBenchHref(project.id, b.id)} className="ink-link font-mono text-[11px]"> + {b.id} + </Link> + <span className="num font-mono text-[11px] text-[var(--color-dim)]"> + {hms(b.start)}–{hms(b.end)} ({(b.end - b.start).toFixed(1)} s) + </span> + {b.quote && <span className="text-[var(--color-dim)]">&ldquo;{b.quote.slice(0, 120)}{b.quote.length > 120 ? "…" : ""}&rdquo;</span>} + {b.walkNote && <span className="text-text-2">— {b.walkNote}</span>} + </li> + ))} + </ul> + <p className="mt-2 text-[11px] text-[var(--color-dim)]"> + <code className="font-mono">umtool trailer {project.id} --candidates --json</code> prints them as a trailer&rsquo;s{" "} + <code className="font-mono">--beats-json</code>. + </p> + </section> + )} + {/* --- corrections ------------------------------------------------ */} {/* Not a decision and not a defect in the CUT: a correction says the diff --git a/umtool/components/projects/report/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx @@ -0,0 +1,92 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { buttonVariants } from "@/components/ui/button"; +import type { Decision } from "@/lib/decisions"; + +// The one-press settle beside a check row (lib/projects/report.mjs `settle`): +// a clip patch through the window writer -- "It's deliberate: b repeats a" +// (repeatOf), "Move to 12:34" (the clock and the QR back on the clip) -- or a +// link check against the sites the QRs open. The row's `fix` is the same +// thing from a terminal; nothing here needs a model. + +export default function DecisionSettle({ + project, + settle, + token = null, +}: { + project: string; + settle: NonNullable<Decision["settle"]>; + token?: string | null; +}) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<string | null>(null); + const [err, setErr] = useState<string | null>(null); + + const run = async () => { + setBusy(true); + setErr(null); + try { + const r = + settle.kind === "patch" + ? await fetch("/api/report/window", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, clip: settle.clip, ...settle.patch, ...(token ? { token } : {}) }), + }) + : await fetch("/api/report/links", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project }), + }); + const j = (await r.json().catch(() => ({}))) as { + error?: string; + verdicts?: { ok: number; dead: unknown[]; unverified: unknown[]; archive: number }; + }; + if (!r.ok) { + setErr(j.error ?? `HTTP ${r.status}`); + return; + } + if (settle.kind === "check-links" && j.verdicts) { + const v = j.verdicts; + setSaid(`${v.ok} of ${v.archive} open · ${v.dead.length} dead · ${v.unverified.length} not verified`); + } else setSaid("saved"); + router.refresh(); + } catch (e) { + setErr(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + return ( + <span className="inline-flex items-center gap-2" data-settle={settle.kind}> + <button + type="button" + data-settle-button={settle.kind === "patch" ? settle.clip : "links"} + disabled={busy} + onClick={() => void run()} + className={buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size: "sm" })} + title={ + settle.kind === "patch" + ? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer` + : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time" + } + > + {busy ? (settle.kind === "check-links" ? "Checking…" : "Saving…") : settle.label} + </button> + {said && !err && ( + <span data-settle-said="" className="text-[11.5px] text-text-2"> + {said} + </span> + )} + {err && ( + <span data-settle-error="" className="text-[11.5px] text-doubt-text"> + {err} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx @@ -14,6 +14,8 @@ import { decisionsForProject } from "@/lib/projects"; 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 { manifestToken } from "@/lib/report/manifest.mjs"; // The Overview tab (canvas "Piece · Overview"): the Next card, then the // piece's decisions and -- when it is an article's video -- the article and @@ -29,6 +31,9 @@ const VIA: Record<string, string> = { export default async function OverviewTab({ project, detail, frame }: ReportTabProps & { frame: PieceFrame }) { const { manifest: m, build, entries } = detail; const decisions = await decisionsForProject(project); + // The settles beside the rows write through the window writer with the + // manifest's token, as every other manifest write does. + const token = await manifestToken(project.dir).catch(() => null); const readme = await readFile(path.join(project.dir, "README.md"), "utf8").catch(() => null); const p = (m.provenance ?? {}) as Record<string, unknown>; const clips = entries.filter((e) => e.kind === "clip"); @@ -53,7 +58,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP <div className="grid grid-cols-1 gap-[22px] lg:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]"> <div className="min-w-0 space-y-4"> {/* --- what is wrong, first ------------------------------------- */} - <ProjectDecisions project={project.id} decisions={decisions} /> + <ProjectDecisions project={project.id} decisions={decisions} token={token} /> {iterations && iterations.iterations.length > 0 && article && ( <section data-piece-iterations={iterations.iterations.length}> @@ -152,7 +157,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP } /** A project's decisions, what is waiting first (ReportProject's section, unchanged). */ -export function ProjectDecisions({ project, decisions }: { project: string; decisions: Decision[] }) { +export function ProjectDecisions({ project, decisions, token = null }: { project: string; decisions: Decision[]; token?: string | null }) { return ( <> {decisions.length > 0 && ( @@ -174,7 +179,11 @@ export function ProjectDecisions({ project, decisions }: { project: string; deci </span> <span className="font-mono text-[12px] text-[var(--color-text)]">{d.target}</span> <span className="text-[12px] text-[var(--color-dim)]">{d.why}</span> - <span className="micro ml-auto">{d.kind}</span> + {/* The one-press settle, when the row knows one; `fix` is its terminal twin. */} + {d.settle && <DecisionSettle project={project} settle={d.settle} token={token} />} + <span className="micro ml-auto" data-fix={d.fix ?? undefined} title={d.fix ? `from a terminal: ${d.fix}` : undefined}> + {d.kind} + </span> </li> ))} </ul> diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts @@ -78,6 +78,19 @@ export type Decision = { severity: Severity; /** Newest evidence first. */ at: number; + /** The command that settles it from a terminal, when the reducer knows one (`umtool check` prints it). */ + fix?: string; + /** + * The one-press settle the project page offers beside the row, when the + * reducer knows one: a clip patch through the window writer (PUT + * /api/report/window -- "It's deliberate", "Move to 12:34"), or a link check + * (POST /api/report/links). `fix` is its terminal twin. + */ + settle?: + | { kind: "patch"; clip: string; patch: Record<string, unknown>; label: string } + | { kind: "check-links"; label: string }; + /** The clips a project-wide row is about (a site's dead links). */ + clips?: string[]; // ---- The inbox's fields (lib/inbox.ts). ADDITIVE: a row without them is // still a decision, and the reducers above never set them. ---- diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -128,6 +128,11 @@ const ACTION_LABEL = { "clip-incorrect": "Remove or fix the clip", "clip-rejected": "Take the clip out", "window-overlap": "Fix the windows", + "clip-cite-off": "Move the cite to the clip", + "patch-markers-stale": "Fix the take patch", + "link-dead": "Fix the links", + "links-unverified": "Check links again", + "links-unchecked": "Check links", "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 @@ -33,6 +33,11 @@ export const WHAT = { "clip-incorrect": "clips marked incorrect", "clip-rejected": "rejected clips still in the cut", "window-overlap": "windows overlap", + "clip-cite-off": "clock or QR off the clip", + "patch-markers-stale": "take patch names clips that are gone", + "link-dead": "QR links that don't open", + "links-unverified": "links not verified", + "links-unchecked": "links not checked", "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 @@ -42,6 +42,9 @@ import { widen } from "umtool-report-to-video/resolve-windows"; import { montageOn } from "umtool-report-to-video/montage"; import { validateGaps } from "umtool-report-to-video/gaps"; 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"; // 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 @@ -166,6 +169,15 @@ export function deadOriginWhy(m, qrs) { const stat0 = (p) => stat(p).then((s) => s, () => null); +/** A source second as the check rows say it: `m:ss`, or `h:mm:ss`. */ +const hmsShort = (sec) => { + const t = Math.max(0, Math.floor(Number(sec) || 0)); + const h = Math.floor(t / 3600); + const mm = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`; +}; + export const manifestPath = (dir) => path.join(dir, MANIFEST_NAME); export async function readManifest(dir) { @@ -733,14 +745,16 @@ const DRAFT_FILE = /^[a-z0-9][a-z0-9-]{0,62}-draft\.json$/; */ export async function reportSignature(dir) { const names = await readdir(dir).catch(() => []); - const drafts = names.filter((n) => DRAFT_FILE.test(n)).sort(); - const [man, out, avail, rev, review, narration, ...draftStats] = await Promise.all([ + const drafts = names.filter((n) => DRAFT_FILE.test(n) || PATCH_FILE_RE.test(n)).sort(); + const [man, out, avail, links, rev, review, narration, ...draftStats] = await Promise.all([ stat0(manifestPath(dir)), stat0(path.join(dir, "out")), // Rewritten IN PLACE by every preflight, which leaves out/'s own mtime // where it was -- so it has to be signed on its own or a re-check would // never reach the index. stat0(path.join(dir, "out", "availability.json")), + // The link check's record (linkCheck.mjs), rewritten in place the same way. + stat0(linksFile(dir)), stat0(path.join(dir, "revisions")), stat0(path.join(dir, DRAFTS_REVIEW_FILE)), stat0(path.join(dir, NARRATION_REVIEW_FILE)), @@ -752,6 +766,7 @@ export async function reportSignature(dir) { man?.size ?? 0, Math.round(out?.mtimeMs ?? 0), Math.round(avail?.mtimeMs ?? 0), + signed(links), Math.round(rev?.mtimeMs ?? 0), signed(review), signed(narration), @@ -1037,6 +1052,24 @@ export const REPORT_DECISION_KINDS = [ // Where the deliverables are disagrees with `storage.deliverables`, or a // move was cut. `open`: nothing is lost, and one command settles it. "storage-mismatch", + // The clock (`cite`) or the QR's `t=` names a second more than a lead-in + // before what the clip plays, or after it (citeFollow.mjs). `open`: the + // build does not refuse it, but the video cites a moment it does not show. + // Its action moves them to the clip. + "clip-cite-off", + // A take patch beside the manifest (`*.patch.json`) whose deck markers + // name a clip that is not in the cut (patchMarkers.mjs): a take made with + // it is refused. `open`: the project's own build is fine. + "patch-markers-stale", + // A clip QR that does not open on the site it links (linkCheck.mjs, the + // recorded check in out/links.json). BLOCKING, as a QR that resolves + // nowhere always was: one row per site, naming the clips and why. + "link-dead", + // The recorded link check could not reach a site (offline, a timeout, no + // corpus.json): those links are not verified. `info`. + "links-unverified", + // Links never checked, or changed since the check. `info`, with Check links. + "links-unchecked", ]; /** @@ -1263,17 +1296,71 @@ export async function reportDecisions(ctx, summary) { if (a.repeatOf === b.id || b.repeatOf === a.id) continue; const seam = timelineIndex.get(b) === timelineIndex.get(a) + 1 && overlap <= D + 0.01; if (seam) continue; + // "It's deliberate": the one that plays LATER in the cut re-plays the + // earlier one (a callback, a flash-forward) -- `repeatOf` through the + // window writer, which clears this row. + const [first, again] = (timelineIndex.get(a) ?? 0) <= (timelineIndex.get(b) ?? 0) ? [a, b] : [b, a]; add( "window-overlap", a.id, `overlaps ${b.id} by ${overlap.toFixed(1)}s` + (a.lockEnd ? " and has lockEnd, so nothing will trim it" : ""), a.lockEnd ? "open" : "info", - { href: clipHref(a.id) }, + { + href: clipHref(a.id), + fix: `umtool window ${id} ${again.id} --repeat-of ${first.id} # if ${again.id} re-plays ${first.id} on purpose`, + settle: { kind: "patch", clip: again.id, patch: { repeatOf: first.id }, label: `It's deliberate: ${again.id} repeats ${first.id}` }, + }, ); } } + // THE CLOCK AND THE QR NAME A SECOND THE CLIP PLAYS (citeFollow.mjs). The + // writer moves them with an edge now; this is for what was written before, + // or by hand. + for (const e of clips) { + const off = citeOffsets(e, { channelSlug: m.provenance?.channelSlug ?? null }); + if (!off) continue; + 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)}` + : [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, + off.patch.citeUrl !== undefined ? `--cite-url '${off.patch.citeUrl}'` : null, + ].filter(Boolean).join(" "); + add( + "clip-cite-off", + e.id, + `${what} (${off.clockOff ? `cite ${hmsShort(off.clock)}` : `QR t=${off.qr}`}, it plays ${hmsShort(off.from)}–${hmsShort(off.to)})`, + "open", + { + href: clipHref(e.id), + fix: `umtool window ${id} ${e.id} ${flags}`, + settle: { kind: "patch", clip: e.id, patch: off.patch, label: `Move to ${hmsShort(off.at)}` }, + }, + ); + } + + // A TAKE PATCH WHOSE MARKERS NAME A CLIP THAT IS GONE (patchMarkers.mjs). + // The structural writers re-anchor them now; this is for the rest. + for (const p of await stalePatchMarkers(dir, m)) { + if (p.error) { + add("patch-markers-stale", p.file, `does not read (${p.error}) — a take made with it is refused`, "open"); + continue; + } + const named = p.markers.map((mk) => `${mk.label ? `"${mk.label}"` : `marker ${mk.index}`} after ${mk.after}`); + add( + "patch-markers-stale", + p.file, + `${p.markers.length === 1 ? "a deck marker names a clip" : `${p.markers.length} deck markers name clips`} not in the cut: ` + + `${named.slice(0, 4).join(", ")}${named.length > 4 ? ` and ${named.length - 4} more` : ""} — a take made with --patch ${p.file} is refused`, + "open", + { fix: `edit ${p.file}: render.chrome.deck.markers[].after must name clips of the cut (umtool timeline ${id} ls)` }, + ); + } + // A CLIP RULED INCORRECT STILL IN THE CUT. The walk recorded it; nothing // downstream acts on a verdict, so this is where it stops a render. for (const e of incorrectClips(clips)) { @@ -1463,6 +1550,63 @@ export async function reportDecisions(ctx, summary) { ); } + // --- do the QR links open? (linkCheck.mjs) ------------------------------- + // The recorded check, never a live one: the reducer does not fetch. + { + const doc = await readLinkCheck(dir); + const v = linkVerdicts(m, doc); + const checkSettle = { kind: "check-links", label: doc ? "Check links again" : "Check links" }; + const checkFix = `umtool links ${id}`; + if (v.archive > 0) { + const when = v.checkedAt ? ` on ${v.checkedAt.slice(0, 16).replace("T", " ")}` : ""; + const byOrigin = (rows) => { + const g = new Map(); + for (const r of rows) { + const k = r.origin ?? "?"; + if (!g.has(k)) g.set(k, []); + g.get(k).push(r); + } + return g; + }; + for (const [origin, rows] of byOrigin(v.dead)) { + const host = (() => { try { return new URL(origin).host; } catch { return origin; } })(); + const o = v.origins[origin] ?? {}; + const ids = [...new Set(rows.map((r) => r.clip))]; + add( + "link-dead", + host, + `${rows.length} of ${v.archive} QR link${v.archive === 1 ? "" : "s"} don't open on ${host}` + + `${o.generatedAt ? ` (deployed ${o.generatedAt.slice(0, 10)})` : ""}: ${ids.slice(0, 8).join(", ")}${ids.length > 8 ? ` and ${ids.length - 8} more` : ""}` + + ` — ${rows[0].clip}: ${rows[0].why}` + + (rows.some((r) => r.fix) ? `. Every clip with a fix: \`umtool links ${id} --fix\`` : ""), + "blocking", + { fix: checkFix, settle: checkSettle, clips: ids }, + ); + } + for (const [origin, rows] of byOrigin(v.unverified)) { + const host = (() => { try { return new URL(origin).host; } catch { return origin; } })(); + add( + "links-unverified", + host, + `${rows.length} link${rows.length === 1 ? "" : "s"} not verified${when} — ${rows[0].why}`, + "info", + { fix: checkFix, settle: checkSettle }, + ); + } + if (!doc) { + add("links-unchecked", "QR links", `${v.archive} archive link${v.archive === 1 ? "" : "s"} never checked against the site${v.archive === 1 ? "" : "s"} they open`, "info", { fix: checkFix, settle: checkSettle }); + } else if (v.unchecked.length) { + add( + "links-unchecked", + "QR links", + `${v.unchecked.length} link${v.unchecked.length === 1 ? "" : "s"} changed since the check${when}: ${v.unchecked.slice(0, 6).map((l) => l.clip).join(", ")}${v.unchecked.length > 6 ? " …" : ""}`, + "info", + { fix: checkFix, settle: checkSettle }, + ); + } + } + } + // --- the build ----------------------------------------------------------- if (s.build.stale) { add( diff --git a/umtool/lib/report/citeFollow.mjs b/umtool/lib/report/citeFollow.mjs @@ -0,0 +1,182 @@ +// The cite follows the edge (UI notes 2026-10-30, #5). +// +// A clip's `cite` is the second the deck's clock prints, and its `citeUrl`'s +// `t=` is the second the QR opens. Both were written when the clip was found, +// against the window it had then. Tightening moved `start` and left them +// behind: on the Ember cut the clock and the QR ran up to 78 s early on 16 +// clips, and it was caught from a still. +// +// So the window writer (manifest.mjs patchClipEntry) moves them when an edge +// move leaves them outside what plays, and the check reports any left there +// (`clip-cite-off`, lib/projects/report.mjs). One rule, here, for both. +// +// A cite a few seconds BEFORE the clip is a lead-in, not a defect: the Ember +// cut cites up to 5 s ahead on purpose (the QR lands just before the line). +// More than CITE_LEAD_MAX before, or any second after the clip ends, names a +// moment the clip does not play. +// +// A citeUrl is ours to move only when it names THIS recording -- the archive's +// `?v=<channel>/<id>` (Twitch's record id is `v<id>`), or the platform's own +// `watch?v=<id>` / `youtu.be/<id>`. A mirror's clock is not this one's, so its +// `t=` is left as written and never judged. +// +// Plain ESM: the CLI runs it under bare node. + +/** Seconds a cite may sit before the clip and still be a lead-in. */ +export const CITE_LEAD_MAX = 5; +const EPS = 0.02; + +/** What plays: the cut when the clip has the pair (the build honours the pair or neither), else the extent. */ +export function playedSpan(e) { + const cs = Number(e?.cutStart); + const ce = Number(e?.cutEnd); + if (e?.cutStart != null && e?.cutEnd != null && Number.isFinite(cs) && Number.isFinite(ce)) return { from: cs, to: ce }; + return { from: Number(e?.start), to: Number(e?.end) }; +} + +/** The clock's second: `cite`, else the clip's start (attribution.mjs's rule). */ +export const clockOf = (e) => (e?.cite ?? e?.start ?? 0); + +/** + * Where a second sits against what plays: 0 inside (a lead-in of up to + * CITE_LEAD_MAX counts as inside), negative N when it is N s too early + * (measured from the clip's first played second), positive N when N s after + * the clip ends. + */ +export function offsetFrom(at, span, lead = CITE_LEAD_MAX) { + if (!Number.isFinite(at) || !Number.isFinite(span.from) || !Number.isFinite(span.to)) return 0; + if (at < span.from - lead - EPS) return -(span.from - at); + if (at > span.to + EPS) return at - span.to; + return 0; +} + +/** A `t=` value in seconds: `123`, `123.5`, `123s`, `1h2m3s`, `2m3s`; null when it is none of those. */ +export function parseT(raw) { + const s = String(raw ?? "").trim(); + if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, "")); + const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(s); + if (m && (m[1] || m[2] || m[3])) return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0); + return null; +} + +/** Does `u` name the clip's own recording (so the same clock)? */ +export function sameRecording(u, e, channelSlug = null) { + const vid = String(e?.video ?? ""); + if (!vid) return false; + const chan = e?.channel ?? channelSlug; + const v = u.searchParams.get("v"); + if (v != null) { + if (chan && (v === `${chan}/${vid}` || v === `${chan}/v${vid}`)) return true; + if (v === vid) return true; + } + if (/(^|\.)youtu\.be$/.test(u.hostname) && u.pathname === `/${vid}`) return true; + return false; +} + +/** + * The second the clip's citeUrl opens, when it names this recording and + * carries a `t=`; null otherwise (no citeUrl, another recording, no `t`). + */ +export function citeUrlSecond(e, channelSlug = null) { + if (!e?.citeUrl) return null; + let u; + try { + u = new URL(String(e.citeUrl)); + } catch { + return null; + } + if (!u.searchParams.has("t")) return null; + if (!sameRecording(u, e, channelSlug)) return null; + return parseT(u.searchParams.get("t")); +} + +/** + * The citeUrl with its `t=` set to `sec` (whole seconds), keeping a `123s` + * spelling as `<sec>s`. A targeted edit rather than URLSearchParams: a + * re-serialised URL rewrites every other parameter's escaping and churns the + * manifest (resolve-windows.mjs retargetCiteUrl, the same reason). + */ +export function withT(citeUrl, sec) { + const n = Math.max(0, Math.floor(sec)); + return String(citeUrl).replace(/([?&]t=)(\d+(?:\.\d+)?)(s?)(?=&|#|$)|([?&]t=)[^&#]*/, (all, p1, _num, suffix, p4) => + p1 ? `${p1}${n}${suffix}` : `${p4}${n}`, + ); +} + +/** + * After an edge move: the `cite` and the citeUrl's `t=` the clip should carry, + * when either now lies outside what plays. Mutates nothing; returns null when + * both are fine. + * + * The new second is the clip's first played second, floored -- what the + * header shows for a clip with no `cite` at all, and the second a derived QR + * opens. A citeUrl moves to the (new) cite. + * + * @param {Record<string, any>} e the entry AFTER the window patch + * @param {{ channelSlug?: string | null }} [opts] + * @returns {null | { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } }} + */ +export function citeFollow(e, { channelSlug = null } = {}) { + const span = playedSpan(e); + if (!Number.isFinite(span.from) || !Number.isFinite(span.to)) return null; + const out = {}; + let clock = clockOf(e); + if (e.cite != null && offsetFrom(Number(e.cite), span) !== 0) { + const to = Math.floor(span.from); + out.cite = { from: Number(e.cite), to }; + clock = to; + } + const t = citeUrlSecond(e, channelSlug); + if (t != null && offsetFrom(t, span) !== 0) { + const to = withT(e.citeUrl, clock); + if (to !== e.citeUrl) out.citeUrl = { from: String(e.citeUrl), to }; + } + return out.cite || out.citeUrl ? out : null; +} + +/** + * After an explicit `cite` write: the citeUrl's `t=` follows when the two + * agreed before (the QR opened at the clock's whole second). One that said + * something else was somebody's decision and is left. + * + * @param {Record<string, any>} e the entry AFTER the patch + * @param {number} oldClock the clock's second BEFORE the patch + * @param {{ channelSlug?: string | null }} [opts] + * @returns {null | { citeUrl: { from: string, to: string } }} + */ +export function qrFollowsCite(e, oldClock, { channelSlug = null } = {}) { + const t = citeUrlSecond(e, channelSlug); + if (t == null || Math.floor(t) !== Math.floor(oldClock)) return null; + const to = withT(e.citeUrl, clockOf(e)); + return to !== e.citeUrl ? { citeUrl: { from: String(e.citeUrl), to } } : null; +} + +/** + * What the check says about one clip: where its clock and its QR (when the + * citeUrl is this recording's) sit against what plays, in signed seconds (see + * offsetFrom), and the patch that puts them back (`cite`, and `citeUrl` when + * it would not follow the cite by itself). Null when both are fine. + * + * A derived QR (no citeUrl) is not judged here: it opens at the extent's + * start, which is the material somebody reviewed. + * + * @param {Record<string, any>} e + * @param {{ channelSlug?: string | null }} [opts] + */ +export function citeOffsets(e, { channelSlug = null } = {}) { + const span = playedSpan(e); + if (!Number.isFinite(span.from) || !Number.isFinite(span.to)) return null; + const clock = clockOf(e); + const clockOff = e.cite != null ? offsetFrom(Number(clock), span) : 0; + const t = citeUrlSecond(e, channelSlug); + const qrOff = t != null ? offsetFrom(t, span) : 0; + if (!clockOff && !qrOff) return null; + const at = Math.floor(span.from); + /** @type {Record<string, unknown>} */ + const patch = {}; + if (clockOff) patch.cite = at; + // The writer moves the QR with an explicit cite only when they agreed. + const follows = clockOff && t != null && Math.floor(t) === Math.floor(clock); + if (qrOff && !follows) patch.citeUrl = withT(e.citeUrl, clockOff ? at : clock); + return { clockOff, qrOff, clock, qr: t, from: span.from, to: span.to, at, patch }; +} diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -0,0 +1,279 @@ +// Do the cut's QR links open? (UI notes 2026-10-30, #8) +// +// On the Ember cut the Twitch links used the bare id, which the site does not +// open (its record is `v<id>`), and anilyzer's deploy was three weeks old with +// no Ember channels at all -- so most QRs were dead in drafts 1–11, and the +// fix took a headless browser. This resolves every clip's QR against the +// target site's own published contract instead: +// +// corpus.json -> channels[].manifests.transcripts -> slugToPage[<id>] +// -> page-<NNNN>.json (zero-padded to 4) -> the record whose id is <id> +// +// (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 +// 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. +// +// OFFLINE: a site that does not answer is a state, not an error -- its links +// are `unverified` with the reason, and the check row says "couldn't reach". +// +// The result is RECORDED (out/links.json), like the availability preflight's: +// the decisions reducer reads it and never fetches (lib/projects/report.mjs). +// +// Plain ESM: the CLI runs it under bare node. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; +import { qrsOf } from "umtool-report-to-video/lint"; + +export const LINKS_FILE = "links.json"; +export const linksFile = (dir) => path.join(dir, "out", LINKS_FILE); +const FETCH_TIMEOUT_MS = 20_000; + +/** + * An archive viewer link's parts: `<origin>/?v=<channel>/<id>&t=…`, or null + * for anything else (a platform's own page, a mirror) -- which this check + * does not judge. + * + * @param {string} url + * @returns {null | { origin: string, channel: string, id: string, t: string | null }} + */ +export function archiveLinkOf(url) { + let u; + try { + u = new URL(String(url)); + } catch { + return null; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + const v = u.searchParams.get("v"); + if (!v || !v.includes("/")) return null; + const cut = v.indexOf("/"); + const channel = v.slice(0, cut); + const id = v.slice(cut + 1); + if (!channel || !id) return null; + return { origin: u.origin, channel, id, t: u.searchParams.get("t") }; +} + +/** + * Every clip QR the cut draws, `{ clip, url }`, by the build's own rules + * (lint.mjs qrsOf: a clip's citeUrl, else its archive moment; none when the + * cut draws no code). + * + * @param {Record<string, any>} m + */ +export function linksOf(m) { + const clips = new Set((m?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id)); + let qrs = []; + try { + qrs = qrsOf(m); + } catch { + qrs = []; + } + const out = []; + const seen = new Set(); + for (const q of qrs) { + if (q.source !== "entry" || !clips.has(q.id) || !q.url) continue; + const key = `${q.id}\u0000${q.url}`; + if (seen.has(key)) continue; + seen.add(key); + out.push({ clip: q.id, url: String(q.url) }); + } + return out; +} + +/** A fetch that gives up: a site that hangs is a site that does not answer. */ +function withTimeout(fetchImpl, ms) { + return (url, init = {}) => fetchImpl(url, { ...init, signal: AbortSignal.timeout(ms) }); +} + +const errText = (e) => { + const m = e instanceof Error ? e.message : String(e); + const cause = e instanceof Error && e.cause instanceof Error ? ` (${e.cause.message})` : ""; + return `${m}${cause}`; +}; + +/** + * 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] + * @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 = () => {} } = {}) { + let fetched = 0; + const counting = withTimeout(async (url, init) => { + fetched += 1; + return fetchImpl(url, init); + }, FETCH_TIMEOUT_MS); + const { getJson } = createJsonCache({ cacheDir, fetchImpl: counting, log }); + /** @type {Record<string, any>} */ + const origins = {}; + const corpusOf = new Map(); + const manifestOf = new Map(); + + async function corpus(origin) { + if (corpusOf.has(origin)) return corpusOf.get(origin); + let doc = null; + try { + doc = await getJson(`${origin}/corpus.json`, { refresh: true }); + origins[origin] = { + state: "ok", + generatedAt: typeof doc?.generatedAt === "string" ? doc.generatedAt : null, + title: typeof doc?.site?.title === "string" ? doc.site.title : null, + }; + } catch (e) { + const msg = errText(e); + // A 404 is a site that answered and publishes no contract; anything + // else (DNS, refused, timeout, 5xx) is a site that did not answer. + origins[origin] = / -> 404$/.test(msg) ? { state: "no-corpus", error: msg } : { state: "unreachable", error: msg }; + doc = null; + } + corpusOf.set(origin, doc); + return doc; + } + + async function channelManifest(url) { + if (manifestOf.has(url)) return manifestOf.get(url); + let doc = null; + let error = null; + try { + doc = await getJson(url, { refresh: true }); + } catch (e) { + error = errText(e); + } + const r = { doc, error }; + manifestOf.set(url, r); + return r; + } + + const out = []; + for (const { clip, url } of links) { + const a = archiveLinkOf(url); + if (!a) { + out.push({ clip, url, state: "direct" }); + continue; + } + const host = new URL(a.origin).host; + const c = await corpus(a.origin); + if (!c) { + const o = origins[a.origin]; + out.push({ + clip, url, state: "unverified", origin: a.origin, + why: o.state === "no-corpus" ? `${host} publishes no corpus.json` : `couldn't reach ${host} (${o.error})`, + }); + continue; + } + if (c.site?.scope === "cited") { + out.push({ clip, url, state: "unverified", origin: a.origin, why: `${host} is a cited report site: it publishes no transcripts to look the record up in` }); + continue; + } + const ch = (c.channels ?? []).find((x) => x?.slug === a.channel); + if (!ch) { + out.push({ + clip, url, state: "dead", origin: a.origin, + why: `the channel "${a.channel}" is not on ${host}${origins[a.origin].generatedAt ? ` (its deploy of ${origins[a.origin].generatedAt.slice(0, 10)})` : ""} — publish the site with it, or link elsewhere`, + }); + continue; + } + const manifestUrl = ch.manifests?.transcripts; + if (typeof manifestUrl !== "string" || !manifestUrl) { + out.push({ clip, url, state: "dead", origin: a.origin, why: `${host} publishes no transcripts for "${a.channel}"` }); + continue; + } + const man = await channelManifest(manifestUrl); + if (!man.doc) { + out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${a.channel}'s manifest on ${host} (${man.error})` }); + continue; + } + const s2p = man.doc.slugToPage ?? {}; + const page = s2p[a.id]; + if (page === undefined) { + // The Twitch trap: the corpus directory is the bare id, the site's record is `v<id>`. + const alt = /^\d+$/.test(a.id) && s2p[`v${a.id}`] !== undefined ? `v${a.id}` : null; + out.push({ + clip, url, state: "dead", origin: a.origin, + why: alt + ? `"${a.id}" is not a record on ${host}; the site's record is "${alt}"` + : `"${a.id}" is not published in ${a.channel} on ${host}${origins[a.origin].generatedAt ? ` (deployed ${origins[a.origin].generatedAt.slice(0, 10)})` : ""}`, + ...(alt ? { fix: url.replace(/([?&]v=[^&#]*?)(%2F|\/)(\d+)(?=&|#|$)/i, `$1$2v$3`) } : {}), + }); + continue; + } + const pageUrl = pageUrlFrom(manifestUrl, Number(page)); + const has = (doc) => Array.isArray(doc) && doc.some((r) => r?.id === a.id || r?.slug === a.id); + let found = false; + let error = null; + try { + found = has(await getJson(pageUrl)); + // A cached shard older than the deploy: read it again, once. + if (!found) found = has(await getJson(pageUrl, { refresh: true })); + } catch (e) { + error = errText(e); + } + if (error) out.push({ clip, url, state: "unverified", origin: a.origin, why: `couldn't read ${path.posix.basename(new URL(pageUrl).pathname)} on ${host} (${error})` }); + else if (!found) out.push({ clip, url, state: "dead", origin: a.origin, why: `${host}'s slugToPage puts "${a.id}" on page ${page}, but no record there has that id — the deploy is inconsistent` }); + else out.push({ clip, url, state: "ok", origin: a.origin }); + } + return { version: 1, checkedAt: now().toISOString(), fetched, origins, links: out }; +} + +/** + * Check the project's links now and record the answer in out/links.json. + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @param {{ fetchImpl?: typeof fetch, cacheDir?: string | null, now?: () => Date, log?: (s: string) => void }} [opts] + */ +export async function runLinkCheck(dir, manifest, opts = {}) { + const doc = await checkLinks(linksOf(manifest), opts); + const file = linksFile(dir); + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(tmp, file); + return doc; +} + +/** The last recorded check, or null. */ +export async function readLinkCheck(dir) { + try { + const doc = JSON.parse(await readFile(linksFile(dir), "utf8")); + return doc && Array.isArray(doc.links) ? doc : null; + } catch { + return null; + } +} + +/** + * The recorded check read against the manifest as it is NOW: what is dead, + * what could not be verified (by site), and which of today's links the + * check never saw (a link changed since). + * + * @param {Record<string, any>} m + * @param {Awaited<ReturnType<typeof readLinkCheck>>} doc + */ +export function linkVerdicts(m, doc) { + const current = linksOf(m); + const archive = current.filter((l) => archiveLinkOf(l.url)); + const byKey = new Map((doc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l])); + const dead = []; + const unverified = []; + const unchecked = []; + let ok = 0; + for (const l of archive) { + const r = byKey.get(`${l.clip}\u0000${l.url}`); + if (!r) unchecked.push(l); + else if (r.state === "dead") dead.push(r); + else if (r.state === "unverified") unverified.push(r); + else if (r.state === "ok") ok += 1; + } + return { checkedAt: doc?.checkedAt ?? null, origins: doc?.origins ?? {}, archive: archive.length, direct: current.length - archive.length, ok, dead, unverified, unchecked }; +} diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -0,0 +1,100 @@ +// `umtool links <project> [--json] [--fix]`: do the cut's QR links open on the +// sites they link? (linkCheck.mjs says how, and why it is polite and cached.) +// The same check the project page's Check links runs (POST /api/report/links), +// recorded in out/links.json, which `umtool check` and the decisions read. +// +// --fix rewrite every dead link the check knows the fix for (the Twitch +// trap: `?v=<channel>/<id>` where the site's record is `v<id>`) +// through the window writer, then check again. +// +// Exit 1 when a link is dead, 0 otherwise (unverified is not dead). +// Plain ESM: the CLI runs it under bare node. +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { kindMakesTakes } from "../projects/kinds.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { updateClip } from "./manifest.mjs"; +import { runLinkCheck } from "./linkCheck.mjs"; + +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", + "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", + "(a Twitch id the site serves as v<id>) through the window writer, then checks again.", + "Exit 1 when a link is dead.", +].join("\n"); + +class CliError extends Error {} + +/** One line per site and per dead or unverified link. */ +export function linksSummary(doc) { + const lines = []; + const n = (s) => doc.links.filter((l) => l.state === s).length; + lines.push( + `${doc.links.length} clip QR link(s): ${n("ok")} open · ${n("dead")} dead · ${n("unverified")} not verified · ${n("direct")} not archive links (not checked) · ${doc.fetched} request(s)`, + ); + for (const [origin, o] of Object.entries(doc.origins ?? {})) { + lines.push( + ` ${origin}: ${o.state === "ok" ? `corpus.json${o.generatedAt ? `, deployed ${o.generatedAt.slice(0, 16).replace("T", " ")}` : ""}` : o.state === "no-corpus" ? "no corpus.json" : `couldn't reach — ${o.error}`}`, + ); + } + for (const l of doc.links) { + if (l.state === "dead") lines.push(`DEAD ${l.clip} ${l.why}${l.fix ? `\n fix: ${l.fix}` : ""}`); + else if (l.state === "unverified") lines.push(`UNVERIFIED ${l.clip} ${l.why}`); + } + return lines.join("\n"); +} + +/** + * @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] + * @returns {Promise<number>} + */ +export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir } = {}) { + try { + const words = args.filter((a) => !a.startsWith("--")); + const flags = new Set(args.filter((a) => a.startsWith("--"))); + for (const f of flags) if (!["--json", "--fix", "--help"].includes(f)) throw new CliError(`unknown flag ${f}`); + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(LINKS_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`); + const opts = { ...(fetchImpl ? { fetchImpl } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) }; + 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); + const fixed = []; + if (flags.has("--fix")) { + for (const l of doc.links) { + if (l.state !== "dead" || !l.fix) continue; + await withEditNotes(project, () => updateClip(project.dir, l.clip, { citeUrl: l.fix })); + fixed.push({ clip: l.clip, from: l.url, to: l.fix }); + } + if (fixed.length) { + m = await readManifest(project.dir); + doc = await runLinkCheck(project.dir, m, opts); + } + } + const dead = doc.links.filter((l) => l.state === "dead").length; + if (flags.has("--json")) { + out(JSON.stringify({ ok: dead === 0, project: project.id, ...doc, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2)); + return dead ? 1 : 0; + } + for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`); + out(`${project.id} · ${linksSummary(doc)}`); + out(`recorded in out/links.json (umtool check ${project.id} reads it)`); + return dead ? 1 : 0; + } catch (e) { + err(`umtool links: ${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 @@ -61,6 +61,8 @@ import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./ import { DELIVERABLES_MODES } from "./storage.mjs"; import { createSnapshot, listSnapshots } from "./snapshots.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; +import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs"; +import { syncPatchMarkers } from "./patchMarkers.mjs"; import { DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish, } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; @@ -194,7 +196,7 @@ const WIN_EPS = 0.02; * @param {string} clipId * @param {Record<string, unknown>} patch * @param {{ token?: string | null }} [opts] - * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown> }>} + * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null, snapshot?: Record<string, unknown>, citeFollowed?: { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } } }>} */ export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { @@ -204,14 +206,14 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri // Re-read INSIDE the lock, every time. Nothing is held across requests. const raw = await readFile(manifestFile(dir), "utf8"); const manifest = JSON.parse(raw); - const { entry, before } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); + const { entry, before, citeFollowed } = patchClipEntry(manifest, clipId, patch, { edit, now, raw, dir }); // A gap cut or removed (gaps.mjs) changes what the clip IS in the cut, as a // split does: an undo point first (`umtool timeline <p> undo`, the Cut tab's Undo). const snapshot = GAP_PATCH_KEYS.some((k) => patch[k] !== undefined) ? await autoSnapshot(dir, "gaps") : null; const nextToken = await writeManifestAtomic(dir, manifest); // A moved extent may need a new bench excerpt: queued, never waited for. if (entry.start !== before.start || entry.end !== before.end) benchPrepAfterWrite(dir, [clipId]); - return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}) }; + return { entry, before, token: nextToken, ...(snapshot ? { snapshot } : {}), ...(citeFollowed ? { citeFollowed } : {}) }; }); } @@ -232,7 +234,9 @@ export const GAP_PATCH_KEYS = Object.freeze(["gaps", "gapAdd", "gapRemove"]); * `raw`: the manifest's text before the patch, when the caller has it (the * finale check compares against it); else it is taken here. `dir`: the * project's directory, where an `fx` screenshot written here must be. - * @returns {{ entry: Record<string, any>, before: { start: number, end: number } }} + * @returns {{ entry: Record<string, any>, before: { start: number, end: number }, citeFollowed: null | { cite?: { from: number, to: number }, citeUrl?: { from: string, to: string } } }} + * `citeFollowed`: the cite and/or the citeUrl's `t=` this patch moved with + * an edge (citeFollow.mjs), or null. */ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = null, raw = null, dir = null } = {}) { const original = patch.layout !== undefined ? (raw ?? JSON.stringify(manifest)) : null; @@ -250,6 +254,7 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n const before = { start: entry.start, end: entry.end }; const cutBefore = cutOf(entry); + const clockBefore = clockOf(entry); // The effects' fields as they were, for a check that refuses only what a // write ADDS: a window save, or an fx write, under an fx that already had // a problem is not blamed for it. @@ -378,6 +383,49 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n } } + // ---- the cite follows the edge (citeFollow.mjs) -------------------------- + // + // An edge move that leaves the clock (`cite`) more than a lead-in before + // what plays, or past its end, moves it to the clip's first played second; + // a citeUrl naming this recording whose `t=` is left outside moves with it. + // A patch that writes `cite` itself is the author deciding: then only the + // QR follows, and only when it agreed with the clock before. A patch that + // writes `citeUrl` keeps exactly what it wrote. + let citeFollowed = null; + const channelSlug = manifest?.provenance?.channelSlug ?? null; + const edgeMoved = ["start", "end", "cutStart", "cutEnd"].some((k) => patch[k] !== undefined); + if (patch.citeUrl === undefined) { + if (patch.cite === undefined && edgeMoved) citeFollowed = citeFollow(entry, { channelSlug }); + else if (patch.cite !== undefined) citeFollowed = qrFollowsCite(entry, clockBefore, { channelSlug }); + } else if (patch.cite === undefined && edgeMoved) { + const f = citeFollow({ ...entry, citeUrl: undefined }, { channelSlug }); + if (f?.cite) citeFollowed = { cite: f.cite }; + } + if (citeFollowed?.cite) entry.cite = citeFollowed.cite.to; + if (citeFollowed?.citeUrl) entry.citeUrl = citeFollowed.citeUrl.to; + + // ---- what the walk said that is not a verdict --------------------------- + // + // `walkNote`: an editorial note from the walk ("THIS IS GOLD", "might want + // a bit of silence") -- NOT `correction`, which says the REPORT got a fact + // wrong and is read by the next report pass. `star`: a favourite, which + // makes the clip a trailer candidate (trailerCandidates.mjs). Neither is + // rendered. Empty / false deletes the key. + if (patch.walkNote !== undefined) { + const v = String(patch.walkNote ?? "").trim(); + if (v.length > 2000) throw new Error("walkNote is at most 2000 characters"); + if (v) entry.walkNote = v; + else delete entry.walkNote; + } + if (patch.star !== undefined) { + const v = patch.star; + const on = v === true || v === "true" || v === 1 || v === "1" || v === "on"; + const off = v === false || v === "false" || v === 0 || v === "0" || v === "" || v === null || v === "off"; + if (!on && !off) throw new Error(`star must be true or false, not ${JSON.stringify(v)}`); + if (on) entry.star = true; + else delete entry.star; + } + // ---- a deliberate repeat ------------------------------------------------ // // `repeatOf`: the id of the clip this one re-plays on purpose -- a callback, @@ -665,7 +713,7 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n noteAssistEdit(entry, edit, cutBefore, at); if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant"; - return { entry, before }; + return { entry, before, citeFollowed }; } // --------------------------------------------------------------------------- @@ -1922,10 +1970,15 @@ async function structural(dir, op, token, mutate) { 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); const snapshot = await autoSnapshot(dir, op); const nextToken = await writeManifestAtomic(dir, manifest); - return { ...result, snapshot, token: nextToken }; + // The project's take patches follow a removal as the manifest's markers + // did (patchMarkers.mjs): a marker after a clip that is gone moves to the + // same boundary, so the next `umtool take --patch` is not refused. + const patches = await syncPatchMarkers(dir, timelineBefore, manifest.timeline ?? []).catch(() => []); + return { ...result, snapshot, token: nextToken, ...(patches.length ? { patches } : {}) }; }); } diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs @@ -0,0 +1,167 @@ +// A take patch's deck markers follow the cut (UI notes 2026-10-30, #6). +// +// A take made with `umtool take … --patch draft-1.patch.json` merges that file +// over the manifest (RFC 7386), and a merge patch REPLACES an array: so a +// patch that carries `render.chrome.deck.markers` carries the whole list, each +// marker `after` a clip id. Removing a clip re-anchors the MANIFEST's markers +// (manifest.mjs reanchorAfterRemove) -- and left the patch's naming a clip +// that is gone, so the next take was refused ("draft-9 was refused") until the +// patch was synced by hand, after every section change. +// +// Two halves, one rule: +// - the structural writers re-anchor the project's `*.patch.json` the way +// they re-anchor the manifest: a marker after a removed clip moves to the +// clip before it (the same boundary), or is dropped when none is left; +// - the check reports a patch whose markers name a clip that is not in the +// cut (`patch-markers-stale`, lib/projects/report.mjs) -- a hand edit, a +// patch written before this existed, a clip removed by hand. +// +// Only a patch with no `timeline` of its own: one that replaces the timeline +// names ITS clips, which the manifest knows nothing about. Only the project's +// own directory (the convention: draft-1.patch.json beside the manifest). +// +// Plain ESM: the CLI runs it under bare node. +import { readdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => isObj(e) && (e.kind ?? e.type) === "clip"; + +/** The project's take patches: `*.patch.json` beside the manifest, by name. */ +export async function patchFilesOf(dir) { + const names = await readdir(dir).catch(() => []); + return names.filter((n) => PATCH_FILE_RE.test(n)).sort(); +} + +/** A patch's deck markers, or null when it carries none (or its own timeline). */ +export function patchMarkersOf(patch) { + if (!isObj(patch) || patch.timeline !== undefined) return null; + const markers = patch?.render?.chrome?.deck?.markers; + return Array.isArray(markers) ? markers : null; +} + +/** + * The clips a structural edit took out, each with the clip a marker after it + * should now follow: the nearest clip BEFORE it (in the old order) that is + * still in the cut -- reanchorAfterRemove's "same boundary" -- or null. + * + * @param {Array<Record<string, any>>} before the timeline before the edit + * @param {Array<Record<string, any>>} after the timeline after it + * @returns {Map<string, string | null>} + */ +export function removedAnchors(before, after) { + const still = new Set((after ?? []).filter(isClip).map((e) => e.id)); + const out = new Map(); + (before ?? []).forEach((e, i) => { + if (!isClip(e) || !e.id || still.has(e.id)) return; + let anchor = null; + for (let k = i - 1; k >= 0; k -= 1) { + const p = before[k]; + if (isClip(p) && still.has(p.id)) { + anchor = p.id; + break; + } + } + out.set(e.id, anchor); + }); + return out; +} + +/** + * Re-anchor one patch's markers in place. Returns one sentence per change. + * + * @param {Record<string, any>} patch + * @param {Map<string, string | null>} anchors removedAnchors()'s answer + * @returns {string[]} + */ +export function reanchorPatch(patch, anchors) { + const markers = patchMarkersOf(patch); + if (!markers || !anchors.size) return []; + const notes = []; + const next = markers.filter((mk, k) => { + const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; + if (!anchors.has(after)) return true; + const to = anchors.get(after); + const name = `deck marker ${k}${mk.label ? ` ("${mk.label}")` : ""}`; + if (to) { + mk.after = to; + notes.push(`${name} moved from after ${after} to after ${to} (the same boundary)`); + return true; + } + notes.push(`${name} dropped: no clip before ${after}`); + return false; + }); + if (notes.length) patch.render.chrome.deck.markers = next; + return notes; +} + +/** + * After a structural write: re-anchor every take patch in the project whose + * markers named a clip the write took out. Each changed file is rewritten + * whole (2-space JSON and a newline, tmp + rename). Never fatal: a patch that + * does not read is reported, and the manifest's write stands. + * + * @param {string} dir + * @param {Array<Record<string, any>>} before + * @param {Array<Record<string, any>>} after + * @returns {Promise<Array<{ file: string, notes: string[], error?: string }>>} + */ +export async function syncPatchMarkers(dir, before, after) { + const anchors = removedAnchors(before, after); + if (!anchors.size) return []; + const out = []; + for (const name of await patchFilesOf(dir)) { + const file = path.join(dir, name); + let patch; + try { + patch = JSON.parse(await readFile(file, "utf8")); + } catch (e) { + out.push({ file: name, notes: [], error: `does not read: ${e instanceof Error ? e.message : String(e)}` }); + continue; + } + const notes = reanchorPatch(patch, anchors); + if (!notes.length) continue; + try { + const tmp = `${file}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(patch, null, 2)}\n`); + await rename(tmp, file); + out.push({ file: name, notes }); + } catch (e) { + out.push({ file: name, notes, error: `not written: ${e instanceof Error ? e.message : String(e)}` }); + } + } + return out; +} + +/** + * The check's half: every take patch marker after a clip that is not in the + * cut, and every patch that does not read. + * + * @param {string} dir + * @param {Record<string, any>} manifest + * @returns {Promise<Array<{ file: string, markers: Array<{ index: number, label: string | null, after: string }>, error?: string }>>} + */ +export async function stalePatchMarkers(dir, manifest) { + const ids = new Set((manifest?.timeline ?? []).filter(isClip).map((e) => e.id)); + const out = []; + for (const name of await patchFilesOf(dir)) { + let patch; + try { + patch = JSON.parse(await readFile(path.join(dir, name), "utf8")); + } catch (e) { + out.push({ file: name, markers: [], error: e instanceof Error ? e.message : String(e) }); + continue; + } + const markers = patchMarkersOf(patch); + if (!markers) continue; + const gone = []; + markers.forEach((mk, index) => { + const after = isObj(mk) ? String(mk.after ?? "").trim() : ""; + if (after && !ids.has(after)) gone.push({ index, label: typeof mk.label === "string" ? mk.label : null, after }); + }); + if (gone.length) out.push({ file: name, markers: gone }); + } + return out; +} diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -469,6 +469,11 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => } out(summaryOf(verb, result, attribution)); for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + // The take patches beside the manifest follow the same removal (patchMarkers.mjs). + for (const p of result.patches ?? []) { + for (const line of p.notes ?? []) out(` ${p.file}: ${line}`); + if (p.error) out(` ${p.file}: ${p.error}`); + } if (result.record) out(` on record: ${REMOVED_FILE} (${result.record.reason}${result.record.correction ? `: ${result.record.correction}` : ""}${result.record.note ? `: ${result.record.note}` : ""})`); if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`); else if (result.snapshot?.error) out(` NO undo point: ${result.snapshot.error}`); diff --git a/umtool/lib/report/trailerCandidates.mjs b/umtool/lib/report/trailerCandidates.mjs @@ -0,0 +1,39 @@ +// ★ on the walk makes a clip a trailer candidate (UI notes 2026-10-30, #7). +// +// A favourite is not a verdict and not a correction: it is the walk saying +// "this one is gold", which is exactly the list a trailer is cut from. The +// candidates are the starred clips, in the cut's order, each as a trailer +// beat over what the clip plays (report-to-video/trailer.mjs parseBeats: +// `{ id, start, end }` in source seconds) -- so the list is a `--beats-json` +// as it stands, and whatever lists or suggests trailer beats starts from it. +// +// Plain ESM: the CLI runs it under bare node. +import { playedSpan } from "./citeFollow.mjs"; + +/** + * The cut's starred clips as trailer beats, in timeline order. A clip that + * would not play (incorrect, rejected) is left out. + * + * @param {Record<string, any>} m + * @returns {Array<{ id: string, start: number, end: number, label?: string, quote?: string, walkNote?: string }>} + */ +export function trailerCandidates(m) { + const out = []; + for (const e of m?.timeline ?? []) { + if (e?.type !== "clip" || e.star !== true) continue; + if (e.verdict === "incorrect" || e.verdict === "rejected") continue; + const { from, to } = playedSpan(e); + if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) continue; + out.push({ + id: String(e.id), + start: from, + end: to, + ...(typeof e.quote === "string" && e.quote.trim() ? { quote: e.quote.trim() } : {}), + ...(typeof e.walkNote === "string" && e.walkNote.trim() ? { walkNote: e.walkNote.trim() } : {}), + }); + } + return out; +} + +/** The candidates as `--beats-json` takes them: `{ id, start, end }` only. */ +export const candidateBeats = (m) => trailerCandidates(m).map(({ id, start, end }) => ({ id, start, end })); diff --git a/umtool/lib/report/trailerCli.mjs b/umtool/lib/report/trailerCli.mjs @@ -4,11 +4,14 @@ // // umtool trailer <project> --take <t> (--beats FILE | --beats-json JSON) // [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json] +// umtool trailer <project> --candidates [--json] the walk's ★ clips as beats import { readFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { kindMakesTakes } from "../projects/kinds.mjs"; import { takesDirOf } from "./takes.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { candidateBeats, trailerCandidates } from "./trailerCandidates.mjs"; import { TRAILER_ESTIMATE_MB, TRAILER_XFADE_DEFAULT, @@ -30,6 +33,10 @@ export const TRAILER_USAGE = [ "encoded with the take's render settings, in the heavy slot. Writes takes/<t>/out/<slug>.trailer.mp4", "(--out NAME: that name there; a path: exactly there) and <name>.trailer.json beside it, what was cut.", "--dry-run prints the mapping and writes nothing.", + "", + "umtool trailer <project> --candidates [--json]: the clips starred (★) on the walk, in the cut's order, as beats", + "over what each plays -- with --json exactly what --beats-json takes:", + " umtool trailer <p> --take <t> --beats-json \"$(umtool trailer <p> --candidates --json)\"", ].join("\n"); class CliError extends Error {} @@ -45,7 +52,7 @@ function parse(args) { if (valued.has(a)) { if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); flags[a] = args[++i]; - } else if (["--intro", "--json", "--dry-run", "--help"].includes(a)) flags[a] = ""; + } else if (["--intro", "--json", "--dry-run", "--help", "--candidates"].includes(a)) flags[a] = ""; else throw new CliError(`unknown flag ${a}`); } else positional.push(a); } @@ -110,6 +117,24 @@ export async function trailerCommand(args, { reportsRoot = REPORTS_ROOT, log = c if (r.ambiguous) throw new CliError(`"${p.positional[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${p.positional[0]}"`); if (!kindMakesTakes(r.project.kind)) throw new CliError(`${r.project.id} is a ${r.project.kind}, not a report video`); + if (p.has("--candidates")) { + const m = await readManifest(r.project.dir); + if (!m) throw new CliError(`${r.project.id} has no video.manifest.json`); + if (p.has("--json")) { + log(JSON.stringify(candidateBeats(m))); + return 0; + } + const list = trailerCandidates(m); + if (!list.length) { + log(`${r.project.id}: no clip is starred — ★ one on the walk (s), or \`umtool window <p> <clip> --star\``); + return 0; + } + log(`${r.project.id}: ${list.length} trailer candidate${list.length === 1 ? "" : "s"} (★ on the walk), ${list.reduce((n, b) => n + b.end - b.start, 0).toFixed(1)} s in all`); + for (const b of list) { + log(` ${b.id.padEnd(6)} ${b.start.toFixed(2)}–${b.end.toFixed(2)} (${(b.end - b.start).toFixed(1)} s)${b.quote ? ` “${b.quote.slice(0, 70)}${b.quote.length > 70 ? "…" : ""}”` : ""}${b.walkNote ? ` — ${b.walkNote}` : ""}`); + } + return 0; + } const take = p.flags["--take"]; if (!take) throw new CliError("--take <t>: the finished take to cut the trailer from"); if (!/^[a-z0-9][a-z0-9-]*$/.test(take)) throw new CliError(`--take ${take}: a take id`);