// PROPOSE TIGHT WINDOWS for a cut (UI notes 2026-10-30, item 4: "a batch
// 'propose tight windows' that shows before/after durations for review").
//
// For every clip of the project's cut, lib/report/tightWindow.mjs over what
// this machine already has -- nothing is fetched, nothing is written:
//
// cues the recording's cue file (projects/report.mjs cuesInWindow),
// 60 s either side, for where a sentence starts and ends
// words the project's words file when it is THAT recording's, else the
// corpus's (report-to-video clip-words.mjs: a words sidecar, a
// whisper transcript, the en-orig captions' starts)
// silences the build's own, measured on the build's own file and cached
// (lib/report/cutPoints.mjs -- the bench's ghosts and Play read the
// same); a clip with nothing on disk goes by its words alone
// the bound the cached window holding the clip, when there is one: a
// proposal never reaches past what the bench could play
//
// with no playhead: the cut's sentences when the clip has a cut (its quote),
// else the whole sentences inside the window. Each row is before and after,
// what moved and why; the review list (the Cut tab) applies a row only when
// its Apply is pressed -- PUT /api/report/window, the token, the cite that
// follows the edge -- and `umtool tighten
--apply ` does the same
// through the same writer.
//
// A LOCK IS NOT A REFUSAL HERE. `lock`/`lockStart`/`lockEnd` pin an edge
// against `resolve-windows --write` (the widener), not against a person: five
// of six real cuts are fully locked. A locked clip is proposed like any other
// and its row says it is locked; Apply leaves the locks as they are.
import { clipWords } from "umtool-report-to-video/clip-words";
import { hasLocalMedia } from "umtool-report-to-video/local-media";
import { channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs";
import { readWords } from "./clipEditor.mjs";
import { readReactions } from "./clipEditorBridge.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { manifestToken, updateClip } from "./manifest.mjs";
import { projectCache, windowsFor } from "./serve.mjs";
import { HOW_SAID, tightWindow } from "./tightWindow.mjs";
/** How far either side of a clip its cues are read (seconds). */
const CUE_REACH = 60;
const fin = (v) => typeof v === "number" && Number.isFinite(v);
const r2 = (v) => Math.round(v * 100) / 100;
/**
* @typedef {{
* id: string, quote: string | null, section: unknown,
* before: { start: number, end: number, seconds: number },
* after: { start: number, end: number, seconds: number } | null,
* changed: boolean, how: string | null, said: string[], why: string | null,
* fetched: boolean, locked: boolean, words: string | null,
* clear: { cut: boolean, mute: boolean },
* prior: { cutStart: number | null, cutEnd: number | null, muteFrom: number | null, cite: number | null, citeUrl: string | null },
* }} TightRow
*/
/**
* The proposals for a project's cut (or the named clips).
*
* @param {{ id: string, dir: string }} project
* @param {{ clips?: string[] | null, measure?: boolean }} [opts]
* `measure: false` skips the silences (the words alone), for a cut whose sources are not on disk
* @returns {Promise<{ token: string | null, rows: TightRow[], counts: { clips: number, proposed: number, same: number, none: number } }>}
*/
export async function proposeTightWindows(project, { clips = null, measure = true } = {}) {
const manifest = await readManifest(project.dir);
if (!manifest) throw new Error("no manifest");
const want = clips ? new Set(clips) : null;
const entries = clipsOf(manifest).filter((e) => fin(e.start) && fin(e.end) && typeof e.video === "string" && !hasLocalMedia(e) && (!want || want.has(e.id)));
const token = await manifestToken(project.dir);
const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
const { doc: reactions } = await readReactions(project.dir);
const projectWords = await readWords(project.dir, reactions).catch(() => null);
const cache = await projectCache(project, manifest);
// The build's silences per clip (cached on disk; the first read measures).
/** @type {Map>} */
const silences = new Map();
if (measure && entries.length) {
try {
const { cutPointsFor } = await import("./cutPoints.mjs");
const got = await cutPointsFor(project, { clips: entries.map((e) => e.id) });
for (const row of got.clips ?? []) {
if (!row || row.missing || row.error || !Array.isArray(row.silences) || !fin(row.fetchStart)) continue;
silences.set(row.id, row.silences.map((x) => ({ from: row.fetchStart + x.s, to: row.fetchStart + x.e })));
}
} catch {
/* the words alone */
}
}
/** @type {TightRow[]} */
const rows = [];
for (const e of entries) {
const before = { start: e.start, end: e.end, seconds: r2(e.end - e.start) };
const base = {
id: e.id,
quote: typeof e.quote === "string" ? e.quote : null,
section: e.section ?? null,
before,
locked: !!(e.lock || e.lockStart || e.lockEnd),
// What an Undo of an applied row writes back besides the edges (the writer answers only the edges' `before`).
prior: {
cutStart: fin(e.cutStart) ? e.cutStart : null,
cutEnd: fin(e.cutEnd) ? e.cutEnd : null,
muteFrom: fin(e.muteFrom) ? e.muteFrom : null,
cite: fin(e.cite) ? e.cite : null,
citeUrl: typeof e.citeUrl === "string" ? e.citeUrl : null,
},
};
const wins = /** @type {Array<{ from: number, to: number }>} */ (await windowsFor(project, e, cache).catch(() => []));
const holds = wins.find((w) => w.from <= e.start + 0.02 && w.to >= e.end - 0.02) ?? null;
const c = await cuesInWindow(project.dir, e.id, e.start - CUE_REACH, e.end + CUE_REACH, { manifest }).catch(() => null);
let words = null;
let wordsFrom = null;
if (projectWords?.length && reactions?.source?.video === e.video) {
words = projectWords.filter((w) => w.end >= e.start - CUE_REACH && w.start <= e.end + CUE_REACH).map((w) => ({ start: w.start, end: w.end, text: String(w.w ?? w.word ?? w.text ?? "") }));
wordsFrom = "project";
} else {
const cw = await clipWords(e, manifest.provenance, e.start - CUE_REACH, e.end + CUE_REACH, { channelsDir }).catch(() => null);
if (cw?.words?.length) {
words = cw.words;
wordsFrom = cw.from;
}
}
const r = tightWindow({
clip: { start: e.start, end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null },
cues: c?.cues ?? [],
words,
silences: silences.get(e.id) ?? null,
at: null,
...(holds ? { lo: holds.from, hi: holds.to } : { lo: 0 }),
});
if (!r.ok) {
rows.push({ ...base, after: null, changed: false, how: null, said: [], why: r.why, fetched: !!holds, words: wordsFrom, clear: { cut: false, mute: false } });
continue;
}
const cutOut = fin(e.cutStart) && fin(e.cutEnd) && (e.cutStart < r.start - 0.02 || e.cutEnd > r.end + 0.02);
const muteOut = fin(e.muteFrom) && (e.muteFrom < r.start - 0.02 || e.muteFrom > r.end + 0.02);
rows.push({
...base,
after: { start: r.start, end: r.end, seconds: r2(r.end - r.start) },
changed: r.changed,
how: HOW_SAID[r.how],
said: r.said,
why: null,
fetched: !!holds,
words: wordsFrom,
clear: { cut: !!cutOut, mute: !!muteOut },
});
}
const proposed = rows.filter((x) => x.changed).length;
const none = rows.filter((x) => !x.after).length;
return { token, rows, counts: { clips: rows.length, proposed, same: rows.length - proposed - none, none } };
}
/**
* The window patch that applies one row: its edges, and the cut / the mute
* mark cleared when they no longer fit (as the bench's Save window does).
*
* @param {TightRow} row
*/
export function applyPatchOf(row) {
if (!row.after) return null;
return {
start: row.after.start,
end: row.after.end,
...(row.clear.cut ? { cutStart: "", cutEnd: "" } : {}),
...(row.clear.mute ? { muteFrom: "" } : {}),
};
}
/**
* Apply proposals by clip id through the window writer (the terminal's
* `umtool tighten --apply `), one write each, re-proposed first so a
* row is never applied from a stale reading.
*
* @param {{ id: string, dir: string, kind: string }} project
* @param {string[]} ids
* @returns {Promise>}
*/
export async function applyTightWindows(project, ids) {
const { rows } = await proposeTightWindows(project, { clips: ids });
const out = [];
for (const id of ids) {
const row = rows.find((x) => x.id === id);
if (!row) {
out.push({ id, ok: false, said: "not a clip of the cut with a window" });
continue;
}
const patch = applyPatchOf(row);
if (!patch || !row.changed) {
out.push({ id, ok: false, said: row.why ?? "already tight" });
continue;
}
try {
const token = await manifestToken(project.dir);
const { result: res } = await withEditNotes(project, () => updateClip(project.dir, id, patch, { token }));
const f = res.citeFollowed;
out.push({
id,
ok: true,
said: `${row.before.start}–${row.before.end} → ${row.after?.start}–${row.after?.end} (${row.before.seconds} s → ${row.after?.seconds} s)` +
`${f?.cite ? `; cite ${f.cite.from} → ${f.cite.to}` : ""}${f?.citeUrl ? "; the QR's t= with it" : ""}`,
});
} catch (e) {
out.push({ id, ok: false, said: e instanceof Error ? e.message : String(e) });
}
}
return out;
}