commit 10060b97cb3f931498e4903c68d0ef793b352f25
parent 36b1b1c040a8010f7911c102b5bc15c5f8f77639
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 16:18:03 -0500
umtool: the combo counter's detection -- a post item's attachment that an earlier item of the cut already played (the X media id from the capture's url, else the file's sha256 -- capture.json's when its bytes agree, else hashed -- else, with match=audio, the sound's fingerprint by fpcalc or a coarse ffmpeg energy hash), counted in the cut's order; `umtool posts repeats` lists each with its posts, dates, the tier and the badge each draws, and the posts whose capture has the file but whose entry carries none; `umtool posts combo` sets render.posts.combo and an item's `combo` (off still counts) (operator: "a combo counter … when he uses the same video to reply to someone")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 1291 insertions(+), 1 deletion(-)
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -115,6 +115,7 @@
// narrate <project> [<item>] --import | --take | --script | --pick | --approve | k=v | --all … narration
// fit <project> --all | <item>… narrated posts' videos cut to their best part
// avatar <project> <handle> <image> | avatars <project> the authors' pictures
+// repeats <project> [--match id|file|audio] · combo <project> [<item>] k=v|off the combo counter
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
import process from "node:process";
import {
@@ -1036,6 +1037,8 @@ function usage() {
" | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)",
" umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
" umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards",
+ " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)",
+ " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (the cut's, one item's)",
" umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>",
" the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;",
" Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's",
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -66,6 +66,7 @@ import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFo
import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs";
import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
+import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, validatePostCombo, validatePostComboRender } from "umtool-report-to-video/post-combo";
import { createSnapshot, listSnapshots } from "./snapshots.mjs";
import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs";
@@ -2430,6 +2431,74 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
});
}
+// ---- the combo counter (report-to-video/post-combo.mjs) --------------------
+
+/**
+ * A POST ITEM's COMBO BADGE (`combo`; `umtool posts combo <p> <item> …`, the
+ * post bench's **combo badge**): `false` draws none on this item (it still
+ * counts), `null` takes the cut's again, an object sets this item's
+ * overrides (COMBO_ITEM_KEYS; a key null is the cut's again; none left: the
+ * cut's). Validated with the build's check.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {false | null | Record<string, any>} value
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostCombo(dir, id, value, { token = null } = {}) {
+ if (value !== false && value !== null && !isObj(value)) throw new Error("a post item's combo is false (no badge), null (the cut's) or an object of knobs");
+ if (isObj(value)) for (const k of Object.keys(value)) if (!COMBO_ITEM_KEYS.includes(k)) throw new Error(`${k} is not a post item's combo knob (${COMBO_ITEM_KEYS.join(", ")})`);
+ return structural(dir, "post-combo", token, (m) => {
+ const i = entryIndex(m.timeline, id);
+ const e = m.timeline[i];
+ if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
+ if (value === false) e.combo = false;
+ else if (value === null) delete e.combo;
+ else {
+ const c = isObj(e.combo) ? e.combo : {};
+ for (const [k, v] of Object.entries(value)) {
+ if (v === null || v === undefined) delete c[k];
+ else c[k] = typeof v === "number" ? round2(v) : v;
+ }
+ if (Object.keys(c).length) e.combo = c;
+ else delete e.combo;
+ }
+ const errors = validatePostCombo(e);
+ if (errors.length) throw new StructureRefused(errors);
+ return { id, at: i, entry: e, combo: e.combo ?? null };
+ });
+}
+
+/**
+ * THE CUT's COMBO KNOBS (`render.posts.combo`; `umtool posts combo <p> k=v …`):
+ * each key one of COMBO_DEFAULTS', null back to the default. Validated with
+ * the build's check.
+ *
+ * @param {string} dir
+ * @param {Record<string, any>} patch
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostComboRender(dir, patch, { token = null } = {}) {
+ if (!isObj(patch) || !Object.keys(patch).length) throw new Error("nothing to set");
+ for (const k of Object.keys(patch)) if (!(k in COMBO_DEFAULTS)) throw new Error(`${k} is not a combo knob (${Object.keys(COMBO_DEFAULTS).join(", ")})`);
+ return structural(dir, "post-combo-cut", token, (m) => {
+ if (!isObj(m.render)) m.render = {};
+ const posts = isObj(m.render.posts) ? m.render.posts : {};
+ const c = isObj(posts.combo) ? posts.combo : {};
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null || v === undefined) delete c[k];
+ else c[k] = typeof v === "number" && k !== "minCount" ? round2(v) : v;
+ }
+ if (Object.keys(c).length) posts.combo = c;
+ else delete posts.combo;
+ if (Object.keys(posts).length) m.render.posts = posts;
+ else delete m.render.posts;
+ const errors = validatePostComboRender(m.render);
+ if (errors.length) throw new StructureRefused(errors);
+ return { combo: m.render.posts?.combo ?? null };
+ });
+}
+
// ---- the authors' pictures (report-to-video/post-avatars.mjs) --------------
/**
diff --git a/umtool/lib/report/postComboCli.mjs b/umtool/lib/report/postComboCli.mjs
@@ -0,0 +1,211 @@
+// `umtool posts repeats` / `umtool posts combo` (report-to-video/post-combo.mjs):
+// the COMBO COUNTER from a terminal -- which attachments the cut plays more
+// than once, and the badge's knobs.
+//
+// umtool posts repeats <project> [--match id|file|audio] [--json]
+// umtool posts combo <project> [k=v …] [--json] the cut's (render.posts.combo)
+// umtool posts combo <project> <item> off|on|auto|k=v … [--json] one item's (`combo`)
+//
+// `repeats` lists each repeated attachment with its posts in the cut's order
+// (their dates, the tier that matched) and the badge each draws; a post item
+// whose CAPTURE holds the same file but whose entry carries no attachment (it
+// was captured after it went in) is listed too, marked, with how to bring it
+// in -- it draws no badge and does not count until it plays the attachment.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, comboKnobs, repeatGroups } from "umtool-report-to-video/post-combo";
+import { captureOnlyMedia, projectCombos } from "umtool-report-to-video/post-combo-prints";
+import { channelsDirFor, readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updatePostCombo, updatePostComboRender } from "./manifest.mjs";
+
+export class ComboError extends Error {}
+
+export const REPEATS_USAGE = [
+ "usage: umtool posts repeats <project> [--match id|file|audio] [--json]",
+ " every attachment the cut's post items play more than once, its posts in the cut's order (dates, the tier",
+ " that matched: the X media id, the file's sha256, or -- --match audio -- the sound's fingerprint), and the",
+ " combo badge each draws (×2 from the second use; render.posts.combo). A post whose capture holds the same",
+ " file but whose entry has no attachment yet is listed too, marked: it counts once it plays it.",
+ " umtool posts combo <project> [on=on|off] [label=COMBO] [position=top-right|top-left|bottom-right|bottom-left|center]",
+ " [color=#rrggbb] [scale=0.4-2.5] [sfx=off|hit|coin] [minCount=2-20] [match=id|file|audio] [--json]",
+ " the cut's badge (render.posts.combo; k= back to the default); no knobs prints them.",
+ " umtool posts combo <project> <item> off|on|auto [label=…] [position=…] [color=…] [scale=…] [sfx=…] [--json]",
+ " one post item's: off draws no badge on it (it still counts), on/auto the cut's again; its own label, …",
+].join("\n");
+
+const OFF = new Set(["off", "no", "false", "0"]);
+const ON = new Set(["on", "yes", "true", "1"]);
+
+/** `k=v` words into a combo patch (null: the default / the cut's). */
+export function comboPatchOf(pairs, { item = false } = {}) {
+ const keys = item ? COMBO_ITEM_KEYS : Object.keys(COMBO_DEFAULTS);
+ /** @type {Record<string, any>} */
+ const out = {};
+ for (const pair of pairs) {
+ const eq = pair.indexOf("=");
+ if (eq < 1) throw new ComboError(`${pair}: a knob is key=value`);
+ const k = pair.slice(0, eq);
+ const raw = pair.slice(eq + 1);
+ if (!keys.includes(k)) throw new ComboError(`${k}= is not a ${item ? "post item's " : ""}combo knob (${keys.join(", ")})`);
+ if (raw === "") out[k] = null;
+ else if (k === "on") {
+ if (!ON.has(raw.toLowerCase()) && !OFF.has(raw.toLowerCase())) throw new ComboError("on= takes on or off");
+ out.on = ON.has(raw.toLowerCase());
+ } else if (k === "scale" || k === "minCount") {
+ const v = Number(raw);
+ if (!Number.isFinite(v)) throw new ComboError(`${k}= takes a number`);
+ out[k] = v;
+ } else out[k] = raw;
+ }
+ return out;
+}
+
+async function projectOf(projectArg, root) {
+ const { resolveProject } = await import("../projects/core.mjs");
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new ComboError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new ComboError(`no project matches "${projectArg}"`);
+ return r.project;
+}
+
+/**
+ * THE REPEATS VIEW: the cut's groups with the capture-only posts folded in.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ match?: string | null, cacheDir?: string | null, channelsDir?: string | null }} [o]
+ */
+export async function repeatsView(project, { match = null, cacheDir = undefined, channelsDir = null } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new ComboError(`${project.id} has no manifest`);
+ const corpus = channelsDir ?? channelsDirFor(project.dir, manifest);
+ const opts = { channelsDir: corpus, ...(match ? { match } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) };
+ const cut = await projectCombos(project.dir, manifest, opts);
+ // The posts whose capture has a file their entry does not carry: in the cut's order, as if they played it.
+ const captured = await captureOnlyMedia(manifest, { channelsDir: corpus });
+ const tl = (manifest.timeline ?? []).map((e) => (captured[e?.id] ? { ...e, media: captured[e.id].map((m) => ({ src: `@capture/${m.slug}/${m.name}`, kind: "capture" })) } : e));
+ const prints = (id, i) => (captured[id] ? { mediaId: captured[id][i]?.mediaId ?? null, sha256: captured[id][i]?.sha256 ?? null } : cut.prints[`${id}:${i}`]);
+ const all = repeatGroups(tl, prints, { match: cut.match });
+ const byId = new Map((manifest.timeline ?? []).map((e) => [e?.id, e]));
+ const ids = (manifest.timeline ?? []).map((e) => e?.id);
+ const afterOf = (id) => (ids.indexOf(id) > 0 ? ids[ids.indexOf(id) - 1] : "-");
+ const groups = all.map((g) => {
+ const first = g.members.find((m) => !captured[m.id]) ?? g.members[0];
+ const att = byId.get(first.id)?.media?.[first.i];
+ return {
+ key: g.key,
+ tiers: g.tiers,
+ kind: att?.kind ?? "?",
+ src: att?.src ?? first.src,
+ members: g.members.map((m) => {
+ const c = cut.combos[m.id];
+ const cap = captured[m.id]?.[m.i];
+ return {
+ id: m.id, n: m.n, post: m.post, date: m.date, tier: m.tier, attached: !cap,
+ ...(cap ? { capture: `${cap.slug}/posts-media/${String(m.post ?? "").split("/")[1] ?? ""}/${cap.name}`, captureSlug: cap.slug, after: afterOf(m.id) } : {}),
+ badge: c && c.media === m.i ? c.count : null, show: !!(c && c.media === m.i && c.show),
+ };
+ }),
+ };
+ }).filter((g) => g.members.some((m) => m.attached));
+ groups.forEach((g, k) => (g.key = `g${k + 1}`));
+ return { project: project.id, match: cut.match, knobs: comboKnobs(manifest.render), groups, combos: cut.combos };
+}
+
+const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" };
+const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" };
+
+/** The repeats view as lines. */
+export function repeatsLines(v) {
+ const out = [];
+ const shown = v.groups.filter((g) => g.members.filter((m) => m.attached).length >= 2);
+ out.push(`${shown.length} attachment(s) played more than once in ${v.project} (matched by ${MATCH_WORDS[v.match] ?? v.match}; the badge ${v.knobs.on === false ? "OFF for the cut" : `from ×${v.knobs.minCount}`})`);
+ for (const g of v.groups) {
+ const uses = g.members.filter((m) => m.attached).length;
+ out.push(` ${g.key} ${uses}× ${g.kind} ${g.src}${g.members.length > uses ? ` (+${g.members.length - uses} not attached yet)` : ""}`);
+ for (const m of g.members) {
+ const day = typeof m.date === "string" ? m.date.slice(0, 10) : "?";
+ const badge = !m.attached ? " - " : m.badge && m.badge >= 2 ? (m.show ? `×${m.badge}`.padEnd(5) : `(×${m.badge})`.padEnd(5)) : " 1 ";
+ const how = m.tier ? TIER_WORDS[m.tier] ?? m.tier : "first";
+ out.push(` ${badge} ${m.id} ${day} ${m.post ?? ""} [${how}]${m.attached ? "" : ` NOT ATTACHED: its capture ${m.capture} is the same file`}`);
+ }
+ }
+ const missing = v.groups.flatMap((g) => g.members.filter((m) => !m.attached));
+ if (missing.length) {
+ out.push(` ${missing.length} post(s) above carry no attachment in the cut (captured after they went in); each counts once it plays it.`);
+ out.push(` To make one again from the archive (its words, its capture -- the entry's own edits are NOT kept):`);
+ for (const m of missing) {
+ const postId = String(m.post ?? "").split("/")[1] ?? "";
+ out.push(` umtool timeline ${v.project} remove ${m.id} && umtool timeline ${v.project} insert --after ${m.after} post:${m.captureSlug}/${postId} --id ${m.id}`);
+ }
+ }
+ return out;
+}
+
+/**
+ * @param {"repeats" | "combo"} verb
+ * @param {string[]} words the words after the verb (project first)
+ * @param {Map<string, string | true>} flags
+ * @param {{ root: string, json: boolean, out: (s: string) => void, err: (s: string) => void }} o
+ */
+export async function comboCommand(verb, words, flags, o) {
+ try {
+ return await comboRun(verb, words, flags, o);
+ } catch (e) {
+ if (!(e instanceof ComboError)) throw e;
+ o.err(`umtool posts ${verb}: ${e.message}`);
+ return 2;
+ }
+}
+
+async function comboRun(verb, words, flags, { root, json, out, err }) {
+ const [projectArg, ...rest] = words;
+ if (!projectArg || flags.has("--help")) {
+ err(REPEATS_USAGE);
+ return 2;
+ }
+ const project = await projectOf(projectArg, root);
+ if (verb === "repeats") {
+ const m = flags.get("--match");
+ if (m !== undefined && !["id", "file", "audio"].includes(String(m))) throw new ComboError("--match takes id, file or audio");
+ const v = await repeatsView(project, { match: m === undefined ? null : String(m) });
+ out(json ? JSON.stringify({ ok: true, ...v }, null, 2) : repeatsLines(v).join("\n"));
+ return 0;
+ }
+ // combo: the cut's (no item), or one item's.
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new ComboError(`${project.id} has no manifest`);
+ const isPair = (w) => w.includes("=");
+ if (!rest.length || isPair(rest[0])) {
+ if (!rest.length) {
+ const k = comboKnobs(manifest.render);
+ out(json ? JSON.stringify({ ok: true, combo: manifest.render?.posts?.combo ?? null, knobs: k }, null, 2) : `the cut's combo badge: ${Object.entries(k).map(([a, b]) => `${a}=${b}`).join(" ")}`);
+ return 0;
+ }
+ const patch = comboPatchOf(rest);
+ const { result, editNotes } = await withEditNotes(project, async () => updatePostComboRender(project.dir, patch, { token: await manifestToken(project.dir) }));
+ out(json ? JSON.stringify({ ok: true, combo: result.combo, token: result.token, editNotes }, null, 2) : `the cut's combo badge: ${JSON.stringify(result.combo ?? "the defaults")}`);
+ return 0;
+ }
+ const [ref, ...pairs] = rest;
+ const tl = Array.isArray(manifest.timeline) ? manifest.timeline : [];
+ const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref));
+ if (!hit) throw new ComboError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
+ let value;
+ const word = pairs.length === 1 && !isPair(pairs[0]) ? pairs[0].toLowerCase() : null;
+ if (!pairs.length) {
+ out(json ? JSON.stringify({ ok: true, id: hit.id, combo: hit.combo ?? null, knobs: comboKnobs(manifest.render, hit) }, null, 2) : `${hit.id}: ${hit.combo === false ? "no badge (off)" : hit.combo ? JSON.stringify(hit.combo) : "the cut's badge"}`);
+ return 0;
+ }
+ if (word !== null) {
+ if (OFF.has(word)) value = false;
+ else if (ON.has(word) || word === "auto") value = hit.combo === false || !hit.combo ? null : { on: null };
+ else throw new ComboError(`${pairs[0]}: off, on, auto or key=value`);
+ } else {
+ if (pairs.some((p) => !isPair(p))) throw new ComboError("off / on go alone; knobs are key=value");
+ value = comboPatchOf(pairs, { item: true });
+ }
+ const { result, editNotes } = await withEditNotes(project, async () => updatePostCombo(project.dir, hit.id, value, { token: await manifestToken(project.dir) }));
+ out(json ? JSON.stringify({ ok: true, id: hit.id, combo: result.combo, token: result.token, editNotes }, null, 2) : `${hit.id}: ${result.combo === false ? "no badge on this item (it still counts)" : result.combo ? `its own: ${JSON.stringify(result.combo)}` : "the cut's badge"}`);
+ return 0;
+}
diff --git a/umtool/lib/report/postComboCli.test.mjs b/umtool/lib/report/postComboCli.test.mjs
@@ -0,0 +1,98 @@
+// `umtool posts repeats` / `posts combo` (postComboCli.mjs) and their writers
+// (manifest.mjs updatePostCombo, updatePostComboRender): the repeats listed in
+// the cut's order with the capture-only posts marked; an item's badge off and
+// on; the cut's knobs set, refused in the build's words.
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { postsCommand } from "./postsCli.mjs";
+import { repeatsView } from "./postComboCli.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-combo-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+process.env.UMTOOL_PRINTS_CACHE = path.join(ROOT, "cache");
+const CH = path.join(ROOT, "channels");
+const REPORTS = path.join(ROOT, "reports");
+
+const post = (id, media) => ({
+ type: "post", id: `p-${id}`, post: `obv-x/${id}`, platform: "x", author: "Mr. Obvious", handle: "ObviousRises", date: `2026-11-0${id}T10:00:00.000Z`, text: `post ${id}`,
+ ...(media ? { media: [{ src: `posts-media/obv-x/${id}/${id}_1.mp4`, kind: "gif", seconds: 2, width: 498, height: 280 }] } : {}),
+});
+
+async function project(name) {
+ const dir = path.join(REPORTS, name);
+ for (const id of ["1", "2", "4"]) {
+ await mkdir(path.join(dir, "posts-media", "obv-x", id), { recursive: true });
+ await writeFile(path.join(dir, "posts-media", "obv-x", id, `${id}_1.mp4`), id === "4" ? "ANOTHER" : "THE-SAME-GIF");
+ }
+ // 3 went in before its capture: no attachment in the cut, the same file in the corpus (the replies channel, which 4 comes from).
+ await mkdir(path.join(CH, "obv-x-replies", "posts-media", "3"), { recursive: true });
+ const { createHash } = await import("node:crypto");
+ const sha = createHash("sha256").update("THE-SAME-GIF").digest("hex");
+ await writeFile(path.join(CH, "obv-x-replies", "posts-media", "3", "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: 12, sha256: sha, url: "https://video.twimg.com/tweet_video/C.mp4" }] }));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "obv-x", channelsDir: CH },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" } },
+ timeline: [post("1", true), { type: "clip", id: "c01", video: "v1", start: 1, end: 3 }, post("2", true), { ...post("3", false), post: "obv-x/3" }, { ...post("4", true), post: "obv-x-replies/4" }, { ...post("5", true), media: [{ src: "posts-media/obv-x/1/1_1.mp4", kind: "gif", seconds: 2 }] }],
+ }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+const run = async (args) => {
+ const out = [];
+ const err = [];
+ const code = await postsCommand(args, { root: REPORTS, out: (s) => out.push(s), err: (s) => err.push(s) });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+};
+
+test("posts repeats: the attachment's posts in the cut's order, the badges they draw, and the post whose capture has it", async () => {
+ const p = await project("rep");
+ const v = await repeatsView(p);
+ assert.equal(v.groups.length, 1);
+ assert.deepEqual(v.groups[0].members.map((m) => `${m.id}:${m.attached ? (m.badge ?? 1) : "-"}`), ["p-1:1", "p-2:2", "p-3:-", "p-5:3"]);
+ const three = v.groups[0].members.find((m) => m.id === "p-3");
+ assert.equal(three.captureSlug, "obv-x-replies");
+ assert.equal(three.after, "p-2");
+ const r = await run(["repeats", "rep"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /1 attachment\(s\) played more than once/);
+ assert.match(r.out, /×3\s+p-5/);
+ assert.match(r.out, /NOT ATTACHED: its capture obv-x-replies\/posts-media\/3\/3_1\.mp4/);
+ assert.match(r.out, /insert --after p-2 post:obv-x-replies\/3 --id p-3/);
+ const j = JSON.parse((await run(["repeats", "rep", "--json", "--match", "id"])).out);
+ assert.equal(j.match, "id");
+ assert.equal(j.groups.length, 0, "the GIF's ids differ: by id alone, no repeat");
+ assert.equal((await run(["repeats", "rep", "--match", "pixels"])).code, 2);
+});
+
+test("posts combo: an item's badge off (it still counts) and back; the cut's knobs set and refused in the build's words", async () => {
+ const p = await project("knobs");
+ let r = await run(["combo", "knobs", "p-2", "off"]);
+ assert.equal(r.code, 0, r.err);
+ assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-2").combo, false);
+ let v = await repeatsView(p);
+ assert.deepEqual(v.groups[0].members.filter((m) => m.attached).map((m) => `${m.id}:${m.badge}${m.show ? "!" : ""}`), ["p-1:1", "p-2:2", "p-5:3!"]);
+ r = await run(["combo", "knobs", "p-2", "on"]);
+ assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-2").combo, undefined);
+ r = await run(["combo", "knobs", "p-5", "label=HIT", "color=#22ccff"]);
+ assert.deepEqual((await manifest(p)).timeline.find((e) => e.id === "p-5").combo, { label: "HIT", color: "#22ccff" });
+ r = await run(["combo", "knobs", "p-5", "label="]);
+ assert.deepEqual((await manifest(p)).timeline.find((e) => e.id === "p-5").combo, { color: "#22ccff" });
+ // The cut's.
+ r = await run(["combo", "knobs", "minCount=3", "sfx=hit", "scale=1.5"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual((await manifest(p)).render.posts, { combo: { minCount: 3, sfx: "hit", scale: 1.5 } });
+ v = await repeatsView(p);
+ assert.deepEqual(v.groups[0].members.filter((m) => m.attached).map((m) => m.show), [false, false, true]);
+ r = await run(["combo", "knobs", "sfx=boom"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /render\.posts\.combo\.sfx must be one of off, hit, coin/);
+ r = await run(["combo", "knobs", "minCount=", "sfx=", "scale="]);
+ assert.equal((await manifest(p)).render.posts, undefined, "back to the defaults: no key left");
+ assert.equal((await run(["combo", "knobs", "p-9", "off"])).code, 2);
+ assert.equal((await run(["combo", "knobs", "p-5", "minCount=3"])).code, 2, "minCount is the cut's");
+ r = await run(["combo", "knobs"]);
+ assert.match(r.out, /label=COMBO/);
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -78,9 +78,11 @@ export const POSTS_USAGE = [
" every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as",
" its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read",
" none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.",
+ " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)",
+ " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (umtool posts repeats --help)",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete"]);
+const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -375,6 +377,8 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (verb === "avatar" && projectArg && !flags.has("--help")) return await avatarCommand(projectArg, words.slice(2), { root, json, out });
if (verb === "avatars" && projectArg && !flags.has("--help")) return await avatarsCommand(projectArg, { root, json, dryRun, out });
if (verb === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out });
+ // The combo counter (postComboCli.mjs): the attachments played more than once, the badge's knobs.
+ if (verb === "repeats" || verb === "combo") return await (await import("./postComboCli.mjs")).comboCommand(verb, words.slice(1), flags, { root, json, out, err });
if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) {
err(POSTS_USAGE);
return 2;
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -61,6 +61,9 @@
"./pauses": "./pauses.mjs",
"./post-links": "./post-links.mjs",
"./post-avatars": "./post-avatars.mjs",
+ "./post-combo": "./post-combo.mjs",
+ "./post-combo-prints": "./post-combo-prints.mjs",
+ "./post-combo-render": "./post-combo-render.mjs",
"./post-item": "./post-item.mjs",
"./post-narration": "./post-narration.mjs",
"./post-render": "./post-render.mjs",
diff --git a/umtool/report-to-video/post-combo-prints.mjs b/umtool/report-to-video/post-combo-prints.mjs
@@ -0,0 +1,224 @@
+// THE COMBO COUNTER's PRINTS (post-combo.mjs): what each post item's
+// attachment IS, read from disk -- its X media id and sha256 from the
+// capture's record (capture.json, the project's copy beside the file, else
+// the corpus's `channels/<slug>/posts-media/<postId>/`), the file hashed when
+// no record vouches for it, and (opt-in) its sound's fingerprint. Each
+// file's print is CACHED by its path, size and mtime: in memory, and on disk
+// under UMTOOL_PRINTS_CACHE (default ~/.cache/umtool/media-prints), so a
+// second look at a cut hashes nothing.
+//
+// attachmentPrints(manifest, dir, o) { "<itemId>:<i>": print }
+// projectCombos(dir, manifest, o) the groups and each item's combo (post-combo.mjs), one call
+//
+// Plain ESM, node only: the build, the CLI and umtool's server import it.
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import { createReadStream } from "node:fs";
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { COMBO_DEFAULTS, comboCounts, comboItems, comboKnobs, repeatGroups, tiersOf, xMediaIdOf } from "./post-combo.mjs";
+
+const execFileP = promisify(execFile);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+/** Where the prints are kept: UMTOOL_PRINTS_CACHE, else ~/.cache/umtool/media-prints (XDG_CACHE_HOME honoured). */
+export function printsCacheDir(env = process.env) {
+ if (env.UMTOOL_PRINTS_CACHE) return env.UMTOOL_PRINTS_CACHE;
+ return path.join(/* turbopackIgnore: true */ env.XDG_CACHE_HOME || path.join(/* turbopackIgnore: true */ os.homedir(), ".cache"), "umtool", "media-prints");
+}
+
+const memo = new Map();
+const MEMO_MAX = 4000;
+
+/** A file's cached print fields (`sha256`, `audio`), keyed by its path and signature. */
+async function cached(file, sig, cacheDir, field, make) {
+ // No cache asked for (null): made every time.
+ if (cacheDir === null) return make();
+ const key = createHash("sha1").update(file).digest("hex");
+ let rec = memo.get(key);
+ if (!rec || rec.sig !== sig) {
+ rec = cacheDir ? await readFile(path.join(cacheDir, `${key}.json`), "utf8").then((t) => JSON.parse(t), () => null) : null;
+ if (!rec || rec.sig !== sig) rec = { sig, file };
+ }
+ if (!(field in rec)) {
+ rec[field] = await make();
+ if (cacheDir) {
+ await mkdir(cacheDir, { recursive: true }).catch(() => {});
+ const tmp = path.join(cacheDir, `.${key}.${process.pid}.tmp`);
+ await writeFile(tmp, JSON.stringify(rec), "utf8").then(() => rename(tmp, path.join(cacheDir, `${key}.json`)), () => {});
+ }
+ }
+ if (memo.size >= MEMO_MAX) memo.delete(memo.keys().next().value);
+ memo.set(key, rec);
+ return rec[field];
+}
+
+/** A file's sha256, streamed. */
+export function sha256File(file) {
+ return new Promise((resolve, reject) => {
+ const h = createHash("sha256");
+ createReadStream(file).on("data", (b) => h.update(b)).on("end", () => resolve(h.digest("hex"))).on("error", reject);
+ });
+}
+
+/**
+ * The sound's fingerprint: chromaprint's raw print (`fpcalc -raw`, its first
+ * 30 s), else the coarse hash -- ffmpeg's 8 kHz mono, each 1/8 s its energy
+ * and its zero crossings against the one before (2 bits), 16 steps to a word.
+ * Null for a file with no sound, or when neither tool runs.
+ *
+ * @returns {Promise<{ kind: "chromaprint"|"energy", bits: number, words: number[], seconds: number } | null>}
+ */
+export async function audioPrintOf(file, { fpcalc = process.env.FPCALC_BIN ?? "fpcalc", ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg", exec = execFileP } = {}) {
+ try {
+ const r = await exec(fpcalc, ["-raw", "-json", "-length", "30", file], { maxBuffer: 1 << 24 });
+ const j = JSON.parse(String(r.stdout));
+ if (Array.isArray(j?.fingerprint) && j.fingerprint.length) return { kind: "chromaprint", bits: 32, words: j.fingerprint.map((v) => v >>> 0), seconds: Number(j.duration) || 0 };
+ } catch {
+ // no fpcalc, or no sound it can read: the coarse hash
+ }
+ try {
+ const r = await exec(ffmpeg, ["-nostdin", "-v", "error", "-t", "30", "-i", file, "-vn", "-ac", "1", "-ar", "8000", "-f", "s16le", "-"], { encoding: "buffer", maxBuffer: 1 << 26 });
+ return energyPrint(Buffer.from(r.stdout));
+ } catch {
+ return null;
+ }
+}
+
+/** The coarse hash of 8 kHz mono s16le samples (audioPrintOf's fallback), pure. Null when silent or too short. */
+export function energyPrint(buf, rate = 8000) {
+ const n = Math.floor(buf.length / 2);
+ const block = Math.round(rate / 8);
+ const blocks = Math.floor(n / block);
+ if (blocks < 4) return null;
+ const e = [];
+ const z = [];
+ for (let b = 0; b < blocks; b += 1) {
+ let s = 0;
+ let c = 0;
+ let prev = 0;
+ for (let i = 0; i < block; i += 1) {
+ const v = buf.readInt16LE((b * block + i) * 2);
+ s += v * v;
+ if (i && (v >= 0) !== (prev >= 0)) c += 1;
+ prev = v;
+ }
+ e.push(Math.sqrt(s / block));
+ z.push(c);
+ }
+ if (Math.max(...e) < 30) return null;
+ const bitsOut = [];
+ for (let b = 1; b < blocks; b += 1) bitsOut.push(e[b] > e[b - 1] ? 1 : 0, z[b] > z[b - 1] ? 1 : 0);
+ const words = [];
+ for (let i = 0; i + 16 <= bitsOut.length; i += 16) {
+ let w = 0;
+ for (let j = 0; j < 16; j += 1) w = (w << 1) | bitsOut[i + j];
+ words.push(w >>> 0);
+ }
+ return words.length ? { kind: "energy", bits: 16, words, seconds: n / rate } : null;
+}
+
+/** The capture record a project file came from: beside it in the project, else the corpus's (`posts-media/<slug>/<postId>/<name>`). */
+async function captureRecordOf(dir, src, entry, channelsDir) {
+ const name = path.basename(src);
+ const m = /^posts-media\/([^/]+)\/([^/]+)\/[^/]+$/.exec(src);
+ const tries = [path.join(dir, path.dirname(src), "capture.json")];
+ if (channelsDir && m) tries.push(path.join(channelsDir, m[1], "posts-media", m[2], "capture.json"));
+ const [slug, postId] = typeof entry?.post === "string" ? entry.post.split("/") : [];
+ if (channelsDir && slug && postId && !(m && m[1] === slug && m[2] === postId)) tries.push(path.join(channelsDir, slug, "posts-media", postId, "capture.json"));
+ for (const f of tries) {
+ const cap = await readFile(f, "utf8").then((t) => JSON.parse(t), () => null);
+ const rec = Array.isArray(cap?.media) ? cap.media.find((x) => x?.name === name) : null;
+ if (rec) return rec;
+ }
+ return null;
+}
+
+/**
+ * EVERY ATTACHMENT's PRINT in the cut: `{ "<itemId>:<i>": { mediaId, sha256,
+ * audio?, via } }` -- the media id from the capture's url, the sha256 from its
+ * record when the bytes agree (`via: "capture"`), else the file's own (`via:
+ * "hashed"`), the sound's print when `match` is "audio" and it is a video with
+ * sound. A file not on disk has no print (it cannot be told apart).
+ *
+ * @param {Record<string, any>} manifest
+ * @param {string} dir the project's folder (the manifest's)
+ * @param {{ channelsDir?: string|null, match?: string, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o]
+ */
+export async function attachmentPrints(manifest, dir, { channelsDir = null, match = null, cacheDir = printsCacheDir(), audioPrint = audioPrintOf } = {}) {
+ const tiers = tiersOf(match ?? comboKnobs(manifest?.render).match ?? COMBO_DEFAULTS.match);
+ const out = {};
+ for (const e of comboItems(manifest?.timeline)) {
+ for (const [i, m] of e.media.entries()) {
+ if (!isObj(m) || typeof m.src !== "string") continue;
+ const file = path.resolve(dir, m.src);
+ const st = await stat(file).catch(() => null);
+ if (!st?.isFile()) continue;
+ const sig = `${st.size}|${Math.round(st.mtimeMs)}`;
+ const rec = await captureRecordOf(dir, m.src, e, channelsDir);
+ const p = { mediaId: xMediaIdOf(rec?.url), sha256: null, via: null };
+ if (tiers.includes("sha256")) {
+ if (typeof rec?.sha256 === "string" && /^[0-9a-f]{64}$/.test(rec.sha256) && rec.bytes === st.size) {
+ p.sha256 = rec.sha256;
+ p.via = "capture";
+ } else {
+ p.sha256 = await cached(file, sig, cacheDir, "sha256", () => sha256File(file));
+ p.via = "hashed";
+ }
+ }
+ if (tiers.includes("audio") && m.kind === "video" && m.audio !== false) {
+ p.audio = await cached(file, sig, cacheDir, "audio", () => audioPrint(file));
+ }
+ out[`${e.id}:${i}`] = p;
+ }
+ }
+ return out;
+}
+
+/**
+ * THE CUT's COMBOS in one call: the repeat groups (post-combo.mjs
+ * repeatGroups) over the prints, and each item's combo (comboCounts).
+ *
+ * @param {string} dir
+ * @param {Record<string, any>} manifest
+ * @param {{ channelsDir?: string|null, match?: string|null, cacheDir?: string|null, audioPrint?: typeof audioPrintOf }} [o]
+ */
+export async function projectCombos(dir, manifest, o = {}) {
+ const match = o.match ?? comboKnobs(manifest?.render).match;
+ const prints = await attachmentPrints(manifest, dir, { ...o, match });
+ const groups = repeatGroups(manifest?.timeline, (id, i) => prints[`${id}:${i}`], { match });
+ return { match, groups, combos: comboCounts(manifest?.timeline, groups, manifest?.render), prints };
+}
+
+/**
+ * THE REPEATS THE CUT DOES NOT SHOW YET: a post item with no attachment in
+ * the cut whose capture holds one (captured after the item went in -- its
+ * media was never copied). Its capture is looked for under its own channel,
+ * then every channel the cut's posts come from (a reply captured under the
+ * replies channel). `{ <itemId>: [{ name, slug, mediaId, sha256, url }] }`.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {{ channelsDir?: string|null }} [o]
+ */
+export async function captureOnlyMedia(manifest, { channelsDir = null } = {}) {
+ if (!channelsDir) return {};
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const channels = [...new Set(tl.filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))];
+ const out = {};
+ for (const e of tl) {
+ if (e?.type !== "post" || typeof e.post !== "string" || (Array.isArray(e.media) && e.media.length)) continue;
+ const [own, postId] = e.post.split("/");
+ if (!own || !postId) continue;
+ for (const slug of [own, ...channels.filter((c) => c !== own)]) {
+ const dirOf = path.join(channelsDir, slug, "posts-media", postId);
+ const cap = await readFile(path.join(dirOf, "capture.json"), "utf8").then((t) => JSON.parse(t), () => null);
+ const media = Array.isArray(cap?.media) ? cap.media.filter((m) => typeof m?.name === "string") : [];
+ if (!media.length) continue;
+ out[e.id] = media.map((m) => ({ name: m.name, slug, mediaId: xMediaIdOf(m.url), sha256: typeof m.sha256 === "string" ? m.sha256 : null, url: typeof m.url === "string" ? m.url : null }));
+ break;
+ }
+ }
+ return out;
+}
diff --git a/umtool/report-to-video/post-combo.mjs b/umtool/report-to-video/post-combo.mjs
@@ -0,0 +1,427 @@
+// THE COMBO COUNTER (umtool/docs/report-video.md, "The combo counter"): when a
+// post item's attachment is one an EARLIER item of the cut already played --
+// the same reaction video answering a third person -- a fighting-game badge
+// pops onto the card as that attachment starts: "COMBO ×2", "×3", … (operator,
+// 3 Nov: "an effect that shows a combo counter or something when he uses the
+// same video to reply to someone").
+//
+// WHAT IS A REPEAT. Two attachments are the same when they share, in order of
+// trust:
+//
+// media-id X's own id for the media, from the capture's source url
+// (`amplify_video/<id>`, `ext_tw_video/<id>`, `tweet_video/<id>`,
+// pbs `media/<id>`) -- the same upload, attached again
+// sha256 the file's bytes (capture.json's `media[i].sha256`, trusted when
+// its `bytes` match the project's copy; else the copy hashed)
+// audio (opt-in, `match: "audio"`) the sound's fingerprint and its length
+// (chromaprint's fpcalc, else a coarse energy hash by ffmpeg): the
+// same clip re-encoded
+//
+// Any one tier links two attachments; the links make the groups (a GIF X
+// re-uploads gets a new id every time, and its bytes are what match). The
+// prints are read by post-combo-prints.mjs; everything here is PURE -- the
+// build, Play, the bench and `umtool posts repeats` read the same rules.
+//
+// THE COUNT is the use's number in the cut's ORDER (the timeline's, post items
+// only): the 2nd use is ×2. An item that turns its badge off (`combo: false`)
+// still counts -- the viewer saw the attachment -- its own badge is not drawn.
+// The badge shows from `minCount` (default 2).
+//
+// render.posts.combo = { on, label, position, color, scale, sfx, minCount, match }
+// timeline[i].combo = false | { on?, label?, position?, color?, scale?, sfx? }
+
+/** The cut's knobs (render.posts.combo) and their defaults. */
+export const COMBO_DEFAULTS = Object.freeze({
+ on: true,
+ label: "COMBO",
+ position: "top-right",
+ color: "#ffcf33",
+ scale: 1,
+ sfx: "off",
+ minCount: 2,
+ match: "file",
+});
+export const COMBO_POSITIONS = Object.freeze(["top-right", "top-left", "bottom-right", "bottom-left", "center"]);
+/** The bundled sounds (assets/combo/<name>.wav), and `off`. */
+export const COMBO_SFX = Object.freeze(["off", "hit", "coin"]);
+/** How deep the match goes: `id` the media id alone, `file` + the bytes, `audio` + the sound. */
+export const COMBO_MATCH = Object.freeze(["id", "file", "audio"]);
+export const COMBO_TIERS = Object.freeze(["media-id", "sha256", "audio"]);
+export const COMBO_LABEL_MAX = 16;
+export const COMBO_SCALE = Object.freeze({ min: 0.4, max: 2.5 });
+export const COMBO_MIN_COUNT = Object.freeze({ min: 2, max: 20 });
+/** The knobs a post item may override (minCount and match are the cut's). */
+export const COMBO_ITEM_KEYS = Object.freeze(["on", "label", "position", "color", "scale", "sfx"]);
+
+/**
+ * THE MOTION, in seconds from the attachment's start: a slam in from small to
+ * an OVERSHOOT (1.32×), a spring back through 0.86× to rest, a shake that dies
+ * away, the hold, then a fade out growing a little.
+ */
+export const COMBO_TIMING = Object.freeze({ fadeIn: 0.06, pop: 0.12, settle: 0.34, shake: 0.56, out: 2.2, end: 2.6 });
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r3 = (v) => Math.round(v * 1000) / 1000 + 0;
+const HEX_RE = /^#[0-9a-fA-F]{6}$/;
+
+// ---------------------------------------------------------------------------
+// The media id (tier 1)
+// ---------------------------------------------------------------------------
+
+/**
+ * X's id for a media url, `<kind>/<id>` (`amplify_video/2117…`,
+ * `tweet_video/HWCOFy3bwAAsJJS`, `media/HWEqGNfWYAAbqx_`), or null.
+ */
+export function xMediaIdOf(url) {
+ if (typeof url !== "string" || !url) return null;
+ let u;
+ try {
+ u = new URL(url);
+ } catch {
+ return null;
+ }
+ if (!/(^|\.)twimg\.com$/.test(u.hostname)) return null;
+ const v = /^\/(amplify_video|ext_tw_video|tweet_video)\/([A-Za-z0-9_-]+)/.exec(u.pathname);
+ if (v) return `${v[1]}/${v[2]}`;
+ const thumb = /^\/(amplify_video_thumb|ext_tw_video_thumb|tweet_video_thumb)\/([A-Za-z0-9_-]+)/.exec(u.pathname);
+ if (thumb) return `${thumb[1].replace(/_thumb$/, "")}/${thumb[2]}`;
+ const pic = /^\/media\/([A-Za-z0-9_-]+)/.exec(u.pathname);
+ return pic ? `media/${pic[1]}` : null;
+}
+
+// ---------------------------------------------------------------------------
+// The audio print (tier 3): compared pure
+// ---------------------------------------------------------------------------
+
+const popcount = (x) => {
+ let v = x >>> 0;
+ v -= (v >>> 1) & 0x55555555;
+ v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
+ return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;
+};
+
+/**
+ * How alike two audio prints are, 0-1: the best share of equal bits over
+ * small shifts of one against the other (`bits` per word: 32 for chromaprint,
+ * the energy hash's own). Null when they overlap too little to say.
+ *
+ * @param {{ words: number[], bits?: number }} a
+ * @param {{ words: number[], bits?: number }} b
+ */
+export function printSimilarity(a, b, o = {}) {
+ const x = Array.isArray(a?.words) ? a.words : [];
+ const y = Array.isArray(b?.words) ? b.words : [];
+ const bits = a?.bits ?? 32;
+ // About a second of overlap either way: chromaprint's word is ~0.12 s, the energy hash's 1 s.
+ const { maxShift = bits >= 32 ? 8 : 1, minOverlap = bits >= 32 ? 8 : 3 } = o;
+ let best = null;
+ for (let o = -maxShift; o <= maxShift; o += 1) {
+ let same = 0;
+ let n = 0;
+ for (let i = Math.max(0, -o); i < x.length && i + o < y.length; i += 1) {
+ same += bits - popcount((x[i] ^ y[i + o]) & (bits >= 32 ? 0xffffffff : (1 << bits) - 1));
+ n += 1;
+ }
+ if (n < minOverlap) continue;
+ const s = same / (n * bits);
+ if (best === null || s > best) best = s;
+ }
+ return best;
+}
+
+/** The share of bits two prints must agree on to be the same sound (chromaprint's; the coarse hash's is its own). */
+export const AUDIO_MATCH = Object.freeze({ chromaprint: 0.85, energy: 0.8 });
+
+/** Two attachments' sounds the same: the prints alike and the lengths within 0.3 s (or 3%). */
+export function audioSame(a, b) {
+ if (!isObj(a) || !isObj(b) || a.kind !== b.kind) return false;
+ if (fin(a.seconds) && fin(b.seconds) && Math.abs(a.seconds - b.seconds) > Math.max(0.3, 0.03 * Math.max(a.seconds, b.seconds))) return false;
+ const s = printSimilarity(a, b);
+ return s !== null && s >= (AUDIO_MATCH[a.kind] ?? 0.85);
+}
+
+// ---------------------------------------------------------------------------
+// The groups and the count
+// ---------------------------------------------------------------------------
+
+/** The post items of a timeline in its order, with an attachment. */
+export const comboItems = (timeline) => (Array.isArray(timeline) ? timeline : []).filter((e) => isObj(e) && e.type === "post" && typeof e.id === "string" && Array.isArray(e.media) && e.media.length);
+
+/** The tiers a `match` uses. */
+export const tiersOf = (match) => (match === "id" ? ["media-id"] : match === "audio" ? ["media-id", "sha256", "audio"] : ["media-id", "sha256"]);
+
+/** The strongest tier on which two prints agree, or null. */
+export function linkTier(p, q, tiers = tiersOf("file")) {
+ if (!isObj(p) || !isObj(q)) return null;
+ if (tiers.includes("media-id") && p.mediaId && p.mediaId === q.mediaId) return "media-id";
+ if (tiers.includes("sha256") && p.sha256 && p.sha256 === q.sha256) return "sha256";
+ if (tiers.includes("audio") && p.audio && q.audio && audioSame(p.audio, q.audio)) return "audio";
+ return null;
+}
+
+/**
+ * THE REPEAT GROUPS, pure: every attachment that another item of the cut
+ * also plays. `prints(itemId, i)` is attachment i's print (`{ mediaId?,
+ * sha256?, audio? }`, post-combo-prints.mjs). Each group's members are in
+ * the cut's order, one per item (an item with the attachment twice is one
+ * use), numbered from 1, each with the strongest tier linking it to an
+ * earlier member (`tier`, null for the first).
+ *
+ * @param {Array<Record<string, any>>} timeline
+ * @param {(id: string, i: number) => Record<string, any> | null | undefined} prints
+ * @param {{ match?: string }} [o]
+ * @returns {Array<{ key: string, tiers: string[], members: Array<{ id: string, i: number, n: number, post: string|null, date: string|null, tier: string|null }> }>}
+ */
+export function repeatGroups(timeline, prints, { match = COMBO_DEFAULTS.match } = {}) {
+ const tiers = tiersOf(match);
+ const items = comboItems(timeline);
+ const atts = [];
+ items.forEach((e, order) => e.media.forEach((m, i) => atts.push({ id: e.id, i, order, entry: e, p: prints(e.id, i) ?? null })));
+ // Union-find over the attachments: any tier links two.
+ const up = atts.map((_, k) => k);
+ const find = (k) => (up[k] === k ? k : (up[k] = find(up[k])));
+ for (let a = 0; a < atts.length; a += 1) {
+ for (let b = a + 1; b < atts.length; b += 1) {
+ if (atts[a].id === atts[b].id && atts[a].i === atts[b].i) continue;
+ if (linkTier(atts[a].p, atts[b].p, tiers)) up[find(b)] = find(a);
+ }
+ }
+ const byRoot = new Map();
+ atts.forEach((x, k) => {
+ const r = find(k);
+ if (!byRoot.has(r)) byRoot.set(r, []);
+ byRoot.get(r).push(x);
+ });
+ const groups = [];
+ for (const list of byRoot.values()) {
+ // One use per item: its first attachment in the group.
+ const seen = new Set();
+ const uses = list.sort((a, b) => a.order - b.order || a.i - b.i).filter((x) => (seen.has(x.id) ? false : seen.add(x.id)));
+ if (uses.length < 2) continue;
+ const members = uses.map((x, n) => {
+ let tier = null;
+ for (let j = 0; j < n; j += 1) {
+ const t = linkTier(x.p, uses[j].p, tiers);
+ if (t && (tier === null || COMBO_TIERS.indexOf(t) < COMBO_TIERS.indexOf(tier))) tier = t;
+ }
+ // Linked only through a later member (a chain): the weakest tier of the group says how.
+ return { id: x.id, i: x.i, n: n + 1, post: typeof x.entry.post === "string" ? x.entry.post : null, date: typeof x.entry.date === "string" ? x.entry.date : null, tier, src: typeof x.entry.media[x.i]?.src === "string" ? x.entry.media[x.i].src : null };
+ });
+ const tiersUsed = [...new Set(members.map((m) => m.tier).filter(Boolean))].sort((a, b) => COMBO_TIERS.indexOf(a) - COMBO_TIERS.indexOf(b));
+ groups.push({ key: "", tiers: tiersUsed, members });
+ }
+ groups.sort((a, b) => items.findIndex((e) => e.id === a.members[0].id) - items.findIndex((e) => e.id === b.members[0].id));
+ groups.forEach((g, k) => (g.key = `g${k + 1}`));
+ return groups;
+}
+
+/**
+ * The cut's knobs with every default filled in (render.posts.combo), and an
+ * item's overrides on top (`combo: false` is `{ on: false }`).
+ */
+export function comboKnobs(render, entry = null) {
+ const r = isObj(render?.posts) && isObj(render.posts.combo) ? render.posts.combo : {};
+ const own = entry?.combo === false ? { on: false } : isObj(entry?.combo) ? entry.combo : {};
+ const pick = Object.fromEntries(COMBO_ITEM_KEYS.filter((k) => own[k] !== undefined).map((k) => [k, own[k]]));
+ return { ...COMBO_DEFAULTS, ...r, ...pick };
+}
+
+/**
+ * EACH ITEM's COMBO, pure: `{ [itemId]: { count, media, group, show, knobs,
+ * members } }` for every item in a repeat group -- `count` its use's number,
+ * `media` the attachment it repeats (the first of its attachments with an
+ * earlier use; else its first in a group), `show` whether its badge is drawn
+ * (the cut's `on`, the item's own, count ≥ minCount).
+ */
+export function comboCounts(timeline, groups, render = undefined) {
+ const cut = comboKnobs(render);
+ const out = {};
+ const byId = new Map((Array.isArray(timeline) ? timeline : []).filter(isObj).map((e) => [e.id, e]));
+ // The item's repeat: an attachment with an earlier use before one that is a first, then the lower index.
+ const better = (m, had) => (m.n >= 2) !== (had.count >= 2) ? m.n >= 2 : m.i < had.media;
+ for (const g of groups) {
+ for (const m of g.members) {
+ const had = out[m.id];
+ if (had && !better(m, had)) continue;
+ const entry = byId.get(m.id);
+ const knobs = comboKnobs(render, entry);
+ out[m.id] = {
+ count: m.n,
+ media: m.i,
+ group: g.key,
+ tier: m.tier,
+ show: cut.on !== false && knobs.on !== false && m.n >= Math.max(COMBO_MIN_COUNT.min, cut.minCount),
+ knobs,
+ members: g.members.map(({ id, i, n, post, date, tier }) => ({ id, i, n, post, date, tier })),
+ };
+ }
+ }
+ return out;
+}
+
+/** The text a badge draws: its label and "×<count>". */
+export const comboText = (count, knobs = COMBO_DEFAULTS) => ({ label: String(knobs.label ?? COMBO_DEFAULTS.label), count: `×${count}` });
+
+/** When the badge pops, on the item's clock: the start of the step that plays attachment `media` (null: it never plays). */
+export function comboStart(plan, media) {
+ const st = (Array.isArray(plan?.steps) ? plan.steps : []).find((s) => (s.items ?? []).some((m) => m.i === media));
+ return st && fin(st.at) ? r3(st.at) : null;
+}
+
+// ---------------------------------------------------------------------------
+// The motion
+// ---------------------------------------------------------------------------
+
+const easeOutCubic = (u) => 1 - (1 - u) ** 3;
+
+/**
+ * The badge at `t` seconds after it pops, pure: `{ scale, x, y, rotate,
+ * opacity }` (x, y px of a 1080-high frame, before `k`; rotate degrees), or
+ * null when it is not up. `mirror` tilts it the other way (a left corner).
+ */
+export function comboFrame(t, { mirror = false } = {}) {
+ const T = COMBO_TIMING;
+ if (!fin(t) || t < 0 || t >= T.end) return null;
+ let scale;
+ if (t < T.pop) scale = 0.3 + (1.32 - 0.3) * easeOutCubic(t / T.pop);
+ else if (t < T.settle) {
+ const u = (t - T.pop) / (T.settle - T.pop);
+ scale = 1 + 0.32 * (1 - u) ** 2 * Math.cos(3 * Math.PI * u);
+ } else if (t < T.out) scale = 1;
+ else scale = 1 + 0.12 * ((t - T.out) / (T.end - T.out));
+ const opacity = t < T.fadeIn ? t / T.fadeIn : t >= T.out ? 1 - (t - T.out) / (T.end - T.out) : 1;
+ const d = t >= T.pop && t < T.shake ? 1 - (t - T.pop) / (T.shake - T.pop) : 0;
+ const x = 14 * d * Math.sin(2 * Math.PI * 24 * t);
+ const y = 9 * d * Math.sin(2 * Math.PI * 31 * t + 1);
+ const tilt = mirror ? 7 : -7;
+ const rotate = tilt + 4 * d * Math.sin(2 * Math.PI * 19 * t);
+ return { scale: r3(scale), x: r3(x), y: r3(y), rotate: r3(rotate), opacity: r3(Math.max(0, Math.min(1, opacity))) };
+}
+
+/** The badge's CSS transform for a frame (`k`: px per 1080-frame px). */
+export const comboTransform = (f, k = 1) => `translate(${r3(f.x * k)}px, ${r3(f.y * k)}px) rotate(${f.rotate}deg) scale(${f.scale})`;
+
+// ---------------------------------------------------------------------------
+// Its box and its look
+// ---------------------------------------------------------------------------
+
+/** The badge's size at rest, px of the item's box: label over count, sized from their characters. */
+export function comboSize(count, knobs, boxHeight) {
+ const k = (boxHeight / 1080) * (fin(knobs?.scale) ? knobs.scale : 1);
+ const { label, count: n } = comboText(count, knobs);
+ const N = 118 * k;
+ const L = 40 * k;
+ const w = Math.max(label.length * 0.66 * L + 0.14 * L * label.length, n.length * 0.62 * N) + 48 * k;
+ const h = (label ? L * 1.1 : 0) + N * 0.98 + 30 * k;
+ const even = (v) => Math.max(2, Math.ceil(v / 2) * 2);
+ return { width: even(w), height: even(h), number: Math.round(N), label: Math.round(L), k };
+}
+
+/**
+ * WHERE IT SITS, px of the item's box: centred on the attachment's corner
+ * (`position`), pulled in by a third of its size so it overlaps the picture,
+ * kept inside the box. `region` is what the build draws its frames in: the
+ * badge at its biggest, tilted and shaken, around the same centre.
+ *
+ * @param {{ x: number, y: number, width: number, height: number }} media the attachment's box (stepBoxes)
+ * @param {{ width: number, height: number }} box the item's box
+ */
+export function comboPlace(count, knobs, media, box) {
+ const s = comboSize(count, knobs, box.height);
+ const pos = COMBO_POSITIONS.includes(knobs?.position) ? knobs.position : COMBO_DEFAULTS.position;
+ const left = pos.endsWith("left");
+ const top = pos.startsWith("top");
+ let cx = pos === "center" ? media.x + media.width / 2 : left ? media.x + s.width * 0.18 : media.x + media.width - s.width * 0.18;
+ let cy = pos === "center" ? media.y + media.height / 2 : top ? media.y + s.height * 0.12 : media.y + media.height - s.height * 0.12;
+ // The region: the badge at 1.32×, tilted to 11°, shaken 14 px -- its bounding box, even-sized -- kept in the box.
+ const a = (11 * Math.PI) / 180;
+ const big = 1.32;
+ const rw = big * (s.width * Math.cos(a) + s.height * Math.sin(a)) + 2 * 14 * s.k + 4;
+ const rh = big * (s.width * Math.sin(a) + s.height * Math.cos(a)) + 2 * 9 * s.k + 4;
+ const even = (v) => Math.max(2, Math.ceil(v / 2) * 2);
+ const region = { width: Math.min(even(rw), Math.floor(box.width / 2) * 2), height: Math.min(even(rh), Math.floor(box.height / 2) * 2) };
+ cx = Math.min(box.width - region.width / 2, Math.max(region.width / 2, cx));
+ cy = Math.min(box.height - region.height / 2, Math.max(region.height / 2, cy));
+ region.x = Math.round(cx - region.width / 2);
+ region.y = Math.round(cy - region.height / 2);
+ return { center: { x: r3(cx), y: r3(cy) }, size: s, region, mirror: left };
+}
+
+const esc = (s) => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
+const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => `\\${c === "\n" ? "a " : c}`);
+
+function shade(hex, to, t) {
+ const h = HEX_RE.test(hex) ? hex.slice(1) : COMBO_DEFAULTS.color.slice(1);
+ const g = HEX_RE.test(to) ? to.slice(1) : "000000";
+ const c = [0, 2, 4].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) + (parseInt(g.slice(i, i + 2), 16) - parseInt(h.slice(i, i + 2), 16)) * t));
+ return `#${c.map((v) => v.toString(16).padStart(2, "0")).join("")}`;
+}
+
+/**
+ * THE BADGE's MARKUP, the same in the build's frames and in Play: a `<style>`
+ * (its own class names, `umc-`) and the badge, `size` px, its label over its
+ * count -- a heavy face skewed, the count filled top to bottom from `color`
+ * toward a hot red, a thick dark outline and a red under-shadow. `font`: a url
+ * for the face (the cut's bold); none, sans-serif. Its transform is set per
+ * frame on `[data-combo-badge]`.
+ */
+export function comboBadgeHtml(count, knobs, size, { font = "" } = {}) {
+ const { label, count: n } = comboText(count, knobs);
+ const color = HEX_RE.test(knobs?.color) ? knobs.color : COMBO_DEFAULTS.color;
+ const hot = shade(color, "#ff3b1f", 0.7);
+ const ink = "#1b0b02";
+ const o = Math.max(1, Math.round(size.number * 0.045));
+ const ol = Math.max(1, Math.round(size.label * 0.09));
+ const outline = (w, c) => `drop-shadow(${w}px 0 0 ${c}) drop-shadow(-${w}px 0 0 ${c}) drop-shadow(0 ${w}px 0 ${c}) drop-shadow(0 -${w}px 0 ${c})`;
+ return `<style>
+${font ? `@font-face { font-family: 'UmcFace'; src: url('${cssStr(font)}'); }` : ""}
+.umc-badge { position: absolute; left: 0; top: 0; width: ${size.width}px; height: ${size.height}px; display: flex; flex-direction: column; align-items: center; justify-content: center; transform-origin: 50% 50%; font-family: ${font ? "'UmcFace', " : ""}'Arial Black', 'Helvetica Neue', sans-serif; font-weight: 900; line-height: 1; white-space: nowrap; pointer-events: none; }
+.umc-skew { display: flex; flex-direction: column; align-items: center; transform: skewX(-9deg); }
+.umc-label { font-size: ${size.label}px; letter-spacing: 0.14em; color: #ffffff; filter: ${outline(ol, ink)} drop-shadow(0 ${ol * 2}px 0 ${hot}); margin-bottom: ${Math.round(size.label * 0.08)}px; }
+.umc-count { font-size: ${size.number}px; letter-spacing: 0.01em; background: linear-gradient(180deg, #fffbe6 0%, ${color} 38%, ${hot} 100%); -webkit-background-clip: text; background-clip: text; color: transparent; -webkit-text-fill-color: transparent; filter: ${outline(o, ink)} drop-shadow(0 ${o * 2}px 0 ${hot}) drop-shadow(0 ${o * 3}px ${o * 2}px rgba(0,0,0,0.45)); }
+</style><div class="umc-badge" data-combo-badge="${count}"><div class="umc-skew">${label ? `<span class="umc-label">${esc(label)}</span>` : ""}<span class="umc-count">${esc(n)}</span></div></div>`;
+}
+
+// ---------------------------------------------------------------------------
+// The validators
+// ---------------------------------------------------------------------------
+
+function knobErrors(o, where, keys) {
+ const errors = [];
+ for (const k of Object.keys(o)) if (!keys.includes(k)) errors.push(`${where}.${k} is not a combo knob (${keys.join(", ")})`);
+ if (o.on !== undefined && typeof o.on !== "boolean") errors.push(`${where}.on must be true or false`);
+ if (o.label !== undefined && !(typeof o.label === "string" && o.label.length <= COMBO_LABEL_MAX && !/[\n<>]/.test(o.label))) errors.push(`${where}.label must be a short line (at most ${COMBO_LABEL_MAX} characters; "" for the count alone)`);
+ if (o.position !== undefined && !COMBO_POSITIONS.includes(o.position)) errors.push(`${where}.position must be one of ${COMBO_POSITIONS.join(", ")}`);
+ if (o.color !== undefined && !(typeof o.color === "string" && HEX_RE.test(o.color))) errors.push(`${where}.color must be a #rrggbb colour`);
+ if (o.scale !== undefined && !(fin(o.scale) && o.scale >= COMBO_SCALE.min && o.scale <= COMBO_SCALE.max)) errors.push(`${where}.scale must be ${COMBO_SCALE.min}–${COMBO_SCALE.max}`);
+ if (o.sfx !== undefined && !COMBO_SFX.includes(o.sfx)) errors.push(`${where}.sfx must be one of ${COMBO_SFX.join(", ")}`);
+ if (o.minCount !== undefined && !(Number.isInteger(o.minCount) && o.minCount >= COMBO_MIN_COUNT.min && o.minCount <= COMBO_MIN_COUNT.max)) errors.push(`${where}.minCount must be a whole number ${COMBO_MIN_COUNT.min}–${COMBO_MIN_COUNT.max} (the use the badge first shows on)`);
+ if (o.match !== undefined && !COMBO_MATCH.includes(o.match)) errors.push(`${where}.match must be one of ${COMBO_MATCH.join(", ")}`);
+ return errors;
+}
+
+/** Every reason `render.posts.combo` cannot be built. */
+export function validatePostComboRender(render) {
+ const p = render?.posts;
+ if (p === undefined || p === null) return [];
+ if (!isObj(p)) return ["render.posts must be an object (its `combo` knobs)"];
+ const errors = Object.keys(p).filter((k) => k !== "combo").map((k) => `render.posts.${k} is not a knob (combo)`);
+ if (p.combo === undefined) return errors;
+ if (!isObj(p.combo)) return [...errors, "render.posts.combo must be an object of knobs"];
+ return [...errors, ...knobErrors(p.combo, "render.posts.combo", Object.keys(COMBO_DEFAULTS))];
+}
+
+/** Every reason one post item's `combo` cannot be built (false, or its overrides). */
+export function validatePostCombo(e) {
+ if (e?.combo === undefined || e.combo === false) return [];
+ const where = `timeline ${e?.id ?? "?"}.combo`;
+ if (!isObj(e.combo)) return [`${where} must be false (no badge on this item) or an object of knobs`];
+ return knobErrors(e.combo, where, [...COMBO_ITEM_KEYS]);
+}
+
+/** The cut's: every post item's combo and render.posts.combo (lint.mjs). */
+export function validatePostCombos(manifest) {
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ return [...validatePostComboRender(manifest?.render), ...tl.filter((e) => e?.type === "post").flatMap((e) => validatePostCombo(e))];
+}
diff --git a/umtool/report-to-video/post-combo.test.mjs b/umtool/report-to-video/post-combo.test.mjs
@@ -0,0 +1,251 @@
+// The combo counter (post-combo.mjs, post-combo-prints.mjs): the three tiers
+// of "the same attachment", the count in the cut's order, minCount, an item's
+// badge off, the motion, the knobs' validators.
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import {
+ COMBO_DEFAULTS, COMBO_TIMING, audioSame, comboBadgeHtml, comboCounts, comboFrame, comboKnobs, comboPlace, comboStart,
+ linkTier, printSimilarity, repeatGroups, validatePostCombo, validatePostComboRender, validatePostCombos, xMediaIdOf,
+} from "./post-combo.mjs";
+import { attachmentPrints, energyPrint, projectCombos } from "./post-combo-prints.mjs";
+
+const item = (id, src, extra = {}) => ({ type: "post", id, post: `chan/${id}`, date: `2026-11-0${id.length % 9}T00:00:00.000Z`, text: "", platform: "x", media: [{ src, kind: "gif", seconds: 2 }], ...extra });
+
+test("the X media id comes from the capture's url: video, GIF, thumb and picture; anything else is none", () => {
+ assert.equal(xMediaIdOf("https://video.twimg.com/amplify_video/2117250894920396961/vid/avc1/720x1280/a.mp4?tag=14"), "amplify_video/2117250894920396961");
+ assert.equal(xMediaIdOf("https://video.twimg.com/ext_tw_video/1999/pu/vid/x.mp4"), "ext_tw_video/1999");
+ assert.equal(xMediaIdOf("https://video.twimg.com/tweet_video/HWCOFy3bwAAsJJS.mp4"), "tweet_video/HWCOFy3bwAAsJJS");
+ assert.equal(xMediaIdOf("https://pbs.twimg.com/tweet_video_thumb/HWCOFy3bwAAsJJS.jpg"), "tweet_video/HWCOFy3bwAAsJJS");
+ assert.equal(xMediaIdOf("https://pbs.twimg.com/media/HWEqGNfWYAAbqx_?format=jpg&name=small"), "media/HWEqGNfWYAAbqx_");
+ assert.equal(xMediaIdOf("https://example.com/amplify_video/1/x.mp4"), null);
+ assert.equal(xMediaIdOf(null), null);
+ assert.equal(xMediaIdOf("not a url"), null);
+});
+
+test("tier by tier: the media id first, then the bytes, then (asked for) the sound -- the strongest agreeing tier names the link", () => {
+ const a = { mediaId: "amplify_video/1", sha256: "aa" };
+ assert.equal(linkTier(a, { mediaId: "amplify_video/1", sha256: "bb" }), "media-id");
+ // A GIF X re-uploads has a new id each time: its bytes are what match.
+ assert.equal(linkTier({ mediaId: "tweet_video/A", sha256: "cc" }, { mediaId: "tweet_video/B", sha256: "cc" }), "sha256");
+ assert.equal(linkTier({ mediaId: "tweet_video/A", sha256: "cc" }, { mediaId: "tweet_video/B", sha256: "cc" }, ["media-id"]), null);
+ const fp = (words) => ({ kind: "chromaprint", bits: 32, words, seconds: 10 });
+ const words = Array.from({ length: 40 }, (_, i) => (i * 2654435761) >>> 0);
+ const near = words.map((w, i) => (i % 5 === 0 ? (w ^ 0b111) >>> 0 : w));
+ assert.equal(linkTier({ sha256: "x", audio: fp(words) }, { sha256: "y", audio: fp(near) }), null, "the sound is opt-in");
+ assert.equal(linkTier({ sha256: "x", audio: fp(words) }, { sha256: "y", audio: fp(near) }, ["media-id", "sha256", "audio"]), "audio");
+ // The same print shifted (a clip trimmed by a frame) still matches; a different length does not.
+ assert.ok(printSimilarity(fp(words), fp(words.slice(3))) > 0.99);
+ assert.equal(audioSame(fp(words), { ...fp(words), seconds: 14 }), false);
+ assert.equal(audioSame(fp(words), fp(words.map((w) => (~w) >>> 0))), false);
+});
+
+test("the repeat groups are in the cut's order, one use per item, each numbered and linked by its tier", () => {
+ const timeline = [
+ item("p1", "posts-media/a/1/1_1.mp4"),
+ { type: "clip", id: "c1" },
+ item("p2", "posts-media/a/2/2_1.mp4"),
+ item("p3", "posts-media/a/3/3_1.mp4"),
+ item("p4", "posts-media/a/4/4_1.mp4"),
+ { ...item("p5", "posts-media/a/5/5_1.mp4"), media: [{ src: "x/5a.mp4", kind: "gif", seconds: 2 }, { src: "x/5b.mp4", kind: "gif", seconds: 2 }] },
+ item("p6", "posts-media/a/6/6_1.mp4", { media: undefined }),
+ ];
+ const prints = {
+ "p1:0": { mediaId: "tweet_video/A", sha256: "S" },
+ "p2:0": { mediaId: "tweet_video/B", sha256: "T" },
+ "p3:0": { mediaId: "tweet_video/C", sha256: "S" },
+ "p4:0": { mediaId: "tweet_video/A", sha256: "Q" },
+ // The same attachment twice in one item is one use.
+ "p5:0": { sha256: "T" },
+ "p5:1": { sha256: "T" },
+ };
+ const groups = repeatGroups(timeline, (id, i) => prints[`${id}:${i}`]);
+ assert.deepEqual(groups.map((g) => [g.key, g.members.map((m) => `${m.id}#${m.n}:${m.tier ?? "-"}`)]), [
+ ["g1", ["p1#1:-", "p3#2:sha256", "p4#3:media-id"]],
+ ["g2", ["p2#1:-", "p5#2:sha256"]],
+ ]);
+ assert.deepEqual(groups[0].tiers, ["media-id", "sha256"]);
+ // Moved in the cut, the numbers follow the cut, not the dates.
+ const moved = [timeline[4], timeline[0], timeline[3], timeline[2], timeline[5]];
+ assert.deepEqual(repeatGroups(moved, (id, i) => prints[`${id}:${i}`])[0].members.map((m) => `${m.id}#${m.n}`), ["p4#1", "p1#2", "p3#3"]);
+});
+
+test("the count: ×2 from the second use; minCount raises the first badge; an item's badge off still counts", () => {
+ const timeline = [item("a", "m/a.mp4"), item("b", "m/b.mp4"), item("c", "m/c.mp4"), item("d", "m/d.mp4")];
+ const all = () => ({ sha256: "same" });
+ const groups = repeatGroups(timeline, all);
+ let combos = comboCounts(timeline, groups, {});
+ assert.deepEqual(Object.fromEntries(Object.entries(combos).map(([id, c]) => [id, `${c.count}${c.show ? "!" : ""}`])), { a: "1", b: "2!", c: "3!", d: "4!" });
+ combos = comboCounts(timeline, groups, { posts: { combo: { minCount: 3 } } });
+ assert.deepEqual(Object.values(combos).map((c) => c.show), [false, false, true, true]);
+ // b's badge off: c is still ×3 (the viewer saw b), only b draws none.
+ const off = timeline.map((e) => (e.id === "b" ? { ...e, combo: false } : e));
+ combos = comboCounts(off, repeatGroups(off, all), {});
+ assert.deepEqual(Object.values(combos).map((c) => `${c.count}${c.show ? "!" : ""}`), ["1", "2", "3!", "4!"]);
+ // The cut's off: none drawn, the counts kept.
+ combos = comboCounts(timeline, groups, { posts: { combo: { on: false } } });
+ assert.deepEqual(Object.values(combos).map((c) => c.show), [false, false, false, false]);
+ // An item's own overrides ride on the cut's.
+ const own = timeline.map((e) => (e.id === "c" ? { ...e, combo: { label: "HIT", color: "#22ccff" } } : e));
+ const c = comboCounts(own, repeatGroups(own, all), { posts: { combo: { scale: 1.5 } } }).c;
+ assert.deepEqual([c.knobs.label, c.knobs.color, c.knobs.scale, c.knobs.position], ["HIT", "#22ccff", 1.5, "top-right"]);
+});
+
+test("the badge pops when its attachment's step starts, and moves: slam, overshoot, spring, shake, hold, fade", () => {
+ const plan = { steps: [{ kind: "image", at: 0, items: [{ i: 0 }] }, { kind: "video", at: 3.5, items: [{ i: 1 }] }] };
+ assert.equal(comboStart(plan, 1), 3.5);
+ assert.equal(comboStart(plan, 0), 0);
+ assert.equal(comboStart(plan, 2), null);
+ assert.equal(comboFrame(-0.01), null);
+ assert.equal(comboFrame(COMBO_TIMING.end), null);
+ const f0 = comboFrame(0);
+ assert.ok(f0 && f0.scale < 0.5 && f0.opacity === 0);
+ const peak = comboFrame(COMBO_TIMING.pop);
+ assert.ok(peak.scale > 1.3, `the overshoot (${peak.scale})`);
+ const dips = [];
+ for (let t = COMBO_TIMING.pop; t < COMBO_TIMING.settle; t += 0.01) dips.push(comboFrame(t).scale);
+ assert.ok(Math.min(...dips) < 0.9, "it springs back under its size");
+ const rest = comboFrame(1.5);
+ assert.deepEqual(rest, { scale: 1, x: 0, y: 0, rotate: -7, opacity: 1 });
+ assert.equal(comboFrame(1.5, { mirror: true }).rotate, 7);
+ const shaking = comboFrame(0.2);
+ assert.ok(Math.abs(shaking.x) > 0 || Math.abs(shaking.y) > 0);
+ const fading = comboFrame(2.4);
+ assert.ok(fading.opacity > 0 && fading.opacity < 1 && fading.scale > 1);
+});
+
+test("the badge sits on the attachment's corner, inside the box; its markup carries the count and the label", () => {
+ const box = { width: 1920, height: 1080 };
+ const media = { x: 900, y: 100, width: 960, height: 540 };
+ const k = comboKnobs({});
+ const p = comboPlace(3, k, media, box);
+ assert.ok(p.center.x > media.x + media.width / 2 && p.center.y < media.y + media.height / 2, "top-right");
+ assert.ok(p.region.x >= 0 && p.region.x + p.region.width <= box.width + 1);
+ assert.ok(p.region.width >= p.size.width * 1.3 && p.region.height >= p.size.height * 1.3, "room for the overshoot");
+ assert.equal(p.mirror, false);
+ const left = comboPlace(3, { ...k, position: "bottom-left" }, media, box);
+ assert.ok(left.center.x < media.x + media.width / 2 && left.center.y > media.y + media.height / 2 && left.mirror);
+ // A corner off the box's edge is pulled in.
+ const edge = comboPlace(3, k, { x: 1500, y: 0, width: 420, height: 300 }, box);
+ assert.ok(edge.center.x + edge.size.width / 2 <= box.width && edge.center.y - edge.size.height / 2 >= 0);
+ assert.ok(comboPlace(3, { ...k, scale: 2 }, media, box).size.width > p.size.width * 1.8);
+ const html = comboBadgeHtml(3, k, p.size, { font: "file:///f/Bold.ttf" });
+ assert.match(html, /data-combo-badge="3"/);
+ assert.match(html, />COMBO</);
+ assert.match(html, />×3</);
+ assert.match(html, /UmcFace/);
+ assert.doesNotMatch(comboBadgeHtml(2, { ...k, label: "" }, p.size), /umc-label"/);
+ assert.match(comboBadgeHtml(2, { ...k, label: "<b>" }, p.size), /<b>/);
+});
+
+test("the knobs are refused in the build's words", () => {
+ assert.deepEqual(validatePostComboRender({}), []);
+ assert.deepEqual(validatePostComboRender({ posts: { combo: { ...COMBO_DEFAULTS, sfx: "hit", match: "audio" } } }), []);
+ const bad = validatePostComboRender({ posts: { combo: { on: "yes", position: "middle", color: "red", scale: 9, sfx: "boom", minCount: 1, match: "pixels", size: 2 }, other: 1 } });
+ for (const want of ["render.posts.other", ".on must", ".position must", ".color must", ".scale must", ".sfx must", ".minCount must", ".match must", ".size is not"]) {
+ assert.ok(bad.some((e) => e.includes(want)), `${want} in ${bad.join(" | ")}`);
+ }
+ assert.deepEqual(validatePostCombo({ id: "p", combo: false }), []);
+ assert.deepEqual(validatePostCombo({ id: "p", combo: { on: false, label: "HIT" } }), []);
+ assert.match(validatePostCombo({ id: "p", combo: { minCount: 3 } })[0], /minCount is not a combo knob/);
+ assert.match(validatePostCombo({ id: "p", combo: true })[0], /must be false/);
+ assert.match(validatePostCombo({ id: "p", combo: { label: "x".repeat(17) } })[0], /at most 16/);
+ assert.equal(validatePostCombos({ render: { posts: { combo: { on: 1 } } }, timeline: [{ type: "post", id: "p", combo: 2 }, { type: "clip", id: "c", combo: 2 }] }).length, 2);
+});
+
+// ---------------------------------------------------------------------------
+// The prints, off disk
+// ---------------------------------------------------------------------------
+
+const ff = (args) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);
+ if (r.status !== 0) throw new Error(String(r.stderr));
+};
+
+function project() {
+ const root = mkdtempSync(path.join(os.tmpdir(), "umtool-combo-"));
+ const dir = path.join(root, "proj");
+ const channels = path.join(root, "channels");
+ return { root, dir, channels, done: () => rmSync(root, { recursive: true, force: true }) };
+}
+
+test("the prints: the media id and sha256 from the capture (the project's copy, else the corpus's), else the file hashed; cached", async () => {
+ const p = project();
+ try {
+ const put = (rel, body) => {
+ mkdirSync(path.dirname(path.join(p.dir, rel)), { recursive: true });
+ writeFileSync(path.join(p.dir, rel), body);
+ };
+ // 1 and 3: the same bytes, different X ids (a GIF re-uploaded); 2: other bytes; 4: like 1, no capture anywhere.
+ put("posts-media/ch/1/1_1.mp4", "SAME-BYTES");
+ put("posts-media/ch/2/2_1.mp4", "OTHER");
+ put("posts-media/ch-replies/3/3_1.mp4", "SAME-BYTES");
+ put("posts-media/ch/4/4_1.mp4", "SAME-BYTES");
+ const sha = execFileSync("sha256sum", [path.join(p.dir, "posts-media/ch/1/1_1.mp4")], { encoding: "utf8" }).split(" ")[0];
+ // 1's record copied into the project (posts add does); 3's only in the corpus, under the replies channel.
+ writeFileSync(path.join(p.dir, "posts-media/ch/1/capture.json"), JSON.stringify({ media: [{ name: "1_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/AAA.mp4" }] }));
+ mkdirSync(path.join(p.channels, "ch-replies", "posts-media", "3"), { recursive: true });
+ writeFileSync(path.join(p.channels, "ch-replies", "posts-media", "3", "capture.json"), JSON.stringify({ media: [{ name: "3_1.mp4", bytes: 10, sha256: sha, url: "https://video.twimg.com/tweet_video/BBB.mp4" }] }));
+ // 2's record lies about its bytes (a file replaced since): it is hashed, not trusted.
+ writeFileSync(path.join(p.dir, "posts-media/ch/2/capture.json"), JSON.stringify({ media: [{ name: "2_1.mp4", bytes: 999, sha256: sha, url: "https://video.twimg.com/amplify_video/22/x.mp4" }] }));
+ const manifest = {
+ render: {},
+ timeline: [
+ item("p1", "posts-media/ch/1/1_1.mp4", { post: "ch/1" }),
+ item("p2", "posts-media/ch/2/2_1.mp4", { post: "ch/2" }),
+ item("p3", "posts-media/ch-replies/3/3_1.mp4", { post: "ch/3" }),
+ item("p4", "posts-media/ch/4/4_1.mp4", { post: "ch/4" }),
+ item("p5", "posts-media/ch/5/gone.mp4", { post: "ch/5" }),
+ ],
+ };
+ const cacheDir = path.join(p.root, "cache");
+ const prints = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir });
+ assert.deepEqual(prints["p1:0"], { mediaId: "tweet_video/AAA", sha256: sha, via: "capture" });
+ assert.deepEqual(prints["p3:0"], { mediaId: "tweet_video/BBB", sha256: sha, via: "capture" });
+ assert.equal(prints["p2:0"].via, "hashed");
+ assert.notEqual(prints["p2:0"].sha256, sha);
+ assert.equal(prints["p2:0"].mediaId, "amplify_video/22");
+ assert.deepEqual(prints["p4:0"], { mediaId: null, sha256: sha, via: "hashed" });
+ assert.equal(prints["p5:0"], undefined, "a file not on disk has no print");
+ const r = await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir });
+ assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}#${m.n}`)), [["p1#1", "p3#2", "p4#3"]]);
+ assert.equal(r.combos.p4.count, 3);
+ assert.equal(r.combos.p2, undefined);
+ // id-only: the GIF's new ids do not match.
+ assert.deepEqual((await projectCombos(p.dir, manifest, { channelsDir: p.channels, cacheDir, match: "id" })).groups, []);
+ // Cached: a second look reads the cache (a hash that would fail is never run).
+ const again = await attachmentPrints(manifest, p.dir, { channelsDir: p.channels, cacheDir: path.join(p.root, "cache") });
+ assert.equal(again["p4:0"].sha256, sha);
+ } finally {
+ p.done();
+ }
+});
+
+test("the sound's print: the same clip re-encoded matches, another sound does not; the coarse hash when there is no fpcalc", async () => {
+ const p = project();
+ try {
+ mkdirSync(p.dir, { recursive: true });
+ const a = path.join(p.dir, "a.mp4");
+ const b = path.join(p.dir, "b.mp4");
+ const c = path.join(p.dir, "c.mp4");
+ const src = "aevalsrc=0.6*sin(2*PI*(220+180*sin(2*PI*0.7*t))*t)*(0.5+0.5*sin(2*PI*1.3*t)):s=44100:d=6";
+ ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", src, "-shortest", "-c:v", "libx264", "-c:a", "aac", "-b:a", "128k", a]);
+ ff(["-i", a, "-c:v", "libx264", "-crf", "35", "-c:a", "aac", "-b:a", "64k", b]);
+ ff(["-f", "lavfi", "-i", "color=c=black:s=64x64:d=6", "-f", "lavfi", "-i", "anoisesrc=d=6:c=pink:a=0.4", "-shortest", "-c:v", "libx264", "-c:a", "aac", c]);
+ const vid = (id, src2) => ({ type: "post", id, text: "", date: "2026-11-01T00:00:00Z", media: [{ src: src2, kind: "video", seconds: 6, audio: true }] });
+ const manifest = { render: { posts: { combo: { match: "audio" } } }, timeline: [vid("a", "a.mp4"), vid("b", "b.mp4"), vid("c", "c.mp4")] };
+ const r = await projectCombos(p.dir, manifest, { cacheDir: null });
+ assert.deepEqual(r.groups.map((g) => g.members.map((m) => `${m.id}:${m.tier ?? "-"}`)), [["a:-", "b:audio"]]);
+ assert.notEqual(r.prints["a:0"].sha256, r.prints["b:0"].sha256);
+ // No fpcalc: ffmpeg's energy hash still tells the two sounds apart.
+ const noFp = await projectCombos(p.dir, manifest, { cacheDir: null, audioPrint: (f) => import("./post-combo-prints.mjs").then((m) => m.audioPrintOf(f, { fpcalc: "/nonexistent/fpcalc" })) });
+ assert.equal(noFp.prints["a:0"].audio.kind, "energy");
+ assert.deepEqual(noFp.groups.map((g) => g.members.map((m) => m.id)), [["a", "b"]]);
+ assert.equal(energyPrint(Buffer.alloc(16000 * 2)), null, "silence has no print");
+ } finally {
+ p.done();
+ }
+});