Archilyzer · Source

archilyzer

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

commit 69d936f0cfc73ed94bde451245bce6fd8a310740
parent 74e70fac29663d486fa204eb0cbbd6425ad6098c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 00:21:01 -0400

umtool: the clip editor's writers -- assist edits, restore, split, merge, add; rulings follow their clips (release 35 C2)

updateClip appends an operator edit to an assistant's clip (`assist.edits`,
`assist.by` -> "operator" on the first); restoreClip puts `assist.original`
back; splitClip / mergeClips / addClip are structural (auto snapshot, the
build's checks). lib/report/clipEditor.mjs runs the editor's operations
(trim, restore, split, merge, add, bring-in, ruling, role) and moves a
keep/cut ruling with its clip when the moment key changes. reactions.json is
read through clipEditorBridge.mjs (a local stand-in for the clip finder's
setSpeakerRole until it lands). /api/report/clip-editor serves the view, the
strip's neighbourhood and the operations.

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

Diffstat:
Aumtool/app/api/report/clip-editor/route.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditor.mjs | 353+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditor.test.mjs | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorBridge.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorModel.mjs | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/clipEditorTypes.ts | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
7 files changed, 1275 insertions(+), 1 deletion(-)

diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -0,0 +1,61 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { OpError, StaleToken, StructureRefused, clipEditorView, clipNeighbourhood, runClipEditorOp } from "@/lib/report/clipEditor.mjs"; + +export const dynamic = "force-dynamic"; + +// THE CLIP EDITOR (release 35 C2): `/projects/<id>/clips` on a report video +// whose cut is not a montage -- an assistant's clips (the clip finder's), or +// any report video's, adjusted by a person. lib/report/clipEditor.mjs is the +// one place each write goes through. +// +// GET ?project=<id> the view: clips, token, speakers, unused proposals +// GET ?project=<id>&clip=<id>&from=<s>&to=<s> the strip for a span: turns, laughs, words | cues +// POST { project, op, token?, … } one operation (clipEditor.mjs runClipEditorOp): +// trim | restore | split | merge | add | bring-in | ruling | role +// -> { op, result, carried, view }; 409 on a stale token (reload), 400 with +// the sentence on a refusal (the build's own, for a structural one) +const headers = { "cache-control": "no-store" }; + +async function editorProject(id: unknown) { + const project = await projectRef(String(id ?? "")); + if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; + if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the clip editor is a report video's" }, { status: 400, headers }) }; + return { project }; +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await editorProject(url.searchParams.get("project")); + if ("error" in r) return r.error; + try { + if (url.searchParams.has("from")) { + const n = await clipNeighbourhood(r.project, { + clip: url.searchParams.get("clip"), + from: Number(url.searchParams.get("from")), + to: Number(url.searchParams.get("to")), + }); + return Response.json(n, { headers }); + } + const view = await clipEditorView(r.project); + if (!view) return Response.json({ error: "no manifest" }, { status: 400, headers }); + return Response.json(view, { headers }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers }); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const r = await editorProject(body.project); + if ("error" in r) return r.error; + try { + return Response.json(await runClipEditorOp(r.project, body), { headers }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message }, { status: 409, headers }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400, headers }); + const status = e instanceof OpError ? e.status : 400; + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); + } +} diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -0,0 +1,353 @@ +// THE CLIP EDITOR, server side (release 35 C2): a person hops in on the clips +// an assistant made -- or on any report video's clips -- and trims, splits, +// merges, adds, restores, keeps or cuts them, and says which voice is the +// host. +// +// the view every clip of the cut with its edges, quote, `assist` +// (the clip finder's provenance) and keep/cut ruling; +// the clip finder's speakers and the proposals NOT in the +// cut (reactions.json, when there is one) +// the neighbourhood what the strip under the player draws for a span: the +// speaker turns, the laughs, the words (a words file in +// the project) or else the cues +// the operations ONE writer each, all here: the manifest through +// lib/report/manifest.mjs (updateClip / restoreClip / +// splitClip / mergeClips / addClip), the rulings through +// lib/report/montageRulings.mjs, a speaker's role through +// ./clipEditorBridge.mjs (the clip finder's writer) +// +// A ruling is keyed by the clip's moment (`clipMomentKey`: its cutStart), so an +// edit that moves a clip's start would orphan its keep/cut. After every edit +// the rulings FOLLOW their clips: a ruling whose clip's key changed moves to +// the new key; one whose clip is gone (merged away) is removed. +// +// Nothing here calls a model. +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; +import { channelFor, clipsOf, cuesInWindow, readManifest } from "../projects/report.mjs"; +import { + StaleToken, + StructureRefused, + addClip, + cutOf, + manifestToken, + mergeClips, + restoreClip, + splitClip, + updateClip, +} from "./manifest.mjs"; +import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; +import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; +import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; + +export { StaleToken, StructureRefused }; + +/** How far the strip reaches either side of a clip. */ +export const NEIGHBOURHOOD = 60; +/** The verdicts the clip editor offers (the montage deck has four). */ +export const EDITOR_VERDICTS = Object.freeze(["keep", "cut"]); +export const WORDS_FILE = "words.json"; + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** A project-relative file the project names (a words file): never absolute, never `..`. */ +function projectFile(dir, rel) { + if (typeof rel !== "string" || !rel || path.isAbsolute(rel) || rel.split(/[\\/]/).some((s) => s === ".." || s === "")) return null; + return path.join(/* turbopackIgnore: true */ dir, rel); +} + +const wordsMemo = new Map(); +/** The project's word timings (`reactions.source.words`, else words.json), or null. Memoised on mtime. */ +export async function readWords(dir, reactions = null) { + const rel = typeof reactions?.source?.words === "string" ? reactions.source.words : WORDS_FILE; + const file = projectFile(dir, rel); + if (!file) return null; + const st = await stat(file).catch(() => null); + if (!st?.isFile()) return null; + const key = `${file}|${Math.round(st.mtimeMs)}|${st.size}`; + const hit = wordsMemo.get(file); + if (hit && hit.key === key) return hit.words; + let words = null; + try { + words = wordsOf(JSON.parse(await readFile(file, "utf8"))); + } catch { + words = null; + } + wordsMemo.set(file, { key, words }); + return words; +} + +/** + * @typedef {{ id: string, channel: string | null, video: string, start: number, end: number, + * cutStart: number | null, cutEnd: number | null, quote: string | null, title: string | null, + * assist: Record<string, unknown> | null, key: string | null, ruling: "keep" | "cut" | string | null, montage: boolean }} EditorClip + */ + +/** The page's data: the clips, the token, the clip finder's speakers and unused proposals. */ +export async function clipEditorView(project) { + const manifest = await readManifest(project.dir); + if (!manifest) return null; + const [token, rulings, reactions] = await Promise.all([manifestToken(project.dir), readRulingsState(project.dir), readReactions(project.dir)]); + /** @type {EditorClip[]} */ + const clips = clipsOf(manifest) + .filter((e) => typeof e.video === "string" && fin(e.start) && fin(e.end)) + .map((e) => { + const key = clipMomentKey(e, manifest); + return { + id: e.id, + channel: channelFor(manifest, e), + video: e.video, + start: e.start, + end: e.end, + cutStart: fin(e.cutStart) ? e.cutStart : null, + cutEnd: fin(e.cutEnd) ? e.cutEnd : null, + quote: typeof e.quote === "string" ? e.quote : null, + title: typeof e.title === "string" ? e.title : typeof e.onscreen?.title === "string" ? e.onscreen.title : null, + assist: isObj(e.assist) ? e.assist : null, + key, + ruling: key ? (rulings.doc.rulings[key]?.verdict ?? null) : null, + montage: isObj(e.montage), + }; + }); + const doc = reactions.doc; + return { + clips, + token, + rulingsError: rulings.error, + reactionsError: reactions.error, + reactions: doc + ? { + source: isObj(doc.source) ? doc.source : null, + params: isObj(doc.params) ? doc.params : null, + speakers: Array.isArray(doc.speakers) ? doc.speakers.filter(isObj) : [], + proposals: unusedProposals(doc, clips), + proposalCount: Array.isArray(doc.proposals) ? doc.proposals.length : 0, + } + : null, + repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, + }; +} + +const overlapping = (list, from, to) => + (Array.isArray(list) ? list : []).filter((x) => isObj(x) && fin(x.start) && fin(x.end) && x.end >= from && x.start <= to); + +/** + * What the strip draws for [from, to] around one clip: turns, laughs, words + * (or cues when the project has no word timings), and the source's length + * when known. + */ +export async function clipNeighbourhood(project, { clip, from, to }) { + if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to"); + const { doc } = await readReactions(project.dir); + const words = await readWords(project.dir, doc); + const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker })); + const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null })); + let cues = null; + let duration = fin(doc?.source?.duration) ? doc.source.duration : null; + if (!words?.length || duration === null) { + const c = clip ? await cuesInWindow(project.dir, clip, from, to).catch(() => null) : null; + if (!words?.length) cues = c?.cues?.map((x) => ({ start: x.start, end: x.end, text: x.text })) ?? null; + if (duration === null && fin(c?.duration)) duration = c.duration; + } + return { + from, + to, + turns, + laughs, + words: words?.length ? words.filter((w) => w.end >= from && w.start <= to).map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, end: w.end })) : null, + cues, + duration, + }; +} + +/** The words of a span around one clip (for a quote), from words or cues. */ +async function quoteFor(project, clipId, from, to) { + const n = await clipNeighbourhood(project, { clip: clipId, from: Math.max(0, from - 1), to: to + 1 }).catch(() => null); + if (!n) return ""; + return quoteBetween({ words: n.words, cues: n.cues }, from, to); +} + +/** + * Make the rulings follow their clips after an edit: a moved key moves its + * ruling; a clip gone takes its ruling with it (unless another clip still + * sits on that moment). Returns what it did, as counts. + */ +export async function carryRulings(dir, beforeKeys, afterKeys) { + const state = await readRulingsState(dir); + if (state.error) return { moved: 0, removed: 0, error: state.error }; + const rulings = state.doc.rulings; + const live = new Set(afterKeys.values()); + let moved = 0; + let removed = 0; + for (const [id, k0] of beforeKeys) { + const r = rulings[k0]; + if (!r) continue; + const k1 = afterKeys.get(id); + if (k1 && k1 !== k0) { + if (!rulings[k1]) { + await setMontageRuling(dir, k1, { verdict: r.verdict, reason: r.reason, ...(r.match ? { match: r.match } : {}) }); + moved += 1; + } + if (!live.has(k0)) await setMontageRuling(dir, k0, null); + } else if (!k1 && !live.has(k0)) { + await setMontageRuling(dir, k0, null); + removed += 1; + } + } + return { moved, removed, error: null }; +} + +class OpError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} +export { OpError }; + +const num = (v, what) => { + const x = Number(v); + if (v === null || v === undefined || v === "" || !Number.isFinite(x)) throw new OpError(`${what} must be a number of seconds`); + return x; +}; + +/** + * One operation of the clip editor. `body.op` is one of + * trim { clip, cutStart, cutEnd } the clip's rendered span (its cut, or its + * extent when it has no cut); the extent widens + * to hold a cut; an assistant's clip's quote + * follows its words + * restore { clip } the assistant's version back + * split { clip, at } two clips at that second + * merge { clip } with the next clip + * add { video, channel?, cutStart, cutEnd } a selection on the strip + * bring-in { proposal } one of the clip finder's unused proposals + * ruling { clip, verdict: "keep" | "cut" | null } + * role { speaker, role } reactions.json, through the clip finder's writer + * with `token` (the manifest's, from the view) on every manifest edit. + * Returns `{ op, result, carried, view }`. + */ +export async function runClipEditorOp(project, body, { now = null } = {}) { + if (!isObj(body)) throw new OpError("a body is { op, … }"); + const dir = project.dir; + const token = typeof body.token === "string" ? body.token : null; + const manifest = await readManifest(dir); + if (!manifest) throw new OpError("no manifest", 404); + const beforeKeys = momentKeysOf(manifest); + const clipId = typeof body.clip === "string" ? body.clip : null; + const entry = clipId ? clipsOf(manifest).find((e) => e.id === clipId) : null; + const needClip = () => { + if (!entry) throw new OpError(`no clip ${clipId ?? "(none named)"}`, 404); + return entry; + }; + let result; + let structural = true; + switch (body.op) { + case "trim": { + const e = needClip(); + const a = num(body.cutStart, "cutStart"); + const b = num(body.cutEnd, "cutEnd"); + if (b - a < 0.5) throw new OpError("a clip must be at least half a second"); + if (a < 0) throw new OpError("a clip cannot start before the recording"); + const hasCut = fin(e.cutStart) && fin(e.cutEnd); + const patch = hasCut ? { cutStart: a, cutEnd: b, start: Math.min(e.start, a), end: Math.max(e.end, b) } : { start: a, end: b }; + if (isObj(e.assist)) { + const q = await quoteFor(project, e.id, a, b); + if (q) patch.quote = q; + } + result = await updateClip(dir, e.id, patch, { token, edit: "trim", now }); + break; + } + case "restore": + result = await restoreClip(dir, needClip().id, { token, now }); + break; + case "split": { + const e = needClip(); + const at = num(body.at, "at"); + const { cutStart, cutEnd } = cutOf(e); + const [first, second] = await Promise.all([quoteFor(project, e.id, cutStart, at), quoteFor(project, e.id, at, cutEnd)]); + result = await splitClip(dir, e.id, at, { token, now, quotes: { ...(first ? { first } : {}), ...(second ? { second } : {}) } }); + break; + } + case "merge": + result = await mergeClips(dir, needClip().id, { token, now }); + break; + case "add": { + const video = typeof body.video === "string" ? body.video : entry?.video; + const channel = typeof body.channel === "string" ? body.channel : entry ? channelFor(manifest, entry) : null; + if (!video) throw new OpError("add needs the video"); + const a = num(body.cutStart, "cutStart"); + const b = num(body.cutEnd, "cutEnd"); + const near = entry ?? clipsOf(manifest).find((e) => e.video === video); + const quote = near ? await quoteFor(project, near.id, a, b) : ""; + result = await addClip(dir, { video, ...(channel && channel !== manifest.provenance?.channelSlug ? { channel } : {}), cutStart: a, cutEnd: b, ...(quote ? { quote } : {}) }, { token, now }); + break; + } + case "bring-in": { + const { doc, error } = await readReactions(dir); + if (error) throw new OpError(error); + const p = (Array.isArray(doc?.proposals) ? doc.proposals : []).find((x) => isObj(x) && x.id === body.proposal); + if (!p || !fin(p.start) || !fin(p.end)) throw new OpError(`no proposal ${String(body.proposal ?? "")}`, 404); + const video = doc?.source?.video; + const channel = doc?.source?.channel; + if (typeof video !== "string") throw new OpError("reactions.json names no source video"); + const cut = { cutStart: fin(p.cutStart) ? p.cutStart : p.start, cutEnd: fin(p.cutEnd) ? p.cutEnd : p.end }; + const near = clipsOf(manifest).find((e) => e.video === video); + const quote = near ? await quoteFor(project, near.id, cut.cutStart, cut.cutEnd) : typeof p.text === "string" ? p.text : ""; + result = await addClip( + dir, + { + video, + ...(typeof channel === "string" && channel !== manifest.provenance?.channelSlug ? { channel } : {}), + ...cut, + start: p.start, + end: p.end, + ...(typeof p.clipId === "string" ? { id: p.clipId } : {}), + ...(quote ? { quote } : {}), + proposal: { id: p.id, ...(fin(p.score) ? { score: p.score } : {}), ...(typeof p.why === "string" ? { why: p.why } : {}), start: p.start, end: p.end }, + }, + { token, now }, + ); + break; + } + case "ruling": { + const e = needClip(); + const key = clipMomentKey(e, manifest); + if (!key) throw new OpError(`${e.id} has no moment to rule (no channel?)`); + const v = body.verdict; + if (v !== null && !EDITOR_VERDICTS.includes(v)) throw new OpError(`verdict must be ${EDITOR_VERDICTS.join(" or ")}, or null to clear it`); + result = await setMontageRuling(dir, key, v === null ? null : { verdict: v, reason: typeof body.reason === "string" ? body.reason : "" }); + structural = false; + break; + } + case "role": { + const index = Number(body.speaker); + if (!Number.isInteger(index) || index < 0) throw new OpError("speaker is a speaker's index"); + if (!SPEAKER_ROLES.includes(body.role)) throw new OpError(`role must be one of ${SPEAKER_ROLES.join(", ")}`); + result = await setSpeakerRole(dir, index, body.role); + structural = false; + break; + } + default: + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling or role"); + } + let carried = null; + if (structural) { + const after = await readManifest(dir); + carried = await carryRulings(dir, beforeKeys, momentKeysOf(after)); + } + return { op: body.op, result: summarise(result), carried, view: await clipEditorView(project) }; +} + +/** What a route sends back of a writer's result: ids, never the whole doc. */ +function summarise(r) { + if (!isObj(r)) return null; + const out = {}; + for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k]; + if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; + if (isObj(r.speaker)) out.speaker = r.speaker; + if (r.ruling !== undefined) out.ruling = r.ruling; + return out; +} diff --git a/umtool/lib/report/clipEditor.test.mjs b/umtool/lib/report/clipEditor.test.mjs @@ -0,0 +1,336 @@ +// The clip editor (release 35 C2): the manifest operations (updateClip's +// assist edits, restore, split, merge, add), the operations as the route runs +// them (rulings follow their clips; a speaker's role), and the pure rules +// (snap points, quotes, unused proposals, provenance in words). Synthetic. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { MANIFEST_NAME, StaleToken, StructureRefused, addClip, manifestToken, mergeClips, restoreClip, splitClip, updateClip } from "./manifest.mjs"; +import { carryRulings, clipEditorView, clipNeighbourhood, runClipEditorOp } from "./clipEditor.mjs"; +import { readReactions, setSpeakerRole } from "./clipEditorBridge.mjs"; +import { nearestPoint, provenanceWords, quoteBetween, snapCut, snapPoints, unusedProposals, wordsOf } from "./clipEditorModel.mjs"; +import { momentKeysOf, setMontageRuling } from "./montageRulings.mjs"; + +const NOW = "2026-10-18T22:00:00.000Z"; +const assist = (proposal, original) => ({ by: "assistant", proposal, score: 0.8, why: "host laughs", original, edits: [] }); + +const manifest = () => ({ + schemaVersion: 1, + slug: "rx", + provenance: { channelSlug: "chan", siteOrigin: "https://example.test" }, + render: { width: 640, height: 360, fps: 15 }, + timeline: [ + { type: "clip", id: "r001", video: "v1", start: 10, end: 20, cutStart: 11, cutEnd: 19, quote: "q one", assist: assist("p001", { start: 10, end: 20, cutStart: 11, cutEnd: 19 }) }, + { type: "clip", id: "r002", video: "v1", start: 30, end: 40, cutStart: 31, cutEnd: 39, quote: "q two", assist: assist("p002", { start: 30, end: 40, cutStart: 31, cutEnd: 39 }) }, + { type: "card", id: "k1", heading: "between" }, + { type: "clip", id: "r003", video: "v1", start: 50, end: 60, cutStart: 51, cutEnd: 59, quote: "q three" }, + { type: "clip", id: "plain", video: "v2", start: 5, end: 9 }, + ], +}); + +// Words every second from 0 to 70: "w0" … "w69", each 0.8 s long (a 0.2 s gap). +const WORDS = { words: Array.from({ length: 70 }, (_, i) => ({ w: `w${i}`, start: i, end: i + 0.8 })) }; +const REACTIONS = { + version: 1, + source: { channel: "chan", video: "v1", duration: 80, words: "words.json", diarization: { generatedAt: NOW, engine: "sherpa-onnx" } }, + params: { target: 600, laughMin: 0.25, mergeGap: 6, setupMax: 20, clipMax: 75 }, + speakers: [ + { index: 0, role: "host", label: "Host", seconds: 30, turns: 12, how: "auto" }, + { index: 1, role: "subject", label: "Subject", seconds: 50, turns: 3, how: "auto" }, + ], + turns: [ + { start: 0, end: 9, speaker: 1 }, + { start: 9.5, end: 12, speaker: 0 }, + { start: 12.5, end: 30, speaker: 1 }, + { start: 31, end: 33, speaker: 0 }, + ], + laughs: [{ start: 15, end: 16.5, score: 0.7, speaker: 0 }], + moments: [], + proposals: [ + { id: "p001", start: 10, end: 20, score: 0.8, moments: [], used: true, clipId: "r001", why: "host laughs" }, + { id: "p002", start: 30, end: 40, score: 0.7, moments: [], used: true, clipId: "r002", why: "a comment" }, + { id: "p003", start: 62, end: 68, score: 0.5, moments: [], used: false, why: "a short laugh" }, + { id: "p004", start: 70, end: 75, score: 0.6, moments: [], used: false, why: "a long comment" }, + ], +}; + +async function project({ withReactions = true } = {}) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-clip-editor-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest(), null, 2) + "\n"); + if (withReactions) { + await writeFile(path.join(dir, "reactions.json"), JSON.stringify(REACTIONS, null, 2) + "\n"); + await writeFile(path.join(dir, "words.json"), JSON.stringify(WORDS)); + } + return { id: "reports/rx", dir }; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); +const clip = (m, id) => m.timeline.find((e) => e.id === id); +const rulingsOf = async (dir) => JSON.parse(await readFile(path.join(dir, "montage-rulings.json"), "utf8")).rulings; + +test("updateClip: the first human edit of an assistant's cut flips assist.by and appends the edit; a no-op trim records nothing", async () => { + const { dir } = await project({ withReactions: false }); + try { + await updateClip(dir, "r001", { cutStart: 11, cutEnd: 19 }, { now: NOW }); + let e = clip(await read(dir), "r001"); + assert.equal(e.assist.by, "assistant"); + assert.deepEqual(e.assist.edits, []); + await updateClip(dir, "r001", { cutStart: 11.5 + 0.004, cutEnd: 18 }, { now: NOW }); + e = clip(await read(dir), "r001"); + assert.equal(e.assist.by, "operator"); + assert.deepEqual(e.assist.edits, [{ at: NOW, by: "operator", what: "trim", from: { cutStart: 11, cutEnd: 19 }, to: { cutStart: 11.5, cutEnd: 18 } }]); + // A clip with no assist is edited as it always was: no assist appears. + await updateClip(dir, "plain", { start: 5.5 }, { now: NOW }); + assert.equal(clip(await read(dir), "plain").assist, undefined); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("restoreClip: the assistant's original comes back, by is the assistant's again, the restore is in the edits", async () => { + const { dir } = await project({ withReactions: false }); + try { + await updateClip(dir, "r001", { cutStart: 12, cutEnd: 15, start: 10, end: 20 }, { now: NOW }); + await restoreClip(dir, "r001", { now: NOW }); + const e = clip(await read(dir), "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd], [10, 20, 11, 19]); + assert.equal(e.assist.by, "assistant"); + assert.deepEqual(e.assist.edits.map((x) => x.what), ["trim", "restore"]); + await assert.rejects(restoreClip(dir, "r003"), /no assistant's version/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("splitClip: two clips at the second, the first keeps id + original, the second is the operator's; quotes per half; refused near an edge", async () => { + const { dir } = await project({ withReactions: false }); + try { + const r = await splitClip(dir, "r001", 15, { now: NOW, quotes: { first: "first half", second: "second half" } }); + assert.equal(r.second, "r001-2"); + const m = await read(dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["r001", "r001-2", "r002", "k1", "r003", "plain"]); + const a = clip(m, "r001"); + const b = clip(m, "r001-2"); + assert.deepEqual([a.start, a.end, a.cutStart, a.cutEnd, a.quote], [10, 15, 11, 15, "first half"]); + assert.deepEqual([b.start, b.end, b.cutStart, b.cutEnd, b.quote], [15, 20, 15, 19, "second half"]); + assert.equal(a.assist.by, "operator"); + assert.ok(a.assist.original); + assert.equal(b.assist.original, undefined); + assert.equal(b.assist.proposal, "p001"); + assert.deepEqual(b.assist.edits.at(-1), { at: NOW, by: "operator", what: "split", from: { cutStart: 11, cutEnd: 19 }, to: { cutStart: 15, cutEnd: 19 } }); + await assert.rejects(splitClip(dir, "r001", 14.8), /half a second inside the cut/); + // An undo point was taken first. + assert.ok(r.snapshot); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("mergeClips: with the next clip -- the union, quotes joined, the next removed; a card between, the last clip, another video are refused", async () => { + const { dir } = await project({ withReactions: false }); + try { + const r = await mergeClips(dir, "r001", { now: NOW }); + assert.equal(r.absorbed, "r002"); + const m = await read(dir); + const e = clip(m, "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd, e.quote], [10, 40, 11, 39, "q one q two"]); + assert.equal(clip(m, "r002"), undefined); + assert.deepEqual(e.assist.edits.at(-1).what, "merge"); + await assert.rejects(mergeClips(dir, "r001"), /a card stands between/); + await assert.rejects(mergeClips(dir, "plain"), /the last clip/); + await assert.rejects(mergeClips(dir, "r003"), /different recordings/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("addClip: in time order among the recording's clips, the operator's; a proposal brought in keeps its original", async () => { + const { dir } = await project({ withReactions: false }); + try { + const a = await addClip(dir, { video: "v1", cutStart: 22, cutEnd: 25, quote: "a new one" }, { now: NOW }); + let m = await read(dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["r001", "v1-22", "r002", "k1", "r003", "plain"]); + assert.equal(a.id, "v1-22"); + assert.deepEqual(clip(m, "v1-22").assist, { by: "operator", edits: [{ at: NOW, by: "operator", what: "add", from: null, to: { cutStart: 22, cutEnd: 25 } }] }); + await addClip(dir, { video: "v1", cutStart: 62, cutEnd: 68, start: 61, end: 69, proposal: { id: "p003", score: 0.5, why: "a short laugh", start: 61, end: 69 } }, { now: NOW }); + m = await read(dir); + assert.equal(m.timeline.at(-2).id, "v1-62"); + assert.deepEqual(m.timeline.at(-2).assist.original, { start: 61, end: 69, cutStart: 62, cutEnd: 68 }); + assert.equal(m.timeline.at(-2).assist.proposal, "p003"); + await assert.rejects(addClip(dir, { video: "v1", cutStart: 5, cutEnd: 5.2 }), /half a second/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a stale token is refused by every operation and writes nothing", async () => { + const { dir } = await project({ withReactions: false }); + try { + const before = await readFile(path.join(dir, MANIFEST_NAME), "utf8"); + for (const p of [ + updateClip(dir, "r001", { cutStart: 12, cutEnd: 18 }, { token: "1" }), + splitClip(dir, "r001", 15, { token: "1" }), + mergeClips(dir, "r001", { token: "1" }), + addClip(dir, { video: "v1", cutStart: 1, cutEnd: 2 }, { token: "1" }), + restoreClip(dir, "r001", { token: "1" }), + ]) await assert.rejects(p, StaleToken); + assert.equal(await readFile(path.join(dir, MANIFEST_NAME), "utf8"), before); + assert.ok(StructureRefused); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: trim keeps the ruling with its clip (the key moves), widens the extent, the quote follows the words", async () => { + const p = await project(); + try { + let view = await clipEditorView(p); + await runClipEditorOp(p, { op: "ruling", clip: "r001", verdict: "keep" }); + assert.equal((await rulingsOf(p.dir))["chan/v1@11.00"].verdict, "keep"); + const out = await runClipEditorOp(p, { op: "trim", clip: "r001", cutStart: 9.1, cutEnd: 12.9, token: view.token }, { now: NOW }); + const e = clip(await read(p.dir), "r001"); + assert.deepEqual([e.start, e.end, e.cutStart, e.cutEnd], [9.1, 20, 9.1, 12.9]); + assert.equal(e.quote, "w9 w10 w11 w12"); + const rulings = await rulingsOf(p.dir); + assert.equal(rulings["chan/v1@11.00"], undefined); + assert.equal(rulings["chan/v1@9.10"].verdict, "keep"); + assert.deepEqual(out.carried, { moved: 1, removed: 0, error: null }); + assert.equal(out.view.clips.find((c) => c.id === "r001").ruling, "keep"); + // A plain clip (no cut) is trimmed by its extent, and its quote is left alone. + view = out.view; + await runClipEditorOp(p, { op: "trim", clip: "plain", cutStart: 6, cutEnd: 8, token: view.token }); + const plain = clip(await read(p.dir), "plain"); + assert.deepEqual([plain.start, plain.end, plain.cutStart, plain.quote], [6, 8, undefined, undefined]); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: split quotes each half from the words; merge takes the absorbed clip's ruling away; restore; cut", async () => { + const p = await project(); + try { + await runClipEditorOp(p, { op: "split", clip: "r001", at: 15 }, { now: NOW }); + let m = await read(p.dir); + assert.equal(clip(m, "r001").quote, "w11 w12 w13 w14"); + assert.equal(clip(m, "r001-2").quote, "w15 w16 w17 w18"); + await runClipEditorOp(p, { op: "ruling", clip: "r001-2", verdict: "cut" }); + assert.equal((await rulingsOf(p.dir))["chan/v1@15.00"].verdict, "cut"); + const merged = await runClipEditorOp(p, { op: "merge", clip: "r001" }, { now: NOW }); + assert.deepEqual(merged.carried, { moved: 0, removed: 1, error: null }); + assert.equal((await rulingsOf(p.dir))["chan/v1@15.00"], undefined); + await runClipEditorOp(p, { op: "restore", clip: "r001" }, { now: NOW }); + m = await read(p.dir); + assert.deepEqual([clip(m, "r001").cutStart, clip(m, "r001").cutEnd], [11, 19]); + await assert.rejects(runClipEditorOp(p, { op: "ruling", clip: "r001", verdict: "not-him" }), /keep or cut/); + await assert.rejects(runClipEditorOp(p, { op: "nope" }), /op must be/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("runClipEditorOp: bring in an unused proposal (it leaves the list); add from a selection; set a speaker's role", async () => { + const p = await project(); + try { + let view = await clipEditorView(p); + assert.deepEqual(view.reactions.proposals.map((x) => x.id), ["p004", "p003"]); + const out = await runClipEditorOp(p, { op: "bring-in", proposal: "p003", token: view.token }, { now: NOW }); + view = out.view; + assert.deepEqual(view.reactions.proposals.map((x) => x.id), ["p004"]); + const brought = view.clips.find((c) => c.assist?.proposal === "p003"); + assert.equal(brought.quote, "w62 w63 w64 w65 w66 w67"); + assert.equal(brought.assist.by, "operator"); + await runClipEditorOp(p, { op: "add", clip: "r002", cutStart: 41, cutEnd: 44 }, { now: NOW }); + const m = await read(p.dir); + assert.deepEqual(m.timeline.map((e) => e.id).slice(0, 4), ["r001", "r002", "v1-41", "k1"]); + await runClipEditorOp(p, { op: "role", speaker: 1, role: "host" }); + const { doc } = await readReactions(p.dir); + assert.deepEqual(doc.speakers[1], { index: 1, role: "host", label: "Host", seconds: 50, turns: 3, how: "operator" }); + assert.equal(doc.speakers[0].role, "host"); + await assert.rejects(setSpeakerRole(p.dir, 9, "host"), /no speaker 9/); + await assert.rejects(runClipEditorOp(p, { op: "bring-in", proposal: "p999" }), /no proposal p999/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("clipNeighbourhood: turns, laughs and words in the span; cues and no colours with no reactions.json", async () => { + const p = await project(); + try { + const n = await clipNeighbourhood(p, { clip: "r001", from: 8, to: 14 }); + assert.deepEqual(n.turns.map((t) => t.speaker), [1, 0, 1]); + assert.deepEqual(n.laughs, []); + assert.equal(n.words[0].w, "w8"); + assert.equal(n.duration, 80); + assert.equal(n.cues, null); + const none = await project({ withReactions: false }); + try { + const v = await clipEditorView(none); + assert.equal(v.reactions, null); + const m = await clipNeighbourhood(none, { clip: "r001", from: 8, to: 14 }); + assert.deepEqual([m.turns, m.laughs, m.words], [[], [], null]); + } finally { + await rm(none.dir, { recursive: true, force: true }); + } + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("carryRulings: a moved key moves its ruling, a gone clip takes its ruling, a ruled new key is not overwritten", async () => { + const p = await project({ withReactions: false }); + try { + await setMontageRuling(p.dir, "chan/v1@11.00", { verdict: "keep" }); + await setMontageRuling(p.dir, "chan/v1@31.00", { verdict: "cut" }); + await setMontageRuling(p.dir, "chan/v1@51.00", { verdict: "cut" }); + await setMontageRuling(p.dir, "chan/v1@52.00", { verdict: "keep" }); + const before = momentKeysOf(await read(p.dir)); + const after = new Map(before); + after.set("r001", "chan/v1@12.00"); + after.delete("r002"); + after.set("r003", "chan/v1@52.00"); + const r = await carryRulings(p.dir, before, after); + const rulings = await rulingsOf(p.dir); + assert.deepEqual(r, { moved: 1, removed: 1, error: null }); + assert.equal(rulings["chan/v1@12.00"].verdict, "keep"); + assert.equal(rulings["chan/v1@11.00"], undefined); + assert.equal(rulings["chan/v1@31.00"], undefined); + assert.equal(rulings["chan/v1@52.00"].verdict, "keep"); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); + +test("the pure rules: snap points, snapping a cut, a span's words, unused proposals, provenance in words", () => { + const words = wordsOf(WORDS); + const pts = snapPoints({ words: words.slice(0, 4), turns: [{ start: 0, end: 1.5, speaker: 0 }, { start: 2.5, end: 4, speaker: 1 }] }); + assert.deepEqual(pts, [0, 0.9, 1.5, 1.9, 2.5, 2.9, 3.8]); + assert.equal(nearestPoint(1.6, pts), 1.5); + assert.equal(nearestPoint(10, pts), null); + assert.deepEqual(snapCut({ cutStart: 0.95, cutEnd: 3.7 }, pts), { cutStart: 0.9, cutEnd: 3.8 }); + assert.deepEqual(snapCut({ cutStart: 1.5, cutEnd: 1.8 }, [1.6, 1.7]), { cutStart: 1.5, cutEnd: 1.8 }); + assert.deepEqual(snapPoints({ cues: [{ start: 0, end: 3, text: "a" }, { start: 3, end: 6, text: "b" }] }), [0, 3, 6]); + assert.equal(quoteBetween({ words }, 2, 4), "w2 w3"); + assert.equal(quoteBetween({ cues: [{ start: 0, end: 3, text: "one" }, { start: 3, end: 6, text: "two" }] }, 1, 3), "one"); + assert.deepEqual(unusedProposals(REACTIONS, [{ assist: { proposal: "p001" } }, { assist: { proposal: "p002" } }]).map((x) => x.id), ["p004", "p003"]); + assert.equal(unusedProposals(null, []).length, 0); + assert.equal(provenanceWords({ by: "assistant", score: 0.834, why: "host laughs" }), "by the assistant · 0.83 · host laughs"); + assert.equal(provenanceWords({ by: "operator", proposal: "p1", score: 0.5, edits: [{ what: "trim" }] }), "edited by you · the assistant scored it 0.50 · 1 edit"); + assert.equal(provenanceWords({ by: "operator", edits: [{ what: "add" }] }), "added by you · 1 edit"); + assert.equal(provenanceWords(null), null); +}); + +test("manifestToken changes with every operation (the page's next write carries the new one)", async () => { + const p = await project({ withReactions: false }); + try { + const t0 = await manifestToken(p.dir); + await new Promise((r) => setTimeout(r, 15)); + const out = await runClipEditorOp(p, { op: "merge", clip: "r001", token: t0 }); + assert.notEqual(out.view.token, t0); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/clipEditorBridge.mjs b/umtool/lib/report/clipEditorBridge.mjs @@ -0,0 +1,88 @@ +// THE CLIP EDITOR's seam onto the clip finder (release 35 C2 → C1). +// +// `<project>/reactions.json` is the clip finder's (lane C1, `common/lib/clips/`; +// the shape is plans/release-35/clip-finder.md). The clip editor READS it and +// writes exactly one thing into it -- a speaker's role, when the operator says +// "This is the host" on the strip -- through C1's exported `setSpeakerRole`. +// +// Until C1 lands this module holds a THIN LOCAL WRITER behind the same two +// names (`readReactions`, `setSpeakerRole`) and says that re-proposing is not +// here yet (`reproposeAvailable`). Swapping to C1's is a change to this file +// alone: every caller in umtool imports from here. +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const REACTIONS_FILE = "reactions.json"; +export const SPEAKER_ROLES = Object.freeze(["host", "subject", "other"]); +const ROLE_LABEL = { host: "Host", subject: "Subject", other: "Other" }; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** + * The project's reactions.json: `{ doc, error }`. No file is `{ doc: null, + * error: null }` (a report video the clip finder never ran on); a file that + * does not parse, or is not version 1, is an error and never read as empty. + * @param {string} dir + */ +export async function readReactions(dir) { + let text; + try { + text = await readFile(path.join(/* turbopackIgnore: true */ dir, REACTIONS_FILE), "utf8"); + } catch (err) { + if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") return { doc: null, error: null }; + return { doc: null, error: String(err) }; + } + try { + const doc = JSON.parse(text); + if (!isObj(doc) || doc.version !== 1) return { doc: null, error: `${REACTIONS_FILE} is not version 1` }; + return { doc, error: null }; + } catch (e) { + return { doc: null, error: `${REACTIONS_FILE} does not parse: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +let queue = Promise.resolve(); +/** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */ +function withLock(fn) { + const run = queue.then(fn, fn); + queue = run.then( + () => undefined, + () => undefined, + ); + return run; +} + +/** + * Set one speaker's role, the operator's (`how: "operator"`). Atomic (tmp + + * rename), in the file's own formatting. Other speakers are left as they are: + * a voice split in two clusters may be the host twice. + * + * LOCAL STAND-IN for C1's `setSpeakerRole` (same arguments, same effect). + * @param {string} dir + * @param {number} index the speaker's `index` + * @param {"host" | "subject" | "other"} role + */ +export async function setSpeakerRole(dir, index, role) { + if (!SPEAKER_ROLES.includes(role)) throw new Error(`role must be one of ${SPEAKER_ROLES.join(", ")}`); + const file = path.join(/* turbopackIgnore: true */ dir, REACTIONS_FILE); + return withLock(async () => { + const { doc, error } = await readReactions(dir); + if (error) throw new Error(`${error}; not writing it`); + if (!doc) throw new Error(`no ${REACTIONS_FILE} in this project`); + const speakers = Array.isArray(doc.speakers) ? doc.speakers : []; + const s = speakers.find((x) => isObj(x) && x.index === index); + if (!s) throw new Error(`no speaker ${index} in ${REACTIONS_FILE}`); + s.role = role; + s.label = ROLE_LABEL[role]; + s.how = "operator"; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); + return { speaker: s, doc }; + }); +} + +/** Whether "Re-propose" can run here (C1's `umtool clips propose`): not until C1 lands. */ +export const reproposeAvailable = false; +/** What the button says while it cannot. */ +export const REPROPOSE_UNAVAILABLE = "Re-propose arrives with the clip finder (umtool clips propose)"; diff --git a/umtool/lib/report/clipEditorModel.mjs b/umtool/lib/report/clipEditorModel.mjs @@ -0,0 +1,148 @@ +// THE CLIP EDITOR's pure rules (release 35 C2), shared by the page and the +// server: snap points, a span's words, the proposals not in the cut, and a +// clip's provenance in words. No node imports -- a client component holds the +// same rules as the route. + +/** @typedef {{ w?: string, word?: string, text?: string, start: number, end: number }} Word */ +/** @typedef {{ start: number, end: number, text: string }} Cue */ +/** @typedef {{ start: number, end: number, speaker: number }} Turn */ + +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r2 = (n) => Math.round(n * 100) / 100; + +/** A word's text, whichever key the transcriber used. */ +export const wordText = (w) => String(w?.w ?? w?.word ?? w?.text ?? "").trim(); + +/** A list of words from what a words file may hold: an array, or `{ words: [...] }`. Kept: timed ones, in time order. */ +export function wordsOf(raw) { + const list = Array.isArray(raw) ? raw : Array.isArray(raw?.words) ? raw.words : []; + return list.filter((w) => w && fin(w.start) && fin(w.end) && w.end >= w.start && wordText(w)).sort((a, b) => a.start - b.start); +} + +/** + * Where an edge may snap to: the middle of every gap between two words (a + * word gap), every edge of a silence between turns, and -- with no words -- + * every cue boundary. Sorted, 2 dp, no repeats. + * @param {{ words?: Word[] | null, turns?: Turn[] | null, cues?: Cue[] | null, minGap?: number }} o + */ +export function snapPoints({ words = null, turns = null, cues = null, minGap = 0.05 } = {}) { + const out = new Set(); + const ws = Array.isArray(words) ? words : []; + for (let i = 0; i + 1 < ws.length; i++) { + const a = ws[i].end; + const b = ws[i + 1].start; + if (fin(a) && fin(b) && b - a >= minGap) out.add(r2((a + b) / 2)); + } + if (ws.length) { + out.add(r2(ws[0].start)); + out.add(r2(ws[ws.length - 1].end)); + } + const ts = (Array.isArray(turns) ? turns : []).filter((t) => fin(t.start) && fin(t.end)).sort((a, b) => a.start - b.start); + for (let i = 0; i + 1 < ts.length; i++) { + if (ts[i + 1].start - ts[i].end >= minGap) { + out.add(r2(ts[i].end)); + out.add(r2(ts[i + 1].start)); + } + } + if (!ws.length) { + for (const c of Array.isArray(cues) ? cues : []) { + if (fin(c.start)) out.add(r2(c.start)); + if (fin(c.end)) out.add(r2(c.end)); + } + } + return [...out].sort((a, b) => a - b); +} + +/** The snap point nearest `t`, within `max` seconds, or null. */ +export function nearestPoint(t, points, max = 1.5) { + let best = null; + for (const p of points) { + if (Math.abs(p - t) <= max && (best === null || Math.abs(p - t) < Math.abs(best - t))) best = p; + } + return best; +} + +/** + * Both edges of a cut snapped to their nearest points, keeping it at least + * half a second long; an edge with no point within `max` stays. + * @param {{ cutStart: number, cutEnd: number }} cut + * @param {number[]} points + */ +export function snapCut(cut, points, max = 1.5) { + const a = nearestPoint(cut.cutStart, points, max) ?? cut.cutStart; + const b = nearestPoint(cut.cutEnd, points, max) ?? cut.cutEnd; + if (b - a < 0.5) return { cutStart: cut.cutStart, cutEnd: cut.cutEnd }; + return { cutStart: r2(a), cutEnd: r2(b) }; +} + +/** + * The words spoken in [from, to]: from the word timings when there are any + * (a word counts when its middle is inside), else the cues overlapping it. + * @param {{ words?: Word[] | null, cues?: Cue[] | null }} o + */ +export function quoteBetween({ words = null, cues = null }, from, to) { + if (Array.isArray(words) && words.length) { + return words + .filter((w) => (w.start + w.end) / 2 >= from && (w.start + w.end) / 2 <= to) + .map(wordText) + .join(" ") + .replace(/\s+/g, " ") + .trim(); + } + return (Array.isArray(cues) ? cues : []) + .filter((c) => c.end > from + 0.05 && c.start < to - 0.05) + .map((c) => String(c.text ?? "").trim()) + .join(" ") + .replace(/\s+/g, " ") + .trim(); +} + +/** + * The clip finder's proposals NOT in the cut: no clip's `assist.proposal` + * names them. (reactions.json's own `used` says what the last propose did; + * the manifest says what the cut holds now, after a person brought one in or + * removed one.) Ranked best first. + * @param {{ proposals?: Array<{ id: string, score?: number }> } | null} reactions + * @param {Array<{ assist?: { proposal?: string } }>} clips + */ +export function unusedProposals(reactions, clips) { + const inCut = new Set(clips.map((c) => c?.assist?.proposal).filter((p) => typeof p === "string")); + return (Array.isArray(reactions?.proposals) ? reactions.proposals : []) + .filter((p) => p && typeof p.id === "string" && fin(p.start) && fin(p.end) && !inCut.has(p.id)) + .sort((a, b) => (b.score ?? 0) - (a.score ?? 0)); +} + +/** A speaker's role from reactions.json's speakers, or null. */ +export function roleOf(speakers, index) { + const s = (Array.isArray(speakers) ? speakers : []).find((x) => x && x.index === index); + return s && typeof s.role === "string" ? s.role : null; +} + +/** + * A clip's provenance in words: "by the assistant · 0.83 · host laughs …", + * "edited by you · 3 edits", "added by you" -- or null for a clip the clip + * finder never touched. + * @param {{ by?: string, proposal?: string, score?: number, why?: string, edits?: unknown[] } | null | undefined} assist + */ +export function provenanceWords(assist) { + if (!assist || typeof assist !== "object") return null; + const edits = Array.isArray(assist.edits) ? assist.edits : []; + const n = edits.length; + if (assist.by === "assistant") { + return ["by the assistant", fin(assist.score) ? assist.score.toFixed(2) : null, assist.why || null].filter(Boolean).join(" · "); + } + const added = edits.some((e) => e && /** @type {{ what?: string }} */ (e).what === "add"); + const head = added ? (assist.proposal ? "brought in by you" : "added by you") : "edited by you"; + return [head, assist.proposal && fin(assist.score) ? `the assistant scored it ${assist.score.toFixed(2)}` : null, n ? `${n} edit${n === 1 ? "" : "s"}` : null] + .filter(Boolean) + .join(" · "); +} + +/** m:ss.s, for edges. */ +export function edgeClock(s) { + const v = Math.max(0, Number(s) || 0); + const h = Math.floor(v / 3600); + const m = Math.floor((v % 3600) / 60); + const sec = (v % 60).toFixed(1).padStart(4, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`; +} diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -0,0 +1,64 @@ +// The clip editor's shapes (release 35 C2), as lib/report/clipEditor.mjs +// returns them and components/projects/review/ClipEditor.tsx reads them. + +export type AssistEdit = { at: string; by: string; what: string; from: { cutStart: number; cutEnd: number } | null; to: { cutStart: number; cutEnd: number } }; +export type Assist = { + by: "assistant" | "operator"; + proposal?: string; + score?: number; + why?: string; + original?: { start: number; end: number; cutStart?: number; cutEnd?: number }; + edits?: AssistEdit[]; +}; + +export type EditorClip = { + id: string; + channel: string | null; + video: string; + start: number; + end: number; + cutStart: number | null; + cutEnd: number | null; + quote: string | null; + title: string | null; + assist: Assist | null; + key: string | null; + ruling: string | null; + montage: boolean; +}; + +export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator" }; +export type Proposal = { id: string; start: number; end: number; score?: number; why?: string; moments?: string[]; used?: boolean; clipId?: string | null }; + +export type EditorView = { + clips: EditorClip[]; + token: string | null; + rulingsError: string | null; + reactionsError: string | null; + reactions: { + source: { channel?: string; video?: string; duration?: number; words?: string | null } | null; + params: Record<string, number> | null; + speakers: Speaker[]; + proposals: Proposal[]; + proposalCount: number; + } | null; + repropose: { available: boolean; why: string | null }; +}; + +export type Turn = { start: number; end: number; speaker: number }; +export type Laugh = { start: number; end: number; score: number | null; speaker: number | null }; +export type TimedWord = { w: string; start: number; end: number }; +export type Cue = { start: number; end: number; text: string }; + +export type Neighbourhood = { + from: number; + to: number; + turns: Turn[]; + laughs: Laugh[]; + words: TimedWord[] | null; + cues: Cue[] | null; + duration: number | null; +}; + +/** The take "Render a take" makes again (the clip deck's rule), or null: the Takes page chooses. */ +export type RenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" } | null; diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -164,7 +164,7 @@ const WIN_EPS = 0.02; * @param {{ token?: string | null }} [opts] * @returns {Promise<{ entry: Record<string, unknown>, before: {start:number,end:number}, token: string | null }>} */ -export async function updateClip(dir, clipId, patch, { token = null } = {}) { +export async function updateClip(dir, clipId, patch, { token = null, edit = "trim", now = null } = {}) { return withManifestLock(async () => { const current = await manifestToken(dir); if (token !== null && current !== token) throw new StaleToken(token, current); @@ -178,8 +178,14 @@ export async function updateClip(dir, clipId, patch, { token = null } = {}) { // real manifest carries `scroll` and `chart` entries -- and the card-only // check would have let a window be written onto one of those. if (entry.type !== "clip") throw new Error(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`); + // Restore (release 35 C2): the assistant's own edges, read inside the lock. + if (patch === RESTORE_PATCH) { + patch = restorePatchOf(entry); + edit = "restore"; + } const before = { start: entry.start, end: entry.end }; + const cutBefore = cutOf(entry); for (const k of WINDOW_FIELDS) { if (patch[k] === undefined) continue; const v = Number(patch[k]); @@ -373,11 +379,229 @@ export async function updateClip(dir, clipId, patch, { token = null } = {}) { // and a row saved from the On-screen table cannot store different shapes. if (patch.onscreen !== undefined) setOnscreen(entry, patch.onscreen); + // ---- an assistant's clip, edited by a person (release 35 C2) ------------- + // + // A clip the clip finder proposed carries `assist`. The first human edit + // of its cut flips `assist.by` to "operator" (a re-propose never touches + // it again) and every edit is appended to `assist.edits`. Restore puts the + // assistant's `original` back, and the clip is the assistant's again. + const at = now ?? new Date().toISOString(); + noteAssistEdit(entry, edit, cutBefore, at); + if (edit === "restore" && isObj(entry.assist) && entry.assist.proposal) entry.assist.by = "assistant"; + const nextToken = await writeManifestAtomic(dir, manifest); return { entry, before, token: nextToken }; }); } +// --------------------------------------------------------------------------- +// The clip editor's operations (release 35 C2): an assistant's clips, adjusted +// by a person -- trim (updateClip above), restore, split, merge, add. The +// manifest clip's `assist` key is the clip finder's (plans/release-35/ +// clip-finder.md): `{ by, proposal?, score?, why?, original?, edits[] }`. +// Split, merge and add are structural (an auto snapshot first, so the Cut +// tab's Undo takes one back; the build's structure checks after). +// --------------------------------------------------------------------------- + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +/** How many edits a clip keeps; the oldest go first. */ +export const ASSIST_EDITS_MAX = 200; +/** What updateClip restores from (a sentinel: the edges are read inside the lock). */ +export const RESTORE_PATCH = Object.freeze({ restore: true }); + +/** The span a clip renders: its cut, else its extent. */ +export const cutOf = (e) => ({ cutStart: e.cutStart ?? e.start, cutEnd: e.cutEnd ?? e.end }); + +function restorePatchOf(entry) { + const o = isObj(entry.assist) ? entry.assist.original : null; + if (!isObj(o)) throw new Error(`${entry.id} has no assistant's version to restore`); + const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null); + const cutStart = n(o.cutStart); + const cutEnd = n(o.cutEnd); + const start = n(o.start) ?? cutStart; + const end = n(o.end) ?? cutEnd; + if (start === null || end === null) throw new Error(`${entry.id}'s assistant's version has no edges`); + return { start, end, cutStart, cutEnd }; +} + +/** + * Append one operator edit to a clip's `assist` and flip `by` -- when the clip + * has `assist` and its cut moved (a trim that leaves the cut where it was is + * no edit). Mutates; returns whether it recorded one. + */ +export function noteAssistEdit(entry, what, from, at = new Date().toISOString()) { + if (!isObj(entry.assist)) return false; + const to = cutOf(entry); + if ((what === "trim" || what === "restore") && from && from.cutStart === to.cutStart && from.cutEnd === to.cutEnd) return false; + entry.assist.by = "operator"; + const edits = Array.isArray(entry.assist.edits) ? entry.assist.edits : []; + edits.push({ at, by: "operator", what, from: from ?? null, to }); + entry.assist.edits = edits.slice(-ASSIST_EDITS_MAX); + return true; +} + +/** Restore the assistant's version of a clip (`assist.original`). */ +export async function restoreClip(dir, clipId, { token = null, now = null } = {}) { + return updateClip(dir, clipId, RESTORE_PATCH, { token, now }); +} + +function clipAt(timeline, id) { + const i = entryIndex(timeline, id); + const e = timeline[i]; + if (e?.type !== "clip") throw new Error(`${id} is a ${e?.type ?? "non-clip"} entry, not a clip`); + return { i, e }; +} + +const textOr = (v, fallback) => (v === undefined ? fallback : String(v ?? "").trim() || null); + +/** + * Split a clip in two at source second `at` (inside its cut, half a second + * from either edge). The first half keeps the id, the ruling's moment and the + * assistant's `original`; the second is a fresh id after it, the operator's. + * `quotes` ({ first, second }) replace each half's quote (the words in it). + * + * @param {string} dir + * @param {string} clipId + * @param {number} at + * @param {{ token?: string | null, quotes?: { first?: string, second?: string }, now?: string | null }} [opts] + */ +export async function splitClip(dir, clipId, at, { token = null, quotes = {}, now = null } = {}) { + return structural(dir, "split", token, (m) => { + const { i, e } = clipAt(m.timeline, clipId); + const t = round2(Number(at)); + const { cutStart, cutEnd } = cutOf(e); + if (!Number.isFinite(t) || t - cutStart < 0.5 || cutEnd - t < 0.5) { + throw new Error(`split at a second at least half a second inside the cut (${cutStart}–${cutEnd})`); + } + const stamp = now ?? new Date().toISOString(); + const from = cutOf(e); + const hasCut = e.cutStart != null && e.cutEnd != null; + const b = JSON.parse(JSON.stringify(e)); + // The first half: up to the split. + e.end = t; + if (hasCut) e.cutEnd = t; + if (e.muteFrom != null && e.muteFrom >= t) delete e.muteFrom; + const qa = textOr(quotes.first, e.quote ?? null); + if (qa) e.quote = qa; + else delete e.quote; + // The second: from the split, a fresh id. + b.id = freshEntryId(m.timeline, e.id); + b.start = t; + if (hasCut) b.cutStart = t; + if (b.cite != null) b.cite = t; + if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; + delete b.claim; + const qb = textOr(quotes.second, b.quote ?? null); + if (qb) b.quote = qb; + else delete b.quote; + if (isObj(e.assist)) { + const prior = Array.isArray(e.assist.edits) ? e.assist.edits : []; + b.assist = { by: "operator", ...pick(e.assist, ["proposal", "score", "why"]), edits: prior.slice() }; + noteAssistEdit(e, "split", from, stamp); + noteAssistEdit(b, "split", from, stamp); + } + m.timeline.splice(i + 1, 0, b); + return { id: e.id, second: b.id, entries: [e, b] }; + }); +} + +const pick = (o, keys) => Object.fromEntries(keys.filter((k) => o[k] !== undefined).map((k) => [k, o[k]])); + +/** + * Merge a clip with the NEXT clip in the timeline (same source; nothing but + * clips between them is refused -- a card between two clips is a decision). + * The first keeps its id; the merged span runs from the earlier edge to the + * later; the quotes join (or `quote` replaces them). + * + * @param {string} dir + * @param {string} clipId + * @param {{ token?: string | null, quote?: string, now?: string | null }} [opts] + */ +export async function mergeClips(dir, clipId, { token = null, quote, now = null } = {}) { + return structural(dir, "merge", token, (m) => { + const { i, e } = clipAt(m.timeline, clipId); + const j = m.timeline.findIndex((x, k) => k > i && x?.type === "clip"); + if (j < 0) throw new Error(`${clipId} is the last clip: nothing to merge it with`); + if (j !== i + 1) throw new Error(`a ${m.timeline[i + 1]?.type ?? "entry"} stands between ${clipId} and ${m.timeline[j].id}`); + const b = m.timeline[j]; + const chan = (x) => x.channel ?? m.provenance?.channelSlug ?? null; + if (chan(e) !== chan(b) || e.video !== b.video) throw new Error(`${clipId} and ${b.id} are cut from different recordings`); + const stamp = now ?? new Date().toISOString(); + const from = cutOf(e); + const cb = cutOf(b); + const hasCut = (e.cutStart != null && e.cutEnd != null) || (b.cutStart != null && b.cutEnd != null); + e.start = round2(Math.min(e.start, b.start)); + e.end = round2(Math.max(e.end, b.end)); + if (hasCut) { + e.cutStart = round2(Math.min(from.cutStart, cb.cutStart)); + e.cutEnd = round2(Math.max(from.cutEnd, cb.cutEnd)); + } + if (e.muteFrom != null) delete e.muteFrom; + if (b.muteFrom != null) e.muteFrom = b.muteFrom; + const q = quote !== undefined ? textOr(quote, null) : [e.quote, b.quote].filter((x) => typeof x === "string" && x.trim()).join(" ") || null; + if (q) e.quote = q; + else delete e.quote; + if (!isObj(e.assist) && isObj(b.assist)) e.assist = { by: "operator", ...pick(b.assist, ["proposal", "score", "why"]), edits: [] }; + noteAssistEdit(e, "merge", from, stamp); + m.timeline.splice(j, 1); + return { id: e.id, absorbed: b.id, entry: e }; + }); +} + +/** + * Add a clip the operator chose (a selection on the strip, or one of the + * clip finder's unused proposals brought in), in time order among the clips + * of the same recording. `proposal` ({ id, score?, why?, start?, end? }) marks + * it the assistant's proposal, its `original` the proposal's edges; either + * way a person put it in, so `assist.by` is "operator". + * + * @param {string} dir + * @param {{ channel?: string, video: string, cutStart: number, cutEnd: number, start?: number, end?: number, quote?: string, title?: string, id?: string, proposal?: { id: string, score?: number, why?: string, start?: number, end?: number } }} spec + * @param {{ token?: string | null, now?: string | null }} [opts] + */ +export async function addClip(dir, spec, { token = null, now = null } = {}) { + return structural(dir, "add", token, (m) => { + if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }"); + if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id"); + const num = (k, v) => { + const x = Number(v); + if (!Number.isFinite(x) || x < 0) throw new Error(`${k} must be a number ≥ 0`); + return round2(x); + }; + const cutStart = num("cutStart", spec.cutStart); + const cutEnd = num("cutEnd", spec.cutEnd); + if (cutEnd - cutStart < 0.5) throw new Error(`a clip must be at least half a second (${cutStart}–${cutEnd})`); + const start = Math.min(spec.start === undefined ? cutStart : num("start", spec.start), cutStart); + const end = Math.max(spec.end === undefined ? cutEnd : num("end", spec.end), cutEnd); + const channel = typeof spec.channel === "string" && spec.channel ? spec.channel : null; + const p = isObj(spec.proposal) ? spec.proposal : null; + const base = typeof spec.id === "string" && ENTRY_ID_RE.test(spec.id) ? spec.id : `${spec.video}-${Math.floor(cutStart)}`; + const entry = { type: "clip", id: freshEntryId(m.timeline, base), ...(channel ? { channel } : {}), video: spec.video, start, end, cutStart, cutEnd }; + const quote = typeof spec.quote === "string" ? spec.quote.trim() : ""; + if (quote) entry.quote = quote.slice(0, 2000); + const title = typeof spec.title === "string" ? spec.title.trim() : ""; + if (title) entry.title = title.slice(0, 300); + const stamp = now ?? new Date().toISOString(); + entry.assist = { + by: "operator", + ...(p ? pick({ proposal: typeof p.id === "string" ? p.id : undefined, score: typeof p.score === "number" ? p.score : undefined, why: typeof p.why === "string" ? p.why : undefined }, ["proposal", "score", "why"]) : {}), + ...(p ? { original: { start: num("start", p.start ?? cutStart), end: num("end", p.end ?? cutEnd), cutStart, cutEnd } } : {}), + edits: [{ at: stamp, by: "operator", what: "add", from: null, to: { cutStart, cutEnd } }], + }; + // In time order among the same recording's clips; else at the end. + const chan = (x) => x.channel ?? m.provenance?.channelSlug ?? null; + const mine = chan(entry); + const same = m.timeline.map((x, k) => ({ x, k })).filter(({ x }) => x?.type === "clip" && x.video === entry.video && chan(x) === mine); + let at = m.timeline.length; + if (same.length) { + const before = same.filter(({ x }) => cutOf(x).cutStart <= cutStart); + at = before.length ? before[before.length - 1].k + 1 : same[0].k; + } + m.timeline.splice(at, 0, entry); + return { id: entry.id, at, entry }; + }); +} + // --------------------------------------------------------------------------- // Writing an ADJUDICATION back into a ledger entry.