import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { CLIP_MIN_S, DEFAULT_PARAMS, USE_MIN_SCORE, analyze, laughKey, laughVoiceSpan, normalizeScope, voiceLaughs, widenTo, assignRoles, attributeLaughs, buildProposals, cleanTurns, cleanWords, energyLaughs, findMoments, laughEvents, laughScore, normalizeParams, rankIntoTarget, sentenceStarts, snapEdge, stableIds, tailEnd, textIn, textLaughs, turnStats, wordsFromCues, } from "./clips.mjs"; import { applyProposals, clipFromProposal, fixedClips, isAssistantClip, validateAssist } from "./assist.mjs"; import { REACTIONS_FILE, operatorRoles, readReactions, setSpeakerRole, writeReactions } from "./reactions.mjs"; import { HOST, LAUGHS, SUBJECT, reactionStream } from "../../testing/clips/reactionStream.mjs"; const tmp = () => mkdtempSync(path.join(os.tmpdir(), "clips-")); test("normalizeParams: the defaults, a value inside its bounds, a refusal outside them", () => { assert.deepEqual(normalizeParams(), { ...DEFAULT_PARAMS }); assert.equal(normalizeParams({ target: 300, laughMin: null }).target, 300); assert.throws(() => normalizeParams({ target: 2 }), /target must be a number from 10/); assert.throws(() => normalizeParams({ laughMin: "x" }), /laughMin/); }); test("turnStats + assignRoles: the host is the cluster of short turns spread across the stream, not the one with the most seconds", () => { const s = reactionStream(); const stats = turnStats(s.turns, s.duration); const host = stats.find((x) => x.index === HOST); const subject = stats.find((x) => x.index === SUBJECT); assert.ok(host && subject); assert.equal(host.short, 7); assert.equal(subject.short, 0); assert.ok(subject.seconds > host.seconds); const roles = assignRoles({ turns: s.turns, duration: s.duration }); assert.deepEqual(roles.map((r) => [r.index, r.role, r.label, r.how]), [ [0, "host", "Host", "auto"], [1, "subject", "Subject", "auto"], ]); }); test("assignRoles: the operator's word stands; a tiny cluster never wins; a split voice merges by its centroid", () => { const s = reactionStream(); // The operator says cluster 1 is the host: cluster 0 becomes the subject. const flipped = assignRoles({ turns: s.turns, duration: s.duration, operator: { 1: "host" } }); assert.deepEqual(flipped.map((r) => [r.index, r.role, r.how]), [ [0, "subject", "auto"], [1, "host", "operator"], ]); // A third cluster: two short turns (a sliver of the speech) — never the host by itself. const turns = [...s.turns, { start: 41, end: 42, speaker: 2 }, { start: 300, end: 301, speaker: 2 }]; const three = assignRoles({ turns, duration: s.duration }); assert.equal(three.find((r) => r.index === 2)?.role, "other"); assert.equal(three.find((r) => r.index === 2)?.label, "Speaker 3"); // …unless its voice is the host's: then it is the host too, sameAs 0. const merged = assignRoles({ turns, duration: s.duration, centroids: { 0: [1, 0, 0], 1: [0, 1, 0], 2: [0.9, 0.1, 0.05] } }); assert.deepEqual(merged.find((r) => r.index === 2), { index: 2, role: "host", label: "Host", seconds: 2, turns: 2, how: "auto", sameAs: 0 }); const apart = assignRoles({ turns, duration: s.duration, centroids: { 0: [1, 0, 0], 1: [0, 1, 0], 2: [0.3, 0.3, 0.9] } }); assert.equal(apart.find((r) => r.index === 2)?.role, "other"); }); test("cleanTurns drops broken turns and sorts; wordsFromCues spreads a cue's words over it, the first a sentence start", () => { assert.deepEqual(cleanTurns([{ start: 5, end: 4, speaker: 0 }, { start: 2, end: 3.456, speaker: 1 }, { start: 1, end: 2, speaker: 0 }, { start: 1, end: 2 }]), [ { start: 1, end: 2, speaker: 0 }, { start: 2, end: 3.46, speaker: 1 }, ]); const w = wordsFromCues([{ start: 10, end: 12, text: "aa bb" }, { start: 12, end: 13, text: " " }]); assert.deepEqual(w, [ { w: "aa", start: 10, end: 11, cueStart: true }, { w: "bb", start: 11, end: 12 }, ]); assert.deepEqual(sentenceStarts(cleanWords(w)), [10]); }); test("sentenceStarts, snapEdge, tailEnd: edges sit in the gaps between words, a tail ends in the next silence", () => { const words = cleanWords([ { w: "one", start: 0, end: 0.4 }, { w: "two.", start: 0.5, end: 0.9 }, { w: "three", start: 1.0, end: 1.4 }, { w: "four", start: 2.2, end: 2.6 }, { w: "five", start: 2.7, end: 3.1 }, ]); assert.deepEqual(sentenceStarts(words), [0, 1.0, 2.2]); assert.equal(snapEdge(words, 1.2, "start"), 0.95); // inside "three": its start, half the 0.1 gap back assert.equal(snapEdge(words, 1.7, "start"), 1.7); // in a gap: stays assert.equal(snapEdge(words, 1.2, "end"), 1.55); // the end of "three", 0.15 into the long gap assert.equal(tailEnd(words, 0.6), 1.6); // the silence after "three" assert.equal(tailEnd(words, 5), 5.3); // no words after: a short pad assert.equal(textIn(words, 0.45, 1.5), "two. three"); assert.equal(textIn(words, 0, 4, 12), "one two.…"); }); test("laughScore sums the family (at most 1); laughEvents joins runs over the bar", () => { assert.equal(laughScore([0.5, 0.4, 0.3]), 1); assert.equal(laughScore({ 16: 0.2, 21: 0.1, 17: 0.9 }), 0.30000000000000004); const ev = laughEvents({ t0: 10, hop: 0.5, window: 1, scores: [0, 0.3, 0.5, 0.1, 0.4, 0, 0, 0, 0.9] }, { laughMin: 0.25 }); // windows 1-2 (10.5–12), 4 (12–13: within the bridge, joined), 8 (14–15) assert.deepEqual(ev, [ { start: 10.5, end: 13, score: 0.4 }, { start: 14, end: 15, score: 0.9 }, ]); }); test("textLaughs finds the markers; energyLaughs finds wordless loud bursts in the host's turns only", () => { const words = cleanWords([ { w: "[laughter]", start: 5, end: 6 }, { w: "hahaha!", start: 6.2, end: 6.8 }, { w: "lol", start: 20, end: 20.3 }, { w: "hello", start: 30, end: 30.4 }, { w: "phaha", start: 40, end: 40.4 }, ]); assert.deepEqual(textLaughs(words), [ { start: 4.7, end: 7.5, score: 0.5, src: "text" }, { start: 19.7, end: 21, score: 0.5, src: "text" }, ]); const energy = new Array(40).fill(-40); energy[4] = -20; // 2–3 s: wordless, in the host's turn energy[10] = -20; // 5–6 s: in the subject's turn energy[20] = -20; // 10–11 s: but a word is there const turns = [{ start: 0, end: 4, speaker: 0 }, { start: 4, end: 20, speaker: 1 }]; const speakers = [{ index: 0, role: "host" }, { index: 1, role: "subject" }]; const got = energyLaughs({ t0: 0, hop: 0.5, window: 1, energy }, { words: cleanWords([{ w: "x", start: 10.2, end: 10.5 }]), turns, speakers }); assert.deepEqual(got, [{ start: 2, end: 3, score: 0.3, src: "energy" }]); }); test("attributeLaughs: a host turn that overlaps makes it the host's; else the most overlap; else nobody", () => { const turns = [{ start: 0, end: 10, speaker: 1 }, { start: 9, end: 11, speaker: 0 }, { start: 20, end: 30, speaker: 2 }]; const speakers = [{ index: 0, role: "host" }, { index: 1, role: "subject" }, { index: 2, role: "other" }]; const got = attributeLaughs([{ start: 5, end: 9.5 }, { start: 2, end: 3 }, { start: 15, end: 16 }, { start: 25, end: 26 }], turns, speakers); assert.deepEqual(got.map((l) => l.speaker), [0, 1, null, 2]); }); test("findMoments: host laughs and host comments, scored; a comment needs 1.5 s of words", () => { const s = reactionStream(); const speakers = assignRoles({ turns: s.turns, duration: s.duration }); const laughs = attributeLaughs(laughEvents(s.laughScan, { laughMin: 0.25 }), s.turns, speakers); const moments = findMoments({ turns: s.turns, speakers, laughs, words: cleanWords(s.words) }); assert.equal(moments.filter((m) => m.kind === "laugh").length, LAUGHS.length); assert.equal(moments.filter((m) => m.kind === "comment").length, 7); assert.deepEqual(moments.map((m) => m.id).slice(0, 3), ["m001", "m002", "m003"]); const strong = moments.find((m) => m.kind === "laugh" && m.t === 94.5); const weak = moments.find((m) => m.kind === "laugh" && m.t === 519.5); assert.ok(strong && weak && strong.score > weak.score); // A comment beside a laugh outranks one with none. const near = moments.find((m) => m.kind === "comment" && m.t === 95); const plain = moments.find((m) => m.kind === "comment" && m.t === 170); assert.ok(near && plain && near.score > plain.score); // No words in a host turn: no comment. const quiet = findMoments({ turns: [{ start: 0, end: 5, speaker: 0 }], speakers: [{ index: 0, role: "host" }], laughs: [], words: [] }); assert.deepEqual(quiet, []); }); test("buildProposals: the setup starts on a sentence of the subject's line, the reaction and tail follow, near spans merge", () => { const s = reactionStream(); const words = cleanWords(s.words); const speakers = assignRoles({ turns: s.turns, duration: s.duration }); const laughs = attributeLaughs(laughEvents(s.laughScan, { laughMin: 0.25 }), s.turns, speakers); const moments = findMoments({ turns: s.turns, speakers, laughs, words }); const props = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: {} }); const p = props.find((x) => x.moments.includes("m002")); assert.ok(p); // The laugh at 94.5 merged with the comment at 95 (they overlap). assert.deepEqual(p.moments, ["m002", "m003"]); // The setup: the latest sentence start at least 3 s before the laugh, in the gap before a word. assert.ok(p.start >= 94.5 - DEFAULT_PARAMS.setupMax && p.start <= 94.5 - 3, `start ${p.start}`); assert.ok(sentenceStarts(words).some((t) => Math.abs(t - 0.05 - p.start) < 0.11), `start ${p.start} on a sentence`); assert.ok(p.end > 100 && p.end <= 100 + 1.5 + 0.2, `end ${p.end}`); assert.match(p.why, /^host laughs \(3\.5 s\) .* after the narrated line/); // A tight clipMax splits nothing into overlong clips. const capped = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: { clipMax: 8, mergeGap: 60 } }); assert.ok(capped.every((x) => x.end - x.start <= 8 + 1e-9), JSON.stringify(capped.map((x) => x.end - x.start))); // A wide merge gap joins close spans while they fit clipMax. const wide = buildProposals({ moments, turns: s.turns, speakers, words, duration: s.duration, params: { mergeGap: 60, clipMax: 600 } }); assert.ok(wide.length < props.length); }); test("stableIds: a proposal that overlaps a previous one keeps its id; new ones take the next numbers", () => { const first = stableIds([{ start: 0, end: 10 }, { start: 20, end: 30 }]); assert.deepEqual(first.map((p) => p.id), ["p001", "p002"]); const again = stableIds([{ start: 1, end: 10 }, { start: 12, end: 15 }, { start: 21, end: 31 }], first); assert.deepEqual(again.map((p) => p.id), ["p001", "p003", "p002"]); }); test("rankIntoTarget: the best first while they fit; a proposal on a fixed clip is that clip; too short or too weak is never used", () => { const props = [ { id: "p001", start: 0, end: 30, score: 0.2 }, { id: "p002", start: 40, end: 60, score: 0.9 }, { id: "p003", start: 70, end: 100, score: 0.5 }, { id: "p004", start: 110, end: 115, score: 0.3 }, ]; const r = rankIntoTarget(props, { target: 60 }); assert.deepEqual(r.map((p) => [p.id, p.used]), [["p001", false], ["p002", true], ["p003", true], ["p004", true]]); const f = rankIntoTarget(props, { target: 60, fixed: [{ id: "r009", start: 0, end: 25 }] }); assert.deepEqual(f.map((p) => [p.id, p.used, p.fixedClip ?? null]), [["p001", true, "r009"], ["p002", true, null], ["p003", false, null], ["p004", true, null]]); // The floor: under CLIP_MIN_S, or scoring under USE_MIN_SCORE, stays listed and unused however much room is left. const junk = rankIntoTarget( [ { id: "p001", start: 0, end: 2, score: 0.9 }, { id: "p002", start: 10, end: 16, score: 0.106 }, { id: "p003", start: 20, end: 25, score: USE_MIN_SCORE }, ], { target: 600 }, ); assert.deepEqual(junk.map((p) => [p.id, p.used]), [["p001", false], ["p002", false], ["p003", true]]); assert.equal(CLIP_MIN_S, 5); }); test("widenTo + buildProposals: a span under CLIP_MIN_S is widened about its middle, edges in the word gaps", () => { const words = cleanWords(Array.from({ length: 40 }, (_, i) => ({ w: `w${i}`, start: i * 0.5, end: i * 0.5 + 0.4 }))); const w = widenTo(words, 9, 10, 5, 100); assert.ok(w.end - w.start >= 5, JSON.stringify(w)); assert.ok(w.start <= 9 && w.end >= 10); assert.ok(Math.abs((w.start + w.end) / 2 - 9.5) < 0.3); // Inside the recording. const edge = widenTo(words, 0, 1, 5, 100); assert.equal(edge.start, 0); assert.ok(edge.end >= 5); // A lone short laugh with nothing around it still makes a 5 s proposal. const speakers = [{ index: 0, role: "host", seconds: 10 }]; const moments = [{ id: "m001", t: 50, end: 51, kind: "laugh" as const, score: 0.5, speaker: 0, text: "" }]; const props = buildProposals({ moments, turns: [{ start: 49, end: 52, speaker: 0 }], speakers, words: [], duration: 100, params: {} }); assert.equal(props.length, 1); assert.ok(props[0].end - props[0].start >= 5); }); test("scope: only that part of the recording is read; normalizeParams keeps it", () => { assert.equal(normalizeParams({}).scope, null); assert.deepEqual(normalizeParams({ scope: [100, 300] }).scope, [100, 300]); assert.deepEqual(normalizeParams({ scope: [100, null] }).scope, [100, null]); assert.equal(normalizeParams({ scope: [0, null] }).scope, null); assert.equal(normalizeParams({ scope: "all" }).scope, null); assert.throws(() => normalizeScope([300, 100]), /0 ≤ from < to/); assert.throws(() => normalizeScope("x"), /scope must be/); const s = reactionStream(); const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { scope: [300, 450], target: 600 } }); assert.equal(a.duration, 450); assert.deepEqual(a.params.scope, [300, 450]); assert.ok(a.turns.every((t) => t.start >= 300 && t.end <= 450)); // The laugh at 340 is in; 95 and 520 are not. assert.deepEqual(a.laughs.map((l) => Math.round(l.start)), [340]); assert.ok(a.proposals.every((p) => p.end > 300 && p.start < 450)); assert.deepEqual(a.speakers.map((x) => [x.index, x.role]), [[0, "host"], [1, "subject"]]); }); test("voiceLaughs: a laugh in the subject's voice is the subject's, the host's over a narrated line the host's; else the overlap rule", () => { const speakers = [{ index: 1, role: "host", seconds: 100 }, { index: 4, role: "subject", seconds: 900 }, { index: 7, role: "other", seconds: 5 }]; const centroids = { 1: [1, 0, 0], 4: [0, 1, 0], 7: [0, 0, 1] }; const laughs = [ { start: 10, end: 12, score: 0.5, speaker: 1 }, // overlap said host, the voice is the narrator's { start: 20, end: 21, score: 0.5, speaker: 4 }, // overlap said subject, the voice is the host's { start: 30, end: 31, score: 0.5, speaker: 1 }, // neither voice clearly: the overlap stands { start: 40, end: 41, score: 0.5, speaker: 4 }, // no embedding ]; const voices = { [laughKey(laughs[0])]: [0.05, 0.4, 0.1], [laughKey(laughs[1])]: [0.3, 0.02, 0.1], [laughKey(laughs[2])]: [0.15, 0.1, 0.9], }; const got = voiceLaughs(laughs, speakers, centroids, voices); assert.deepEqual(got.map((l) => [l.speaker, l.by ?? null]), [[4, "voice"], [1, "voice"], [1, null], [4, null]]); assert.ok(got[0].voice && got[0].voice.subject > got[0].voice.host); assert.equal(got[3].voice, undefined); assert.deepEqual(laughVoiceSpan({ start: 10, end: 10.5 }), { start: 9.5, dur: 1.5 }); // Through analyze: the voice decides, and a narrator's laugh weighs less than a host's. const s = reactionStream(); const a0 = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan }); const lv = Object.fromEntries(a0.laughs.map((l, i) => [laughKey(l), i === 0 ? [0, 1, 0] : [1, 0, 0]])); const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, centroids: { 0: [1, 0, 0], 1: [0, 1, 0] }, laughVoices: lv }); assert.equal(a.laughs[0].speaker, SUBJECT); assert.equal(a.laughs[0].by, "voice"); assert.deepEqual(a.laughs[0].voice, { host: 0, subject: 1 }); assert.equal(a.laughs[1].speaker, HOST); const m0 = a.moments.find((m) => m.kind === "laugh" && m.t === a.laughs[0].start); const was = a0.moments.find((m) => m.kind === "laugh" && m.t === a0.laughs[0].start); assert.ok(m0 && was && m0.score < was.score * 0.5, `${m0?.score} vs ${was?.score}`); }); test("analyze: deterministic; the model's laughs when there is a scan, the transcript's markers when there is none", () => { const s = reactionStream(); const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { target: 120 } }); const b = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan, params: { target: 120 } }); assert.deepEqual(a, b); assert.equal(a.laughSource, "model"); assert.equal(a.laughs.length, 3); assert.ok(a.laughs.every((l) => l.speaker === HOST && !("src" in l))); assert.ok(a.proposals.length >= 5); const used = a.proposals.filter((p) => p.used).reduce((n, p) => n + p.end - p.start, 0); assert.ok(used <= 120 * 1.03, `used ${used}`); // The two strong laughs are the two best proposals. const best = [...a.proposals].sort((x, y) => y.score - x.score).slice(0, 2); assert.deepEqual(best.map((p) => p.moments.some((id) => a.moments.find((m) => m.id === id)?.kind === "laugh")), [true, true]); // No model: the "haha" words are the laughs, and the same moments come out. const c = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: null, params: { target: 120 } }); assert.equal(c.laughSource, "text"); assert.equal(c.laughs.length, 3); assert.ok(c.laughs.every((l) => l.src === "text")); // With an energy-only scan: "text+energy". const d = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: { t0: 0, hop: 0.5, window: 1, scores: null, energy: s.laughScan.scores.map(() => -30) } }); assert.equal(d.laughSource, "text+energy"); }); test("validateAssist: the plan's shape passes; broken keys are named", () => { const s = reactionStream(); const clip = clipFromProposal({ id: "p001", start: 48.2, end: 66, score: 0.83, why: "host laughs" }, { id: "r001", channel: "c", video: "v", duration: 600, words: cleanWords(s.words) }); assert.deepEqual(clip.assist, { by: "assistant", proposal: "p001", score: 0.83, why: "host laughs", original: { start: 46.7, end: 67.5, cutStart: 48.2, cutEnd: 66 }, edits: [] }); assert.equal(clip.start, 46.7); assert.ok(clip.quote.length > 0 && clip.quote.length <= 160); const edited = { ...clip, assist: { ...clip.assist, by: "operator", edits: [{ at: "2026-10-18T22:00:00Z", by: "operator", what: "trim", from: { cutStart: 48.2 }, to: { cutStart: 49 } }] } }; const added = { type: "clip", id: "r002", channel: "c", video: "v", start: 1, end: 5, assist: { by: "operator" } }; assert.deepEqual(validateAssist({ timeline: [clip, edited, added, { type: "clip", id: "x", start: 0, end: 1 }] }), []); const bad = validateAssist({ timeline: [ { type: "clip", id: "a", start: 0, end: 1, assist: { by: "robot" } }, { type: "clip", id: "b", start: 0, end: 1, assist: { by: "assistant" } }, { type: "clip", id: "c", start: 0, end: 1, assist: { by: "operator", score: 2, original: { start: 0 }, edits: [{ at: "nope", by: "operator", what: "nudge" }] } }, { type: "card", id: "d", assist: { by: "operator" } }, ], }); assert.equal(bad.length, 9, bad.join("\n")); assert.match(bad.join("\n"), /entry a: assist\.by must be/); assert.match(bad.join("\n"), /entry b: assist\.proposal must name/); assert.match(bad.join("\n"), /edits\[0\]\.what must be one of trim, split, merge, add, restore/); assert.match(bad.join("\n"), /entry d: assist is only for clips/); }); test("applyProposals: adds, updates in place, removes the assistant's; never moves the operator's, a ruled one or a locked one", () => { const s = reactionStream(); const words = cleanWords(s.words); const base = { channel: "c", video: "v", duration: 600, words }; const first = applyProposals([], { ...base, proposals: [ { id: "p001", start: 10, end: 20, score: 0.5, why: "a", used: true }, { id: "p002", start: 30, end: 40, score: 0.4, why: "b", used: true }, { id: "p003", start: 50, end: 60, score: 0.1, why: "c", used: false }, ], }); assert.deepEqual(first.timeline.map((e) => e.id), ["r001", "r002"]); assert.deepEqual(first.proposals.map((p) => p.clipId), ["r001", "r002", null]); assert.deepEqual(first.changes, { added: ["r001", "r002"], updated: [], removed: [], kept: 0 }); // The operator trims r002; adds a clip of their own at 70; a card sits first. const tl = [{ type: "card", id: "intro" }, ...first.timeline]; const r2 = tl.find((e) => e.id === "r002"); Object.assign(r2, { cutStart: 31, assist: { ...r2.assist, by: "operator" } }); tl.push({ type: "clip", id: "mine", channel: "c", video: "v", start: 69, end: 76, cutStart: 70, cutEnd: 75, assist: { by: "operator" } }); assert.deepEqual(fixedClips(tl, base).map((c) => c.id), ["r002", "mine"]); // A re-proposal: p001 moved, p002 is gone, p003 is now used, p004 is new and the cut is short. const second = applyProposals(tl, { ...base, proposals: [ { id: "p001", start: 11, end: 20, score: 0.5, why: "a", used: true }, { id: "p003", start: 50, end: 60, score: 0.6, why: "c", used: true }, { id: "p005", start: 70, end: 74, score: 0.7, why: "e", used: true, fixedClip: "mine" }, { id: "p004", start: 5, end: 8, score: 0.6, why: "d", used: true }, ], }); assert.deepEqual(second.timeline.map((e) => e.id), ["intro", "r004", "r001", "r002", "r003", "mine"]); assert.equal(second.timeline.find((e) => e.id === "r002").cutStart, 31); // the operator's, untouched assert.equal(second.timeline.find((e) => e.id === "r001").cutStart, 11); assert.deepEqual(second.changes, { added: ["r003", "r004"], updated: ["r001"], removed: [], kept: 0 }); assert.deepEqual(second.proposals.map((p) => p.clipId), ["r001", "r003", "mine", "r004"]); // A ruled or locked assistant clip is never removed. const third = applyProposals(second.timeline, { ...base, proposals: [], isProtected: (e) => e.id === "r001" }); assert.deepEqual(third.timeline.map((e) => e.id), ["intro", "r001", "r002", "mine"]); assert.deepEqual(third.changes.removed.sort(), ["r003", "r004"]); assert.ok(isAssistantClip(third.timeline[1]) && !isAssistantClip(third.timeline[2])); }); test("reactions.json: written whole, read back; setSpeakerRole marks the operator's role and records when", async () => { const dir = tmp(); try { assert.equal(await readReactions(dir), null); const s = reactionStream(); const a = analyze({ turns: s.turns, duration: s.duration, words: s.words, laughScan: s.laughScan }); const doc = { version: 1 as const, source: { channel: "c", video: "v", duration: 600, words: null, diarization: { generatedAt: null, engine: null } }, ...a, proposals: a.proposals.map((p) => ({ ...p, clipId: null })) }; await writeReactions(dir, doc); const back = await readReactions(dir); assert.ok(back); assert.equal(back.speakers.length, 2); assert.deepEqual(operatorRoles(back), {}); const after = await setSpeakerRole(dir, 1, "host", { now: () => new Date("2026-10-18T23:00:00Z") }); assert.deepEqual(after.speakers.map((x) => [x.index, x.role, x.how]), [[0, "other", "auto"], [1, "host", "operator"]]); assert.equal(after.rolesChangedAt, "2026-10-18T23:00:00.000Z"); assert.deepEqual(operatorRoles(await readReactions(dir)), { 1: "host" }); await setSpeakerRole(dir, 1, null); assert.deepEqual(operatorRoles(await readReactions(dir)), {}); await assert.rejects(setSpeakerRole(dir, 7, "host"), /no speaker 7/); await assert.rejects(setSpeakerRole(dir, 0, "boss" as never), /a role is one of/); // Not a reactions file: null, and the writer refuses. writeFileSync(path.join(dir, REACTIONS_FILE), JSON.stringify({ version: 2 })); assert.equal(await readReactions(dir), null); await assert.rejects(setSpeakerRole(dir, 0, "host"), /no reactions\.json/); assert.ok(readFileSync(path.join(dir, REACTIONS_FILE), "utf8").includes("2")); } finally { rmSync(dir, { recursive: true, force: true }); } });