Archilyzer · Source

archilyzer

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

commit 1a2c940cf0794e1844b12763828b40f9860dda8d
parent 0322c2868ab9d58a8f1a2fc11023f38e7d186111
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:19:33 -0500

umtool: the inspector's writers -- provenance, title, teaser insert, published embed ids, a still at second N (redesign L6)

inspectorEdits.mjs: updateProvenance (siteOrigin, channelSlug, channel), updateTitle, insertTeaser
(start | end | after/before an entry, checked by the build's validateTeaser), setSiteVideos -- each one
structural write to the draft with its own undo point (manifest.mjs structuralEdit, the one door).
embedIds.mjs: the clips citing a Rumble URL-slug folder the archive does not serve, read through L1's
siteVideoFor, and their fixes. stillGrab.mjs: one ffmpeg frame of a fetched window into shots/.
The ledger's add/set/rm take an undo point each (one undo stack).

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

Diffstat:
Aumtool/lib/report/embedIds.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/inspectorEdits.mjs | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/inspectorEdits.test.mjs | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 27++++++++++++++++++++++++---
Aumtool/lib/report/stillGrab.mjs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 703 insertions(+), 3 deletions(-)

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/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,188 @@ +// 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/); +}); 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) }; }); } @@ -4760,3 +4764,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/stillGrab.mjs b/umtool/lib/report/stillGrab.mjs @@ -0,0 +1,128 @@ +// 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); + const tmp = path.join(dir, `.${file}.part-${process.pid}.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("/")); +}