Archilyzer · Source

archilyzer

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

commit 1b258d99ffc1313732d7caede84773fd956b063a
parent 31af39e1d4622b31e619f9ea0cb99e2dbe5ff8b2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 23:20:09 -0500

Merge lane/agent-to-ui: inspector panels for this week's hand edits -- provenance, a teaser or closing card, ledger rows, a post's excerpt/media/recording, the Rumble embed-id fix, a still at second N, the project's title (redesign L6)

Each is a self-contained inspector component (umtool/components/projects/inspector/, {project, block?}) mounted in the
Cut tab now, for the workspace (L7) to mount unchanged; each writes the draft under the manifest lock with one undo
point, has a CLI twin with its registry row (provenance, timeline teaser-insert, ledger, posts set-item, links
--embed-ids, still, title), and its page-write route refuses other sites. A post's attachment switched off keeps its
crop, trim and sound (mediaOff) and comes back as it was. Agents did each of these by hand on 2-8 Nov.

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

Diffstat:
Aumtool/app/api/report/embed-ids/route.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/ledger/route.ts | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/post-item/inspector/route.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/post-narration/route.ts | 4+++-
Aumtool/app/api/report/provenance/route.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/still-frame/route.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/teaser/route.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/title/route.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 4++++
Aumtool/components/projects/inspector/LedgerInspector.tsx | 253+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/LinksInspector.tsx | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/PostItemInspector.tsx | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/ProvenanceInspector.tsx | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/StillInspector.tsx | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/TeaserInspector.tsx | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/TitleInspector.tsx | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/shared.tsx | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 34++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 11+++++++++++
Mumtool/docs/cli.md | 13++++++++++++-
Mumtool/docs/knobs.md | 18++++++++++++++++++
Aumtool/e2e/fixtures/inspector-fixture.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 5+++++
Aumtool/e2e/inspector-ledger.spec.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-post-item.spec.ts | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-provenance.spec.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-rumble-cite.spec.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-still.spec.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-teaser-insert.spec.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/inspector-title.spec.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/groups.mjs | 40++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/cli/verbs.mjs | 23++++++++++++++++++++++-
Aumtool/lib/report/embedIds.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/excerptPick.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/excerptPick.test.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/inspectorCli.mjs | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/inspectorEdits.mjs | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/inspectorEdits.test.mjs | 279+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/linksCli.mjs | 7+++++++
Mumtool/lib/report/manifest.mjs | 51+++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postsCli.mjs | 9+++++++++
Aumtool/lib/report/stillGrab.mjs | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/timelineCli.mjs | 10+++++++++-
Mumtool/report-to-video/post-item.mjs | 10++++++++++
44 files changed, 3939 insertions(+), 8 deletions(-)

diff --git a/umtool/app/api/report/embed-ids/route.ts b/umtool/app/api/report/embed-ids/route.ts @@ -0,0 +1,61 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken } from "@/lib/report/manifest.mjs"; +import { embedIdFixes, embedIdRows } from "@/lib/report/embedIds.mjs"; +import { setSiteVideos } from "@/lib/report/inspectorEdits.mjs"; +import { readLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// THE PUBLISHED EMBED ID (umtool redesign L6, the Links panel's "Use the published embed id"; 4 and 8 Nov: a +// Rumble clip's QR named the URL-slug folder the corpus keeps it under, and the archive serves the EMBED id): +// every clip of the cut citing such a folder, its embed id read from the folder's metadata.info.json through L1's +// one mapping (shareLine.mjs siteVideoFor), with what the last link check (out/links.json) said of its QR. The +// fix writes `siteVideo` (and a citeUrl that named the folder) -- one write, one undo point. No network: the +// check is `umtool links <p>`'s; `umtool links <p> --embed-ids` is this route's twin. +// +// GET ?project=<id> { rows: [{ clip, channel, video, siteVideo, url, fixedUrl, citeUrl, state }], checkedAt, token } +// POST { project, token, clips?: [id…] } those rows fixed (no clips: every row) +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const doc = await readLinkCheck(r.project.dir); + const rows = await embedIdRows(r.project.dir, r.manifest as Record<string, unknown>, { doc }); + return Response.json({ rows, checkedAt: doc?.checkedAt ?? null, token: await manifestToken(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/embed-ids"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if (typeof body.token !== "string" || !body.token) return Response.json({ error: "token is required: GET the route first (a write over a newer draft is refused, never silent)" }, { status: 400 }); + const clips = Array.isArray(body.clips) ? body.clips.map(String) : null; + try { + const { result, editNotes } = await withEditNotes(r.project, async () => { + // The rows as the manifest is NOW (read inside the request, the writer checks the token). + const m = (await readManifest(r.project.dir)) as Record<string, unknown>; + const rows = await embedIdRows(r.project.dir, m, { doc: await readLinkCheck(r.project.dir) }); + return setSiteVideos(r.project.dir, embedIdFixes(rows, clips), { token: body.token as string }); + }); + return Response.json({ ok: true, fixed: result.fixed, token: result.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/ledger/route.ts b/umtool/app/api/report/ledger/route.ts @@ -0,0 +1,110 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, addLedgerRow, manifestToken, removeLedgerRow, updateLedgerRow } from "@/lib/report/manifest.mjs"; +import { isMeasureLedger, parseLedgerValue } from "@/lib/report/ledgerRows.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { EVENTS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureSchema } from "umtool-report-to-video/ledger-totals"; + +export const dynamic = "force-dynamic"; + +// A MEASURE LEDGER's ROWS (umtool redesign L6, the inspector's Ledger panel; weight video rev 9): the rows the +// instruments draw from (`manifest.ledger`, read by the build through ledgerSchema), added, changed and removed +// through the manifest's own writers -- addLedgerRow / updateLedgerRow / removeLedgerRow, each row checked by +// ledgerRows.mjs ledgerRowOf against the schema (the CLI's checks, word for word), one undo point each. +// `umtool ledger <p> add|set|rm` is the same writer. +// +// GET ?project=<id>[&entry=<timeline id>] the schema's vocabulary (tracks, forms, regimes, declared fields, +// events, the six adjudication words), the rows (those pinned to the +// entry when one is named), the token +// POST { project, token, op: "add", row } a new row (its id in it) +// POST { project, token, op: "set", id, patch, unset?: [key…] } a row changed +// POST { project, token, op: "rm", id } a row removed (refused while anything names it) +// A string value is read as the CLI reads a flag's text (ledgerRows.mjs parseLedgerValue: a number key a +// number, true/false, "a|b" a list for flags, "null" clears). +const noStore = { "cache-control": "no-store" }; +type Row = Record<string, unknown> & { id?: string; entryId?: string }; + +const parsed = (patch: unknown) => { + const out: Record<string, unknown> = {}; + if (!patch || typeof patch !== "object" || Array.isArray(patch)) return out; + for (const [k, v] of Object.entries(patch as Record<string, unknown>)) out[k] = typeof v === "string" ? parseLedgerValue(k, v) : v; + return out; +}; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { ledgerSchema?: Record<string, unknown>; ledger?: Row[] }; + const rows = Array.isArray(m.ledger) ? m.ledger : []; + const entry = url.searchParams.get("entry"); + let schema = null; + let schemaError = null; + if (isMeasureLedger(m)) { + try { + const s = measureSchema(m.ledgerSchema); + schema = { + unit: (m.ledgerSchema?.unit as string | undefined) ?? "", + tracks: s.tracks.map((t: { key: string; label: string; role: string; regimes: string[] | null }) => ({ key: t.key, label: t.label, role: t.role, regimes: t.regimes })), + forms: s.forms, + regimes: s.regimes.map((x: { key: string; label: string }) => ({ key: x.key, label: x.label })), + fields: s.fields.map((f: { key: string; label?: string; kind?: string; options?: unknown }) => ({ key: f.key, label: f.label ?? f.key, kind: f.kind ?? "text", options: Array.isArray(f.options) ? f.options : null })), + events: EVENTS, promiseForms: PROMISE_FORMS, outcomes: PROMISE_OUTCOMES, scopeConfidence: SCOPE_CONFIDENCE, valueKinds: VALUE_KINDS, + }; + } catch (e) { + schemaError = e instanceof Error ? e.message : String(e); + } + } + return Response.json( + { + kind: isMeasureLedger(m) ? "measure" : rows.length || m.ledgerSchema ? "headcount" : null, + schema, + schemaError, + total: rows.length, + rows: entry ? rows.filter((x) => x?.entryId === entry) : rows, + entries: ((r.manifest as { timeline?: { id?: string; type?: string }[] }).timeline ?? []).map((e) => String(e?.id ?? "")).filter(Boolean), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/ledger"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const token = typeof body.token === "string" ? body.token : null; + const id = String(body.id ?? ""); + try { + if (body.op === "add") { + const row = parsed(body.row); + const { result, editNotes } = await withEditNotes(r.project, () => addLedgerRow(r.project.dir, row, { token })); + return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "set") { + const unset = Array.isArray(body.unset) ? body.unset.map(String) : []; + const { result, editNotes } = await withEditNotes(r.project, () => updateLedgerRow(r.project.dir, id, parsed(body.patch), { token, unset })); + return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "rm") { + // A removal is checked against the draft this panel read: never a blind delete. + if (!token) return Response.json({ error: "token is required to remove a row: GET the route first" }, { status: 400 }); + const { result, editNotes } = await withEditNotes(r.project, () => removeLedgerRow(r.project.dir, id, { token })); + return Response.json({ ok: true, removed: result.row?.id ?? id, token: result.token, editNotes }, { headers: noStore }); + } + return Response.json({ error: "op is add, set or rm" }, { status: 400 }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/post-item/inspector/route.ts b/umtool/app/api/report/post-item/inspector/route.ts @@ -0,0 +1,121 @@ +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import { cardText, excerptErrors, excerptRanges, excerptSpansOf } from "umtool-report-to-video/post-item"; +import { pickedTake } from "umtool-report-to-video/post-narration"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; +import { attachmentOf } from "@/lib/report/postsCli.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// A POST ITEM, AS THE INSPECTOR EDITS IT (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item +// excerpt=…` and `posts narrate --recording` by hand): the card's words as the excerpt reads them (cardText), +// the excerpt's spans and where they stand, the item's attachments and the post's files it does not carry, and +// its narration's takes. Its writes are the post bench's: POST /api/report/post-item {op: "set"} (the excerpt, +// an attachment off or its sound), the multipart POST /api/report/post-narration (a recording), and here: +// +// GET ?project=<id>&id=<item> the view above, and the token +// POST { project, token, id, op: "media-on", file: "posts-media/…" } a file of the post the item never carried put +// on it, measured as `posts set-item media.add=` measures one (refused +// when the item carries it, shown or switched off) +// POST { project, token, id, op: "media-off", i } attachment i switched OFF, kept whole in `mediaOff` (its crop, +// blur, trim, sound kept; nothing draws it) -- `set-item media.<i>.shown=off` +// POST { project, token, id, op: "media-show", j } the attachment switched off at j shown again, as it was +// -- `set-item media-off.<j>.shown=on` +const noStore = { "cache-control": "no-store" }; +const MEDIA_RE = /\.(png|jpe?g|webp|gif|mp4|m4v|mov|webm)$/i; +type Entry = Record<string, unknown> & { id: string; type?: string; post?: string; media?: Array<Record<string, unknown>>; mediaOff?: Array<Record<string, unknown>>; narration?: Record<string, unknown> }; + +/** The post's own files in the project (posts-media/<channel>/<postId>/), pictures and videos, its screenshots left out. */ +async function postFiles(dir: string, e: Entry): Promise<string[]> { + const roots = new Set<string>(); + if (typeof e.post === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(e.post)) roots.add(`posts-media/${e.post}`); + for (const m of [...(e.media ?? []), ...(e.mediaOff ?? [])]) if (typeof m?.src === "string" && m.src.startsWith("posts-media/")) roots.add(path.posix.dirname(m.src)); + const out: string[] = []; + for (const rel of roots) { + if (rel.split("/").includes("..")) continue; + const names = await readdir(path.join(dir, ...rel.split("/"))).catch(() => [] as string[]); + for (const n of names.sort()) { + if (!MEDIA_RE.test(n) || /^shot/i.test(n) || n.startsWith(".")) continue; + const st = await stat(path.join(dir, ...rel.split("/"), n)).catch(() => null); + if (st?.isFile()) out.push(`${rel}/${n}`); + } + } + return out; +} + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; + const id = q.get("id") ?? ""; + const e = tl.find((x) => x?.type === "post" && x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const text = cardText(e) as string; + const spans = excerptSpansOf(e) as string[] | null; + const media = (e.media ?? []).map((m, i) => ({ + i, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null, + mute: m?.mute === true, seconds: typeof m?.seconds === "number" ? m.seconds : null, audio: m?.audio === true, + })); + const off = (e.mediaOff ?? []).map((m, j) => ({ j, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null })); + const carried = new Set([...media.map((m) => m.src), ...off.map((m) => m.src)]); + const takes = Array.isArray(e.narration?.takes) ? (e.narration.takes as Array<Record<string, unknown>>) : []; + const picked = pickedTake(e) as (Record<string, unknown> & { file: string; index: number }) | null; + return Response.json( + { + id: e.id, post: e.post ?? null, author: e.author ?? null, handle: e.handle ?? null, text, + excerpt: spans, ranges: spans ? excerptRanges(text, spans) : null, excerptErrors: excerptErrors(e), + media, off, files: (await postFiles(r.project.dir, e)).filter((f) => !carried.has(f)), + narration: { + takes: takes.map((t, i) => ({ i, file: String(t.file ?? ""), engine: typeof t.engine === "string" ? t.engine : null, voice: typeof t.voice === "string" ? t.voice : null, seconds: typeof t.seconds === "number" ? t.seconds : null })), + picked: picked ? picked.index : null, + off: e.narration?.off === true, + }, + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-item/inspector"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if (!["media-on", "media-off", "media-show"].includes(String(body.op))) return Response.json({ error: "op is media-on, media-off or media-show" }, { status: 400 }); + const id = String(body.id ?? ""); + const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; + const e = tl.find((x) => x?.type === "post" && x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const token = typeof body.token === "string" ? body.token : null; + try { + let patch: Record<string, unknown>; + if (body.op === "media-on") { + const file = String(body.file ?? ""); + // Only one of the post's own files (the list GET gives): never a path from elsewhere in the project. + if (!(await postFiles(r.project.dir, e)).includes(file)) return Response.json({ error: `${file} is not one of ${id}'s post files` }, { status: 400 }); + // A file the item carries already -- shown, or switched off with its knobs -- is not added twice. + if ([...(e.media ?? []), ...(e.mediaOff ?? [])].some((m) => m?.src === file)) return Response.json({ error: `${id} carries ${file} already (switched off: show it again)` }, { status: 400 }); + patch = { mediaAdd: [await attachmentOf(r.project.dir, file)] }; + } else if (body.op === "media-off") patch = { mediaHide: [Number(body.i)] }; + else patch = { mediaShow: [Number(body.j)] }; + const { result, editNotes } = await withEditNotes(r.project, () => updatePostItem(r.project.dir, id, patch, { token })); + return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } catch (e2) { + if (e2 instanceof StaleToken) return Response.json({ error: e2.message, stale: true }, { status: 409 }); + if (e2 instanceof StructureRefused) return Response.json({ error: e2.message, errors: e2.errors }, { status: 400 }); + return Response.json({ error: e2 instanceof Error ? e2.message : String(e2) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -354,7 +354,9 @@ async function record(request: Request) { const parts = []; for (const [k, b] of blobs.entries()) { if (b.size > 200 * 1024 * 1024) return Response.json({ error: "a part is larger than 200 MB" }, { status: 413 }); - const f = path.join(up, `p${k + 1}.${/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm"}`); + // A file chosen from disk (the inspector's "Use my recording") keeps its own extension; a browser recording its type's. + const own = /\.(wav|mp3|m4a|aac|ogg|opus|flac|webm|mp4|mov)$/i.exec(typeof b.name === "string" ? b.name : "")?.[1]?.toLowerCase(); + const f = path.join(up, `p${k + 1}.${own ?? (/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm")}`); await writeFile(f, new Uint8Array(await b.arrayBuffer())); parts.push({ file: f, text: texts[k] ?? "", para: Number.isInteger(paras[k]) ? paras[k] : k }); } diff --git a/umtool/app/api/report/provenance/route.ts b/umtool/app/api/report/provenance/route.ts @@ -0,0 +1,71 @@ +import { readdir } from "node:fs/promises"; +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { provenanceView, updateProvenance } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; +import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs"; +import { CHANNELS_DIR, SITES_DIR } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT'S PROVENANCE (umtool redesign L6, the inspector's Provenance panel; `umtool provenance` is the +// same writer): provenance.siteOrigin, channelSlug and channel -- the keys agents set by hand this week (a +// `umtool new` with no --from leaves channelSlug empty, and `check` blocks on it). The link policy beside them +// is /api/report/link-policy's. +// +// GET ?project=<id> the three keys, the link policy, the cut's channels (with their clip counts) and the +// corpus's, the sites (SITES_DIR, each with a siteUrl), the token +// PUT { project, token, patch: { siteOrigin?, channelSlug?, channel? } } set them ("" or null removes one) +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { provenance?: Record<string, unknown>; timeline?: { type?: string; channel?: string }[] }; + const counts = new Map<string, number>(); + for (const e of m.timeline ?? []) if (e?.type === "clip" && typeof e.channel === "string" && e.channel) counts.set(e.channel, (counts.get(e.channel) ?? 0) + 1); + const corpus = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR, { withFileTypes: true }).then( + (d) => d.filter((x) => x.isDirectory() && !x.name.startsWith(".")).map((x) => x.name).sort().slice(0, 4000), + () => [] as string[], + ); + return Response.json( + { + provenance: provenanceView(m), + linkPolicy: m.provenance?.linkPolicy ?? null, + channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)), + corpusChannels: corpus, + sites: [...sitesByOrigin(SITES_DIR)].map(([origin, s]) => ({ origin, siteId: s.siteId, title: s.title })), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/provenance"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const { result, editNotes } = await withEditNotes(r.project, () => + updateProvenance(r.project.dir, (body.patch ?? {}) as Record<string, unknown>, { token: typeof body.token === "string" ? body.token : null }), + ); + invalidateProjects(); + return Response.json({ ok: true, ...result, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/still-frame/route.ts b/umtool/app/api/report/still-frame/route.ts @@ -0,0 +1,58 @@ +import { readFile, stat } from "node:fs/promises"; +import { resolveClip, resolveReport } from "@/lib/report/serve.mjs"; +import { StillRefused, grabStill, listShots, shotFileOf } from "@/lib/report/stillGrab.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// A STILL AT SECOND N (umtool redesign L6: Play's Still button; `umtool still` is the twin): one frame of the +// clip on screen at the playhead's SOURCE second, grabbed from its fetched window (lib/report/stillGrab.mjs: a +// single `ffmpeg -ss -frames:v 1`, not heavy work) into the project's shots/ beside its other shots -- where a +// clip's fx.zoom / fx.receipts read pictures from. Nothing is fetched, and nothing in the cut is written. +// +// GET ?project=<id> { shots: [{ rel, name, bytes, mtime, still: { clip, at } | null }] } +// GET ?project=<id>&file=shots/<name> the picture +// POST { project, clip, at, take? } grab it -> { rel, clip, video, at, bytes } +const noStore = { "cache-control": "no-store" }; +const TYPES: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const file = url.searchParams.get("file"); + if (file) { + const abs = shotFileOf(r.project.dir, file); + if (!abs) return new Response("not a picture in shots/", { status: 404 }); + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) return new Response("gone", { status: 404 }); + const ext = abs.slice(abs.lastIndexOf(".")).toLowerCase(); + return new Response(new Uint8Array(await readFile(abs)), { headers: { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": "no-cache" } }); + } + return Response.json({ shots: await listShots(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/still-frame"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const take = typeof body.take === "string" && body.take ? body.take : null; + const r = await resolveClip(String(body.project ?? ""), String(body.clip ?? ""), { take }); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const done = await grabStill(r.project, r.manifest, r.clip.id, Number(body.at)); + const { file: _abs, ...rest } = done; + return Response.json({ ok: true, ...rest }, { headers: noStore }); + } catch (e) { + if (e instanceof StillRefused) return Response.json({ error: e.message }, { status: e.status }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } +} diff --git a/umtool/app/api/report/teaser/route.ts b/umtool/app/api/report/teaser/route.ts @@ -0,0 +1,73 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updateTeaser } from "@/lib/report/manifest.mjs"; +import { insertTeaser, teaserLimits, teaserLineOf } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// A TEASER OR CLOSING CARD (umtool redesign L6, the inspector's Insert a card): a `type: "teaser"` entry -- its +// lines (the first its title; each with a break and a hold), its beat -- inserted at the start, the end, or +// beside an entry, or an existing one's lines and beat changed. Checked by the build's validateTeaser; one write, +// one undo point each. `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins. +// +// GET ?project=<id> the cut's entries (id, type, a label) for the position, +// its teasers as written, the limits, the token +// POST { project, token, op: "insert", spec: { id?, lines, beat? }, position: "start" | "end" | { after } | { before } } +// POST { project, token, op: "set", id, patch: { lines?, beat? } } +const noStore = { "cache-control": "no-store" }; +type Entry = { id?: string; type?: string; heading?: string; title?: string; label?: string; lines?: unknown[]; beat?: number; video?: string }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const tl = (Array.isArray((r.manifest as { timeline?: unknown }).timeline) ? (r.manifest as { timeline: Entry[] }).timeline : []) as Entry[]; + return Response.json( + { + entries: tl.map((e, at) => ({ id: String(e?.id ?? ""), type: String(e?.type ?? "?"), at, label: e?.heading ?? e?.title ?? e?.label ?? e?.video ?? null })), + teasers: tl.flatMap((e, at) => (e?.type === "teaser" ? [{ id: String(e.id), at, lines: e.lines ?? [], beat: typeof e.beat === "number" ? e.beat : null }] : [])), + limits: teaserLimits(), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/teaser"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if (typeof body.token !== "string" || !body.token) return Response.json({ error: "token is required: GET the route first (a write over a newer draft is refused, never silent)" }, { status: 400 }); + const token = body.token as string; + try { + if (body.op === "insert") { + const { result, editNotes } = await withEditNotes(r.project, () => insertTeaser(r.project.dir, (body.spec ?? {}) as Record<string, unknown>, body.position ?? "end", { token })); + invalidateProjects(); + return Response.json({ ok: true, id: result.id, at: result.at, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "set") { + const patch = { ...((body.patch ?? {}) as Record<string, unknown>) }; + // The lines as the insert writes them: a line that is only its words is a string, empty keys left out. + if (Array.isArray(patch.lines)) patch.lines = patch.lines.map((l: unknown) => teaserLineOf(l)); + const { result, editNotes } = await withEditNotes(r.project, () => updateTeaser(r.project.dir, String(body.id ?? ""), patch, { token })); + return Response.json({ ok: true, id: result.id, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + return Response.json({ error: "op is insert or set" }, { status: 400 }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/title/route.ts b/umtool/app/api/report/title/route.ts @@ -0,0 +1,58 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { SUBTITLE_MAX, TITLE_MAX, updateTitle } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7; 9 Nov: four news projects' were set with jq): +// the manifest's `title` and `subtitle`. `umtool title <p> "<title>" [--subtitle "…"]` is the same writer. +// +// GET ?project=<id> { title, subtitle, limits, token } +// PUT { project, token, title?, subtitle? } set them (subtitle "" or null removes it); one undo point +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { title?: unknown; subtitle?: unknown }; + return Response.json( + { + title: typeof m.title === "string" ? m.title : null, + subtitle: typeof m.subtitle === "string" ? m.subtitle : null, + limits: { title: TITLE_MAX, subtitle: SUBTITLE_MAX }, + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/title"); + if (refused) return refused; + const cross = crossSiteRefusal(request.headers); + if (cross) return Response.json({ error: cross }, { status: 403 }); + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const patch: Record<string, unknown> = {}; + if ("title" in body) patch.title = body.title; + if ("subtitle" in body) patch.subtitle = body.subtitle; + try { + const { result, editNotes } = await withEditNotes(r.project, () => updateTitle(r.project.dir, patch, { token: typeof body.token === "string" ? body.token : null })); + invalidateProjects(); + return Response.json({ ok: true, ...result, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -931,6 +931,10 @@ const COMMANDS = { vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))), // Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs. clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))), + // The inspector's twins (umtool redesign L6): provenance, title, a still at second N -- lib/report/inspectorCli.mjs. + provenance: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).provenanceCommand(argv.slice(argv.indexOf("provenance") + 1))), + title: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).titleCommand(argv.slice(argv.indexOf("title") + 1))), + still: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).stillCommand(argv.slice(argv.indexOf("still") + 1))), // A clip's share line (lane output-modes): lib/report/shareLineCli.mjs. share: async () => process.exit(await (await import("../lib/report/shareLineCli.mjs")).shareCommand(argv.slice(argv.indexOf("share") + 1))), // Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs. diff --git a/umtool/components/projects/inspector/LedgerInspector.tsx b/umtool/components/projects/inspector/LedgerInspector.tsx @@ -0,0 +1,253 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// A MEASURE LEDGER's ROWS (umtool redesign L6, item 3; agents added and fixed them with jq this week): the rows the +// instruments draw from, each with its date, scope (a track), form, value (a number, or a regime and its event on +// a regime track), basis (the phrase that settles the scope) and source (src, channel/video, cite) -- added, +// changed or removed through POST /api/report/ledger, the ledger CLI's checks word for word, one undo point each. +// `umtool ledger <p> add|set|rm` is the twin. With `block` (a timeline entry's id): the rows pinned to it, and a +// new row pinned to it. + +type Track = { key: string; label: string; role: string; regimes: string[] | null }; +type Schema = { + unit: string; tracks: Track[]; forms: string[]; regimes: { key: string; label: string }[]; + fields: { key: string; label: string; kind: string; options: unknown[] | null }[]; + events: string[]; promiseForms: string[]; outcomes: string[]; scopeConfidence: string[]; valueKinds: string[]; +}; +type Row = Record<string, unknown> & { id: string }; +type View = { kind: "measure" | "headcount" | null; schema: Schema | null; schemaError: string | null; total: number; rows: Row[]; entries: string[]; token: string | null }; + +/** The keys the form shows, in order: what a row needs, then its source. */ +const BASE_KEYS = ["id", "date", "scope", "population", "value", "event", "scopeBasis", "label", "quote", "src", "channel", "video", "cite", "entryId"] as const; +const REQUIRED = new Set(["id", "date", "scope", "population", "scopeBasis"]); +const PAGE = 40; + +const textOf = (v: unknown) => (v === undefined || v === null ? "" : Array.isArray(v) ? v.join("|") : String(v)); + +export default function LedgerInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [editing, setEditing] = useState<string | null>(null); // a row id, or "" for a new row + const [form, setForm] = useState<Record<string, string>>({}); + const [filter, setFilter] = useState(""); + const [shown, setShown] = useState(PAGE); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async () => { + const q = new URLSearchParams({ project, ...(block ? { entry: block } : {}) }); + const { ok, j } = await call<View>(`/api/report/ledger?${q.toString()}`); + if (ok) setView(j); + return ok ? j : null; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, load); + const declared = view?.schema?.fields ?? []; + const keys = useMemo(() => [...BASE_KEYS, ...declared.map((f) => f.key)], [declared]); + const rows = useMemo(() => { + const all = [...(view?.rows ?? [])].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id)); + const f = filter.trim().toLowerCase(); + return f ? all.filter((r) => [r.id, r.date, r.scope, r.population, r.display, r.label, r.quote].some((v) => String(v ?? "").toLowerCase().includes(f))) : all; + }, [view, filter]); + if (!view || !view.kind) return null; + if (view.kind !== "measure" || !view.schema) { + return ( + <InspectorFrame kind="ledger" title={`Ledger — ${view.total} rows`}> + <p className="m-0 text-muted">{view.schemaError ?? "This ledger is not a measure ledger (ledgerSchema.kind \"measure\"): its rows are written by its own tools."}</p> + </InspectorFrame> + ); + } + const s = view.schema; + const track = s.tracks.find((t) => t.key === form.scope) ?? null; + const regimeTrack = track?.role === "regime"; + + const open = (id: string | null) => { + setSaid(null); + if (id === null) { + setEditing(null); + return; + } + if (id === "") { + const today = new Date().toISOString().slice(0, 10); + setForm({ id: "", date: today, scope: s.tracks[0]?.key ?? "", population: s.forms[0] ?? "", ...(block ? { entryId: block } : {}) }); + } else { + const r = view.rows.find((x) => x.id === id); + setForm(Object.fromEntries(keys.map((k) => [k, textOf(r?.[k])]))); + } + setEditing(id); + }; + const set = (k: string, v: string) => { + setSaid(null); + setForm((f) => ({ ...f, [k]: v })); + }; + const save = async () => { + setBusy(true); + setSaid(null); + try { + let body: Record<string, unknown>; + if (editing === "") { + const row = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== "").map(([k, v]) => [k, v.trim()])); + body = { project, token: view.token, op: "add", row }; + } else { + const was = view.rows.find((x) => x.id === editing); + const patch: Record<string, string> = {}; + const unset: string[] = []; + for (const k of keys) { + if (k === "id") continue; + const now = (form[k] ?? "").trim(); + if (now === textOf(was?.[k])) continue; + if (now === "" && !REQUIRED.has(k)) unset.push(k); + else patch[k] = now; + } + // A new value (or form, or event) is drawn by its own words again: the display is recomputed from it. + if (["value", "population", "event", "scope"].some((k) => k in patch || unset.includes(k))) unset.push("display"); + if (!Object.keys(patch).length && !unset.length) { + setSaid({ ok: true, text: "Nothing changed." }); + return; + } + body = { project, token: view.token, op: "set", id: editing, patch, unset }; + } + const { ok, status, j } = await call<{ row?: Row }>("/api/report/ledger", { method: "POST", body: JSON.stringify(body) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setEditing(null); + setSaid({ ok: true, text: `${editing === "" ? "Added" : "Saved"} ${j.row?.id ?? ""}: ${String(j.row?.display ?? "")} — in the draft.` }); + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + const remove = async (id: string) => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call("/api/report/ledger", { method: "POST", body: JSON.stringify({ project, token: view.token, op: "rm", id }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setEditing(null); + setSaid({ ok: true, text: `Removed ${id}.` }); + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + + const input = (k: string, label: string, hint?: string, extra?: React.ComponentProps<"input">) => ( + <Field key={k} label={label} hint={hint}> + <Input data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)} {...extra} /> + </Field> + ); + const select = (k: string, label: string, options: { value: string; label: string }[], blank?: string) => ( + <Field key={k} label={label}> + <Select data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)}> + {blank !== undefined && <option value="">{blank}</option>} + {options.map((o) => ( + <option key={o.value} value={o.value}> + {o.label} + </option> + ))} + </Select> + </Field> + ); + const regimes = regimeTrack ? (track?.regimes ?? s.regimes.map((r) => r.key)) : []; + const editor = editing !== null && ( + <div data-ledger-editor={editing || "new"} className="mt-2 rounded border border-[var(--color-line)] px-2 py-2"> + <div className="grid gap-2 sm:grid-cols-4"> + {editing === "" ? input("id", "Id", "a letter, then letters, digits . : - _") : <Field label="Id"><span className="font-mono text-[12.5px]">{editing}</span></Field>} + {input("date", "Date", "YYYY-MM-DD")} + {select("scope", "Scope", s.tracks.map((t) => ({ value: t.key, label: `${t.label} (${t.key})` })))} + {select("population", "Form", s.forms.map((f) => ({ value: f, label: f })))} + {regimeTrack + ? select("value", "Value", regimes.map((k) => ({ value: k, label: s.regimes.find((r) => r.key === k)?.label ?? k })), "—") + : input("value", "Value", s.unit ? `a number in ${s.unit}` : "a number")} + {regimeTrack ? select("event", "Event", s.events.map((e) => ({ value: e, label: e })), "—") : null} + {select("entryId", "Pinned to", view.entries.map((id) => ({ value: id, label: id })), "no entry")} + {input("cite", "Cite", "source second")} + {input("channel", "Channel", "source channel slug")} + {input("video", "Video", "source video id")} + <div className="sm:col-span-2">{input("src", "Source", "what it is: a title @ a time")}</div> + <div className="sm:col-span-4">{input("scopeBasis", "Basis", "the phrase that settles the scope (never defaulted)")}</div> + <div className="sm:col-span-2">{input("label", "Label")}</div> + <div className="sm:col-span-2"> + <Field label="Quote"> + <Textarea data-ledger-field="quote" rows={2} value={form.quote ?? ""} onChange={(e) => set("quote", e.target.value)} /> + </Field> + </div> + {declared.map((f) => + f.options ? select(f.key, f.label, f.options.map((o) => ({ value: String(o), label: String(o) })), "—") : input(f.key, f.label, `declared (${f.kind})`), + )} + </div> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-ledger-save={editing || "new"} disabled={busy} onClick={() => void save()}> + {editing === "" ? "Add row" : "Save row"} + </Button> + <Button type="button" size="sm" variant="quiet" data-ledger-cancel="" disabled={busy} onClick={() => open(null)}> + Cancel + </Button> + {editing !== "" && ( + <Button type="button" size="sm" variant="quiet" className="ml-auto" data-ledger-remove={editing} disabled={busy} onClick={() => void remove(editing)}> + Remove row + </Button> + )} + </div> + </div> + ); + return ( + <InspectorFrame + kind="ledger" + title={`Ledger — ${block ? `${view.rows.length} pinned to ${block} · ` : ""}${view.total} rows`} + aside={ + <> + <Input data-ledger-filter="" placeholder="filter" className="h-7 w-[12rem]" value={filter} onChange={(e) => { setFilter(e.target.value); setShown(PAGE); }} /> + <Button type="button" size="sm" variant="outline" data-ledger-add="" onClick={() => open("")}> + Add a row + </Button> + </> + } + > + {editing === "" && editor} + <ul className="flex max-h-[320px] flex-col gap-0.5 overflow-y-auto"> + {rows.slice(0, shown).map((r) => ( + <li key={r.id} data-ledger-row={r.id} className="flex flex-col"> + <div className="flex flex-wrap items-baseline gap-2 text-[12px]"> + <span className="w-[4.5rem] font-mono text-text">{r.id}</span> + <span className="num font-mono text-[11.5px] text-muted">{String(r.date ?? "")}</span> + <span className="text-[11.5px] text-text-2">{String(r.scope ?? "")} · {String(r.population ?? "")}</span> + <span className="font-mono text-[12px]">{String(r.display ?? r.value ?? "—")}</span> + {r.entryId ? <span className="text-[11px] text-muted">@{String(r.entryId)}</span> : null} + <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted">{String(r.label ?? "")}</span> + <Button type="button" size="sm" variant={editing === r.id ? "pressed" : "quiet"} data-ledger-edit={r.id} onClick={() => open(editing === r.id ? null : r.id)}> + {editing === r.id ? "Close" : "Edit"} + </Button> + </div> + {editing === r.id && editor} + </li> + ))} + </ul> + {rows.length > shown && ( + <Button type="button" size="sm" variant="quiet" data-ledger-more="" onClick={() => setShown((n) => n + PAGE)}> + {rows.length - shown} more + </Button> + )} + <div className="mt-1.5"> + <SaidLine said={said} testid="ledger-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/LinksInspector.tsx b/umtool/components/projects/inspector/LinksInspector.tsx @@ -0,0 +1,98 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// THE RUMBLE CITE FIX (umtool redesign L6, item 5; 4 and 8 Nov: a Rumble clip's QR named the URL-slug folder the +// corpus keeps it under, and the archive serves the EMBED id -- 15/15 dead on quartering-midterms): each clip of +// the cut that cites such a folder, with its published embed id read from the folder's metadata through L1's one +// mapping, and "Use the published embed id" -- per row, and once for every dead Rumble row (every row only when no +// check has read any of them). It writes `siteVideo` (a citeUrl naming the folder moves with it): POST /api/report/embed-ids, +// one write, one undo point. No network; `umtool links <p>` checks the sites, `umtool links <p> --embed-ids` is +// this panel's twin. With `block`, only that clip's row. + +type Row = { clip: string; channel: string | null; video: string; siteVideo: string; url: string | null; fixedUrl: string | null; citeUrl: string | null; state: string }; +type View = { rows: Row[]; checkedAt: string | null; token: string | null }; + +export default function LinksInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async () => { + const { ok, j } = await call<View>(`/api/report/embed-ids?project=${encodeURIComponent(project)}`); + if (ok) setView(j); + return ok ? j : null; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, load); + if (!view) return null; + const rows = block ? view.rows.filter((r) => r.clip === block) : view.rows; + const dead = rows.filter((r) => r.state === "dead"); + // Once a check has read these rows, "all" is the dead ones only (a row it found open is left as it is); with no + // check yet, every row. + const checked = rows.some((r) => r.state !== "unchecked"); + const allOf = checked ? dead : rows; + const use = async (clips: string[]) => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call<{ fixed?: { clip: string; siteVideo: string }[] }>("/api/report/embed-ids", { method: "POST", body: JSON.stringify({ project, token: view.token, clips }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + const fixed = j.fixed ?? []; + setSaid({ ok: true, text: `${fixed.map((f) => `${f.clip} → ${f.siteVideo}`).join(", ")}: saved to the draft — Check links on the Overview reads the site again.` }); + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + return ( + <InspectorFrame + kind="links" + title={`Rumble cites — ${rows.length} clip${rows.length === 1 ? "" : "s"} naming a folder id`} + aside={ + checked && rows.length && !dead.length ? ( + <span className="text-[11.5px] text-muted" data-embed-no-dead="">no dead links at the last check</span> + ) : allOf.length > 1 ? ( + <Button type="button" size="sm" variant="go" data-embed-use-all={allOf.length} disabled={busy} onClick={() => void use(allOf.map((r) => r.clip))}> + {checked ? `Use the published embed id for all ${dead.length} dead` : `Use the published embed id for all ${rows.length}`} + </Button> + ) : null + } + > + {rows.length === 0 ? ( + <p className="m-0 text-muted" data-embed-none=""> + Every clip names the id its archive serves{view.checkedAt ? ` (links last checked ${view.checkedAt.slice(0, 16).replace("T", " ")})` : ""}. + </p> + ) : ( + <ul className="flex flex-col gap-1"> + {rows.map((r) => ( + <li key={r.clip} data-embed-row={r.clip} data-embed-state={r.state} className="flex flex-wrap items-baseline gap-2"> + <span className="font-mono text-text">{r.clip}</span> + <span className="font-mono text-[11.5px] text-muted"> + {r.channel ?? "?"}/{r.video} → <span className="text-text-2">{r.siteVideo}</span> + </span> + <span className={r.state === "dead" ? "text-[11.5px] text-[var(--color-bad)]" : "text-[11.5px] text-muted"}>{r.state === "unchecked" ? "not checked" : r.state}</span> + <Button type="button" size="sm" variant="outline" className="ml-auto" data-embed-use={r.clip} disabled={busy} onClick={() => void use([r.clip])} title={r.fixedUrl ?? undefined}> + Use the published embed id + </Button> + </li> + ))} + </ul> + )} + <div className="mt-1.5"> + <SaidLine said={said} testid="embed-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/PostItemInspector.tsx b/umtool/components/projects/inspector/PostItemInspector.tsx @@ -0,0 +1,259 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "@/lib/report/excerptPick.mjs"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// A POST ITEM (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item excerpt=…` and `posts narrate +// --recording` by hand), with `block` the item's id: +// THE EXCERPT select words of the post and Add them: the selection snapped to whole words, merged with the +// spans already picked, settled where the build will find each one (excerptPick.mjs), saved as +// `entry.excerpt` -- verbatim spans in the post's order, read joined with " … ", the card still +// showing the whole post with the rest dimmed (POST /api/report/post-item {op: "set"}). +// ITS MEDIA each attachment shown or not (off keeps it whole in `mediaOff` -- crop, blur, trim, sound -- and +// on puts it back as it was; a file of the post the item never carried can be put on) and a video's +// sound on or off. +// MY RECORDING a sound file of your own read of it, kept as a recorded take and picked (the multipart POST +// /api/report/post-narration: trimmed, levelled; `umtool posts narrate <p> <item> --recording <file> +// --no-clean --no-convert` is the twin). + +type Range = { start: number; end: number }; +type View = { + id: string; post: string | null; author: string | null; handle: string | null; text: string; + excerpt: string[] | null; ranges: Range[] | null; excerptErrors: string[]; + media: { i: number; src: string | null; kind: string | null; mute: boolean; seconds: number | null; audio: boolean }[]; + off: { j: number; src: string | null; kind: string | null }[]; + files: string[]; + narration: { takes: { i: number; file: string; engine: string | null; voice: string | null; seconds: number | null }[]; picked: number | null; off: boolean }; + token: string | null; +}; + +/** A (node, offset) of the selection as a character offset into `root`'s text. */ +function offsetIn(root: HTMLElement, node: Node, off: number): number | null { + if (!root.contains(node)) return null; + const r = document.createRange(); + r.selectNodeContents(root); + r.setEnd(node, off); + return r.toString().length; +} + +export default function PostItemInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [missing, setMissing] = useState<string | null>(null); + const [ranges, setRanges] = useState<Range[]>([]); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [file, setFile] = useState<File | null>(null); + const textRef = useRef<HTMLDivElement>(null); + const fileRef = useRef<HTMLInputElement>(null); + const load = useCallback(async (reset = true) => { + if (!block) return null; + const { ok, j } = await call<View>(`/api/report/post-item/inspector?${new URLSearchParams({ project, id: block }).toString()}`); + if (!ok) { + setMissing(j.error ?? "not a post item"); + return null; + } + setMissing(null); + setView(j); + if (reset) setRanges(j.ranges ?? []); + return j; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, () => load(false)); + if (!block) return null; + if (missing) return <InspectorFrame kind="post-item" title={`Post item ${block}`}><p className="m-0 text-muted">{missing}</p></InspectorFrame>; + if (!view) return null; + + const saved = view.ranges ?? []; + const dirty = JSON.stringify(ranges) !== JSON.stringify(saved); + const write = async (url: string, body: Record<string, unknown>, ok: string) => { + setBusy(true); + setSaid(null); + try { + const r = await call(url, { method: "POST", body: JSON.stringify({ project, token: view.token, id: view.id, ...body }) }); + if (!r.ok) { + setSaid({ ok: false, text: refusal(r.j, r.status) }); + if (r.j.stale) await load(); + return false; + } + await load(); + setSaid({ ok: true, text: ok }); + announceManifestChanged(project); + router.refresh(); + return true; + } finally { + setBusy(false); + } + }; + + const addSelection = () => { + const sel = window.getSelection(); + const root = textRef.current; + if (!sel || sel.rangeCount === 0 || !root) return; + const range = sel.getRangeAt(0); + const a = offsetIn(root, range.startContainer, range.startOffset); + const b = offsetIn(root, range.endContainer, range.endOffset); + if (a === null || b === null) { + setSaid({ ok: false, text: "select words inside the post's text first" }); + return; + } + const r = snapToWords(view.text, a, b); + if (!r) { + setSaid({ ok: false, text: "the selection holds no words" }); + return; + } + setSaid(null); + setRanges((rs) => settleRanges(view.text, addRange(rs, r))); + sel.removeAllRanges(); + }; + const saveExcerpt = () => { + const spans = spansOf(view.text, ranges); + // The build's own rule, checked before the write: each span found where it was picked. + const back = rangesOf(view.text, spans); + if (spans.length && JSON.stringify(back) !== JSON.stringify(ranges)) { + setSaid({ ok: false, text: "a span could not be placed where it was picked — clear and pick again" }); + return; + } + void write("/api/report/post-item", { op: "set", patch: { excerpt: spans.length ? spans : null } }, spans.length ? `Excerpt saved to the draft: ${spans.length} span${spans.length === 1 ? "" : "s"}, read joined with " … ".` : "Excerpt cleared: the whole post is read."); + }; + const keepMyRecording = async () => { + if (!file) return; + setBusy(true); + setSaid(null); + try { + const form = new FormData(); + form.set("project", project); + form.set("id", view.id); + form.set("label", "operator"); + form.append("part", file, file.name); + form.append("text", (view.excerpt?.length ? view.excerpt.join(" … ") : view.text).slice(0, 4000)); + form.append("para", "0"); + form.set("note", `my recording (${file.name})`); + const r = await fetch("/api/report/post-narration", { method: "POST", body: form }); + const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds?: number }; gain?: number; error?: string }; + if (!r.ok || !j.take) { + setSaid({ ok: false, text: j.error ?? `HTTP ${r.status}` }); + return; + } + setFile(null); + if (fileRef.current) fileRef.current.value = ""; + await load(); + announceManifestChanged(project); + setSaid({ ok: true, text: `Kept as ${j.take.file}${typeof j.take.seconds === "number" ? ` (${j.take.seconds.toFixed(1)} s` : " ("}${typeof j.gain === "number" ? `, levelled ${j.gain >= 0 ? "+" : ""}${j.gain} dB)` : ")"} and picked.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + + const pieces = piecesOf(view.text, ranges); + const picked = view.narration.picked !== null ? view.narration.takes[view.narration.picked] : null; + return ( + <InspectorFrame kind="post-item" title={`Post item ${view.id}${view.author ? ` — ${view.author}` : ""}${view.handle ? ` @${view.handle}` : ""}`}> + <div className="grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]"> + <div className="flex min-w-0 flex-col gap-1.5" data-post-excerpt={view.excerpt?.length ?? 0}> + <span className="micro">excerpt — select words, then Add</span> + <div + ref={textRef} + data-post-text="" + className="max-h-[220px] overflow-y-auto whitespace-pre-wrap rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1.5 text-[12.5px] leading-relaxed text-text-2 select-text" + > + {pieces.map((p) => + p.picked ? ( + <mark key={p.start} data-excerpt-piece={p.start} className="rounded-[2px] bg-[color-mix(in_srgb,var(--signal)_30%,transparent)] text-text"> + {p.text} + </mark> + ) : ( + <span key={p.start} className={ranges.length ? "opacity-60" : undefined}> + {p.text} + </span> + ), + )} + </div> + {ranges.length > 0 && ( + <ol className="flex flex-col gap-0.5"> + {spansOf(view.text, ranges).map((s, i) => ( + <li key={`${ranges[i].start}`} data-excerpt-span={i} className="flex items-baseline gap-2 text-[11.5px]"> + <span className="min-w-0 flex-1 truncate">&ldquo;{s}&rdquo;</span> + <Button type="button" size="sm" variant="quiet" data-excerpt-span-remove={i} onClick={() => setRanges((rs) => rs.filter((_, k) => k !== i))}> + Remove + </Button> + </li> + ))} + </ol> + )} + {view.excerptErrors.length > 0 && <p className="m-0 text-[11.5px] text-[var(--color-bad)]">{view.excerptErrors.join("; ")}</p>} + <div className="flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="outline" data-excerpt-add="" onMouseDown={(e) => e.preventDefault()} onClick={addSelection}> + Add the selection + </Button> + <Button type="button" size="sm" variant="go" data-excerpt-save="" disabled={busy || !dirty} onClick={saveExcerpt}> + {ranges.length ? "Save excerpt" : "Save: read it whole"} + </Button> + <Button type="button" size="sm" variant="quiet" data-excerpt-clear="" disabled={busy || !ranges.length} onClick={() => setRanges([])}> + Clear + </Button> + <Button type="button" size="sm" variant="quiet" data-excerpt-revert="" disabled={busy || !dirty} onClick={() => setRanges(saved)}> + Revert + </Button> + </div> + </div> + <div className="flex min-w-0 flex-col gap-2"> + <div className="flex flex-col gap-1" data-post-media-list={view.media.length}> + <span className="micro">media</span> + {view.media.length === 0 && view.off.length === 0 && view.files.length === 0 && <span className="text-muted">no attachment</span>} + {view.media.map((m) => ( + <div key={`${m.i}:${m.src}`} data-post-media={m.i} className="flex flex-wrap items-center gap-x-3 gap-y-0.5"> + <label className="inline-flex min-w-0 items-center gap-1.5"> + <input type="checkbox" data-post-media-shown="" checked disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-off", i: m.i }, `${m.src ?? `attachment ${m.i}`}: off (kept as it was set; on puts it back).`)} /> + <span className="truncate font-mono text-[11.5px]" title={m.src ?? ""}>{m.src?.split("/").pop() ?? `attachment ${m.i}`}</span> + <span className="text-[11px] text-muted">{m.kind}{m.seconds ? ` ${m.seconds.toFixed(1)} s` : ""}</span> + </label> + {m.kind === "video" && m.audio && ( + <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2"> + <input type="checkbox" data-post-media-sound="" checked={!m.mute} disabled={busy} onChange={(e) => void write("/api/report/post-item", { op: "set", patch: { media: { [m.i]: { mute: e.target.checked ? null : true } } } }, e.target.checked ? "Sound on." : "Sound off.")} /> + sound + </label> + )} + </div> + ))} + {view.off.map((m) => ( + <label key={`off:${m.j}:${m.src}`} data-post-media-off={m.j} className="inline-flex min-w-0 items-center gap-1.5 text-muted"> + <input type="checkbox" data-post-media-off-shown="" checked={false} disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-show", j: m.j }, `${m.src?.split("/").pop() ?? `attachment ${m.j}`}: on again, as it was.`)} /> + <span className="truncate font-mono text-[11.5px]" title={m.src ?? ""}>{m.src?.split("/").pop() ?? `attachment ${m.j}`}</span> + <span className="text-[11px]">off</span> + </label> + ))} + {view.files.map((f) => ( + <label key={f} data-post-file={f} className="inline-flex min-w-0 items-center gap-1.5 text-muted"> + <input type="checkbox" data-post-file-shown="" checked={false} disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-on", file: f }, `${f.split("/").pop()}: on the item.`)} /> + <span className="truncate font-mono text-[11.5px]" title={f}>{f.split("/").pop()}</span> + <span className="text-[11px]">not shown</span> + </label> + ))} + </div> + <div className="flex flex-col gap-1" data-post-recording={view.narration.takes.length}> + <span className="micro">my recording</span> + <span className="text-[11.5px] text-muted" data-post-takes=""> + {view.narration.takes.length ? `${view.narration.takes.length} take${view.narration.takes.length === 1 ? "" : "s"}; plays ${picked ? `${picked.file.split("/").pop()}${picked.engine ? ` (${picked.engine})` : ""}` : "none"}` : "not narrated yet"} + </span> + <input ref={fileRef} type="file" accept="audio/*,video/*" data-post-recording-file="" className="text-[11.5px]" onChange={(e) => setFile(e.target.files?.[0] ?? null)} /> + <div> + <Button type="button" size="sm" variant="outline" data-post-recording-use="" disabled={busy || !file} onClick={() => void keepMyRecording()} title="your read of it, trimmed and levelled, kept as a recorded take and picked"> + Use my recording + </Button> + </div> + </div> + </div> + </div> + <div className="mt-1.5"> + <SaidLine said={said} testid="post-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/ProvenanceInspector.tsx b/umtool/components/projects/inspector/ProvenanceInspector.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input } from "@/components/ui/field"; +import LinkPolicyPanel from "../report/LinkPolicyPanel"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// THE PROJECT'S PROVENANCE (umtool redesign L6, item 1; the owed provenance writer): where the cut's QRs open +// (provenance.siteOrigin), the channel a clip with no `channel` of its own is from (provenance.channelSlug -- +// `check` blocks without it), the sweep's display name (provenance.channel); and, under them, the link policy per +// channel (LinkPolicyPanel, its own writer). PUT /api/report/provenance; `umtool provenance <p> set` is the twin. + +type Prov = { siteOrigin: string | null; channelSlug: string | null; channel: string | null }; +type View = { + provenance: Prov; + channels: { slug: string; clips: number }[]; + corpusChannels: string[]; + sites: { origin: string; siteId: string; title: string | null }[]; + token: string | null; +}; +const KEYS = ["siteOrigin", "channelSlug", "channel"] as const; + +export default function ProvenanceInspector({ project }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [draft, setDraft] = useState<Record<(typeof KEYS)[number], string>>({ siteOrigin: "", channelSlug: "", channel: "" }); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [policyKey, setPolicyKey] = useState(0); + const load = useCallback(async (reset = true) => { + const { ok, j } = await call<View>(`/api/report/provenance?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + if (reset) setDraft({ siteOrigin: j.provenance.siteOrigin ?? "", channelSlug: j.provenance.channelSlug ?? "", channel: j.provenance.channel ?? "" }); + return j; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, () => load(false)); + if (!view) return null; + const changed = KEYS.filter((k) => draft[k].trim() !== (view.provenance[k] ?? "")); + const set = (k: (typeof KEYS)[number], v: string) => { + setSaid(null); + setDraft((d) => ({ ...d, [k]: v })); + }; + const save = async () => { + setBusy(true); + setSaid(null); + try { + const patch = Object.fromEntries(changed.map((k) => [k, draft[k].trim() || null])); + const { ok, status, j } = await call<{ changed?: Record<string, unknown> }>("/api/report/provenance", { method: "PUT", body: JSON.stringify({ project, token: view.token, patch }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setPolicyKey((n) => n + 1); + setSaid({ ok: true, text: `Saved to the draft: ${Object.keys(j.changed ?? {}).join(", ") || "nothing changed"}.` }); + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + const slugs = [...view.channels.map((c) => c.slug), ...view.corpusChannels.filter((s) => !view.channels.some((c) => c.slug === s))]; + return ( + <InspectorFrame kind="provenance" title="Provenance"> + <div className="grid gap-2 sm:grid-cols-3"> + <Field label="Site origin" hint="the archive its QRs open"> + <Input data-provenance-field="siteOrigin" list={`prov-sites-${project}`} placeholder="https://…" value={draft.siteOrigin} onChange={(e) => set("siteOrigin", e.target.value)} /> + </Field> + <Field label="Channel slug" hint={view.provenance.channelSlug ? "a clip with no channel is from it" : "empty: check blocks until it is set"}> + <Input data-provenance-field="channelSlug" list={`prov-channels-${project}`} value={draft.channelSlug} onChange={(e) => set("channelSlug", e.target.value)} /> + </Field> + <Field label="Channel name" hint="the sweep's display name"> + <Input data-provenance-field="channel" value={draft.channel} onChange={(e) => set("channel", e.target.value)} /> + </Field> + </div> + <datalist id={`prov-sites-${project}`}> + {view.sites.map((s) => ( + <option key={s.origin} value={s.origin}> + {s.title ?? s.siteId} + </option> + ))} + </datalist> + <datalist id={`prov-channels-${project}`}> + {slugs.map((s) => ( + <option key={s} value={s} /> + ))} + </datalist> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-provenance-save="" disabled={busy || !changed.length} onClick={() => void save()}> + Save provenance + </Button> + <Button type="button" size="sm" variant="quiet" data-provenance-revert="" disabled={busy || !changed.length} onClick={() => void load().then(() => setSaid(null))}> + Revert + </Button> + <SaidLine said={said} testid="provenance-said" /> + </div> + <div className="mt-2" data-provenance-link-policy=""> + <LinkPolicyPanel key={policyKey} project={project} /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/StillInspector.tsx b/umtool/components/projects/inspector/StillInspector.tsx @@ -0,0 +1,101 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { InspectorFrame, SaidLine, call, type InspectorProps, type Said } from "./shared"; + +// A STILL AT SECOND N (umtool redesign L6, item 6): one frame of the clip on screen at the playhead's SOURCE +// second, from its fetched window, saved in the project's shots/ (POST /api/report/still-frame; a single ffmpeg +// frame, nothing fetched, nothing in the cut written). `StillButton` sits by Play's controls; `StillInspector` +// lists the project's shots (with `block` a clip's id: that clip's stills). `umtool still` is the twin. + +type Shot = { rel: string; name: string; bytes: number; mtime: string; still: { clip: string; at: number } | null }; + +const shotUrl = (project: string, rel: string, v = "") => `/api/report/still-frame?${new URLSearchParams({ project, file: rel }).toString()}${v ? `&v=${encodeURIComponent(v)}` : ""}`; + +export default function StillInspector({ project, block = null }: InspectorProps) { + const [shots, setShots] = useState<Shot[] | null>(null); + const load = useCallback(async () => { + const { ok, j } = await call<{ shots: Shot[] }>(`/api/report/still-frame?project=${encodeURIComponent(project)}`); + if (ok) setShots(j.shots); + }, [project]); + useEffect(() => { + void load(); + // A still grabbed in Play (another component) is listed here once it lands. + const on = () => void load(); + window.addEventListener("umtool:still-grabbed", on); + return () => window.removeEventListener("umtool:still-grabbed", on); + }, [load]); + if (!shots) return null; + const list = block ? shots.filter((s) => s.still?.clip === block) : shots; + return ( + <InspectorFrame kind="still" title={`Shots — ${list.length}`} aside={<span className="font-mono text-[11px] text-muted">umtool still {project} &lt;clip&gt; --at &lt;s&gt;</span>}> + {list.length === 0 ? ( + <p className="m-0 text-muted">No pictures in shots/ yet — Play&rsquo;s Still button grabs the frame on screen.</p> + ) : ( + <ul className="flex flex-wrap gap-2"> + {list.map((s) => ( + <li key={s.rel} data-shot={s.rel} className="flex w-[160px] flex-col gap-0.5"> + <a href={shotUrl(project, s.rel, s.mtime)} target="_blank" rel="noreferrer"> + {/* eslint-disable-next-line @next/next/no-img-element */} + <img src={shotUrl(project, s.rel, s.mtime)} alt={s.name} className="h-[90px] w-[160px] rounded border border-[var(--color-line)] object-contain" loading="lazy" /> + </a> + <span className="truncate font-mono text-[10.5px] text-muted" title={s.rel}> + {s.still ? `${s.still.clip} @ ${s.still.at.toFixed(2)} s` : s.name} + </span> + </li> + ))} + </ul> + )} + </InspectorFrame> + ); +} + +/** + * Play's STILL button: the frame of the clip on screen at the playhead (`source()` -- the clip's id and the SOURCE + * second, or null on a card) grabbed into shots/. + */ +export function StillButton({ project, take = null, source, className }: { project: string; take?: string | null; source: () => { clip: string; at: number } | null; className?: string }) { + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [last, setLast] = useState<string | null>(null); + const grab = async () => { + const s = source(); + if (!s) { + setSaid({ ok: false, text: "a card has no frame to keep: pause on a clip" }); + return; + } + setBusy(true); + setSaid(null); + try { + const { ok, j } = await call<{ rel?: string; at?: number }>("/api/report/still-frame", { method: "POST", body: JSON.stringify({ project, clip: s.clip, at: s.at, ...(take ? { take } : {}) }) }); + if (!ok || !j.rel) { + setSaid({ ok: false, text: j.error ?? "the frame could not be grabbed" }); + return; + } + setLast(j.rel); + setSaid({ ok: true, text: `${j.rel} (${s.clip} @ ${(j.at ?? s.at).toFixed(2)} s)` }); + window.dispatchEvent(new CustomEvent("umtool:still-grabbed", { detail: { rel: j.rel } })); + } finally { + setBusy(false); + } + }; + return ( + <span className={cn("inline-flex flex-wrap items-center gap-1.5", className)} data-play-still-box=""> + <Button type="button" size="sm" variant="outline" data-play-still="" disabled={busy} onClick={() => void grab()} title="keep the frame on screen as a picture in the project's shots/ (umtool still): from the clip's fetched window, at the playhead's source second"> + {busy ? "Grabbing…" : "Still"} + </Button> + {said && ( + <span className="inline-flex items-center gap-1.5"> + <SaidLine said={said} testid="play-still-said" /> + {said.ok && last && ( + <a className="ink-link text-[11.5px]" href={shotUrl(project, last, String(Date.now()))} target="_blank" rel="noreferrer" data-play-still-open=""> + open + </a> + )} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/inspector/TeaserInspector.tsx b/umtool/components/projects/inspector/TeaserInspector.tsx @@ -0,0 +1,168 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// A TEASER OR CLOSING CARD (umtool redesign L6, item 2): with no `block`, a NEW card -- where it goes (the end: a +// closing card; the start: a cold open; after an entry), its lines (the first its title; each with the end of +// its words as a second tier, `break`, and a `hold`), its beat -- inserted; with `block` a teaser's id, its lines +// and beat changed. POST /api/report/teaser (op insert | set); the build's teaser rules refuse in their words. +// `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins. + +type Line = { text: string; break: string; hold: string; keep?: Record<string, unknown> }; +type View = { + entries: { id: string; type: string; at: number; label: string | null }[]; + teasers: { id: string; at: number; lines: unknown[]; beat: number | null }[]; + limits: { lines: [number, number]; rows: number; chars: number; hold: number; beat: { min: number; max: number } }; + token: string | null; +}; + +const blank = (): Line => ({ text: "", break: "", hold: "" }); +/** A line as written into the editor's fields (keys it does not show kept as they are). */ +function lineOf(l: unknown): Line { + if (typeof l === "string") return { text: l, break: "", hold: "" }; + const o = (l && typeof l === "object" ? l : {}) as Record<string, unknown>; + const { text, break: brk, hold, ...keep } = o; + return { text: typeof text === "string" ? text : "", break: typeof brk === "string" ? brk : "", hold: typeof hold === "number" ? String(hold) : "", ...(Object.keys(keep).length ? { keep } : {}) }; +} +/** The line as the writer takes it: a string when it is only its words. */ +function valueOf(l: Line): unknown { + const o: Record<string, unknown> = { ...(l.keep ?? {}), text: l.text.trim() }; + if (l.break.trim()) o.break = l.break.trim(); + if (l.hold.trim()) o.hold = Number(l.hold); + return Object.keys(o).length === 1 ? o.text : o; +} + +export default function TeaserInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [lines, setLines] = useState<Line[]>([blank()]); + const [id, setId] = useState(""); + const [beat, setBeat] = useState(""); + const [position, setPosition] = useState("end"); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const editing = block ? view?.teasers.find((t) => t.id === block) ?? null : null; + const load = useCallback(async (reset = true) => { + const { ok, j } = await call<View>(`/api/report/teaser?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + const t = block ? j.teasers.find((x) => x.id === block) : null; + if (t && reset) { + setLines(t.lines.length ? t.lines.map(lineOf) : [blank()]); + setBeat(t.beat === null ? "" : String(t.beat)); + } + return j; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, () => load(false)); + if (!view) return null; + if (block && !editing) return <InspectorFrame kind="teaser" title="Teaser"><p className="m-0 text-muted">No teaser {block} in the draft.</p></InspectorFrame>; + + const setLine = (i: number, patch: Partial<Line>) => { + setSaid(null); + setLines((ls) => ls.map((l, k) => (k === i ? { ...l, ...patch } : l))); + }; + // "after:<id>@<at>": the entry's index names one of an id's twins (a variant's), as the writer's `at` does. + const posValue = () => { + if (position === "end" || position === "start") return position; + const m = /^after:(.*)@(\d+)$/.exec(position); + return m ? { after: m[1], at: Number(m[2]) } : { after: position.slice("after:".length) }; + }; + const submit = async () => { + setBusy(true); + setSaid(null); + try { + const values = lines.filter((l) => l.text.trim()).map(valueOf); + const beatV = beat.trim() ? Number(beat) : null; + const body = editing + ? { project, token: view.token, op: "set", id: editing.id, patch: { lines: values, beat: beatV } } + : { project, token: view.token, op: "insert", position: posValue(), spec: { lines: values, ...(id.trim() ? { id: id.trim() } : {}), ...(beatV !== null ? { beat: beatV } : {}) } }; + const { ok, status, j } = await call<{ id?: string; at?: number }>("/api/report/teaser", { method: "POST", body: JSON.stringify(body) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + if (editing) { + await load(); + setSaid({ ok: true, text: `Saved ${j.id} to the draft.` }); + } else { + await load(); + setLines([blank()]); + setId(""); + setBeat(""); + setSaid({ ok: true, text: `Inserted ${j.id} at ${(j.at ?? 0) + 1} — Undo last edit takes it back.` }); + } + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + const lim = view.limits; + return ( + <InspectorFrame kind="teaser" title={editing ? `Teaser ${editing.id}` : "Insert a teaser or closing card"}> + {!editing && ( + <div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,10rem)_minmax(0,7rem)]"> + <Field label="Where"> + <Select data-teaser-position="" value={position} onChange={(e) => { setPosition(e.target.value); setSaid(null); }}> + <option value="end">At the end (a closing card)</option> + <option value="start">At the start (a cold open)</option> + {view.entries.map((e) => ( + <option key={`${e.id}@${e.at}`} value={`after:${e.id}@${e.at}`}> + After {e.id} ({e.type}{e.label ? `: ${String(e.label).slice(0, 40)}` : ""}) + </option> + ))} + </Select> + </Field> + <Field label="Id" hint={position === "start" ? "blank: cold" : position === "end" ? "blank: close" : "blank: teaser"}> + <Input data-teaser-id="" value={id} onChange={(e) => setId(e.target.value)} /> + </Field> + <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}> + <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} /> + </Field> + </div> + )} + {editing && ( + <div className="max-w-[10rem]"> + <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}> + <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} /> + </Field> + </div> + )} + <ol className="mt-2 flex flex-col gap-1.5"> + {lines.map((l, i) => ( + <li key={i} data-teaser-line={i} className="grid items-end gap-1.5 sm:grid-cols-[minmax(0,1fr)_minmax(0,11rem)_minmax(0,5rem)_auto]"> + <Field label={i === 0 ? `Title line (≤ ${lim.chars} characters a line)` : `Line ${i + 1}`}> + <Input data-teaser-line-field="text" value={l.text} maxLength={lim.chars} onChange={(e) => setLine(i, { text: e.target.value })} /> + </Field> + <Field label={i === 0 ? "Break (its words' end)" : "Break"}> + <Input data-teaser-line-field="break" value={l.break} onChange={(e) => setLine(i, { break: e.target.value })} /> + </Field> + <Field label={i === 0 ? `Hold (0–${lim.hold} s)` : "Hold"}> + <Input data-teaser-line-field="hold" type="number" step={0.1} min={0} max={lim.hold} value={l.hold} onChange={(e) => setLine(i, { hold: e.target.value })} /> + </Field> + <Button type="button" size="sm" variant="quiet" data-teaser-line-remove={i} disabled={lines.length === 1} onClick={() => setLines((ls) => ls.filter((_, k) => k !== i))}> + Remove + </Button> + </li> + ))} + </ol> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="outline" data-teaser-add-line="" disabled={lines.length >= lim.lines[1]} onClick={() => setLines((ls) => [...ls, blank()])}> + Add a line + </Button> + <Button type="button" size="sm" variant="go" data-teaser-insert={editing ? "set" : "insert"} disabled={busy || !lines.some((l) => l.text.trim())} onClick={() => void submit()}> + {editing ? "Save teaser" : "Insert card"} + </Button> + <SaidLine said={said} testid="teaser-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/TitleInspector.tsx b/umtool/components/projects/inspector/TitleInspector.tsx @@ -0,0 +1,76 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared"; + +// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7): the manifest's `title` and `subtitle`, through +// PUT /api/report/title (`umtool title <p> "<title>" [--subtitle "…"]`). An empty subtitle removes it. + +type View = { title: string | null; subtitle: string | null; limits: { title: number; subtitle: number }; token: string | null }; + +export default function TitleInspector({ project }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [title, setTitle] = useState(""); + const [subtitle, setSubtitle] = useState(""); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async (reset = true) => { + const { ok, j } = await call<View>(`/api/report/title?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + if (reset) { + setTitle(j.title ?? ""); + setSubtitle(j.subtitle ?? ""); + } + return j; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + useOnManifestChanged(project, () => load(false)); + if (!view) return null; + const dirty = title.trim() !== (view.title ?? "") || subtitle.trim() !== (view.subtitle ?? ""); + const save = async () => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call("/api/report/title", { method: "PUT", body: JSON.stringify({ project, token: view.token, title, subtitle }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setSaid({ ok: true, text: "Saved to the draft." }); + announceManifestChanged(project); + router.refresh(); + } finally { + setBusy(false); + } + }; + return ( + <InspectorFrame kind="title" title="Title"> + <div className="grid gap-2 sm:grid-cols-2"> + <Field label="Title"> + <Input data-title-field="title" value={title} maxLength={view.limits.title} onChange={(e) => { setTitle(e.target.value); setSaid(null); }} /> + </Field> + <Field label="Subtitle" hint="blank: none"> + <Input data-title-field="subtitle" value={subtitle} maxLength={view.limits.subtitle} onChange={(e) => { setSubtitle(e.target.value); setSaid(null); }} /> + </Field> + </div> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-title-save="" disabled={busy || !dirty || !title.trim()} onClick={() => void save()}> + Save title + </Button> + <Button type="button" size="sm" variant="quiet" data-title-revert="" disabled={busy || !dirty} onClick={() => { setTitle(view.title ?? ""); setSubtitle(view.subtitle ?? ""); setSaid(null); }}> + Revert + </Button> + <SaidLine said={said} testid="title-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/shared.tsx b/umtool/components/projects/inspector/shared.tsx @@ -0,0 +1,116 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi"; + +export { announceManifestChanged }; + +// --------------------------------------------------------------------------- +// THE INSPECTOR PANELS' COMMON PARTS (umtool redesign L6). Every panel in this directory is self-contained: it +// takes `{ project, block? }` (the project id; the block -- a timeline entry's id -- it inspects, when it is about +// one), reads its own state from its API route and writes through it, so L7 can mount it in the workspace's +// inspector unchanged. Today they are mounted in the Cut tab (and Play's Still button). Every write lands in the +// working draft (video.manifest.json) with its own undo point; none touches a take's patch. No AI anywhere. +// --------------------------------------------------------------------------- + +export type InspectorProps = { project: string; block?: string | null }; + +/** What a write said: a sentence, good or bad. */ +export type Said = { ok: boolean; text: string } | null; + +/** A JSON request; the parsed body (or {}) and whether it was 2xx. A stale token says so. */ +export async function call<T = Record<string, unknown>>(url: string, init?: RequestInit): Promise<{ ok: boolean; status: number; j: T & { error?: string; errors?: string[]; stale?: boolean } }> { + const r = await fetch(url, { cache: "no-store", ...init, headers: init?.body && typeof init.body === "string" ? { "content-type": "application/json", ...(init.headers ?? {}) } : init?.headers }); + const j = (await r.json().catch(() => ({}))) as T & { error?: string; errors?: string[]; stale?: boolean }; + return { ok: r.ok, status: r.status, j }; +} + +/** The sentence for a refused write. */ +export const refusal = (j: { error?: string; errors?: string[]; stale?: boolean }, status: number) => + j.stale ? "The draft changed since this panel read it — it has been read again; check and save once more." : (j.errors?.length ? j.errors.join("; ") : j.error) ?? `HTTP ${status}`; + +/** A panel's frame: a heading, the body. */ +export function InspectorFrame({ kind, title, aside, className, children }: { kind: string; title: React.ReactNode; aside?: React.ReactNode; className?: string; children: React.ReactNode }) { + return ( + <section data-inspector={kind} className={cn("min-w-0 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]", className)}> + <div className="mb-1.5 flex flex-wrap items-baseline gap-2"> + <h3 className="micro">{title}</h3> + {aside ? <span className="ml-auto flex flex-wrap items-center gap-2">{aside}</span> : null} + </div> + {children} + </section> + ); +} + +/** The line under a panel's buttons. */ +export function SaidLine({ said, testid }: { said: Said; testid: string }) { + if (!said) return null; + return ( + <span role="status" {...{ [`data-${testid}`]: said.ok ? "ok" : "refused" }} className={cn("text-[11.5px]", said.ok ? "text-text-2" : "text-[var(--color-bad)]")}> + {said.text} + </span> + ); +} + +/** + * A row's "Edit" that opens a panel under it (the Cut tab's per-row inspector, until L7's workspace has one + * inspector for the selected block). + */ +export function InspectorToggle({ label = "Edit", testid, children, className }: { label?: string; testid: string; children: React.ReactNode; className?: string }) { + const [open, setOpen] = useState(false); + return ( + <> + <Button type="button" size="sm" variant={open ? "pressed" : "quiet"} className={className} aria-expanded={open} {...{ [`data-${testid}`]: open ? "open" : "" }} onClick={() => setOpen((o) => !o)}> + {open ? "Close" : label} + </Button> + {open ? <div className="basis-full pt-1.5">{children}</div> : null} + </> + ); +} + +/** + * Read again whenever the draft changed under the panel (the page's MANIFEST_CHANGED: another panel's write, the + * timeline's Undo), so its token is never the stale one. `reread` keeps a form being typed in (it refreshes the + * view, not the fields). + */ +export function useOnManifestChanged(project: string, reread: () => unknown) { + const fn = useRef(reread); + fn.current = reread; + useEffect(() => { + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project === project) void fn.current(); + }; + window.addEventListener(MANIFEST_CHANGED, on); + return () => window.removeEventListener(MANIFEST_CHANGED, on); + }, [project]); +} + +/** + * Its children only once the `<details>` it sits in has been opened (an Options panel): the panels inside read + * nothing until somebody looks. Outside a `<details>`, at once. + */ +export function WhenOpen({ children }: { children: React.ReactNode }) { + const ref = useRef<HTMLSpanElement>(null); + const [open, setOpen] = useState(false); + useEffect(() => { + const d = ref.current?.closest("details"); + if (!d) { + setOpen(true); + return; + } + const on = () => { + if (d.open) setOpen(true); + }; + on(); + d.addEventListener("toggle", on); + return () => d.removeEventListener("toggle", on); + }, []); + return ( + <> + <span ref={ref} hidden /> + {open ? children : null} + </> + ); +} diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -38,6 +38,15 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/ import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; import IntroRow from "./IntroEditor"; +// The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector. +import { InspectorToggle, WhenOpen } from "../inspector/shared"; +import TitleInspector from "../inspector/TitleInspector"; +import ProvenanceInspector from "../inspector/ProvenanceInspector"; +import TeaserInspector from "../inspector/TeaserInspector"; +import LedgerInspector from "../inspector/LedgerInspector"; +import PostItemInspector from "../inspector/PostItemInspector"; +import LinksInspector from "../inspector/LinksInspector"; +import StillInspector from "../inspector/StillInspector"; // 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. @@ -219,6 +228,10 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <Link href={postBenchHref(project.id, e.id)} className="ink-link text-[11px]" data-post-bench-link={e.id}> bench </Link> + {/* Its excerpt by selection, its media on/off, my recording (the inspector, L6). */} + <InspectorToggle testid="post-edit" label="Edit"> + <PostItemInspector project={project.id} block={e.id} /> + </InspectorToggle> </div> {words && <div className="mt-0.5 text-[12px] text-[var(--color-dim)]">{words.length > 160 ? `${words.slice(0, 157)}…` : words}</div>} <div className="basis-full"> @@ -244,6 +257,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </span> {e.seconds != null && <span className="num micro ml-auto">{e.seconds}s</span>} <PlayLink project={project.id} clip={e.id} where="row" variant="icon" className={e.seconds != null ? "" : "ml-auto"} /> + {e.kind === "teaser" && ( + <InspectorToggle testid="teaser-edit" label="Edit"> + <TeaserInspector project={project.id} block={e.id} /> + </InspectorToggle> + )} <div className="basis-full"> <RowNotes id={e.id} project={project.id} /> </div> @@ -498,6 +516,16 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <PronunciationPanel project={project.id} /> </Options> )} + {/* The project's own facts, each an inspector panel (L6): what agents set by hand this week. */} + <Options id="cut-project" label="Project" hint="title · provenance · Rumble cites · ledger · shots" bodyClassName="w-[min(1100px,calc(100vw-3rem))] flex-col items-stretch"> + <WhenOpen> + <TitleInspector project={project.id} /> + <ProvenanceInspector project={project.id} /> + {clips.length > 0 && <LinksInspector project={project.id} />} + {(Array.isArray(m?.ledger) || m?.ledgerSchema) && <LedgerInspector project={project.id} />} + <StillInspector project={project.id} /> + </WhenOpen> + </Options> <Advanced id="cut" hint="voices · tight windows · bench prep"> {clips.length > 0 && ( <VoiceMatchPanel @@ -544,6 +572,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor )} {/* The intro the cut opens on (render.intro), first, and its editor with a live preview (lane intro-play). */} <IntroRow project={project.id} written={m?.render?.intro ?? null} open={search.intro === "1"} /> + {/* A teaser or closing card, inserted (the inspector, L6; `umtool timeline <p> teaser-insert`). */} + <div className="mb-1.5 flex flex-wrap items-center gap-2" data-cut-insert-card-row=""> + <InspectorToggle testid="cut-insert-card" label="Insert a teaser or closing card"> + <TeaserInspector project={project.id} /> + </InspectorToggle> + </div> <TimelineList project={project.id} count={entries.length} groupCount={groupBars.list.length}> {sectionBars.opening && <SectionBar section={sectionBars.opening} />} {entries.map((e, at) => ( diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -41,6 +41,7 @@ import { useIntroPage } from "./useIntroPage"; import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs"; import ComboBadge, { type ComboInfo } from "./ComboBadge"; import CopyShareLine from "../CopyShareLine"; +import { StillButton } from "../inspector/StillInspector"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -712,6 +713,14 @@ export default function PlayCut({ if (take) return openInDraftHref(project, take, { clip: it.id, play: { at } }); return clipBenchHref(project, it.id, { play: { at, take: null } }); }, [project, take, now]); + // ---- a still at second N (the inspector, L6): the clip on screen at the playhead's SOURCE second ---- + const stillSource = useCallback(() => { + const e = now(); + const it = planRef.current.items[e.cur]; + if (!it?.clip) return null; + const src = sourceAt(it, e.t); + return src === null ? null : { clip: it.id, at: Math.round(src * 100) / 100 }; + }, [now]); /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ const placeHref = useCallback(() => { const e = now(); @@ -1392,6 +1401,8 @@ export default function PlayCut({ > {postNow ? "Edit this post" : "Edit this clip"} </button> + {/* The frame on screen kept as a picture in shots/ (umtool still): never a write to the cut. */} + {item?.clip && <StillButton project={project} take={take ?? null} source={stillSource} />} {/* The clip's source across its life cycle (lane L5): found, downloaded, … published. */} {item?.clip && entry?.video && entry.sourceChannel && ( <Link diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -20,6 +20,7 @@ Inbox cannot disagree about what is wrong with one. | `ls [--kind --template --state --open --blocking --q --sort --json]` | the index, as text or JSON | | `show <project> [--json]` | one project: summary, the cut, per-clip status, decisions | | `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) | +| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `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>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) | | `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write | | `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for | @@ -98,7 +99,11 @@ Inbox cannot disagree about what is wrong with one. | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | | `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) | | `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) | +| `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | +| `title <project> ["<title>"] [--subtitle "…" \| --no-subtitle] [--json]` | the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | +| `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` | +| `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | | `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) | | `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) | @@ -155,7 +160,12 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `ls [--kind KIND] [--template TEMPLATE] [--state STATE] [--open] [--blocking] [--q Q] [--sort recent\|name]` | every project, as text | form · *corpus* | | `show <project>` | one project: summary, the cut, per-clip status, decisions | form · *project* | | `check [<project>] [--all-severities]` | what blocks a build (exit 1 on anything blocking) | form · *project* | -| `links <project> [--fix]` | do the clip QRs open on their sites (out/links.json) | form · *project* | +| `links <project> [--fix] [--embed-ids] [--clips CLIPS] [--dry-run]` | do the clip QRs open on their sites (out/links.json) | form · *project* | +| `provenance <project> ls` | the project's provenance: site origin, channel slug, channel, link policy | form · *project* | +| `provenance <project> set [--site-origin SITE-ORIGIN] [--channel-slug CHANNEL-SLUG] [--channel CHANNEL]` | the project's site origin, channel slug and channel name ("" removes one) | form · *draft* | +| `title <project> [<title>] [--subtitle SUBTITLE] [--no-subtitle]` | the project's title and subtitle (no words: print them) | form · *draft* | +| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* | +| `still <project> ls` | the pictures in the project's shots/ | form · *project* | | `cast ls` | the characters' voices across projects | form · *corpus* | | `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* | | `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* | @@ -302,6 +312,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `timeline <project> post <post>` | a post added, or the one with its id replaced | form · *draft* | | `timeline <project> post-remove <id>` | a post out of the cut | form · *draft* | | `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* | +| `timeline <project> teaser-insert [--at end\|start] [--after AFTER] [--before BEFORE] [--id ID] [--beat N] [--line LINE…] [--lines-json JSON]` | a teaser or closing card inserted (default at the end) | form · *draft* | | `timeline <project> undo [--take TAKE]` | the newest automatic snapshot back | form · *draft* | | `timeline <project> sections` | the deck's sections and their clips | form · *project* | | `timeline <project> section-move <ids>… --to-section N [--start]` | clips to the end (or start) of section N | form · *draft* | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -2273,3 +2273,21 @@ A days-since counter for a promise (`render.chrome.deck.promise`, measure-extras | a timeline entry's `hideModules` | `["promise", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=promise` (`--take <t>` for a take) | <!-- modules:end --> + +## The inspector panels (this week's hand edits, in the UI) + +Umtool redesign L6: what agents set by hand in the week of 2–9 Nov, each now a panel of +`components/projects/inspector/` (`{project, block?}`, mounted today in the Cut tab and Play; L7 moves them into the +workspace's inspector) and a command, through ONE writer (`lib/report/inspectorEdits.mjs`, or the manifest's own). +Every write lands in the **working draft** (`video.manifest.json`, never a take's patch) with its own undo point +(`auto-before-<op>`): the Cut tab's **Undo last edit** / `umtool timeline <p> undo` takes exactly it back. + +| Panel (where) | What it sets | From a terminal | Route | +|---|---|---|---| +| **Title** (Cut tab › Project) | `title` (one line, ≤ 200) and `subtitle` (≤ 300; empty removes it) | `umtool title <p> "<title>" [--subtitle "…" \| --no-subtitle] [--json]` | `GET/PUT /api/report/title` | +| **Provenance** (Cut tab › Project) | `provenance.siteOrigin` (an http(s) origin, no path), `provenance.channelSlug` (a slug; `check` blocks without it), `provenance.channel` (the display name); empty removes one. The **Link policy** per channel under it (its own writer, above) | `umtool provenance <p> [ls] \| set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | `GET/PUT /api/report/provenance` | +| **Insert a teaser or closing card** (Cut tab, beside the intro row; a teaser row's **Edit**) | a `teaser` entry: where (the end, id `close`; the start, `cold`; after an entry), its lines (the first its title; each a `break` — the end of its words, a second tier — and a `hold`, 0–4 s), its `beat` (0.4–2.5 s); the build's teaser rules refuse in their words. A row's Edit changes its lines and beat | `umtool timeline <p> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json …` · `umtool timeline <p> teaser <id> <patch>` | `GET/POST /api/report/teaser` (`op: insert \| set`) | +| **Ledger** (Cut tab › Project, a measure ledger) | a row's `date`, `scope` (a track), form, `value` (a number; a regime and its `event` on a regime track), `scopeBasis`, its source (`src`, `channel`, `video`, `cite`), `label`, `quote`, `entryId` and the schema's declared fields — added, changed (a new value redraws its `display`), removed; the ledger CLI's checks word for word | `umtool ledger <p> add\|set\|rm …` | `GET/POST /api/report/ledger` (`op: add \| set \| rm`) | +| **Post item** (a post row's **Edit**) | its **excerpt**: select words of the post and **Add the selection** — snapped to whole words, merged, a span whose words come earlier too widened to where it was picked (`lib/report/excerptPick.mjs`), saved as `excerpt` (verbatim spans, read joined " … "); its **media** on/off (off keeps the attachment whole — crop, blur, trim, sound — in the item's `mediaOff`, which nothing draws or plays; on puts it back as it was) and a video's **sound** (`mute`); **Use my recording**: a sound file of your own read, trimmed and levelled, kept as `take-<n>.recorded-operator.wav` and picked | `umtool posts set-item <p> <item> excerpt='[…]' media.<i>.shown=off media-off.<j>.shown=on media.add=<file> media.<i>.mute=on` · `umtool posts narrate <p> <item> --recording <file> --no-clean --no-convert` | `POST /api/report/post-item` (`op: set`), `GET/POST /api/report/post-item/inspector` (`op: media-on \| media-off \| media-show`), multipart `POST /api/report/post-narration` | +| **Rumble cites** (Cut tab › Project) | each clip naming a Rumble URL-slug FOLDER the archive does not serve, with its embed id (L1's `siteVideoFor`, from the folder's `metadata.info.json`) and what the last link check said; **Use the published embed id** (a row) and **… for all N dead** (every row only when no check has read any; after a check that found none dead it says so) write `siteVideo` (a citeUrl naming the folder moves with it), one write. No network | `umtool links <p> --embed-ids [--clips a,b] [--dry-run] [--json]` | `GET/POST /api/report/embed-ids` | +| **Still** (Play, beside Edit this clip; Cut tab › Project › Shots lists them) | the frame on screen — the clip's fetched window at the playhead's SOURCE second, one `ffmpeg -ss -frames:v 1` (not heavy) — as `shots/still-<clip>-<s>s.png`; nothing fetched, the cut not written | `umtool still <p> <clip> --at <source s> [--take <t>] [--json]` · `umtool still <p> ls` | `GET/POST /api/report/still-frame` | diff --git a/umtool/e2e/fixtures/inspector-fixture.mjs b/umtool/e2e/fixtures/inspector-fixture.mjs @@ -0,0 +1,129 @@ +// THE INSPECTOR PANELS (umtool redesign L6; e2e/inspector-*.spec.ts): one WRITABLE project per panel, each +// play-cut-fixture's cut (c01 c02 k01 c03 c04 on playvid, its window cached in out/clips-raw) unless said, each +// with a made take (takes/short/take.json) the specs check is never written -- every UI edit lands in the draft. +// +// inspector-provenance-fixture provenance with no channelSlug (the gap `umtool new` leaves) and an old origin +// inspector-title-fixture the title, a subtitle +// inspector-teaser-fixture no teaser yet +// inspector-ledger-fixture a MEASURE ledger (one value track, one regime track) with two rows, w01 pinned to c01 +// inspector-post-fixture two post items -- p-long (a long text post, an excerpt picked by selection) and +// p-vid (a video with sound, and a picture of the post it does not carry) -- from +// post-items-fixture's archive files +// inspector-rumble-fixture three Rumble clips on inspectrumble, two naming a URL-slug FOLDER the archive does not +// serve (v7slug1 -> v7emb01, v7slug2 -> v7emb02, in the project's .shadow-channels), +// one its own; out/links.json records both folder links dead +// inspector-still-fixture the cut alone (Play's Still button) +// +// Synthetic, like every fixture. +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const TAKE = (dir) => JSON.parse(readFileSync(path.join(dir, "takes", "short", "take.json"), "utf8")); + +/** + * @param {{ reports: string, channels: string, deckManifest: Function, cachedWindow: string, makePlayCutFixture: Function }} o + */ +export async function makeInspectorFixtures({ reports, channels, deckManifest, cachedWindow, makePlayCutFixture }) { + const cut = (name, title, edit = (m) => m) => { + const { dir } = makePlayCutFixture({ reports, deckManifest, cachedWindow, name, title }); + const file = path.join(dir, "video.manifest.json"); + const m = edit(JSON.parse(readFileSync(file, "utf8"))); + writeFileSync(file, JSON.stringify(m, null, 2) + "\n"); + TAKE(dir); // the take is there to be left alone + return dir; + }; + + cut("inspector-provenance-fixture", "The Inspector Provenance Fixture", (m) => ({ ...m, provenance: { siteOrigin: "https://old.example" } })); + cut("inspector-title-fixture", "The Inspector Title Fixture", (m) => ({ ...m, subtitle: "an old subtitle" })); + cut("inspector-teaser-fixture", "The Inspector Teaser Fixture"); + cut("inspector-still-fixture", "The Inspector Still Fixture"); + cut("inspector-ledger-fixture", "The Inspector Ledger Fixture", (m) => ({ + ...m, + ledgerSchema: { + kind: "measure", unit: "lb", yLabel: "POUNDS", yMin: 200, yMax: 400, + tracks: [ + { key: "weight", role: "value", label: "What he says he weighs" }, + { key: "regime", role: "regime", label: "The diet he names", regimes: ["keto", "off"] }, + ], + forms: ["current", "past", "delta", "status"], + regimes: [{ key: "keto", label: "Keto" }, { key: "off", label: "No diet" }], + fields: [], + }, + ledger: [ + { id: "w01", date: "2026-10-01", asOf: null, scope: "weight", population: "current", value: 291, display: "291 lb", label: "on the scale", scopeBasis: "his words: I weigh 291", scopeConfidence: "read", valueKind: "uttered", flags: [], entryId: "c01", channel: "inspchan", video: "playvid", cite: 1 }, + { id: "d01", date: "2026-09-01", asOf: null, scope: "regime", population: "status", value: "keto", event: "start", display: "keto", label: "starts keto", scopeBasis: "I'm doing keto", scopeConfidence: "read", valueKind: "uttered", flags: [] }, + ], + })); + + // ---- post items -------------------------------------------------------------------------------------------- + { + const name = "inspector-post-fixture"; + const dir = path.join(reports, name); + const media = path.join(dir, "posts-media", "postchan-x", "3"); + mkdirSync(media, { recursive: true }); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "playvid_0.00-9.00.mp4")); + const cap = path.join(channels, "postchan-x", "posts-media"); + copyFileSync(path.join(cap, "3", "3_1.mp4"), path.join(media, "3_1.mp4")); + copyFileSync(path.join(cap, "2", "2_1.png"), path.join(media, "3_2.png")); + const base = (id, text, o = {}) => ({ + type: "post", id, post: `postchan-x/${id.slice(2)}`, platform: "x", author: "Post Subject", handle: "postsubject", + date: "2026-10-30T12:00:00.000Z", text, url: `https://x.com/postsubject/status/${id.slice(2)}`, subjects: ["postsubject"], ...o, + }); + const timeline = [ + { type: "clip", id: "c01", video: "playvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence." }, + base("p-5", "The scale said 291 this morning. I said the scale was broken, and then the scale said 290 by the evening. Nobody believes the scale anyway."), + base("p-3", "@someone_private Yes, and here is the video.", { media: [{ src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true }] }), + ]; + const m = deckManifest(name, "The Inspector Post Fixture", timeline); + m.provenance = { ...m.provenance, channelSlug: "postchan-x" }; + m.render.fetchPad = 0; + m.render.lockedEdges = false; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + // "Use my recording"'s file: a second and a half of a tone with silence either side (the trim keeps the tone). + const wav = path.join(path.dirname(reports), "inspector-recording.wav"); + const ff = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=330:duration=1.5", "-af", "adelay=400|400,apad=pad_dur=0.4", "-ar", "48000", "-ac", "1", wav], { encoding: "utf8" }); + if (ff.status !== 0) throw new Error(`ffmpeg failed: ${ff.stderr}`); + mkdirSync(path.join(dir, "takes", "short"), { recursive: true }); + writeFileSync(path.join(dir, "takes", "short", "take.json"), JSON.stringify({ id: "short", group: "takes", order: 1, label: "Short", kind: "different", preview: "preview.mp4", window: "full", style: null, patch: { timeline: [timeline[1]] } }, null, 2) + "\n"); + } + + // ---- Rumble clips naming the URL-slug folder --------------------------------------------------------------- + { + const dir = cut("inspector-rumble-fixture", "The Inspector Rumble Fixture", (m) => ({ + ...m, + provenance: { siteOrigin: "https://archive.example", channelSlug: "inspectrumble", channelsFallback: false }, + timeline: [ + { type: "clip", id: "r01", video: "v7slug1", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "the first" }, + { type: "clip", id: "r02", video: "v7slug2", start: 3.5, end: 5.5, cite: 4, section: 0, lock: true, quote: "the second" }, + { type: "clip", id: "r03", video: "v7own03", start: 6.0, end: 8.0, cite: 6, section: 0, lock: true, quote: "its own id" }, + ], + })); + const ch = path.join(dir, ".shadow-channels", "inspectrumble"); + writeFileSync(path.join(mkdirP(ch), "config.json"), JSON.stringify({ platform: "rumble", handling: "transcribe", url: "https://rumble.com/c/inspectrumble", name: "Inspect Rumble" }, null, 2)); + for (const [folder, id] of [["v7slug1", "v7emb01"], ["v7slug2", "v7emb02"], ["v7own03", "v7own03"]]) { + writeFileSync(path.join(mkdirP(path.join(ch, "data", folder)), "metadata.info.json"), JSON.stringify({ id, extractor: "Rumble", webpage_url: `https://rumble.com/${folder}-a-title.html`, title: `Recording ${folder}` })); + } + // The last link check: both folder links dead (the archive serves the embed ids), the own id open -- each + // QR's link as the build draws it (linkCheck.mjs linksOf), so the panel reads them against the cut as it is. + const { linksOf, withArchiveId } = await import("../../lib/report/linkCheck.mjs"); + const m = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")); + const embed = { r01: ["v7slug1", "v7emb01"], r02: ["v7slug2", "v7emb02"] }; + writeFileSync(path.join(mkdirP(path.join(dir, "out")), "links.json"), JSON.stringify({ + version: 1, checkedAt: "2026-11-08T10:00:00.000Z", fetched: 3, + origins: { "https://archive.example": { state: "ok", generatedAt: "2026-11-07T10:00:00.000Z", title: "Archive" } }, + links: linksOf(m).map((l) => { + const e = embed[l.clip]; + return e + ? { clip: l.clip, url: l.url, state: "dead", origin: "https://archive.example", why: `no record ${e[0]}`, fix: withArchiveId(l.url, e[0], e[1]), fixSiteVideo: e[1] } + : { clip: l.clip, url: l.url, state: "ok", origin: "https://archive.example" }; + }), + }, null, 2) + "\n"); + } +} + +function mkdirP(d) { + mkdirSync(d, { recursive: true }); + return d; +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -67,6 +67,7 @@ import { makePostComboFixture } from "./post-combo-fixture.mjs"; import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs"; import { makeInstrumentsFixture } from "./instruments-fixture.mjs"; import { makeIntroPlayFixture } from "./intro-play-fixture.mjs"; +import { makeInspectorFixtures } from "./inspector-fixture.mjs"; import { makeIngredientRailFixture } from "./ingredient-rail-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); @@ -2149,6 +2150,10 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out rmSync(path.join(dvDir, "takes"), { recursive: true, force: true }); } +// The inspector panels (inspector-*.spec.ts, umtool redesign L6, WRITE): one project per panel +// (inspector-fixture.mjs), each with a take the specs check is never written. +await makeInspectorFixtures({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture }); + // One undo stack (undo.spec.ts, WRITES): two trims a moment apart, then two undos -- its own copy. { const { dir: unDir } = makePlayCutFixture({ diff --git a/umtool/e2e/inspector-ledger.spec.ts b/umtool/e2e/inspector-ledger.spec.ts @@ -0,0 +1,99 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { openPanel } from "./panels"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// THE LEDGER PANEL (umtool redesign L6, item 3; components/projects/inspector/LedgerInspector.tsx and the new +// /api/report/ledger): a measure ledger's rows -- date, scope, value, basis, source -- added, changed and removed +// from the Cut tab's Project panel through the ledger CLI's own checks (`umtool ledger <p> add|set|rm`), each in +// the draft with its undo point, no take touched. inspector-ledger-fixture (WRITES): w01 (weight, pinned to c01), +// d01 (keto, a regime row). +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial", timeout: 120_000 }); + +const P = "reports/inspector-ledger-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-ledger-fixture"); +type Row = Record<string, unknown> & { id: string }; +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const ledger = () => (JSON.parse(manifestText()) as { ledger: Row[] }).ledger; +const row = (id: string) => ledger().find((r) => r.id === id); +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +test("add a row (date, scope, value, basis, source), refused without its basis; change one; remove one", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="ledger"]'); + await expect(panel.locator("[data-ledger-row]")).toHaveCount(2); + await expect(panel.locator('[data-ledger-row="w01"]')).toContainText("291 lb"); + + // A new row with no basis: the writer's sentence, nothing written. + await panel.locator("[data-ledger-add]").click(); + const ed = panel.locator('[data-ledger-editor="new"]'); + await ed.locator('[data-ledger-field="id"]').fill("w02"); + await ed.locator('[data-ledger-field="date"]').fill("2026-11-01"); + await ed.locator('[data-ledger-field="scope"]').selectOption("weight"); + await ed.locator('[data-ledger-field="population"]').selectOption("current"); + await ed.locator('[data-ledger-field="value"]').fill("288"); + const before = manifestText(); + await ed.locator('[data-ledger-save="new"]').click(); + await expect(panel.locator('[data-ledger-said="refused"]')).toContainText("scopeBasis"); + expect(manifestText()).toBe(before); + + await ed.locator('[data-ledger-field="scopeBasis"]').fill("his words: down to 288"); + await ed.locator('[data-ledger-field="channel"]').fill("inspchan"); + await ed.locator('[data-ledger-field="video"]').fill("playvid"); + await ed.locator('[data-ledger-field="cite"]').fill("2"); + await ed.locator('[data-ledger-field="src"]').fill("A weigh-in @ 0:02"); + await page.screenshot({ path: test.info().outputPath("ledger-add.png") }); + await ed.locator('[data-ledger-save="new"]').click(); + await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Added w02: 288 lb"); + expect(row("w02")).toMatchObject({ id: "w02", date: "2026-11-01", scope: "weight", population: "current", value: 288, display: "288 lb", scopeBasis: "his words: down to 288", channel: "inspchan", video: "playvid", cite: 2, src: "A weigh-in @ 0:02", scopeConfidence: "read", valueKind: "uttered" }); + + // Change w01's value: its display is drawn from the new value; a cleared label is removed. + await panel.locator('[data-ledger-edit="w01"]').click(); + const e1 = panel.locator('[data-ledger-editor="w01"]'); + await expect(e1.locator('[data-ledger-field="value"]')).toHaveValue("291"); + await e1.locator('[data-ledger-field="value"]').fill("290"); + await e1.locator('[data-ledger-field="label"]').fill(""); + await e1.locator('[data-ledger-save="w01"]').click(); + await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Saved w01"); + expect(row("w01")).toMatchObject({ value: 290, display: "290 lb", entryId: "c01" }); + expect(row("w01")?.label).toBeUndefined(); + + // A regime row: its value a regime, its event. + await panel.locator('[data-ledger-edit="d01"]').click(); + const e2 = panel.locator('[data-ledger-editor="d01"]'); + await expect(e2.locator('[data-ledger-field="value"]')).toHaveValue("keto"); + await e2.locator('[data-ledger-field="event"]').selectOption("stop"); + await e2.locator('[data-ledger-save="d01"]').click(); + await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Saved d01"); + expect(row("d01")?.event).toBe("stop"); + + // A removal without the token the panel read is refused. + const bare = await page.request.post("/api/report/ledger", { data: { project: P, op: "rm", id: "d01" } }); + expect(bare.status()).toBe(400); + expect(row("d01")).toBeDefined(); + + await panel.locator('[data-ledger-edit="d01"]').click(); + await panel.locator('[data-ledger-remove="d01"]').click(); + await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Removed d01"); + expect(row("d01")).toBeUndefined(); + await expect(panel.locator("[data-ledger-row]")).toHaveCount(2); + expect(takeText()).toBe(take); +}); + +test("each ledger write is one undo step", async ({ request }) => { + const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("ledger"); + expect(row("d01")).toMatchObject({ event: "stop" }); +}); diff --git a/umtool/e2e/inspector-post-item.spec.ts b/umtool/e2e/inspector-post-item.spec.ts @@ -0,0 +1,162 @@ +import { test, expect as baseExpect, type Page } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// THE POST ITEM PANEL (umtool redesign L6, item 4; components/projects/inspector/PostItemInspector.tsx): a post +// row's Edit on the Cut tab -- the EXCERPT picked by selecting the post's words (snapped to words, settled where +// the build finds each span; was `posts set-item excerpt=…`), its MEDIA on/off and a video's sound, and "Use my +// recording" (a sound file kept as a recorded take and picked; was `posts narrate --recording`). Every write +// lands in the draft; no take touched. inspector-post-fixture (WRITES): p-5 (a long text post), p-3 (a video with +// sound, and a picture of the post it does not carry). +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial", timeout: 120_000 }); + +const P = "reports/inspector-post-fixture"; +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "inspector-post-fixture"); +type Post = Record<string, unknown> & { id: string; excerpt?: string[]; media?: Record<string, unknown>[]; narration?: { takes?: { file: string; engine?: string }[]; pick?: number } }; +const item = (id: string) => (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: Post[] }).timeline.find((e) => e.id === id) as Post; +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +/** Select the `nth` occurrence of `needle` in the element's text, as a person dragging over it would. */ +async function selectText(page: Page, selector: string, needle: string, nth = 0) { + await page.evaluate( + ({ selector, needle, nth }) => { + const root = document.querySelector(selector) as HTMLElement; + const full = root.textContent ?? ""; + let at = -1; + for (let i = 0; i <= nth; i++) at = full.indexOf(needle, at + 1); + if (at < 0) throw new Error(`no "${needle}" in the post's text`); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let pos = 0; + let sN: Node | null = null; + let sO = 0; + let eN: Node | null = null; + let eO = 0; + for (let n = walker.nextNode(); n; n = walker.nextNode()) { + const len = (n.textContent ?? "").length; + if (!sN && at < pos + len) { + sN = n; + sO = at - pos; + } + if (sN && at + needle.length <= pos + len) { + eN = n; + eO = at + needle.length - pos; + break; + } + pos += len; + } + const r = document.createRange(); + r.setStart(sN as Node, sO); + r.setEnd(eN as Node, eO); + const sel = window.getSelection() as Selection; + sel.removeAllRanges(); + sel.addRange(r); + }, + { selector, needle, nth }, + ); +} + +test("the excerpt, picked by selecting the post's words: a span whose words come earlier too is widened to where it was picked", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + const row = page.locator('[data-entry="p-5"]'); + await row.locator("[data-post-edit]").click(); + const panel = row.locator('[data-inspector="post-item"]'); + await expect(panel.locator("[data-post-text]")).toContainText("The scale said 291 this morning."); + // "scale said" is said twice: the second one, picked, is read as "the scale said" so the build finds it there. + await selectText(page, '[data-entry="p-5"] [data-post-text]', "scale said", 1); + await panel.locator("[data-excerpt-add]").click(); + await selectText(page, '[data-entry="p-5"] [data-post-text]', "obody believ"); + await panel.locator("[data-excerpt-add]").click(); + await expect(panel.locator("[data-excerpt-span]")).toHaveCount(2); + await expect(panel.locator('[data-excerpt-span="0"]')).toContainText("“the scale said”"); + await expect(panel.locator('[data-excerpt-span="1"]')).toContainText("“Nobody believes”"); + await page.screenshot({ path: test.info().outputPath("post-excerpt.png") }); + await panel.locator("[data-excerpt-save]").click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("Excerpt saved to the draft: 2 spans"); + expect(item("p-5").excerpt).toEqual(["the scale said", "Nobody believes"]); + await expect(panel.locator("[data-excerpt-piece]")).toHaveCount(2); + + // Removing a span and saving keeps the other; Clear and save reads it whole. + await panel.locator('[data-excerpt-span-remove="1"]').click(); + await panel.locator("[data-excerpt-save]").click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("1 span"); + expect(item("p-5").excerpt).toEqual(["the scale said"]); + expect(takeText()).toBe(take); +}); + +test("media on/off and a video's sound: off keeps the attachment whole (its crop), on puts it back as it was", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + // A crop set on the bench first: the knob off->on must not lose. + let r = await request.post("/api/report/post-item", { data: { project: P, op: "set", id: "p-3", patch: { media: { 0: { crop: [0.1, 0.1, 0.8, 0.8] } } } } }); + expect(r.ok(), await r.text()).toBe(true); + await page.goto(urls.projectHref(P, { tab: "cut" })); + const row = page.locator('[data-entry="p-3"]'); + await row.locator("[data-post-edit]").click(); + const panel = row.locator('[data-inspector="post-item"]'); + await expect(panel.locator('[data-post-media="0"]')).toContainText("3_1.mp4"); + await expect(panel.locator('[data-post-file="posts-media/postchan-x/3/3_2.png"]')).toBeVisible(); + + // Each box is the draft's state: a click asks for the change, the box shows it once it is written. + await panel.locator('[data-post-media="0"] [data-post-media-sound]').click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("Sound off."); + expect(item("p-3").media?.[0]).toMatchObject({ src: "posts-media/postchan-x/3/3_1.mp4", mute: true, crop: [0.1, 0.1, 0.8, 0.8] }); + await expect(panel.locator('[data-post-media="0"] [data-post-media-sound]')).not.toBeChecked(); + + // The picture of the post it never carried, put on. + await panel.locator('[data-post-file="posts-media/postchan-x/3/3_2.png"] [data-post-file-shown]').click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("3_2.png: on the item."); + expect(item("p-3").media?.map((m) => [m.src, m.kind])).toEqual([["posts-media/postchan-x/3/3_1.mp4", "video"], ["posts-media/postchan-x/3/3_2.png", "image"]]); + // A file the item carries already is not added twice. + r = await request.post("/api/report/post-item/inspector", { data: { project: P, op: "media-on", id: "p-3", file: "posts-media/postchan-x/3/3_2.png" } }); + expect(r.status()).toBe(400); + expect((await r.json()).error).toContain("carries posts-media/postchan-x/3/3_2.png already"); + + // The video OFF: out of what plays, kept whole in mediaOff -- its crop, its sound off. + await panel.locator('[data-post-media="0"] [data-post-media-shown]').click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("off (kept as it was set"); + expect(item("p-3").media?.map((m) => m.src)).toEqual(["posts-media/postchan-x/3/3_2.png"]); + expect((item("p-3") as Post & { mediaOff?: Record<string, unknown>[] }).mediaOff).toEqual([ + { src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true, crop: [0.1, 0.1, 0.8, 0.8], mute: true }, + ]); + await expect(panel.locator('[data-post-media-off="0"]')).toContainText("3_1.mp4"); + await expect(panel.locator('[data-post-file="posts-media/postchan-x/3/3_1.mp4"]')).toHaveCount(0); + // ON again: back as it was, crop and all. + await panel.locator('[data-post-media-off="0"] [data-post-media-off-shown]').click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("on again, as it was"); + expect(item("p-3").media?.[1]).toEqual({ src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true, crop: [0.1, 0.1, 0.8, 0.8], mute: true }); + expect("mediaOff" in item("p-3")).toBe(false); + expect(existsSync(path.join(DIR, "posts-media", "postchan-x", "3", "3_1.mp4"))).toBe(true); + expect(takeText()).toBe(take); +}); + +test("Use my recording: a sound file kept as a recorded take of the item and picked", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + expect(item("p-5").narration).toBeUndefined(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + const row = page.locator('[data-entry="p-5"]'); + await row.locator("[data-post-edit]").click(); + const panel = row.locator('[data-inspector="post-item"]'); + await expect(panel.locator("[data-post-takes]")).toContainText("not narrated yet"); + await panel.locator("[data-post-recording-file]").setInputFiles(path.join(HERE, "..", ".e2e-song", "inspector-recording.wav")); + await panel.locator("[data-post-recording-use]").click(); + await expect(panel.locator('[data-post-said="ok"]')).toContainText("Kept as", { timeout: 30_000 }); + const n = item("p-5").narration; + expect(n?.takes).toHaveLength(1); + expect(n?.takes?.[0].file).toMatch(/take-1\.recorded-operator\.wav$/); + expect(existsSync(path.join(DIR, ...String(n?.takes?.[0].file).split("/")))).toBe(true); + await expect(panel.locator("[data-post-takes]")).toContainText("1 take; plays take-1.recorded-operator.wav"); + await page.screenshot({ path: test.info().outputPath("post-recording.png") }); + expect(takeText()).toBe(take); +}); diff --git a/umtool/e2e/inspector-provenance.spec.ts b/umtool/e2e/inspector-provenance.spec.ts @@ -0,0 +1,70 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync, readdirSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { openPanel } from "./panels"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// THE PROVENANCE PANEL (umtool redesign L6, item 1; components/projects/inspector/ProvenanceInspector.tsx): the +// Cut tab's Project panel sets provenance.siteOrigin, channelSlug and channel in the DRAFT -- the owed provenance +// writer (`umtool provenance <p> set` is its twin) -- one undo point, no take touched; a bad origin is refused in +// the writer's words. inspector-provenance-fixture (WRITES): no channelSlug, an old origin. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial", timeout: 120_000 }); + +const P = "reports/inspector-provenance-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-provenance-fixture"); +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const manifest = () => JSON.parse(manifestText()) as { provenance: Record<string, unknown> }; +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); +const undoPoints = (op: string) => readdirSync(path.join(DIR, "revisions")).filter((f) => f.endsWith(`auto-before-${op}.manifest.json`)).length; + +test("set the site origin, channel slug and name from the Cut tab: the draft written, no take", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + expect(manifest().provenance.channelSlug).toBeUndefined(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="provenance"]'); + await expect(panel.locator('[data-provenance-field="siteOrigin"]')).toHaveValue("https://old.example"); + await expect(panel).toContainText("empty: check blocks until it is set"); + await page.screenshot({ path: test.info().outputPath("provenance-panel.png") }); + + // A bad origin: refused, the draft untouched. + const before = manifestText(); + await panel.locator('[data-provenance-field="siteOrigin"]').fill("https://jeralyzer.pages.dev/some/path"); + await panel.locator("[data-provenance-save]").click(); + await expect(panel.locator('[data-provenance-said="refused"]')).toContainText("siteOrigin is the archive's origin, with no path"); + expect(manifestText()).toBe(before); + + await panel.locator('[data-provenance-field="siteOrigin"]').fill("https://jeralyzer.pages.dev/"); + await panel.locator('[data-provenance-field="channelSlug"]').fill("inspchan"); + await panel.locator('[data-provenance-field="channel"]').fill("Inspector Channel"); + await panel.locator("[data-provenance-save]").click(); + await expect(panel.locator('[data-provenance-said="ok"]')).toContainText("Saved to the draft: siteOrigin, channelSlug, channel"); + expect(manifest().provenance).toMatchObject({ siteOrigin: "https://jeralyzer.pages.dev", channelSlug: "inspchan", channel: "Inspector Channel" }); + expect(undoPoints("provenance")).toBe(1); + expect(takeText()).toBe(take); + // The link policy per channel, under it: the cut's clips are now inspchan's. + await expect(panel.locator('[data-provenance-link-policy] [data-link-policy-direct="inspchan"]')).toBeVisible(); + await page.screenshot({ path: test.info().outputPath("provenance-saved.png") }); + + // Clearing a key removes it. + await panel.locator('[data-provenance-field="channel"]').fill(""); + await panel.locator("[data-provenance-save]").click(); + await expect(panel.locator('[data-provenance-said="ok"]')).toContainText("channel"); + expect(manifest().provenance.channel).toBeUndefined(); + expect(takeText()).toBe(take); +}); + +test("one Undo takes the last provenance write back", async ({ request }) => { + const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("provenance"); + expect(manifest().provenance.channel).toBe("Inspector Channel"); +}); diff --git a/umtool/e2e/inspector-rumble-cite.spec.ts b/umtool/e2e/inspector-rumble-cite.spec.ts @@ -0,0 +1,93 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { openPanel } from "./panels"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// THE RUMBLE CITE FIX (umtool redesign L6, item 5; components/projects/inspector/LinksInspector.tsx): the Cut +// tab's Project panel lists each clip citing a Rumble URL-slug FOLDER the archive does not serve, with the embed +// id it does (L1's siteVideoFor, from the folder's metadata), and "Use the published embed id" writes `siteVideo` +// into the draft -- per row, and once for every dead Rumble row; one undo point per press, no network, no take +// touched (`umtool links <p> --embed-ids` is the twin). inspector-rumble-fixture (WRITES): r01 v7slug1 -> v7emb01, +// r02 v7slug2 -> v7emb02 (both dead at the last check), r03 its own id. +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial", timeout: 120_000 }); + +const P = "reports/inspector-rumble-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-rumble-fixture"); +type Clip = { id: string; video: string; siteVideo?: string }; +const clips = () => (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: Clip[] }).timeline; +const sv = () => Object.fromEntries(clips().map((c) => [c.id, c.siteVideo ?? null])); +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +test("one row: Use the published embed id -- siteVideo in the draft, the folder id kept", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="links"]'); + await expect(panel.locator("[data-embed-row]")).toHaveCount(2); + await expect(panel.locator('[data-embed-row="r01"]')).toHaveAttribute("data-embed-state", "dead"); + await expect(panel.locator('[data-embed-row="r01"]')).toContainText("inspectrumble/v7slug1 → v7emb01"); + await expect(panel.locator('[data-embed-row="r03"]')).toHaveCount(0); + await expect(panel.locator("[data-embed-use-all]")).toContainText("for all 2 dead"); + await page.screenshot({ path: test.info().outputPath("rumble-cites.png") }); + + await panel.locator('[data-embed-use="r01"]').click(); + await expect(panel.locator('[data-embed-said="ok"]')).toContainText("r01 → v7emb01"); + expect(sv()).toEqual({ r01: "v7emb01", r02: null, r03: null }); + expect(clips().find((c) => c.id === "r01")?.video).toBe("v7slug1"); + await expect(panel.locator("[data-embed-row]")).toHaveCount(1); + expect(takeText()).toBe(take); + + // A write without the token the panel read is refused, never blind. + const bare = await request.post("/api/report/embed-ids", { data: { project: P, clips: ["r02"] } }); + expect(bare.status()).toBe(400); + expect(sv().r02).toBeNull(); + + // One press, one undo step. + const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("embed-ids"); + expect(sv()).toEqual({ r01: null, r02: null, r03: null }); +}); + +test("every dead Rumble row in one press", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="links"]'); + await expect(panel.locator("[data-embed-row]")).toHaveCount(2); + await panel.locator("[data-embed-use-all]").click(); + await expect(panel.locator('[data-embed-said="ok"]')).toContainText("r01 → v7emb01, r02 → v7emb02"); + expect(sv()).toEqual({ r01: "v7emb01", r02: "v7emb02", r03: null }); + await expect(panel.locator("[data-embed-none]")).toBeVisible(); + expect(takeText()).toBe(take); +}); + +test("a check that found the folder links open: no 'all' press, a row is fixed only by its own", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + // Back to the folder ids, then a check that read both links open. + const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect(sv()).toEqual({ r01: null, r02: null, r03: null }); + const file = path.join(DIR, "out", "links.json"); + const doc = JSON.parse(readFileSync(file, "utf8")) as { links: { state: string; fix?: string; fixSiteVideo?: string; why?: string }[] }; + doc.links = doc.links.map(({ fix: _f, fixSiteVideo: _s, why: _w, ...l }) => ({ ...l, state: "ok" })); + writeFileSync(file, JSON.stringify(doc, null, 2) + "\n"); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="links"]'); + await expect(panel.locator("[data-embed-row]")).toHaveCount(2); + await expect(panel.locator('[data-embed-row="r01"]')).toHaveAttribute("data-embed-state", "ok"); + await expect(panel.locator("[data-embed-no-dead]")).toContainText("no dead links at the last check"); + await expect(panel.locator("[data-embed-use-all]")).toHaveCount(0); + expect(sv()).toEqual({ r01: null, r02: null, r03: null }); +}); diff --git a/umtool/e2e/inspector-still.spec.ts b/umtool/e2e/inspector-still.spec.ts @@ -0,0 +1,52 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync, readdirSync, statSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { openPanel } from "./panels"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// A STILL AT SECOND N (umtool redesign L6, item 6; components/projects/inspector/StillInspector.tsx): Play's Still +// button keeps the frame on screen -- the clip's fetched window at the playhead's source second, one ffmpeg frame -- +// as shots/still-<clip>-<s>s.png, listed on the Cut tab's Project panel; the cut itself is never written +// (`umtool still` is the twin). inspector-still-fixture (WRITES shots/): play-cut-fixture's cut, its window cached. +// --------------------------------------------------------------------------- + +test.describe.configure({ timeout: 120_000 }); + +const P = "reports/inspector-still-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-still-fixture"); +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +test("Still in Play: the frame at the playhead into shots/, listed on the Cut tab, the draft untouched", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const before = manifestText(); + const take = takeText(); + await page.goto(urls.playHref(P, { clip: "c01", at: 0.5 })); + const root = page.locator("[data-play-cut]"); + await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 }); + await expect(page.locator("[data-play-readout]")).toContainText("c01"); + await page.locator("[data-play-still]").click(); + const said = page.locator('[data-play-still-said="ok"]'); + await expect(said).toContainText("shots/still-c01-", { timeout: 20_000 }); + await page.screenshot({ path: test.info().outputPath("play-still.png") }); + const shots = readdirSync(path.join(DIR, "shots")).filter((f) => f.startsWith("still-c01-")); + expect(shots).toHaveLength(1); + expect(statSync(path.join(DIR, "shots", shots[0])).size).toBeGreaterThan(100); + // Its second is the clip's source second (c01 plays 1.0-3.0): inside the clip. + const at = Number(/still-c01-(\d+)_(\d{2})s\.png/.exec(shots[0])?.slice(1, 3).join(".")); + expect(at).toBeGreaterThanOrEqual(1); + expect(at).toBeLessThanOrEqual(3); + expect(manifestText()).toBe(before); + expect(takeText()).toBe(take); + + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="still"]'); + await expect(panel.locator(`[data-shot="shots/${shots[0]}"]`)).toBeVisible(); + await expect(panel.locator(`[data-shot="shots/${shots[0]}"] img`)).toHaveJSProperty("complete", true); +}); diff --git a/umtool/e2e/inspector-teaser-insert.spec.ts b/umtool/e2e/inspector-teaser-insert.spec.ts @@ -0,0 +1,87 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// INSERT A TEASER OR CLOSING CARD (umtool redesign L6, item 2; components/projects/inspector/TeaserInspector.tsx): +// the Cut tab's "Insert a teaser or closing card" -- where, the lines with a break and a hold, the beat -- writes +// a `teaser` entry into the draft (`umtool timeline <p> teaser-insert` is the twin), refused in the build's teaser +// words, its row's Edit changes it after; no take touched. inspector-teaser-fixture (WRITES). +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial", timeout: 120_000 }); + +const P = "reports/inspector-teaser-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-teaser-fixture"); +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const timeline = () => (JSON.parse(manifestText()) as { timeline: Record<string, unknown>[] }).timeline; +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +test("a closing card at the end: its lines, a break and a hold, its beat -- and a bad break refused", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await page.locator("[data-cut-insert-card]").click(); + const panel = page.locator('[data-inspector="teaser"]'); + await expect(panel.locator("[data-teaser-position]")).toHaveValue("end"); + await panel.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]').fill("The 291 scale bet"); + await panel.locator("[data-teaser-add-line]").click(); + const l1 = panel.locator('[data-teaser-line="1"]'); + await l1.locator('[data-teaser-line-field="text"]').fill("Scale video: not posted as of Nov 8"); + // A break that is not the end of its words: the build's rule, said; nothing written. + await l1.locator('[data-teaser-line-field="break"]').fill("not posted"); + const before = manifestText(); + await panel.locator('[data-teaser-insert="insert"]').click(); + await expect(panel.locator('[data-teaser-said="refused"]')).toContainText("break must be the end of its text"); + expect(manifestText()).toBe(before); + + await l1.locator('[data-teaser-line-field="break"]').fill("as of Nov 8"); + await l1.locator('[data-teaser-line-field="hold"]').fill("1.6"); + await panel.locator("[data-teaser-beat]").fill("1.3"); + await page.screenshot({ path: test.info().outputPath("teaser-insert.png") }); + await panel.locator('[data-teaser-insert="insert"]').click(); + await expect(panel.locator('[data-teaser-said="ok"]')).toContainText("Inserted close at 6"); + expect(timeline().at(-1)).toEqual({ type: "teaser", id: "close", lines: ["The 291 scale bet", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 }); + expect(takeText()).toBe(take); + // Its row is in the cut. + await expect(page.locator('[data-entry="close"][data-kind="teaser"]')).toBeVisible(); +}); + +test("a cold open at the start, then its row's Edit changes its beat; Undo takes that edit back", async ({ page, request }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await page.locator("[data-cut-insert-card]").click(); + const panel = page.locator('[data-inspector="teaser"]'); + await panel.locator("[data-teaser-position]").selectOption("start"); + await panel.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]').fill("Cold open"); + await panel.locator('[data-teaser-insert="insert"]').click(); + await expect(panel.locator('[data-teaser-said="ok"]')).toContainText("Inserted cold at 1"); + expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"] }); + + await page.reload(); + const row = page.locator('[data-entry="cold"]'); + await row.locator("[data-teaser-edit]").click(); + const edit = row.locator('[data-inspector="teaser"]'); + await expect(edit.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]')).toHaveValue("Cold open"); + await edit.locator("[data-teaser-beat]").fill("0.9"); + await edit.locator('[data-teaser-insert="set"]').click(); + await expect(edit.locator('[data-teaser-said="ok"]')).toContainText("Saved cold to the draft."); + expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"], beat: 0.9 }); + expect(takeText()).toBe(take); + + // The route wants the token it handed out: a write without one is refused. + const bare = await request.post("/api/report/teaser", { data: { project: P, op: "set", id: "cold", patch: { beat: 1.1 } } }); + expect(bare.status()).toBe(400); + expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"], beat: 0.9 }); + + const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } }); + expect(r.ok(), await r.text()).toBe(true); + expect((await r.json()).op).toBe("teaser"); + expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"] }); +}); diff --git a/umtool/e2e/inspector-title.spec.ts b/umtool/e2e/inspector-title.spec.ts @@ -0,0 +1,49 @@ +import { test, expect as baseExpect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { openPanel } from "./panels"; +import * as urls from "./urls"; + +// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it. +const expect = baseExpect.configure({ timeout: 15_000 }); + +// --------------------------------------------------------------------------- +// THE TITLE PANEL (umtool redesign L6, item 7; 9 Nov: four news projects' title/subtitle set with jq): the Cut +// tab's Project panel writes the manifest's `title` and `subtitle` in the draft (`umtool title` is the twin), +// an empty subtitle removes it, no take touched. inspector-title-fixture (WRITES). +// --------------------------------------------------------------------------- + +test.describe.configure({ timeout: 120_000 }); + +const P = "reports/inspector-title-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-title-fixture"); +const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { title?: string; subtitle?: string }; +const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8"); + +test("retitle the project and drop its subtitle from the Cut tab", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 768 }); + const take = takeText(); + await page.goto(urls.projectHref(P, { tab: "cut" })); + await openPanel(page, "options", "cut-project"); + const panel = page.locator('[data-inspector="title"]'); + await expect(panel.locator('[data-title-field="title"]')).toHaveValue("The Inspector Title Fixture"); + await expect(panel.locator('[data-title-field="subtitle"]')).toHaveValue("an old subtitle"); + await panel.locator('[data-title-field="title"]').fill("Losing the same hundred pounds"); + await panel.locator('[data-title-field="subtitle"]').fill("Every weight he has given on camera"); + await panel.locator("[data-title-save]").click(); + await expect(panel.locator('[data-title-said="ok"]')).toContainText("Saved to the draft."); + expect(manifest()).toMatchObject({ title: "Losing the same hundred pounds", subtitle: "Every weight he has given on camera" }); + // The head follows (the crumb is the title). + await expect(page.locator("body")).toContainText("Losing the same hundred pounds"); + await page.screenshot({ path: test.info().outputPath("title-panel.png") }); + + await panel.locator('[data-title-field="subtitle"]').fill(""); + await panel.locator("[data-title-save]").click(); + await expect(panel.locator('[data-title-said="ok"]')).toBeVisible(); + expect("subtitle" in manifest()).toBe(false); + // An empty title cannot be saved. + await panel.locator('[data-title-field="title"]').fill(" "); + await expect(panel.locator("[data-title-save]")).toBeDisabled(); + expect(takeText()).toBe(take); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -53,8 +53,12 @@ export const GROUPS = [ usage: [ " 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 links <project> --embed-ids [--clips a,b] [--dry-run] [--json] the published Rumble embed id (siteVideo)", + " on every clip citing a URL-slug folder; no network, one write (the Cut tab's Project > Rumble cites)", ], docs: [ + ["`links <project> --embed-ids [--clips a,b] [--dry-run] [--json]`", + "the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], ["`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>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on))"], ], @@ -840,6 +844,38 @@ export const GROUPS = [ ], }, { + cmd: "provenance", + usage: [ + " umtool provenance <project> [ls] | set [--site-origin URL] [--channel-slug S] [--channel \"Name\"] [--json]", + " the project's provenance (where its QRs open, the channel its clips are from); \"\" removes one", + ], + docs: [ + ["`provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel \"…\"] [--json]`", + "the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `\"\"` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], + ], + }, + { + cmd: "title", + usage: [ + " umtool title <project> [\"<title>\"] [--subtitle \"…\" | --no-subtitle] [--json] the project's title and subtitle", + ], + docs: [ + ["`title <project> [\"<title>\"] [--subtitle \"…\" \\| --no-subtitle] [--json]`", + "the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], + ], + }, + { + cmd: "still", + usage: [ + " umtool still <project> <clip> --at <source s> [--take <id>] [--json] | ls a frame of the clip's fetched", + " window into shots/ (Play's Still button)", + ], + docs: [ + ["`still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]`", + "a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], + ], + }, + { cmd: "share", usage: [ " umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform", @@ -863,8 +899,12 @@ export const GROUPS = [ " manifest first (revisions/…-auto-before-<op>), is checked by the build, notes a generated cut", " umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:", " the writes go into its patch (takes/<id>/take.json), each with an undo point of its own", + " umtool timeline <project> teaser-insert [--at start|end | --after <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"]", + " [--hold S] [--line …] | --lines-json <json|@file> a teaser or closing card inserted (default at the end)", ], docs: [ + ["`timeline <project> teaser-insert [--at start\\|end \\| --after <id> \\| --before <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"] [--hold S] [--line …] \\| --lines-json <json\\|@file> [--json]`", + "a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"], ["`timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\\|@file>` · `undo`", "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"], ["`timeline <project> insert (--to-section N \\| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]`", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -95,7 +95,23 @@ export const VERBS = Object.freeze([ ]), form("show", "project", "one project: summary, the cut, per-clip status, decisions", [project()]), form("check", "project", "what blocks a build (exit 1 on anything blocking)", [project({ required: false, help: "one project; none: every project" }), bool("--all-severities", "the info rows too")]), - form("links", "project", "do the clip QRs open on their sites (out/links.json)", [project(), bool("--fix", "rewrite the dead links it knows the fix for")], { timeoutMin: 30 }), + form("links", "project", "do the clip QRs open on their sites (out/links.json)", [ + project(), bool("--fix", "rewrite the dead links it knows the fix for"), + bool("--embed-ids", "no check: every clip citing a Rumble URL-slug folder gets the embed id the archive serves (siteVideo), one write to the draft"), + opt("--clips", { help: "with --embed-ids: a,b (none: every such clip)" }), dry(), + ], { timeoutMin: 30 }), + // The inspector's twins (umtool redesign L6): the project's provenance, its title, a still at second N. + form("provenance ls", "project", "the project's provenance: site origin, channel slug, channel, link policy", [project()], { shape: "provenance <project> ls" }), + form("provenance set", "draft", "the project's site origin, channel slug and channel name (\"\" removes one)", [ + project(), opt("--site-origin", { help: "https://… (the archive its QRs open)" }), opt("--channel-slug", { help: "the channel a clip with no channel is from" }), opt("--channel", { help: "the display name" }), + ], { shape: "provenance <project> set" }), + form("title", "draft", "the project's title and subtitle (no words: print them)", [ + project(), arg("title", { required: false, help: "the new title (none: print them)" }), opt("--subtitle"), bool("--no-subtitle", "remove the subtitle"), + ]), + form("still", "project", "one frame of a clip's fetched window at a source second, into shots/", [ + project(), clip(), num("--at", { required: true, help: "the SOURCE second" }), takeOpt({ help: "a take's (version's) clip" }), + ], { confirm: { what: "write the frame into shots/ (a file, no undo point; a still of the same second is replaced)" } }), + form("still ls", "project", "the pictures in the project's shots/", [project()], { shape: "still <project> ls" }), // ---- the cast ---- form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }), @@ -366,6 +382,11 @@ function timeline() { tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]), tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]), tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]), + tl("teaser-insert", "draft", "a teaser or closing card inserted (default at the end)", [ + pick("--at", ["end", "start"]), opt("--after", { help: "an entry's id: after it" }), opt("--before", { help: "an entry's id: before it" }), opt("--id"), num("--beat"), + many("--line", { repeat: true, help: "its lines, one per line (the first its title)" }), + opt("--lines-json", { type: "json", atFile: true, help: "the lines as JSON, each a string or {text, break?, hold?} (@file: from a terminal)" }), + ]), tl("undo", "draft", "the newest automatic snapshot back", [takeOpt({ help: "a take's own undo" })]), tl("sections", "project", "the deck's sections and their clips", []), tl("section-move", "draft", "clips to the end (or start) of section N", [ids(), num("--to-section", { required: true }), bool("--start")]), diff --git a/umtool/lib/report/embedIds.mjs b/umtool/lib/report/embedIds.mjs @@ -0,0 +1,79 @@ +// THE PUBLISHED EMBED ID, found on this disk (umtool redesign L6, the Links panel's "use the published embed id"; +// owed 4 and 8 Nov: `umtool links` showed 15/15 DEAD on quartering-midterms, a QR naming the Rumble URL-slug folder +// the corpus keeps a recording under while the archive serves its EMBED id). +// +// `embedIdRows` lists every clip of the cut that cites a folder id the archive does not serve -- the id +// shareLine.mjs siteVideoFor (L1's one mapping) reads from the folder's metadata.info.json -- with the QR it draws +// now, the QR it would draw with `siteVideo`, and what the last link check (out/links.json) said of it. No network: +// the check is the `links` command's; this is the fix, which needs only the corpus. `embedIdFixes` is what +// setSiteVideos (inspectorEdits.mjs) writes for the rows asked: `siteVideo`, and a citeUrl that named the folder id +// moved to the embed id (linkCheck.mjs withArchiveId). +// +// Plain ESM: the CLI (`umtool links <p> --embed-ids`) runs it under bare node. +import { archiveLinkOf, linksOf, withArchiveId } from "./linkCheck.mjs"; +import { siteVideoFor } from "./shareLine.mjs"; + +/** + * @typedef {{ clip: string, channel: string | null, video: string, siteVideo: string, url: string | null, fixedUrl: string | null, + * citeUrl: string | null, state: "dead" | "ok" | "unverified" | "direct" | "unchecked" }} EmbedRow + */ + +/** + * The clips whose folder id is not the archive's, read from the project's channels trees (its shadow, then the + * corpus behind it). A clip that pins `siteVideo` already is never looked up. + * + * @param {string} dir the project's directory + * @param {Record<string, any>} manifest + * @param {{ doc?: { links?: Array<{ clip: string, url: string, state: string }> } | null, layers?: string[] | null }} [opts] + * @returns {Promise<EmbedRow[]>} + */ +export async function embedIdRows(dir, manifest, { doc = null, layers = null } = {}) { + let trees = layers; + if (!trees) { + const { channelsLayersFor, hasShadowChannels } = await import("../projects/report.mjs"); + trees = channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) }); + } + const qr = new Map(linksOf(manifest).map((l) => [l.clip, l.url])); + const checked = new Map((doc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l.state])); + /** @type {EmbedRow[]} */ + const rows = []; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip" || e.siteVideo || e.video == null) continue; + const slug = e.channel ?? manifest?.provenance?.channelSlug ?? null; + const video = String(e.video); + let embed = null; + for (const d of trees) { + embed = await siteVideoFor({ channelsDir: d, slug, video }).catch(() => null); + if (embed) break; + } + if (!embed) continue; + const url = qr.get(e.id) ?? null; + const cite = typeof e.citeUrl === "string" && e.citeUrl ? e.citeUrl : null; + const citeNamesFolder = cite ? archiveLinkOf(cite)?.id === video : false; + // The QR after the fix: a citeUrl naming the folder moves to the embed id; a QR built from the moment follows + // `siteVideo` by itself (site-links.mjs archiveMomentUrl). + const fixedUrl = url && archiveLinkOf(url)?.id === video ? withArchiveId(url, video, embed) : url; + rows.push({ + clip: String(e.id), channel: slug, video, siteVideo: embed, url, fixedUrl, + citeUrl: citeNamesFolder ? withArchiveId(cite, video, embed) : null, + state: /** @type {EmbedRow["state"]} */ (url ? checked.get(`${e.id}\u0000${url}`) ?? "unchecked" : "unchecked"), + }); + } + return rows; +} + +/** + * The writes for `clips` (null: every row), as setSiteVideos takes them. A clip named that is not a row is refused. + * @param {EmbedRow[]} rows + * @param {string[] | null} clips + */ +export function embedIdFixes(rows, clips = null) { + const by = new Map(rows.map((r) => [r.clip, r])); + const want = clips ?? rows.map((r) => r.clip); + const missing = want.filter((c) => !by.has(c)); + if (missing.length) throw new Error(`${missing.join(", ")}: no published embed id to use (not a Rumble folder id, or siteVideo is set already)`); + return want.map((c) => { + const r = /** @type {EmbedRow} */ (by.get(c)); + return { clip: r.clip, siteVideo: r.siteVideo, ...(r.citeUrl ? { citeUrl: r.citeUrl } : {}) }; + }); +} diff --git a/umtool/lib/report/excerptPick.mjs b/umtool/lib/report/excerptPick.mjs @@ -0,0 +1,112 @@ +// PICKING A POST ITEM's EXCERPT BY SELECTING ITS WORDS (umtool redesign L6, item 4): a selection in the post's +// text (character offsets into cardText, post-item.mjs) made into the excerpt's span format the build reads -- +// `entry.excerpt`, VERBATIM strings of the post's words in the post's order, each found by indexOf from the end +// of the one before (post-item.mjs excerptRanges). Pure, no imports: the inspector's client component runs it, +// and pnpm test:scripts checks it. + +const isWordChar = (c) => !!c && !/\s/.test(c); + +/** + * A selection snapped OUT to whole words and trimmed of the space at its ends: `[start, end)` in `text`, or null + * when it holds no word. + * @param {string} text + * @param {number} start + * @param {number} end + */ +export function snapToWords(text, start, end) { + let a = Math.max(0, Math.min(start, end)); + let b = Math.min(text.length, Math.max(start, end)); + while (a < b && /\s/.test(text[a])) a += 1; + while (b > a && /\s/.test(text[b - 1])) b -= 1; + if (a >= b) return null; + while (a > 0 && isWordChar(text[a - 1])) a -= 1; + while (b < text.length && isWordChar(text[b])) b += 1; + return { start: a, end: b }; +} + +/** + * The ranges with `r` added, in the post's order, overlapping or touching ranges merged. + * @param {Array<{ start: number, end: number }>} ranges + * @param {{ start: number, end: number }} r + */ +export function addRange(ranges, r) { + const all = [...ranges, r].sort((x, y) => x.start - y.start); + const out = []; + for (const x of all) { + const last = out.at(-1); + if (last && x.start <= last.end) last.end = Math.max(last.end, x.end); + else out.push({ ...x }); + } + return out; +} + +/** + * Where the build will FIND each span (indexOf from the end of the one before): a span whose words occur earlier + * in the post too would be read there, so it is widened a word to the left until it is found where it was + * picked. Returns the ranges (possibly widened) in order. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + */ +export function settleRanges(text, ranges) { + const out = []; + let from = 0; + for (const r0 of ranges) { + let r = { ...r0 }; + // Widen left, a word at a time, until the span is found where it stands (it always is at worst at `from`). + while (text.indexOf(text.slice(r.start, r.end), from) !== r.start && r.start > from) { + // The start of the word before: back over the space, then over its letters. + let a = r.start; + while (a > from && /\s/.test(text[a - 1])) a -= 1; + while (a > from && isWordChar(text[a - 1])) a -= 1; + if (a === r.start) break; + r = { start: a, end: r.end }; + } + const last = out.at(-1); + if (last && r.start <= last.end) last.end = Math.max(last.end, r.end); + else out.push(r); + from = r.end; + } + return out; +} + +/** + * The excerpt (the strings) the ranges spell. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + * @returns {string[]} + */ +export const spansOf = (text, ranges) => ranges.map((r) => text.slice(r.start, r.end)); + +/** + * The ranges an excerpt stands at (post-item.mjs excerptRanges' rule), or null when a span is not found. + * @param {string} text + * @param {string[]} spans + */ +export function rangesOf(text, spans) { + const out = []; + let from = 0; + for (const sp of spans) { + const at = text.indexOf(sp, from); + if (at < 0) return null; + out.push({ start: at, end: at + sp.length }); + from = at + sp.length; + } + return out; +} + +/** + * The text cut into pieces for drawing: each `{ text, start, end, picked }`, a picked piece one range. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + */ +export function piecesOf(text, ranges) { + const out = []; + let at = 0; + for (const r of ranges) { + if (r.start > at) out.push({ text: text.slice(at, r.start), start: at, end: r.start, picked: false }); + out.push({ text: text.slice(r.start, r.end), start: r.start, end: r.end, picked: true }); + at = r.end; + } + if (at < text.length) out.push({ text: text.slice(at), start: at, end: text.length, picked: false }); + return out; +} diff --git a/umtool/lib/report/excerptPick.test.mjs b/umtool/lib/report/excerptPick.test.mjs @@ -0,0 +1,43 @@ +// Picking a post item's excerpt by selecting its words (excerptPick.mjs): snapped to words, merged, settled +// where the build's indexOf will find each span. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "./excerptPick.mjs"; +import { excerptRanges } from "umtool-report-to-video/post-item"; + +const T = "The scale said 291. I said the scale was broken. Then the scale said 290."; + +test("a selection snaps out to whole words, trimmed", () => { + const r = snapToWords(T, T.indexOf("cale said 2"), T.indexOf("291") + 2); + assert.deepEqual(spansOf(T, [r]), ["scale said 291."]); + assert.equal(snapToWords(T, 3, 4), null); + assert.deepEqual(snapToWords(T, 0, 1), { start: 0, end: 3 }); +}); + +test("ranges merge in the post's order", () => { + let rs = addRange([], { start: 20, end: 30 }); + rs = addRange(rs, { start: 0, end: 5 }); + rs = addRange(rs, { start: 28, end: 40 }); + assert.deepEqual(rs, [{ start: 0, end: 5 }, { start: 20, end: 40 }]); +}); + +test("a span whose words come earlier too is widened until the build finds it where it was picked", () => { + const W = "scale said"; + const second = T.lastIndexOf(W); + assert.ok(T.indexOf(W) < second); + const picked = [{ start: second, end: second + W.length }]; + const settled = settleRanges(T, picked); + const spans = spansOf(T, settled); + assert.deepEqual(excerptRanges(T, spans).map((r) => r.end), [second + W.length]); + assert.deepEqual(spans, ["the scale said"]); + // Two spans: the second found after the first. + const two = settleRanges(T, [{ start: 0, end: 9 }, picked[0]]); + assert.deepEqual(excerptRanges(T, spansOf(T, two)), two); + assert.deepEqual(rangesOf(T, spansOf(T, two)), two); +}); + +test("the pieces cover the text, the picked ones marked", () => { + const p = piecesOf(T, [{ start: 4, end: 9 }]); + assert.equal(p.map((x) => x.text).join(""), T); + assert.deepEqual(p.filter((x) => x.picked).map((x) => x.text), ["scale"]); +}); diff --git a/umtool/lib/report/inspectorCli.mjs b/umtool/lib/report/inspectorCli.mjs @@ -0,0 +1,309 @@ +// The inspector's CLI twins (umtool redesign L6; every knob the UI sets has one, docs/knobs.md): +// +// umtool provenance <project> [ls] [--json] +// umtool provenance <project> set [--site-origin URL|""] [--channel-slug SLUG|""] [--channel "Name"|""] [--json] +// umtool title <project> ["<title>"] [--subtitle "…" | --no-subtitle] [--json] +// umtool still <project> <clip> --at <source s> [--take <take>] [--json] | umtool still <project> ls [--json] +// umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S] +// --line "<text>" [--break "<words>"] [--hold S] [--line …] | --lines-json <json|@file> [--json] +// umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json] +// +// Each the same writer as its inspector panel (inspectorEdits.mjs, stillGrab.mjs): the draft written, one undo +// point per write (`umtool timeline <p> undo` takes it back). Exit 0 done, 1 refused, 2 a usage error. +// Plain ESM: the CLI runs it under bare node. +import { readFile } from "node:fs/promises"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { StaleToken, StructureRefused, manifestToken } from "./manifest.mjs"; +import { insertTeaser, provenanceView, setSiteVideos, updateProvenance, updateTitle } from "./inspectorEdits.mjs"; + +class CliError extends Error {} + +export const PROVENANCE_USAGE = [ + "usage: umtool provenance <project> [ls] [--json]", + " umtool provenance <project> set [--site-origin <https://…>] [--channel-slug <slug>] [--channel \"<name>\"] [--json]", + " THE PROJECT'S PROVENANCE: provenance.siteOrigin (the archive its QRs open), provenance.channelSlug (the channel a", + " clip with no `channel` is from -- `check` blocks without it), provenance.channel (the sweep's display name). An", + " empty value removes a key. One write, one undo point. The link policy: umtool link-policy <p>.", +].join("\n"); + +export const TITLE_USAGE = [ + "usage: umtool title <project> [\"<title>\"] [--subtitle \"<line>\" | --no-subtitle] [--json]", + " the project's TITLE and SUBTITLE (the manifest's `title` / `subtitle`: the head, the intro's title card, the", + " posting artifacts). With no words, prints them. One write, one undo point.", +].join("\n"); + +export const STILL_USAGE = [ + "usage: umtool still <project> <clip> --at <source seconds> [--take <take>] [--json]", + " umtool still <project> ls [--json]", + " A STILL AT SECOND N: one frame of the clip's fetched window at that SOURCE second (the second Play's Still", + " button reads off the playhead), saved as shots/still-<clip>-<s>s.png beside the project's other shots; nothing", + " fetched (a second no fetched window holds is refused). ls: the project's shots/, newest first.", +].join("\n"); + +export const TEASER_INSERT_USAGE = [ + "usage: umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]", + " --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json '<json>'|@file [--json]", + " A TEASER OR CLOSING CARD inserted (type teaser): the first line its title, each --line the next, a --break / --hold", + " after a --line that line's; default at the end (id \"close\"; at the start \"cold\"). Checked by the build's teaser", + " rules; one write, one undo point.", +].join("\n"); + +async function projectOf(arg, root) { + if (!arg) throw new CliError("which project?"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + return r.project; +} + +/** Words, and `--key value` / `--key=value` flags (the booleans named), in order (a repeated flag kept each time). */ +function parse(args, booleans = []) { + const words = []; + /** @type {Array<[string, string | true]>} */ + const seq = []; + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (!a.startsWith("--")) { + words.push(a); + continue; + } + const eq = a.indexOf("="); + if (eq > 0) seq.push([a.slice(2, eq), a.slice(eq + 1)]); + else if (booleans.includes(a.slice(2))) seq.push([a.slice(2), true]); + else { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + seq.push([a.slice(2), args[i + 1]]); + i += 1; + } + } + const flags = new Map(seq); + return { words, flags, seq }; +} + +/** The exit code for a writer's refusal, said on stderr. */ +function refused(err, who, e) { + if (e instanceof StructureRefused) err(`umtool ${who}: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`); + else if (e instanceof StaleToken) err(`umtool ${who}: ${e.message} — somebody else wrote it; run it again`); + else err(`umtool ${who}: ${e instanceof Error ? e.message : String(e)}`); + return e instanceof CliError ? 2 : 1; +} + +const undoLine = (r) => (r?.snapshot?.rel && !r.snapshot.skipped ? ` undo point: ${r.snapshot.rel}` : null); +const write = (project, fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir))); + +/** `umtool provenance`. */ +export async function provenanceCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { words, flags } = parse(args, ["json", "help"]); + const [projectArg, verb = "ls"] = words; + if (!projectArg || flags.has("help")) { + err(PROVENANCE_USAGE); + return 2; + } + const json = flags.get("json") === true; + const project = await projectOf(projectArg, root); + if (verb === "ls") { + const m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const view = { ...provenanceView(m), linkPolicy: m.provenance?.linkPolicy ?? null }; + if (json) out(JSON.stringify({ project: project.id, provenance: view, token: await manifestToken(project.dir) }, null, 2)); + else for (const [k, v] of Object.entries(view)) out(`${k.padEnd(12)} ${v === null ? "—" : typeof v === "string" ? v : JSON.stringify(v)}`); + return 0; + } + if (verb !== "set") throw new CliError(`unknown: provenance ${verb} — ls or set`); + /** @type {Record<string, string>} */ + const keys = { "--site-origin": "siteOrigin", "--channel-slug": "channelSlug", "--channel": "channel" }; + const patch = {}; + for (const [f, v] of flags) { + if (f === "json") continue; + if (!(`--${f}` in keys)) throw new CliError(`unknown flag --${f} (--site-origin, --channel-slug, --channel)`); + patch[keys[`--${f}`]] = v === true ? "" : v; + } + if (!Object.keys(patch).length) throw new CliError("set needs --site-origin, --channel-slug or --channel"); + const { result } = await write(project, (token) => updateProvenance(project.dir, patch, { token })); + if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2)); + else { + const changed = Object.entries(result.changed); + out(changed.length ? changed.map(([k, [a, b]]) => `${k}: ${a ?? "—"} -> ${b ?? "—"}`).join("\n") : "unchanged"); + const u = undoLine(result); + if (u) out(u); + } + return 0; + } catch (e) { + return refused(err, "provenance", e); + } +} + +/** `umtool title`. */ +export async function titleCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { words, flags } = parse(args, ["json", "help", "no-subtitle"]); + const [projectArg, ...rest] = words; + if (!projectArg || flags.has("help")) { + err(TITLE_USAGE); + return 2; + } + for (const f of flags.keys()) if (!["json", "subtitle", "no-subtitle"].includes(f)) throw new CliError(`unknown flag --${f}`); + const json = flags.get("json") === true; + const project = await projectOf(projectArg, root); + const patch = {}; + if (rest.length) patch.title = rest.join(" "); + const SUBTITLE = "--subtitle"; + if (flags.has(SUBTITLE.slice(2))) patch.subtitle = String(flags.get(SUBTITLE.slice(2))); + if (flags.has("no-subtitle")) patch.subtitle = null; + if (!Object.keys(patch).length) { + const m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const view = { title: m.title ?? null, subtitle: typeof m.subtitle === "string" ? m.subtitle : null }; + if (json) out(JSON.stringify({ project: project.id, ...view, token: await manifestToken(project.dir) }, null, 2)); + else out(`${view.title ?? "—"}${view.subtitle ? `\n ${view.subtitle}` : ""}`); + return 0; + } + const { result } = await write(project, (token) => updateTitle(project.dir, patch, { token })); + if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2)); + else { + out(`title: ${result.title}${result.subtitle ? `\nsubtitle: ${result.subtitle}` : "\nsubtitle: —"}`); + const u = undoLine(result); + if (u) out(u); + } + return 0; + } catch (e) { + return refused(err, "title", e); + } +} + +/** `umtool still`. */ +export async function stillCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { words, flags } = parse(args, ["json", "help"]); + const [projectArg, clip] = words; + if (!projectArg || !clip || flags.has("help")) { + err(STILL_USAGE); + return 2; + } + for (const f of flags.keys()) if (!["json", "at", "take"].includes(f)) throw new CliError(`unknown flag --${f}`); + const json = flags.get("json") === true; + const project = await projectOf(projectArg, root); + const { grabStill, listShots } = await import("./stillGrab.mjs"); + if (clip === "ls") { + const shots = await listShots(project.dir); + if (json) out(JSON.stringify({ project: project.id, shots }, null, 2)); + else { + for (const s of shots) out(`${s.rel} ${s.still ? `${s.still.clip} @ ${s.still.at} s` : ""} ${s.mtime.slice(0, 16).replace("T", " ")}`); + out(`${shots.length} picture(s) in shots/`); + } + return 0; + } + if (!flags.has("at")) throw new CliError("--at <source seconds> is the second to grab"); + const take = flags.has("take") ? String(flags.get("take")) : null; + let m = take ? (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const r = await grabStill(project, m, clip, Number(flags.get("at"))); + if (json) out(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2)); + else out(`${r.rel} (${r.clip} @ ${r.at} s of ${r.video}, ${r.bytes} bytes)`); + return 0; + } catch (e) { + return refused(err, "still", e); + } +} + +/** A `--lines-json` value: JSON, or `@file` of it. */ +async function jsonArg(v) { + const text = String(v).startsWith("@") ? await readFile(String(v).slice(1), "utf8") : String(v); + try { + return JSON.parse(text); + } catch (e) { + throw new CliError(`--lines-json is not JSON: ${e instanceof Error ? e.message : e}`); + } +} + +/** The flags teaser-insert reads besides --line / --break / --hold (lib/cli/verbs.mjs's form names them). */ +const TEASER_INSERT_FLAGS = ["--json", "--at", "--after", "--before", "--id", "--beat", "--lines-json"]; + +/** `umtool timeline <p> teaser-insert …` (timelineCli.mjs hands it the words after the verb). */ +export async function teaserInsertVerb(project, args, { out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { flags, seq, words } = parse(args, ["json", "help"]); + if (flags.has("help")) { + err(TEASER_INSERT_USAGE); + return 2; + } + if (words.length) throw new CliError(`teaser-insert takes flags, not ${words.join(" ")} (--line "…")`); + const json = flags.get("json") === true; + /** @type {Array<string | Record<string, unknown>>} */ + let lines = []; + for (const [k, v] of seq) { + if (k === "line") lines.push({ text: String(v) }); + else if (k === "break" || k === "hold") { + const last = lines.at(-1); + if (!last || typeof last === "string") throw new CliError(`--${k} goes after the --line it belongs to`); + last[k] = k === "hold" ? Number(v) : String(v); + } else if (!TEASER_INSERT_FLAGS.includes(`--${k}`)) throw new CliError(`unknown flag --${k}`); + } + if (flags.has("lines-json")) { + if (lines.length) throw new CliError("--lines-json or --line, not both"); + const j = await jsonArg(flags.get("lines-json")); + if (!Array.isArray(j)) throw new CliError("--lines-json is a list of lines"); + lines = j; + } + lines = lines.map((l) => (typeof l === "object" && l && Object.keys(l).length === 1 && "text" in l ? String(l.text) : l)); + const at = flags.get("at"); + const position = flags.has("after") ? { after: String(flags.get("after")) } : flags.has("before") ? { before: String(flags.get("before")) } : at === "start" ? "start" : at === undefined || at === "end" ? "end" : null; + if (position === null) throw new CliError("--at is start or end (--after <id> / --before <id> for elsewhere)"); + const spec = { lines, ...(flags.has("id") ? { id: String(flags.get("id")) } : {}), ...(flags.has("beat") ? { beat: Number(flags.get("beat")) } : {}) }; + const { result } = await write(project, (token) => insertTeaser(project.dir, spec, position, { token })); + if (json) out(JSON.stringify({ ok: true, project: project.id, op: "teaser-insert", inserted: { id: result.id, at: result.at, entry: result.entry }, token: result.token }, null, 2)); + else { + out(`inserted teaser ${result.id} at ${result.at}: ${JSON.stringify(result.entry.lines)}`); + const u = undoLine(result); + if (u) out(u); + } + return 0; + } catch (e) { + return refused(err, "timeline teaser-insert", e); + } +} + +/** `umtool links <p> --embed-ids [--clips a,b] [--dry-run] [--json]` (linksCli.mjs hands it over). */ +export async function embedIdsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + try { + const { words, flags } = parse(args, ["json", "help", "dry-run"]); + if (!words[0] || flags.has("help")) { + err("usage: umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]\n every clip citing a Rumble URL-slug folder the archive does not serve gets the EMBED id it serves (siteVideo),\n read from the folder's metadata.info.json; a citeUrl naming the folder moves with it. No network; one write."); + return 2; + } + for (const f of flags.keys()) if (!["json", "clips", "dry-run"].includes(f)) throw new CliError(`unknown flag --${f}`); + const json = flags.get("json") === true; + const project = await projectOf(words[0], root); + const m = await readManifest(project.dir); + if (!m) throw new CliError(`${project.id} has no video.manifest.json`); + const { embedIdFixes, embedIdRows } = await import("./embedIds.mjs"); + const { readLinkCheck } = await import("./linkCheck.mjs"); + const rows = await embedIdRows(project.dir, m, { doc: await readLinkCheck(project.dir) }); + const clips = flags.has("clips") ? String(flags.get("clips")).split(",").map((s) => s.trim()).filter(Boolean) : null; + if (!rows.length && !clips) { + if (json) out(JSON.stringify({ ok: true, project: project.id, rows: [], fixed: [] }, null, 2)); + else out("no clip cites a folder id the archive does not serve"); + return 0; + } + const fixes = embedIdFixes(rows, clips); + if (flags.has("dry-run")) { + if (json) out(JSON.stringify({ ok: true, project: project.id, rows, would: fixes }, null, 2)); + else for (const f of fixes) out(`would: ${f.clip} siteVideo ${f.siteVideo}${f.citeUrl ? ` citeUrl ${f.citeUrl}` : ""}`); + return 0; + } + const { result } = await write(project, (token) => setSiteVideos(project.dir, fixes, { token })); + if (json) out(JSON.stringify({ ok: true, project: project.id, rows, fixed: result.fixed, token: result.token }, null, 2)); + else { + for (const f of result.fixed) out(`fixed ${f.clip}: ${f.video} -> siteVideo ${f.siteVideo} (the Rumble embed id)${f.citeUrl ? `, citeUrl ${f.citeUrl}` : ""}`); + out(" `umtool links <p>` checks them against the site"); + const u = undoLine(result); + if (u) out(u); + } + return 0; + } catch (e) { + return refused(err, "links --embed-ids", e); + } +} diff --git a/umtool/lib/report/inspectorEdits.mjs b/umtool/lib/report/inspectorEdits.mjs @@ -0,0 +1,284 @@ +// THE INSPECTOR'S WRITERS (umtool redesign L6, "inspector panels for this week's hand edits"): what agents did by +// hand this week, each now one write the UI and its CLI twin share -- the project's provenance (siteOrigin, +// channelSlug, channel), its title and subtitle, a teaser or closing card inserted, and the published Rumble embed +// ids (`siteVideo`) written onto the clips that cite a URL-slug folder. +// +// Every one lands in the WORKING DRAFT (video.manifest.json; L3: never a take's patch) through manifest.mjs's +// structural door (`structuralEdit`): the mtime token, the read inside the lock, the build's own checks, an undo +// point `auto-before-<op>` (every op its own in the app -- the Cut tab's Undo takes exactly it back), the atomic +// write. The checks of a value are pure and exported, so the route and the CLI refuse in the same words. +// +// Plain ESM: the CLI runs it under bare node. +import { StructureRefused, entryIndex, freshEntryId, patchClipEntry, structuralEdit } from "./manifest.mjs"; +import { TEASER_BEAT, TEASER_LIMITS, validateTeaser } from "umtool-report-to-video/deck"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const round2 = (n) => Math.round(n * 100) / 100; + +// --------------------------------------------------------------------------- +// PROVENANCE: where the cut's clips come from and where its QRs open. +// --------------------------------------------------------------------------- + +/** The provenance keys the inspector writes (the link policy has its own writer, updateLinkPolicy). */ +export const PROVENANCE_EDIT_KEYS = Object.freeze(["siteOrigin", "channelSlug", "channel"]); +const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const CHANNEL_NAME_MAX = 120; + +/** + * A provenance patch checked and normalised: each key a string to set, or null / "" to remove it. siteOrigin is + * an http(s) origin (a path, query or hash refused; the trailing slash dropped), channelSlug a corpus slug, + * channel the sweep's display name (one line). Throws a sentence naming every problem. + * + * @param {unknown} patch + * @returns {Record<string, string | null>} + */ +export function provenancePatchOf(patch) { + if (!isObj(patch)) throw new Error("a provenance patch is an object: { siteOrigin?, channelSlug?, channel? }"); + const errors = []; + const out = {}; + for (const k of Object.keys(patch)) { + if (!PROVENANCE_EDIT_KEYS.includes(k)) errors.push(`${k} is not a provenance key this writer sets (${PROVENANCE_EDIT_KEYS.join(", ")}; the link policy: umtool link-policy)`); + } + for (const k of PROVENANCE_EDIT_KEYS) { + if (!(k in patch)) continue; + const raw = patch[k]; + if (raw === null || raw === undefined || (typeof raw === "string" && !raw.trim())) { + out[k] = null; + continue; + } + if (typeof raw !== "string") { + errors.push(`${k} must be text`); + continue; + } + const v = raw.trim(); + if (k === "siteOrigin") { + let u = null; + try { + u = new URL(v); + } catch { + /* below */ + } + if (!u || (u.protocol !== "http:" && u.protocol !== "https:")) errors.push(`siteOrigin must be an http:// or https:// address (got \`${v}\`)`); + else if ((u.pathname && u.pathname !== "/") || u.search || u.hash) errors.push(`siteOrigin is the archive's origin, with no path (\`${u.origin}\`, not \`${v}\`)`); + else out[k] = u.origin; + } else if (k === "channelSlug") { + if (!SLUG_RE.test(v)) errors.push(`channelSlug must be a channel's slug (letters, digits, . _ -), not \`${v}\``); + else out[k] = v; + } else { + if (/[\r\n]/.test(v)) errors.push("channel must be one line"); + else if (v.length > CHANNEL_NAME_MAX) errors.push(`channel is ${v.length} characters (at most ${CHANNEL_NAME_MAX})`); + else out[k] = v; + } + } + if (errors.length) throw new Error(errors.join("; ")); + if (!Object.keys(out).length) throw new Error("nothing to change"); + return out; +} + +/** The patch applied to a manifest in memory; returns what changed (`{ key: [from, to] }`). */ +export function applyProvenancePatch(m, patch) { + const p = provenancePatchOf(patch); + const prov = isObj(m.provenance) ? m.provenance : {}; + const changed = {}; + for (const [k, v] of Object.entries(p)) { + const was = typeof prov[k] === "string" ? prov[k] : null; + if (v === null) delete prov[k]; + else prov[k] = v; + if (was !== v) changed[k] = [was, v]; + } + m.provenance = prov; + return changed; +} + +/** What the inspector reads: the three keys as written (null when absent). */ +export const provenanceView = (m) => + Object.fromEntries(PROVENANCE_EDIT_KEYS.map((k) => [k, typeof m?.provenance?.[k] === "string" && m.provenance[k] ? m.provenance[k] : null])); + +/** + * Set the project's provenance keys (one write, one undo point `auto-before-provenance`). + * + * @param {string} dir + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updateProvenance(dir, patch, { token = null } = {}) { + provenancePatchOf(patch); // refused before the lock is taken + return structuralEdit(dir, "provenance", token, (m) => { + const changed = applyProvenancePatch(m, patch); + return { provenance: provenanceView(m), changed }; + }); +} + +// --------------------------------------------------------------------------- +// THE TITLE AND SUBTITLE (9 Nov: four news projects' title/subtitle were set with jq -- no verb existed). +// --------------------------------------------------------------------------- + +export const TITLE_MAX = 200; +export const SUBTITLE_MAX = 300; + +/** + * A title patch checked: `title` one line, not empty, at most TITLE_MAX; `subtitle` one line at most SUBTITLE_MAX, + * null or "" removes it. A key not given is kept. + * + * @param {unknown} patch + * @returns {{ title?: string, subtitle?: string | null }} + */ +export function titlePatchOf(patch) { + if (!isObj(patch)) throw new Error("a title patch is an object: { title?, subtitle? }"); + const errors = []; + const out = {}; + for (const k of Object.keys(patch)) if (k !== "title" && k !== "subtitle") errors.push(`${k} is not title or subtitle`); + if ("title" in patch) { + const v = typeof patch.title === "string" ? patch.title.trim() : null; + if (!v) errors.push("title must be words (a project always has one)"); + else if (/[\r\n]/.test(v)) errors.push("title must be one line"); + else if (v.length > TITLE_MAX) errors.push(`title is ${v.length} characters (at most ${TITLE_MAX})`); + else out.title = v; + } + if ("subtitle" in patch) { + const raw = patch.subtitle; + if (raw === null || raw === undefined || (typeof raw === "string" && !raw.trim())) out.subtitle = null; + else if (typeof raw !== "string") errors.push("subtitle must be text"); + else if (/[\r\n]/.test(raw.trim())) errors.push("subtitle must be one line"); + else if (raw.trim().length > SUBTITLE_MAX) errors.push(`subtitle is ${raw.trim().length} characters (at most ${SUBTITLE_MAX})`); + else out.subtitle = raw.trim(); + } + if (errors.length) throw new Error(errors.join("; ")); + if (!Object.keys(out).length) throw new Error("nothing to change: give a title, a subtitle, or both"); + return out; +} + +/** + * Set the project's title and/or subtitle (one write, one undo point `auto-before-title`). + * + * @param {string} dir + * @param {{ title?: unknown, subtitle?: unknown }} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updateTitle(dir, patch, { token = null } = {}) { + const p = titlePatchOf(patch); + return structuralEdit(dir, "title", token, (m) => { + if (p.title !== undefined) m.title = p.title; + if (p.subtitle === null) delete m.subtitle; + else if (p.subtitle !== undefined) m.subtitle = p.subtitle; + return { title: m.title ?? null, subtitle: typeof m.subtitle === "string" ? m.subtitle : null }; + }); +} + +// --------------------------------------------------------------------------- +// A TEASER OR CLOSING CARD INSERTED (a "cold" open, a "close" at the end): `{type: "teaser", id, lines, beat?}`, +// checked by the build's validateTeaser before it is written. +// --------------------------------------------------------------------------- + +/** The teaser line keys the inspector writes (the rest -- role, lead, replace, together -- through `timeline teaser`). */ +export const TEASER_INSERT_LINE_KEYS = Object.freeze(["text", "break", "hold", "replace", "together", "role", "lead"]); + +/** + * One line as written: a string when it is only its text, else `{ text, break?, hold?, … }` with empty keys left out. + * @param {unknown} l + */ +export function teaserLineOf(l) { + if (typeof l === "string") return l.trim(); + if (!isObj(l)) throw new Error("a teaser line is its words, or { text, break?, hold? }"); + const out = {}; + for (const k of Object.keys(l)) if (!TEASER_INSERT_LINE_KEYS.includes(k)) throw new Error(`${k} is not a teaser line key (${TEASER_INSERT_LINE_KEYS.join(", ")})`); + out.text = typeof l.text === "string" ? l.text.trim() : l.text; + if (typeof l.break === "string" && l.break.trim()) out.break = l.break.trim(); + if (l.hold !== undefined && l.hold !== null && l.hold !== "") out.hold = round2(Number(l.hold)); + for (const k of ["replace", "together"]) if (l[k] === true) out[k] = true; + if (typeof l.role === "string" && l.role) out.role = l.role; + if (typeof l.lead === "string" && l.lead.trim()) out.lead = l.lead.trim(); + return Object.keys(out).length === 1 ? out.text : out; +} + +/** + * Where an insert lands, as an index of the timeline BEFORE the insert: "start" (0), "end" (its length), + * `{ after: <id> }` or `{ before: <id> }` (an id the timeline holds once; `at` names it when it repeats). + * + * @param {Array<Record<string, unknown>>} timeline + * @param {unknown} position + */ +export function insertIndexOf(timeline, position) { + if (position === "start" || position === 0) return 0; + if (position === "end" || position === undefined || position === null) return timeline.length; + if (isObj(position) && typeof position.after === "string") return entryIndex(timeline, position.after, position.at ?? null) + 1; + if (isObj(position) && typeof position.before === "string") return entryIndex(timeline, position.before, position.at ?? null); + throw new Error('a position is "start", "end", { after: <id> } or { before: <id> }'); +} + +/** + * The teaser entry a spec makes, its id fresh in the timeline (the spec's, else "close" at the end / "cold" at + * the start / "teaser"), checked by the build's validateTeaser (throws StructureRefused with its sentences). + * + * @param {Array<Record<string, unknown>>} timeline + * @param {{ id?: unknown, lines?: unknown, beat?: unknown }} spec + * @param {number} index where it will be inserted (names the default id) + */ +export function teaserEntryOf(timeline, spec, index) { + if (!isObj(spec)) throw new Error("a teaser is { id?, lines: [...], beat? }"); + const lines = Array.isArray(spec.lines) ? spec.lines.map(teaserLineOf).filter((l) => (typeof l === "string" ? l : l.text)) : null; + if (!lines || !lines.length) throw new StructureRefused([`a teaser needs ${TEASER_LIMITS.lines[0]} to ${TEASER_LIMITS.lines[1]} lines (the first is its title)`]); + const base = typeof spec.id === "string" && spec.id.trim() ? spec.id.trim() : index === 0 ? "cold" : index >= timeline.length ? "close" : "teaser"; + if (!/^[A-Za-z0-9_-]{1,64}$/.test(base)) throw new StructureRefused([`id must be letters, digits, dashes or underscores (got \`${base}\`)`]); + if (typeof spec.id === "string" && spec.id.trim() && timeline.some((e) => e?.id === base)) { + throw new StructureRefused([`the cut already has an entry ${base}: name the card something else`]); + } + const entry = { type: "teaser", id: freshEntryId(timeline, base), lines }; + if (spec.beat !== undefined && spec.beat !== null && spec.beat !== "") { + const b = Number(spec.beat); + entry.beat = Number.isFinite(b) ? round2(b) : spec.beat; + } + const errors = validateTeaser(entry, `the new teaser ${entry.id}`); + if (errors.length) throw new StructureRefused(errors); + return entry; +} + +/** + * INSERT A TEASER OR CLOSING CARD (`umtool timeline <p> teaser-insert`, the inspector's Insert a card): one + * structural write, one undo point `auto-before-teaser-insert`. + * + * @param {string} dir + * @param {{ id?: unknown, lines?: unknown, beat?: unknown }} spec + * @param {unknown} position "start" | "end" | { after } | { before } + * @param {{ token?: string | null }} [opts] + */ +export async function insertTeaser(dir, spec, position, { token = null } = {}) { + return structuralEdit(dir, "teaser-insert", token, (m) => { + const i = insertIndexOf(m.timeline, position); + const entry = teaserEntryOf(m.timeline, spec, i); + m.timeline.splice(i, 0, entry); + return { id: entry.id, at: i, entry }; + }); +} + +/** The teaser's limits, for a form's hints (the build's numbers). */ +export const teaserLimits = () => ({ lines: [...TEASER_LIMITS.lines], rows: TEASER_LIMITS.rows, chars: TEASER_LIMITS.chars, hold: TEASER_LIMITS.hold, beat: { ...TEASER_BEAT } }); + +// --------------------------------------------------------------------------- +// THE PUBLISHED EMBED ID (a Rumble clip whose `video` is the URL-slug folder the corpus keeps it under, while the +// archive serves the EMBED id: shareLine.mjs siteVideoFor). `siteVideo` written on each, a citeUrl that named the +// folder id moved with it -- every clip in ONE write, one undo point `auto-before-embed-ids`. +// --------------------------------------------------------------------------- + +/** + * @param {string} dir + * @param {Array<{ clip: string, siteVideo: string, citeUrl?: string | null }>} fixes + * @param {{ token?: string | null }} [opts] + */ +export async function setSiteVideos(dir, fixes, { token = null } = {}) { + if (!Array.isArray(fixes) || !fixes.length) throw new Error("nothing to fix"); + for (const f of fixes) { + if (!isObj(f) || typeof f.clip !== "string" || typeof f.siteVideo !== "string" || !f.siteVideo) throw new Error("a fix is { clip, siteVideo, citeUrl? }"); + } + return structuralEdit(dir, "embed-ids", token, (m) => { + const done = []; + for (const f of fixes) { + const e = m.timeline[entryIndex(m.timeline, f.clip)]; + if (e?.type !== "clip") throw new Error(`${f.clip} is not a clip`); + const patch = { siteVideo: f.siteVideo, ...(typeof f.citeUrl === "string" && f.citeUrl ? { citeUrl: f.citeUrl } : {}) }; + const { entry } = patchClipEntry(m, f.clip, patch); + done.push({ clip: f.clip, video: String(entry.video), siteVideo: entry.siteVideo, ...(patch.citeUrl ? { citeUrl: entry.citeUrl } : {}) }); + } + return { fixed: done }; + }); +} diff --git a/umtool/lib/report/inspectorEdits.test.mjs b/umtool/lib/report/inspectorEdits.test.mjs @@ -0,0 +1,279 @@ +// The inspector's writers (umtool redesign L6): provenance, title, a teaser inserted, the published embed ids, the +// ledger's undo points, and a still grabbed from a fetched window -- each one write to the draft with its own +// undo point, refused in the build's words. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-inspector-")); +process.env.REPORTS_DIR = path.join(ROOT, "reports"); +process.env.CHANNELS_DIR = path.join(ROOT, "channels"); +process.env.CHANNELS_FALLBACK = "1"; +const ed = await import("./inspectorEdits.mjs"); +const { embedIdFixes, embedIdRows } = await import("./embedIds.mjs"); +const { grabStill, listShots, shotFileOf, stillNameOf } = await import("./stillGrab.mjs"); +const { addLedgerRow, manifestToken, setUndoEveryMs, undoStructural, StaleToken, StructureRefused } = await import("./manifest.mjs"); +// The app's rule (instrumentation.ts): every op its own undo point. +setUndoEveryMs(0); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const MANIFEST = () => ({ + schemaVersion: 1, + slug: "insp", + title: "The Inspector", + provenance: { siteOrigin: "https://old.example", channelSlug: "chan" }, + render: { fps: 30, transition: 0 }, + timeline: [ + { type: "clip", id: "c01", video: "vid1", start: 1, end: 3, cite: 1 }, + { type: "clip", id: "c02", video: "v7slug1", channel: "rumblechan", start: 4, end: 6, cite: 4 }, + { type: "clip", id: "c03", video: "v7slug2", channel: "rumblechan", start: 1, end: 2, cite: 1, citeUrl: "https://site.example/?v=rumblechan/v7slug2&t=1" }, + ], +}); + +let n = 0; +async function project(m = MANIFEST()) { + n += 1; + const dir = path.join(ROOT, "reports", `p${n}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return { id: `p${n}`, dir }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); +const undoPoints = async (dir) => (await readdir(path.join(dir, "revisions")).catch(() => [])).filter((f) => f.includes("auto-before-")); + +test("provenance: checked, normalised, one write with its own undo point", async () => { + assert.deepEqual(ed.provenancePatchOf({ siteOrigin: "https://jeralyzer.pages.dev/", channelSlug: " the-quartering ", channel: "" }), { + siteOrigin: "https://jeralyzer.pages.dev", channelSlug: "the-quartering", channel: null, + }); + assert.throws(() => ed.provenancePatchOf({ siteOrigin: "https://x.example/path" }), /no path/); + assert.throws(() => ed.provenancePatchOf({ siteOrigin: "ftp://x" }), /http/); + assert.throws(() => ed.provenancePatchOf({ channelSlug: "a b" }), /slug/); + assert.throws(() => ed.provenancePatchOf({ linkPolicy: {} }), /link-policy/); + assert.throws(() => ed.provenancePatchOf({}), /nothing to change/); + + const p = await project(); + const token = await manifestToken(p.dir); + const r = await ed.updateProvenance(p.dir, { siteOrigin: "https://new.example", channel: "The Channel" }, { token }); + assert.deepEqual(r.provenance, { siteOrigin: "https://new.example", channelSlug: "chan", channel: "The Channel" }); + assert.deepEqual(r.changed.siteOrigin, ["https://old.example", "https://new.example"]); + const m = await read(p.dir); + assert.equal(m.provenance.siteOrigin, "https://new.example"); + assert.equal(m.provenance.channel, "The Channel"); + assert.equal((await undoPoints(p.dir)).filter((f) => f.endsWith("auto-before-provenance.manifest.json")).length, 1); + // A stale token is refused, the draft untouched. + await assert.rejects(ed.updateProvenance(p.dir, { channelSlug: "x" }, { token }), (e) => e instanceof StaleToken); + // Undo takes exactly it back. + await undoStructural(p.dir); + assert.equal((await read(p.dir)).provenance.siteOrigin, "https://old.example"); +}); + +test("title and subtitle: one line each, the subtitle removable", async () => { + assert.throws(() => ed.titlePatchOf({ title: " " }), /words/); + assert.throws(() => ed.titlePatchOf({ title: "a\nb" }), /one line/); + assert.throws(() => ed.titlePatchOf({}), /nothing to change/); + const p = await project(); + let r = await ed.updateTitle(p.dir, { title: " A New Title ", subtitle: "and its line" }); + assert.deepEqual(r, { ...r, title: "A New Title", subtitle: "and its line" }); + r = await ed.updateTitle(p.dir, { subtitle: "" }); + assert.equal(r.subtitle, null); + const m = await read(p.dir); + assert.equal(m.title, "A New Title"); + assert.equal("subtitle" in m, false); + assert.equal((await undoPoints(p.dir)).length, 2); +}); + +test("teaser insert: start, end, after; the id fresh; refused in the build's words", async () => { + const lines = ["The 291 scale bet", { text: "Oct 23: bet at 291", hold: "" }, { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }]; + assert.deepEqual(ed.teaserLineOf({ text: " x ", break: "", hold: "" }), "x"); + assert.deepEqual(ed.teaserLineOf({ text: "a b", break: "b", hold: "1.234" }), { text: "a b", break: "b", hold: 1.23 }); + assert.throws(() => ed.teaserLineOf({ text: "a", colour: "red" }), /not a teaser line key/); + + const p = await project(); + let r = await ed.insertTeaser(p.dir, { lines, beat: 1.3 }, "end"); + assert.equal(r.id, "close"); + assert.equal(r.at, 3); + r = await ed.insertTeaser(p.dir, { lines: ["Cold open"] }, "start"); + assert.equal(r.id, "cold"); + r = await ed.insertTeaser(p.dir, { lines: ["Between"] }, { after: "c01" }); + assert.equal(r.id, "teaser"); + r = await ed.insertTeaser(p.dir, { lines: ["Again"] }, "start"); + assert.equal(r.id, "cold-2"); + const m = await read(p.dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["cold-2", "cold", "c01", "teaser", "c02", "c03", "close"]); + assert.deepEqual(m.timeline.at(-1), { type: "teaser", id: "close", lines: ["The 291 scale bet", "Oct 23: bet at 291", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 }); + assert.equal((await undoPoints(p.dir)).filter((f) => f.includes("teaser-insert")).length, 4); + + await assert.rejects(ed.insertTeaser(p.dir, { lines: [] }, "end"), (e) => e instanceof StructureRefused); + await assert.rejects(ed.insertTeaser(p.dir, { id: "c01", lines: ["x"] }, "end"), /already has an entry c01/); + await assert.rejects(ed.insertTeaser(p.dir, { lines: [{ text: "abc", break: "zzz" }] }, "end"), /break must be the end of its text/); + await assert.rejects(ed.insertTeaser(p.dir, { lines: ["x"], beat: 9 }, "end"), /beat must be from/); + await assert.rejects(ed.insertTeaser(p.dir, { lines: ["x"] }, { after: "nope" }), /no timeline entry with id nope/); + assert.equal((await read(p.dir)).timeline.length, 7); +}); + +async function rumbleChannel() { + const ch = path.join(ROOT, "channels", "rumblechan"); + for (const [dirId, id] of [["v7slug1", "v7emb01"], ["v7slug2", "v7emb02"], ["v7same3", "v7same3"]]) { + await mkdir(path.join(ch, "data", dirId), { recursive: true }); + await writeFile(path.join(ch, "data", dirId, "metadata.info.json"), JSON.stringify({ id, extractor: "Rumble", webpage_url: `https://rumble.com/${dirId}-x.html` })); + } + await writeFile(path.join(ch, "config.json"), JSON.stringify({ platform: "rumble", url: "https://rumble.com/c/rumblechan" })); +} + +test("the published embed id: found on disk, written as siteVideo (a citeUrl naming the folder moved), one undo point", async () => { + await rumbleChannel(); + const p = await project(); + const m = await read(p.dir); + const rows = await embedIdRows(p.dir, m, { layers: [path.join(ROOT, "channels")] }); + assert.deepEqual(rows.map((r) => [r.clip, r.video, r.siteVideo]), [["c02", "v7slug1", "v7emb01"], ["c03", "v7slug2", "v7emb02"]]); + assert.equal(rows[1].citeUrl, "https://site.example/?v=rumblechan/v7emb02&t=1"); + assert.equal(rows[1].fixedUrl, "https://site.example/?v=rumblechan/v7emb02&t=1"); + assert.equal(rows[0].state, "unchecked"); + assert.throws(() => embedIdFixes(rows, ["c01"]), /no published embed id/); + + const r = await ed.setSiteVideos(p.dir, embedIdFixes(rows, ["c02"])); + assert.deepEqual(r.fixed, [{ clip: "c02", video: "v7slug1", siteVideo: "v7emb01" }]); + let after = await read(p.dir); + assert.equal(after.timeline[1].siteVideo, "v7emb01"); + assert.equal(after.timeline[1].video, "v7slug1"); + // The rest, in one write. + const left = await embedIdRows(p.dir, after, { layers: [path.join(ROOT, "channels")] }); + assert.deepEqual(left.map((x) => x.clip), ["c03"]); + await ed.setSiteVideos(p.dir, embedIdFixes(left)); + after = await read(p.dir); + assert.equal(after.timeline[2].siteVideo, "v7emb02"); + assert.equal(after.timeline[2].citeUrl, "https://site.example/?v=rumblechan/v7emb02&t=1"); + assert.deepEqual(await embedIdRows(p.dir, after, { layers: [path.join(ROOT, "channels")] }), []); + assert.equal((await undoPoints(p.dir)).filter((f) => f.includes("embed-ids")).length, 2); +}); + +test("the ledger's writers take an undo point each", async () => { + const m = MANIFEST(); + m.ledgerSchema = { kind: "measure", unit: "lb", yMin: 200, yMax: 400, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current"], regimes: [], fields: [] }; + m.ledger = []; + const p = await project(m); + await addLedgerRow(p.dir, { id: "w01", date: "2026-10-01", scope: "weight", population: "current", value: 291, scopeBasis: "his words" }); + assert.equal((await undoPoints(p.dir)).filter((f) => f.endsWith("auto-before-ledger.manifest.json")).length, 1); + await undoStructural(p.dir); + assert.deepEqual((await read(p.dir)).ledger, []); +}); + +const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0; + +test("a still at second N: one frame of the fetched window into shots/, listed; a second no window holds refused", { skip: !hasFfmpeg && "no ffmpeg" }, async () => { + const p = await project(); + await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true }); + const win = path.join(p.dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"); + const ff = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=9", "-pix_fmt", "yuv420p", win]); + assert.equal(ff.status, 0, String(ff.stderr)); + const m = await read(p.dir); + const before = await readFile(path.join(p.dir, "video.manifest.json"), "utf8"); + const r = await grabStill(p, m, "c01", 2.5); + assert.equal(r.rel, `shots/${stillNameOf("c01", 2.5)}`); + assert.equal(r.rel, "shots/still-c01-2_50s.png"); + assert.ok((await stat(r.file)).size > 100); + // A still never edits the cut. + assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), before); + const shots = await listShots(p.dir); + assert.deepEqual(shots.map((s) => [s.rel, s.still]), [["shots/still-c01-2_50s.png", { clip: "c01", at: 2.5 }]]); + assert.equal(shotFileOf(p.dir, "shots/still-c01-2_50s.png"), path.join(p.dir, "shots", "still-c01-2_50s.png")); + assert.equal(shotFileOf(p.dir, "shots/../video.manifest.json"), null); + assert.equal(shotFileOf(p.dir, "posts-media/x.png"), null); + await assert.rejects(grabStill(p, m, "c01", 30), /no fetched window/); + await assert.rejects(grabStill(p, m, "nope", 1), /no clip nope/); +}); + +// ---- the CLI twins (inspectorCli.mjs; timelineCli.mjs teaser-insert; linksCli.mjs --embed-ids) ---- +const cli = await import("./inspectorCli.mjs"); +const { timelineCommand } = await import("./timelineCli.mjs"); +const { linksCommand } = await import("./linksCli.mjs"); +const run = async (fn, args) => { + const outs = []; + const errs = []; + const code = await fn(args, { root: path.join(ROOT, "reports"), out: (s) => outs.push(s), err: (s) => errs.push(s) }); + return { code, out: outs.join("\n"), err: errs.join("\n") }; +}; + +test("umtool provenance / title: print, set, refuse", async () => { + const p = await project(); + let r = await run(cli.provenanceCommand, [p.id, "--json"]); + assert.equal(r.code, 0, r.err); + assert.equal(JSON.parse(r.out).provenance.siteOrigin, "https://old.example"); + r = await run(cli.provenanceCommand, [p.id, "set", "--site-origin", "https://jeralyzer.pages.dev/", "--channel-slug", "the-quartering", "--json"]); + assert.equal(r.code, 0, r.err); + assert.equal(JSON.parse(r.out).provenance.channelSlug, "the-quartering"); + r = await run(cli.provenanceCommand, [p.id, "set", "--site-origin", "nope"]); + assert.equal(r.code, 1); + assert.match(r.err, /siteOrigin must be/); + r = await run(cli.provenanceCommand, [p.id, "set", "--bogus", "x"]); + assert.equal(r.code, 2); + r = await run(cli.titleCommand, [p.id, "Losing the same hundred pounds", "--subtitle", "Every weight", "--json"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual([JSON.parse(r.out).title, JSON.parse(r.out).subtitle], ["Losing the same hundred pounds", "Every weight"]); + r = await run(cli.titleCommand, [p.id, "--no-subtitle"]); + assert.equal(r.code, 0, r.err); + const m = await read(p.dir); + assert.equal(m.provenance.siteOrigin, "https://jeralyzer.pages.dev"); + assert.equal(m.title, "Losing the same hundred pounds"); + assert.equal("subtitle" in m, false); +}); + +test("umtool timeline teaser-insert: --line/--break/--hold, at the end by default", async () => { + const p = await project(); + let r = await run(timelineCommand, [p.id, "teaser-insert", "--line", "The 291 scale bet", "--line", "Scale video: not posted as of Nov 8", "--break", "as of Nov 8", "--hold", "1.6", "--beat", "1.3", "--json"]); + assert.equal(r.code, 0, r.err); + const j = JSON.parse(r.out); + assert.equal(j.inserted.id, "close"); + assert.deepEqual(j.inserted.entry, { type: "teaser", id: "close", lines: ["The 291 scale bet", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 }); + r = await run(timelineCommand, [p.id, "teaser-insert", "--at", "start", "--lines-json", '["Cold open", {"text": "a b", "break": "b"}]']); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /inserted teaser cold at 0/); + r = await run(timelineCommand, [p.id, "teaser-insert", "--break", "x"]); + assert.equal(r.code, 2); + r = await run(timelineCommand, [p.id, "teaser-insert", "--line", "abc", "--break", "zzz"]); + assert.equal(r.code, 1); + assert.match(r.err, /refused/); + assert.deepEqual((await read(p.dir)).timeline.map((e) => e.id), ["cold", "c01", "c02", "c03", "close"]); +}); + +test("umtool links --embed-ids: dry run, then the fix; no network", async () => { + await rumbleChannel(); + const p = await project(); + let r = await run(linksCommand, [p.id, "--embed-ids", "--dry-run", "--json"]); + assert.equal(r.code, 0, r.err); + assert.deepEqual(JSON.parse(r.out).would.map((f) => f.clip), ["c02", "c03"]); + r = await run(linksCommand, [p.id, "--embed-ids", "--clips", "c02"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /fixed c02: v7slug1 -> siteVideo v7emb01/); + assert.equal((await read(p.dir)).timeline[2].siteVideo, undefined); + r = await run(linksCommand, [p.id, "--embed-ids", "--clips", "c01"]); + assert.equal(r.code, 1); +}); + +test("an attachment switched off keeps its knobs in mediaOff, and on puts it back as it was", async () => { + const { updatePostItem } = await import("./manifest.mjs"); + const { validatePostItem } = await import("umtool-report-to-video/post-item"); + const m = MANIFEST(); + const vid = { src: "posts-media/x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true }; + const pic = { src: "posts-media/x/3/3_2.png", kind: "image", width: 320, height: 180 }; + m.timeline.push({ type: "post", id: "p-3", post: "x/3", platform: "x", author: "A", handle: "a", date: "2026-10-30T12:00:00.000Z", text: "words", media: [vid, pic] }); + const p = await project(m); + await updatePostItem(p.dir, "p-3", { media: { 0: { crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 } } }); + let r = await updatePostItem(p.dir, "p-3", { mediaHide: [0] }); + assert.deepEqual(r.entry.media, [pic]); + assert.deepEqual(r.entry.mediaOff, [{ ...vid, crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 }]); + assert.deepEqual(validatePostItem(r.entry), []); + r = await updatePostItem(p.dir, "p-3", { mediaShow: [0] }); + assert.deepEqual(r.entry.media, [pic, { ...vid, crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 }]); + assert.equal("mediaOff" in r.entry, false); + await assert.rejects(updatePostItem(p.dir, "p-3", { mediaShow: [0] }), /no attachment switched off at 0/); + await assert.rejects(updatePostItem(p.dir, "p-3", { mediaHide: [5] }), /shows no attachment 5/); + await assert.rejects(updatePostItem(p.dir, "p-3", { mediaHide: [0], hold: 3 }), /go alone/); + // The build's check: a bad switched-off attachment is refused as a shown one is. + assert.match(validatePostItem({ ...r.entry, mediaOff: [{ src: 7 }] }).join(" "), /mediaOff\[0\]/); + assert.match(validatePostItem({ ...r.entry, mediaOff: [] }).join(" "), /mediaOff must be a list/); +}); diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs @@ -28,6 +28,9 @@ export const LINKS_USAGE = [ "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.", + " umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]", + "every clip citing a Rumble URL-slug folder the archive does not serve gets the embed id it serves (siteVideo,", + "from the folder's metadata.info.json; a citeUrl naming the folder moves with it): no network, one write.", ].join("\n"); class CliError extends Error {} @@ -57,6 +60,8 @@ export function linksSummary(doc) { * @returns {Promise<number>} */ export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir, gapMs } = {}) { + // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs). + if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err }); try { const words = args.filter((a) => !a.startsWith("--")); const flags = new Set(args.filter((a) => a.startsWith("--"))); @@ -135,6 +140,8 @@ export const PATCH_MARKERS_USAGE = [ * @returns {Promise<number>} */ export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs). + if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err }); try { const words = args.filter((a) => !a.startsWith("--")); const flags = new Set(args.filter((a) => a.startsWith("--"))); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -1344,7 +1344,9 @@ export async function addLedgerRow(dir, row, { token = null } = {}) { const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); const made = ledgerRowOf(manifest, null, row); manifest.ledger = [...(Array.isArray(manifest.ledger) ? manifest.ledger : []), made]; - return { row: made, token: await writeManifestAtomic(dir, manifest) }; + // An undo point first (one undo stack, L3 S5; the inspector's ledger rows, L6): the Cut tab's Undo takes it back. + const snapshot = await autoSnapshot(dir, "ledger"); + return { row: made, snapshot, token: await writeManifestAtomic(dir, manifest) }; }); } @@ -1368,7 +1370,8 @@ export async function updateLedgerRow(dir, id, patch, { token = null, unset = [] if (patch.id !== undefined && patch.id !== id) throw new Error("a row's id is not changed by set (add the new row, then rm the old)"); const made = ledgerRowOf(manifest, ledger[i], patch, { unset }); ledger[i] = made; - return { row: made, token: await writeManifestAtomic(dir, manifest) }; + const snapshot = await autoSnapshot(dir, "ledger"); + return { row: made, snapshot, token: await writeManifestAtomic(dir, manifest) }; }); } @@ -1392,7 +1395,8 @@ export async function removeLedgerRow(dir, id, { token = null } = {}) { const refs = ledgerRowReferences(manifest, id); if (refs.length) throw new Error(`${id} is still named: ${refs.join("; ")}`); manifest.ledger = ledger.filter((r) => r?.id !== id); - return { row, token: await writeManifestAtomic(dir, manifest) }; + const snapshot = await autoSnapshot(dir, "ledger"); + return { row, snapshot, token: await writeManifestAtomic(dir, manifest) }; }); } @@ -2729,8 +2733,12 @@ const POST_REF_FIELDS = Object.freeze(["id", "author", "handle", "badge", "date" export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (!isObj(patch)) throw new Error("a post item's patch is an object"); for (const k of Object.keys(patch)) { - if (!["media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].join(", ")})`); + if (!["media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].join(", ")})`); } + // An attachment SWITCHED OFF and back ON (`mediaHide: [i]` / `mediaShow: [j]`, the inspector's media on/off): it moves + // whole between `media` and `mediaOff` (post-item.mjs), its knobs kept -- alone in its write, so no index moves under it. + const toggles = ["mediaHide", "mediaShow"].filter((k) => k in patch); + if (toggles.length && Object.keys(patch).length !== toggles.length) throw new Error("mediaHide / mediaShow go alone in a write"); return structural(dir, "post-item", token, (m) => { const i = entryIndex(m.timeline, id); const e = m.timeline[i]; @@ -2802,6 +2810,24 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (!Array.isArray(patch.mediaAdd)) throw new Error("mediaAdd is a list of attachments"); e.media = [...(Array.isArray(e.media) ? e.media : []), ...patch.mediaAdd]; } + if (toggles.length) { + const idx = (v, k) => { + if (!Array.isArray(v) || !v.every((n) => Number.isInteger(n))) throw new Error(`${k} is a list of indices`); + return new Set(v); + }; + const on = Array.isArray(e.media) ? e.media : []; + const off = Array.isArray(e.mediaOff) ? e.mediaOff : []; + const hide = patch.mediaHide !== undefined ? idx(patch.mediaHide, "mediaHide") : new Set(); + const show = patch.mediaShow !== undefined ? idx(patch.mediaShow, "mediaShow") : new Set(); + for (const n of hide) if (!isObj(on[n])) throw new Error(`${id} shows no attachment ${n}${on.length ? ` (0–${on.length - 1})` : ""}`); + for (const n of show) if (!isObj(off[n])) throw new Error(`${id} has no attachment switched off at ${n}${off.length ? ` (0–${off.length - 1})` : ""}`); + const media = [...on.filter((_, n) => !hide.has(n)), ...off.filter((_, n) => show.has(n))]; + const mediaOff = [...off.filter((_, n) => !show.has(n)), ...on.filter((_, n) => hide.has(n))]; + if (media.length) e.media = media; + else delete e.media; + if (mediaOff.length) e.mediaOff = mediaOff; + else delete e.mediaOff; + } // A context post's paraphrase (`quoted`, `parents[i]`): its text is never touched. A hand-made ref (`ref`), its // attachments (`media`) and the words read off its picture (`transcript`) are set here too. const setContext = (ref, cp, what) => { @@ -4760,3 +4786,20 @@ export async function undoStructural(dir, { token = null } = {}) { return { restored: target.rel, op, saved, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) }; }); } + +/** + * THE ONE DOOR FOR A WRITER OUTSIDE THIS FILE (umtool redesign L6: inspectorEdits.mjs -- the + * provenance, the title, a teaser inserted, the published embed ids): `structural`'s write as it is -- + * the token, the read inside the lock, `mutate` (which throws to refuse), the build's checks, the + * undo point `auto-before-<op>` (every op its own in the app), the atomic write. + * + * @template T + * @param {string} dir + * @param {string} op + * @param {string | null} token + * @param {(m: Record<string, any>) => T} mutate + */ +export async function structuralEdit(dir, op, token, mutate) { + if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`); + return structural(dir, op, token, mutate); +} diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -110,6 +110,7 @@ export const POSTS_USAGE = [ " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]", " [media.<i>.push=on|off] [media.<i>.trim=off] [media.<i>.enter=post|item] [quoted.paraphrase=\"…\"|off]", " [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]", + " [media.<i>.shown=off] [media-off.<j>.shown=on] an attachment switched off, kept whole (mediaOff), and on again", " [media.<i>.blur.boxes=x,y,w,h;…|off] [media.<i>.blur.band=below:<f>|above:<f>|between:<a>,<b>[:left:<f>|:right:<f>]|off]", " [media.<i>.blur.style=blur|black|pixelate|off] [media.<i>.censor=<edge>:<f>[:<style>][:<strength>]|off]", " [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…]", @@ -1018,6 +1019,14 @@ export function postItemPatchOf(pairs) { } // AN ATTACHMENT FROM A PROJECT FILE (operator, 4 Nov: "this needs to include the cat video"): measured when it goes in. else if (k === "media.add") (out.mediaAdd ??= []).push(fileArg(raw, k)); + // An attachment switched OFF, kept whole (mediaOff: its knobs kept), and back ON (the inspector's media on/off). + else if (/^media\.\d+\.shown$/.test(k)) { + if (!OFF.has(v)) throw new CliError(`${k}= takes off (on: media-off.<j>.shown=on)`); + (out.mediaHide ??= []).push(Number(k.split(".")[1])); + } else if (/^media-off\.\d+\.shown$/.test(k)) { + if (v !== "on") throw new CliError(`${k}= takes on (the attachment switched off at <j> shown again, as it was)`); + (out.mediaShow ??= []).push(Number(k.split(".")[1])); + } else if (/^media\.\d+$/.test(k)) { if (!OFF.has(v)) throw new CliError(`${k}= takes off (the attachment removed)`); ((out.media ??= {})[k.split(".")[1]] = null); diff --git a/umtool/lib/report/stillGrab.mjs b/umtool/lib/report/stillGrab.mjs @@ -0,0 +1,129 @@ +// A STILL AT SECOND N (umtool redesign L6: Play's "Still" button, `umtool still`): one frame of a clip's fetched +// window, grabbed with ffmpeg (`-ss <offset> -i <window> -frames:v 1`) and saved beside the project's shots -- +// `shots/`, where a clip's fx.zoom / fx.receipts and a still entry read their pictures from -- as +// `shots/still-<clip>-<seconds>.png`. A single-frame grab: not heavy work, never the heavy slot. +// +// What it reads is a window ALREADY ON DISK (serve.mjs windowsFor: the project's out/clips-raw and the corpus clips +// dirs the editor fetched into, a long recording's own file when the window is an excerpt of it). Nothing is +// fetched: a second no fetched window holds is refused, and says to fetch it first. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { FFMPEG_BIN } from "umtool-report-to-video/build-video"; +import { resolveInRoots } from "../paths.mjs"; +import { clipsOf } from "../projects/report.mjs"; +import { windowsFor } from "./serve.mjs"; + +const execFileP = promisify(execFile); + +/** The project's shots directory (relative to the project), where stills land. */ +export const SHOTS_DIR = "shots"; +const PICTURE_RE = /\.(png|jpe?g|webp)$/i; + +export class StillRefused extends Error { + /** @param {string} message @param {number} [status] */ + constructor(message, status = 400) { + super(message); + this.name = "StillRefused"; + this.status = status; + } +} + +/** The file name a still of `clip` at `seconds` gets: `still-<clip>-<s>s.png`, the second to 2 dp (a dot as "_"). */ +export const stillNameOf = (clip, seconds) => `still-${String(clip).replace(/[^A-Za-z0-9_-]+/g, "-")}-${(Math.round(seconds * 100) / 100).toFixed(2).replace(".", "_")}s.png`; + +/** + * The window file a frame at `at` (a SOURCE second) is read from, and its offset: the fetched window that holds + * it (an excerpt's own recording, which holds it too; a window laid in pieces is skipped -- its filler is black). + * + * @param {{ dir: string, id: string }} project + * @param {Record<string, any>} clip + * @param {number} at + */ +export async function stillSourceOf(project, clip, at) { + const windows = await windowsFor(project, clip); + for (const w of windows) { + if (w.piecesOf) continue; + const src = w.excerptOf ? { path: w.excerptOf.path, from: w.excerptOf.from } : { path: w.path, from: w.from }; + const to = w.excerptOf ? Infinity : w.to; + if (!(at >= src.from - 0.01 && at <= to + 0.01)) continue; + const abs = resolveInRoots(src.path); + if (!abs) continue; + if (!(await stat(abs).catch(() => null))?.isFile()) continue; + return { file: abs, offset: Math.max(0, at - src.from) }; + } + return null; +} + +/** + * Grab the frame of `clipId` at source second `at` into `shots/`. Returns `{ rel, file, clip, at, bytes }`. + * Refused (StillRefused) for a clip not in the cut, a second outside every fetched window, or a window with + * no picture. + * + * @param {{ dir: string, id: string }} project + * @param {Record<string, any>} manifest the cut the clip is in (the draft, or a version's) + * @param {string} clipId + * @param {number} at a source second + * @param {{ ffmpeg?: string, name?: string | null }} [opts] + */ +export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG_BIN, name = null } = {}) { + const clip = clipsOf(manifest).find((e) => e.id === clipId); + if (!clip) throw new StillRefused(`no clip ${clipId} in ${project.id}`, 404); + const t = Number(at); + if (!Number.isFinite(t) || t < 0) throw new StillRefused("at is a source second, 0 or more"); + const src = await stillSourceOf(project, clip, t); + if (!src) throw new StillRefused(`no fetched window of ${clip.video} holds ${t.toFixed(2)} s -- fetch ${clipId} first (umtool fetch ${project.id} --clips ${clipId})`, 409); + const file = name ?? stillNameOf(clipId, t); + if (!/^[A-Za-z0-9_.-]{1,120}\.png$/.test(file)) throw new StillRefused(`a still's name is letters, digits, . _ - and .png (got ${file})`); + const dir = path.join(project.dir, SHOTS_DIR); + await mkdir(dir, { recursive: true }); + const out = path.join(dir, file); + // Two grabs of one second at once never share a temp file. + const tmp = path.join(dir, `.${file}.part-${process.pid}-${Math.random().toString(36).slice(2, 10)}.png`); + try { + await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, "-frames:v", "1", "-an", tmp], { timeout: 60_000 }); + const st = await stat(tmp).catch(() => null); + if (!st?.size) throw new StillRefused(`the window of ${clip.video} has no picture at ${t.toFixed(2)} s (an audio-only fetch?)`, 409); + await rename(tmp, out); + return { rel: `${SHOTS_DIR}/${file}`, file: out, clip: clipId, video: String(clip.video), at: Math.round(t * 100) / 100, bytes: st.size }; + } catch (e) { + if (e instanceof StillRefused) throw e; + const msg = String(/** @type {any} */ (e)?.stderr || (e instanceof Error ? e.message : e)).trim().split("\n").slice(-2).join(" "); + throw new StillRefused(`ffmpeg could not grab the frame: ${msg}`, 500); + } finally { + await rm(tmp, { force: true }); + } +} + +/** + * The pictures in the project's shots/ (newest first): `{ rel, name, bytes, mtime, still }`, `still` when it is one + * of these grabs (`still-*`), with its clip and second read back from its name. + * + * @param {string} dir + */ +export async function listShots(dir) { + const root = path.join(dir, SHOTS_DIR); + const names = await readdir(root).catch(() => []); + const out = []; + for (const n of names) { + if (n.startsWith(".") || !PICTURE_RE.test(n)) continue; + const st = await stat(path.join(root, n)).catch(() => null); + if (!st?.isFile()) continue; + const m = /^still-(.+)-(\d+)_(\d{2})s\.png$/.exec(n); + out.push({ + rel: `${SHOTS_DIR}/${n}`, name: n, bytes: st.size, mtime: new Date(st.mtimeMs).toISOString(), + still: m ? { clip: m[1], at: Number(`${m[2]}.${m[3]}`) } : null, + }); + } + return out.sort((a, b) => b.mtime.localeCompare(a.mtime) || a.name.localeCompare(b.name)); +} + +/** A shots/ file's absolute path, never outside shots/ (null when it is not a picture there). */ +export function shotFileOf(dir, rel) { + const r = String(rel ?? ""); + if (!r.startsWith(`${SHOTS_DIR}/`) || r.split("/").length !== 2 || r.includes("..") || !PICTURE_RE.test(r)) return null; + return path.join(dir, ...r.split("/")); +} diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -127,6 +127,9 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> post <json|@file> add a post, or replace the one with its id", " umtool timeline <project> post-remove <id>", " umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)", + " umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]", + " --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json <json|@file>", + " a TEASER OR CLOSING CARD inserted (default at the end, id close; at the start, cold)", " umtool timeline <project> undo restore the newest automatic snapshot", " umtool timeline <project> sections [--json] the deck's sections: §, label, colour, its marker, its clips", " umtool timeline <project> section-move <id> [<id>…] --to-section N [--start]", @@ -540,7 +543,12 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => err(TIMELINE_USAGE); return 2; } - if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`); + // A teaser or closing card inserted (the inspector's twin, inspectorCli.mjs): its own flags (--line repeats). + if (verb === "teaser-insert") { + if (flags.has("--take")) throw new CliError("teaser-insert writes the draft (the project's manifest), not a take"); + return await (await import("./inspectorCli.mjs")).teaserInsertVerb(await projectOf(projectArg, root), args.slice(args.indexOf("teaser-insert") + 1), { out, err }); + } + if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}, teaser-insert`); const project = await projectOf(projectArg, root); // A video entry (video-entry.mjs), into the cut or a take's timeline. if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json }); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -705,6 +705,16 @@ export function validatePostItem(e) { e.media.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.media[${i}]`))); } } + // ITS ATTACHMENTS SWITCHED OFF (umtool redesign L6, the inspector's media on/off): each kept whole -- its crop, + // blur, trim, sound -- in `mediaOff`, which nothing draws or plays (only `media` is read), so "on" puts it back as + // it was. Checked as an attachment is. + if (e.mediaOff !== undefined) { + if (!Array.isArray(e.mediaOff) || !e.mediaOff.length) errors.push(`${w}.mediaOff must be a list of attachments switched off (absent: none)`); + else { + if (e.mediaOff.length > POST_MEDIA_MAX) errors.push(`${w}.mediaOff: at most ${POST_MEDIA_MAX} attachments`); + e.mediaOff.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.mediaOff[${i}]`))); + } + } // Its narration (post-narration.mjs): the script, the takes, the mix's knobs. errors.push(...validatePostNarration(e)); // Its effects (word-zoom.mjs): a word zoomed on as it is read.