Archilyzer · Source

archilyzer

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

commit 1af9460efcd9a969538b5d8df16ac85625044d6d
parent 7341475ec38923eb963758fb621e94c8f07e353e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 02:38:07 -0500

umtool: "parent not read" by re-joining, no TTS (operator, 4 Nov, p-2117216053952655778 / p-2117259673917386879: "we don't need to read this context, or paraphrase it"). New lib/report/postReread.mjs and `umtool posts reread <p> <item> [--without parent:0|parent:1|quoted] [--drop-parts 3,4] [--drop-urls]`: the picked take's kept parts cut out of its own file (ffmpeg atrim) and joined with the read's pauses (POST_PART_GAP), measured, and added as a derived take -- source {kind: "take", from}, steps [{op: "rejoin", drop, ranAt}] (validated: a local op, step key `drop`) -- its parts re-timed with their roles stored, its word timings moved with them, its slurs state kept, picked in ONE write (undoable). `set-item thread.parent.<i>|quoted=context|hidden` on a piece the picked take reads re-joins first, then sets the knob; on one it does not read it is the knob alone (idempotent); --no-reread keeps the guard's refusal. The bench's thread panel: "Read without it" on a context piece the take reads (POST op "reread" on the post-narration route). The guard is unchanged: a piece drawn context or hidden is never read. Also: `timeline threads --write` never moves an item across a section boundary -- a conversation spanning sections is gathered within each (the villain-arc tree on mid-3: its root ends one section, its replies open the next)

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

Diffstat:
Mumtool/app/api/report/post-narration/route.ts | 16+++++++++++++++-
Mumtool/components/projects/PostBench.tsx | 2+-
Mumtool/components/projects/PostThreadPanel.tsx | 45+++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/report/postReread.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postReread.test.mjs | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postThread.test.mjs | 3++-
Mumtool/lib/report/postsCli.mjs | 46++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/timelineCli.mjs | 10+++++-----
Mumtool/report-to-video/post-conversation.mjs | 51++++++++++++++++++++++++++++-----------------------
Mumtool/report-to-video/post-conversation.test.mjs | 5+++++
Mumtool/report-to-video/post-narration.mjs | 12+++++++++---
11 files changed, 498 insertions(+), 42 deletions(-)

diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -11,6 +11,7 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; +import { rereadTake } from "@/lib/report/postReread.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -40,6 +41,8 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // (a job; kept by GET ?job&derive=<from>); `installed: false` // when the editor has no engine for it // POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) +// POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece +// (postReread.mjs: no TTS; a new take, picked, one undo point) // POST {project, op: "undo"} the last structural write undone const noStore = { "cache-control": "no-store" }; @@ -216,6 +219,17 @@ export async function POST(request: Request) { return Response.json({ error: msg }, { status }); } } + if (body.op === "reread") { + // The bench's "Read without it" (postReread.mjs): the picked take's kept parts cut and joined again, no TTS. + const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === "string" && v ? v.split(",") : []); + try { + const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true }); + return Response.json({ ok: true, take: rr.take, entry: rr.result?.entry ?? null, token: rr.result?.token ?? null }, { headers: noStore }); + } catch (err) { + if ((err as Error)?.name === "RereadError") return Response.json({ error: (err as Error).message }, { status: 400 }); + throw err; + } + } if (body.op === "delete") { const { result } = { result: await deleteTake(r.project, e, Number(body.take)) }; return Response.json({ ok: true, entry: result.entry, token: result.token }, { headers: noStore }); @@ -229,7 +243,7 @@ export async function POST(request: Request) { const now = postsOf(after).find((x) => x.id === id); return Response.json({ ok: true, window: f.window, entry: now ?? null, token: result.token }, { headers: noStore }); } - return Response.json({ error: "op is set, take, derive, delete, fit or undo" }, { status: 400 }); + return Response.json({ error: "op is set, take, derive, reread, delete, fit or undo" }, { status: 400 }); } catch (err) { return fail(err); } diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -317,7 +317,7 @@ export default function PostBench({ }} /> <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> - <PostThreadPanel entry={entry} plan={plan} render={render} before={before} scene={scene} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> + <PostThreadPanel project={project} entry={entry} plan={plan} render={render} before={before} scene={scene} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -1,6 +1,6 @@ "use client"; -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { pickedTake } from "umtool-report-to-video/post-narration"; @@ -26,8 +26,10 @@ const ROLE_NAME = (r: string | null) => r === null ? "no text on the card" : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r === "parent:0" ? "the post it answers" : r.startsWith("parent:") ? "the post that answers" : `attachment ${Number(r.slice(6)) + 1}'s words`; export default function PostThreadPanel({ - entry, plan, render, before, scene = null, setS, setEntry, + project = null, entry, plan, render, before, scene = null, setS, setEntry, }: { + /** The project (its "Read without it" re-joins the take through the post-narration route). */ + project?: string | null; entry: Entry; plan: PostPlan; render: Record<string, unknown>; @@ -46,6 +48,24 @@ export default function PostThreadPanel({ // The scene (post-conversation.mjs): the posts its run left on screen, kept on top or collapsing away. const sceneTiles = (layout.tiles as Array<{ scope: string; mode: string; action?: string; ref?: { handle?: string; author?: string; redact?: boolean } }>).filter((t) => t.mode === "scene"); const take = pickedTake(entry) as { parts?: Array<{ start: number; text?: string }> } | null; + // READ WITHOUT IT (lib/report/postReread.mjs): the picked take re-joined without a context piece it reads -- its + // kept parts cut from its own file, no TTS -- a new take picked (one undo point); the page reloads on it. + const [rereading, setRereading] = useState<string | null>(null); + const [rereadError, setRereadError] = useState<string | null>(null); + const reread = async (role: string) => { + if (!project) return; + setRereading(role); + setRereadError(null); + try { + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "reread", id: entry.id, without: [role] }) }); + const j = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; + if (!res.ok || !j.ok) throw new Error(j.error ?? `HTTP ${res.status}`); + window.location.reload(); + } catch (err) { + setRereadError(err instanceof Error ? err.message : String(err)); + setRereading(null); + } + }; const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null; const setOwn = (patch: Thread) => setEntry((e) => { @@ -109,8 +129,8 @@ export default function PostThreadPanel({ const at = startOf(p.parts[0]); const words = p.parts.map((n) => take?.parts?.[n]?.text ?? "").join(" ").trim(); return ( - <li key={i} data-post-thread-piece={p.role ?? "none"} data-source={roles[p.parts[0]]?.source}> - <button type="button" disabled={at === null} className="flex w-full gap-2 px-1 text-left disabled:opacity-60" onClick={() => at !== null && setS(at)} title={`parts ${p.parts.map((n) => n + 1).join(", ")}`}> + <li key={i} className="flex items-center gap-1" data-post-thread-piece={p.role ?? "none"} data-source={roles[p.parts[0]]?.source}> + <button type="button" disabled={at === null} className="flex min-w-0 flex-1 gap-2 px-1 text-left disabled:opacity-60" onClick={() => at !== null && setS(at)} title={`parts ${p.parts.map((n) => n + 1).join(", ")}`}> <span className="w-12 shrink-0 font-mono tabular-nums">{at === null ? "—" : `${at.toFixed(1)}s`}</span> <span className="w-32 shrink-0 text-text-2"> {ROLE_NAME(p.role)} @@ -118,6 +138,18 @@ export default function PostThreadPanel({ </span> <span className="min-w-0 truncate">{words.split(/\s+/).slice(0, 10).join(" ")}…</span> </button> + {project && p.role && (p.role === "quoted" || p.role.startsWith("parent:")) && ( + <button + type="button" + className="ink-link shrink-0 px-1 disabled:opacity-60" + disabled={rereading !== null} + onClick={() => void reread(p.role as string)} + data-post-thread-reread={p.role} + title="re-join the take without this piece (its own audio, no TTS): a new take, picked" + > + {rereading === p.role ? "re-joining…" : "Read without it"} + </button> + )} </li> ); })} @@ -172,6 +204,11 @@ export default function PostThreadPanel({ <p className="m-0 mt-1 text-text-2"> full: in full while read · excerpt: only what is read · context: small and dim · carry: the item before, giving way · hidden: not drawn (never read). Hidden and excerpt redraw the card once saved. </p> + {rereadError && ( + <p className="m-0 mt-1 text-[var(--color-bad,#e5484d)]" data-post-thread-reread-error=""> + {rereadError} + </p> + )} {errors.length > 0 && ( <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-thread-errors=""> {errors.map((er, i) => ( diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs @@ -0,0 +1,218 @@ +// A READ WITHOUT A PIECE, RE-JOINED (umtool/docs/knobs.md, "Thread reads"; +// operator, 4 Nov, p-2117216053952655778 / p-2117259673917386879: "we don't +// need to read this context, or paraphrase it"; p-2116651428425150687: its +// quote's links read aloud): the picked take's kept parts cut out of its own +// file and joined again -- no TTS, nothing re-synthesized. +// +// umtool posts reread <p> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json] +// +// The parts dropped are those whose ROLE (post-thread.mjs partRoles) is a +// piece named by --without, the parts named by number, and (--drop-urls) the +// parts that are nothing but a link (post-narration.mjs isOnlyUrls). The kept +// parts' spans are cut from the take's file (ffmpeg atrim), joined with the +// pauses a read is assembled with (POST_PART_GAP: between paragraphs, inside +// one), measured, and added as a DERIVED take -- `source: {kind: "take", +// from}`, `steps: [{op: "rejoin", drop, ranAt}]` -- its parts re-timed (each +// with its role stored), its word timings moved with them (a word in a part +// dropped goes too: a beep, a zoom still find theirs), its slurs state kept; +// and picked, in ONE write (updatePostNarration: one undo point). The source +// take is never touched. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readdir, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +export const REREAD_USAGE = [ + " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with", + " the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without", + " drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;", + " --drop-parts the parts by number (as posts roles lists them); --drop-urls the parts that are nothing but a link.", + " Its parts are re-timed (roles stored), its word timings moved with them, its slurs state kept.", +].join("\n"); + +export class RereadError extends Error { + constructor(message) { + super(message); + this.name = "RereadError"; + } +} + +const PIECE_RE = /^(parent:\d|quoted)$/; + +/** + * THE RE-JOIN's PLAN, pure: which parts of `entry`'s picked take are kept and + * where each lands in the new take -- `{ take, keep: [k…], drop: [{ k, why }], + * spans: [{ k, from, to, at }], parts, words, script, seconds, steps }`. + * `spans` are in the source take's seconds (`at` the kept part's start in + * the new one). Throws RereadError when there is nothing to drop, no part + * left, or the take has no parts timed. + * + * @param {Record<string, any>} entry + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean }} o + */ +export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = false } = {}) { + const t = pickedTake(entry); + if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to re-join`); + const parts = Array.isArray(t.parts) ? t.parts : []; + if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { + throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); + } + for (const w of without) if (!PIECE_RE.test(w)) throw new RereadError(`--without ${w}: a piece is parent:0, parent:1 or quoted`); + for (const n of dropParts) if (!(Number.isInteger(n) && n >= 1 && n <= parts.length)) throw new RereadError(`--drop-parts ${n}: ${entry.id}'s take has parts 1-${parts.length}`); + const roles = partRoles(entry); + const drop = []; + parts.forEach((p, k) => { + const role = roles[k]?.role ?? null; + if (role && without.includes(role)) drop.push({ k, why: role }); + else if (dropParts.includes(k + 1)) drop.push({ k, why: `part ${k + 1}` }); + else if (dropUrls && isOnlyUrls(p.text)) drop.push({ k, why: "url" }); + }); + if (!drop.length) throw new RereadError(`${entry.id}'s picked take reads none of that${without.length ? ` (${without.join(", ")})` : ""}: nothing to drop`); + const dropped = new Set(drop.map((d) => d.k)); + const keep = parts.map((_, k) => k).filter((k) => !dropped.has(k)); + if (!keep.length) throw new RereadError(`${entry.id}: that drops every part of its take -- nothing would be read`); + // The kept parts, joined with the read's pauses (a new paragraph's, a part inside one's). + const spans = []; + let cur = 0; + keep.forEach((k, j) => { + const p = parts[k]; + const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1]].para ? POST_PART_GAP.para : POST_PART_GAP.inside; + const at = r3(cur + gap); + spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap }); + cur = at + p.seconds; + }); + const newParts = spans.map((s, j) => { + const p = parts[s.k]; + const { gapBefore: _g, role: _r, ...rest } = p; + const role = roles[s.k]?.role ?? null; + return { ...rest, n: j + 1, start: s.at, seconds: r3(p.seconds), ...(role ? { role } : {}) }; + }); + // Its words moved with their parts (a word is its part's when it starts inside the part's span). + const words = Array.isArray(t.words) + ? t.words.flatMap((w) => { + const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); + if (!s) return []; + const d = s.at - s.from; + return [{ w: w.w, start: r3(Math.max(0, w.start + d)), end: r3(Math.max(0, w.end + d)) }]; + }) + : null; + const script = spans.reduce((acc, s, j) => { + const p = parts[s.k]; + const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; + return acc + sep + String(p.text ?? "").trim(); + }, ""); + return { take: t, keep, drop, spans, parts: newParts, words, script, seconds: r3(cur), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; +} + +/** The ffmpeg arguments that cut the plan's spans out of `src` and join them with silence into `out`. */ +export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { + const chains = []; + const labels = []; + plan.spans.forEach((s, j) => { + if (s.gap > 0) { + chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=duration=${s.gap}[g${j}]`); + labels.push(`[g${j}]`); + } + chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}[a${j}]`); + labels.push(`[a${j}]`); + }); + chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); + return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", chains.join(";"), "-map", "[out]", "-c:a", "pcm_s16le", out]; +} + +/** A file's sample rate and channel layout (ffprobe). */ +async function audioFormat(file) { + const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", "-of", "default=noprint_wrappers=1", file]); + const rate = Number(/sample_rate=(\d+)/.exec(String(stdout))?.[1]) || 48000; + const ch = Number(/channels=(\d+)/.exec(String(stdout))?.[1]) || 1; + return { rate, layout: ch >= 2 ? "stereo" : "mono" }; +} + +/** + * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan + * takes them): the file written, measured, the take added and picked in one + * write. `dryRun`: the plan only. Returns `{ plan, take?, result? }`. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + */ +export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, dryRun = false, measure = undefined } = {}) { + const plan = rereadPlan(e, { without, dropParts, dropUrls }); + if (dryRun) return { plan }; + const t = plan.take; + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), "rejoin", t.engine === "derived" ? "take" : t.engine ?? "take"); + const abs = (r) => path.join(project.dir, ...String(r).split("/")); + const src = abs(t.file); + if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s picked take is not on disk: ${t.file}`); + const fmt = await audioFormat(src); + try { + await execFileP(FFMPEG(), rejoinArgs(src, abs(rel), plan, fmt), { maxBuffer: 1 << 24 }); + } catch (err) { + await rm(abs(rel), { force: true }); + throw new RereadError(`ffmpeg could not re-join ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); + } + const m = await (measure ?? (await import("./postNarrationCli.mjs")).measureTake)(abs(rel)); + const take = { + file: rel, + engine: "derived", + voice: t.voice ?? "?", + seconds: fin(m.seconds) && m.seconds > 0 ? m.seconds : plan.seconds, + source: { kind: "take", from: takeIdOf(t) }, + steps: plan.steps, + script: plan.script, + at: new Date().toISOString(), + ...(fin(m.lufs) ? { lufs: m.lufs } : fin(t.lufs) ? { lufs: t.lufs } : {}), + ...(t.slurs ? { slurs: t.slurs } : {}), + ...(plan.words ? { words: plan.words } : {}), + parts: plan.parts, + }; + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { plan, take, result }; +} + +/** The pieces a set-item thread patch draws as context or hidden that `e`'s picked take reads (set-item's re-join). */ +export function piecesHidden(e, thread) { + if (!thread || typeof thread !== "object") return []; + const read = new Set(partRoles(e).map((r) => r.role).filter(Boolean)); + const out = []; + const off = (m) => m === "context" || m === "hidden"; + if (Array.isArray(thread.parent)) thread.parent.forEach((m, i) => off(m) && read.has(`parent:${i}`) && out.push(`parent:${i}`)); + else if (off(thread.parent)) for (const r of read) if (r.startsWith("parent:")) out.push(r); + if (off(thread.quoted) && read.has("quoted")) out.push("quoted"); + return out; +} + +/** `umtool posts reread <p> <item> …`. */ +export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new RereadError(`${project.id} has no manifest`); + const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`)); + if (!e) throw new RereadError(`no post item ${ref} in ${project.id}`); + const r = await rereadTake(project, e, { without, dropParts, dropUrls, dryRun }); + const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + if (json) { + out(JSON.stringify({ ok: true, id: e.id, dryRun, drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1), seconds: r.take?.seconds ?? r.plan.seconds, take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); + return 0; + } + out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${(r.take?.seconds ?? r.plan.seconds).toFixed(2)} s (was ${Number(r.plan.take.seconds).toFixed(2)} s)`); + if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); + return 0; +} diff --git a/umtool/lib/report/postReread.test.mjs b/umtool/lib/report/postReread.test.mjs @@ -0,0 +1,132 @@ +// postReread.mjs: A READ WITHOUT A PIECE, RE-JOINED -- the picked take's kept +// parts cut from its own file and joined with the read's pauses (no TTS); the +// plan (spans, the parts re-timed with their roles, the words moved, the +// guard), the file (ffmpeg, measured), the one write (picked, undoable), and +// set-item's re-join: a piece drawn context that the take reads is re-joined +// first; one it does not read is the knob alone (idempotent). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { validatePostItem } from "umtool-report-to-video/post-item"; +import { threadReadErrors } from "umtool-report-to-video/post-thread"; +import { piecesHidden, rejoinArgs, rereadPlan, rereadTake } from "./postReread.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { undoStructural } from "./manifest.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-reread-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning."; +const REPLY = "That is exactly what I was saying yesterday morning."; + +const parts = () => [ + { n: 1, para: 0, text: "The first thing anyone notices is the noise from the street.", start: 0, seconds: 3.6, file: "narration/parts-cache/a.wav" }, + { n: 2, para: 1, text: "Then the lights in the hall go out without warning.", start: 4.2, seconds: 3.2 }, + { n: 3, para: 100, text: REPLY, start: 8.2, seconds: 3.1 }, +]; +const words = () => [ + { w: "The", start: 0.1, end: 0.3 }, { w: "Then", start: 4.3, end: 4.6 }, { w: "That", start: 8.3, end: 8.5 }, { w: "morning", start: 10.9, end: 11.2 }, +]; +const item = (o = {}) => ({ + type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: REPLY, + parents: [{ id: "900", author: "Neighbour", handle: "neighbour_one", date: "2026-10-29T10:00:00.000Z", text: PARENT }], + narration: { script: REPLY, takes: [{ file: "narration/posts/1/take-2.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: 11.3, slurs: "said", words: words(), parts: parts() }], pick: 0 }, + ...o, +}); + +test("THE PLAN: the parts reading the post it answers dropped; the rest re-timed with the read's pauses, their roles stored, the words moved with them", () => { + const p = rereadPlan(item(), { without: ["parent:0"] }); + assert.deepEqual(p.drop.map((d) => [d.k, d.why]), [[0, "parent:0"], [1, "parent:0"]]); + assert.deepEqual(p.keep, [2]); + assert.deepEqual(p.spans, [{ k: 2, from: 8.2, to: 11.3, at: 0, gap: 0 }]); + assert.deepEqual(p.parts, [{ n: 1, para: 100, text: REPLY, start: 0, seconds: 3.1, role: "post" }]); + assert.deepEqual(p.words, [{ w: "That", start: 0.1, end: 0.3 }, { w: "morning", start: 2.7, end: 3 }]); + assert.equal(p.script, REPLY); + assert.equal(p.seconds, 3.1); + assert.deepEqual(p.steps.map((s) => [s.op, s.drop]), [["rejoin", ["parent:0"]]]); + // A part by number: the pauses of a read (a paragraph's 0.6 s between pieces). + const q = rereadPlan(item(), { dropParts: [2] }); + assert.deepEqual(q.spans.map((s) => [s.k, s.at, s.gap]), [[0, 0, 0], [2, 4.2, 0.6]]); + assert.equal(q.parts[0].file, "narration/parts-cache/a.wav", "a part's own file kept"); + // Links: only the parts that are nothing but one. + const linked = item({ narration: { ...item().narration, takes: [{ ...item().narration.takes[0], parts: [...parts().slice(0, 2), { n: 3, para: 2, text: "https://. web.archive.org slash web slash 2021032015. 1733/. …", start: 8.2, seconds: 2 }, { ...parts()[2], n: 4, start: 10.8 }] }] } }); + assert.deepEqual(rereadPlan(linked, { dropUrls: true }).drop.map((d) => [d.k, d.why]), [[2, "url"]]); +}); + +test("the plan's refusals: nothing to drop (the take does not read it), every part dropped, a take read in one go", () => { + assert.throws(() => rereadPlan(item(), { without: ["quoted"] }), /reads none of that \(quoted\): nothing to drop/); + assert.throws(() => rereadPlan(item(), { dropParts: [1, 2, 3] }), /drops every part/); + assert.throws(() => rereadPlan(item(), { without: ["nonsense"] }), /a piece is parent:0, parent:1 or quoted/); + const oneGo = item({ narration: { script: REPLY, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 3 }], pick: 0 } }); + assert.throws(() => rereadPlan(oneGo, { without: ["parent:0"] }), /read in one go/); + // set-item's pieces: only what the take reads, as context or hidden. + assert.deepEqual(piecesHidden(item(), { parent: ["context", "auto"] }), ["parent:0"]); + assert.deepEqual(piecesHidden(item(), { parent: "full" }), []); + assert.deepEqual(piecesHidden(item(), { quoted: "hidden" }), []); +}); + +test("the ffmpeg arguments: each kept span trimmed, the pauses silence, joined in order", () => { + const p = rereadPlan(item(), { dropParts: [2] }); + const argv = rejoinArgs("/in.wav", "/out.wav", p, { rate: 24000, layout: "mono" }); + const fc = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(fc, /\[0:a\]atrim=start=0:end=3\.6,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono\[a0\]/); + assert.match(fc, /anullsrc=r=24000:cl=mono,atrim=duration=0\.6\[g1\]/); + assert.match(fc, /\[a0\]\[g1\]\[a1\]concat=n=3:v=0:a=1\[out\]/); +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(path.join(dir, "narration", "posts", "1"), { recursive: true }); + // The take: 11.3 s of tone, as a read's file stands in for one. + execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=220:duration=11.3:sample_rate=24000", path.join(dir, "narration", "posts", "1", "take-2.orpheus-thread.wav")]); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("RE-JOINED: the file cut and joined (its length the kept parts'), a derived take (source, steps) picked in ONE write, undoable; the guard is satisfied once the parent is context", async () => { + const p = await project("rejoin", [item()]); + const e = (await manifest(p)).timeline[0]; + const r = await rereadTake(p, e, { without: ["parent:0"] }); + assert.match(r.take.file, /^narration\/posts\/1\/take-3\.rejoin-orpheus\.wav$/); + assert.ok(Math.abs(r.take.seconds - 3.1) < 0.06, `measured ${r.take.seconds}`); + const now = (await manifest(p)).timeline[0]; + assert.equal(now.narration.pick, 1); + const t = now.narration.takes[1]; + assert.deepEqual([t.engine, t.source, t.steps[0].op, t.steps[0].drop, t.slurs], ["derived", { kind: "take", from: "take-2.orpheus-thread" }, "rejoin", ["parent:0"], "said"]); + assert.deepEqual(t.parts.map((x) => x.role), ["post"]); + assert.deepEqual(validatePostItem(now), []); + assert.deepEqual(threadReadErrors({ ...now, thread: { parent: "context" } }), [], "the parent drawn as context, read by no part"); + await undoStructural(p.dir); + assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "undone"); +}); + +test("set-item thread.parent.0=context on a piece the take reads RE-JOINS first (no TTS), then sets the knob; again: the knob alone; --no-reread: refused", async () => { + const p = await project("setitem", [item()]); + const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; + }; + const refused = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context", "--no-reread"]); + assert.notEqual(refused.code, 0); + assert.match(refused.err + refused.out, /drawn as context/); + const r = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /re-read p-1 without parent:0: narration\/posts\/1\/take-3\.rejoin-orpheus\.wav/); + let e = (await manifest(p)).timeline[0]; + assert.deepEqual([e.narration.takes.length, e.narration.pick, e.thread.parent[0]], [2, 1, "context"]); + // Idempotent: the picked take reads no parent now -- the knob alone. + const again = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context"]); + assert.equal(again.code, 0, again.err); + assert.doesNotMatch(again.out, /re-read/); + e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.takes.length, 2); + // posts reread --dry-run: the plan only. + const dry = await cli(["reread", "setitem", "p-1", "--drop-parts", "1", "--dry-run"]); + assert.match(dry.err + dry.out, /only part|drops every part/); +}); diff --git a/umtool/lib/report/postThread.test.mjs b/umtool/lib/report/postThread.test.mjs @@ -70,7 +70,8 @@ test("set-item thread.*: the knobs merge; hiding a parent the read reads is REFU const ok = await cli(["set-item", "knobs", "p-1", "thread.shrink=0.5", "thread.dim=0.4"]); assert.equal(ok.code, 0, ok.err); assert.deepEqual((await manifest(p)).timeline[0].thread, { shrink: 0.5, dim: 0.4 }); - const bad = await cli(["set-item", "knobs", "p-1", "thread.parent=hidden"]); + // --no-reread keeps the guard's refusal (without it, set-item re-joins the take first: postReread.test.mjs). + const bad = await cli(["set-item", "knobs", "p-1", "thread.parent=hidden", "--no-reread"]); assert.notEqual(bad.code, 0); assert.match(bad.err, /part 1 reads the post it answers, which is drawn hidden.*thread\.parent=full/); assert.equal((await manifest(p)).timeline[0].thread.parent, undefined); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -43,6 +43,14 @@ const ROLES_LINES = [ " words, an attachment's), stored or inferred, what the card shows for each, and the guard (umtool posts roles --help).", ]; +// `umtool posts reread` (postReread.mjs REREAD_USAGE): its lines, kept here so the usage is one block. +const REREAD_LINES = [ + " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " a READ RE-JOINED without a piece (no TTS): the picked take's kept parts cut from its own file and joined again, a new", + " take that is picked (one undo point) -- the post it answers or quotes left unread, a part by number, a part that is", + " only a link. set-item thread.parent.<i>|quoted=context|hidden on a piece the take reads runs it first (--no-reread: refused).", +]; + // `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block. const SLURS_USAGE_LINES = [ " umtool posts slurs <project> [ls] | on | off | level strong|all | visual blackout|placeholder", @@ -94,6 +102,7 @@ export const POSTS_USAGE = [ " on screen (auto: full when read, carried in when it is the item before, else context), the shrink, dim and their", " seconds, the pan's seconds. A setting that would narrate a post the card hides is refused (umtool posts roles).", ...ROLES_LINES, + ...REREAD_LINES, " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", " (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", @@ -121,7 +130,7 @@ export const POSTS_USAGE = [ " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto items that carry none", ].join("\n"); -const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]); +const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -393,7 +402,20 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); - if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out }); + if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out, reread: !flags.has("--no-reread") }); + if (verb === "reread") { + // A read re-joined without a piece (postReread.mjs): no TTS, a new take picked in one write. + const { REREAD_USAGE, rereadCommand } = await import("./postReread.mjs"); + if (!projectArg || !ref || flags.has("--help")) { + err(REREAD_USAGE); + return 2; + } + const list = (v) => (v === null ? [] : String(v).split(",").map((x) => x.trim()).filter(Boolean)); + const dropParts = list(flags.has("--drop-parts") ? str("--drop-parts") : null).map(Number); + return await rereadCommand(await projectOf(projectArg, root), ref, { without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), dryRun, json, out }).catch((e) => { + throw e?.name === "RereadError" ? new CliError(e.message) : e; + }); + } if (verb === "narrate") { const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs"); if (!projectArg || flags.has("--help")) { @@ -749,7 +771,7 @@ async function contextCommand(projectArg, { root, json, dryRun, out }) { } /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ -async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { +async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread = true }) { const fitPair = pairs.find((p) => /^fit=/.test(p)); if (fitPair) { if (pairs.length > 1) throw new CliError("fit= goes alone (it is posts fit on this item)"); @@ -789,12 +811,28 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref)); if (!hit) throw new CliError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + // A piece drawn context or hidden that its take READS (operator, 4 Nov: "we don't need to read this context"): the + // take re-joined without it first (postReread.mjs, no TTS) -- then the knob; one the take does not read: the knob alone. + // --no-reread keeps the guard's refusal. + let rejoined = null; + if (reread && patch.thread) { + const { piecesHidden, rereadTake, RereadError } = await import("./postReread.mjs"); + const pieces = piecesHidden(hit, patch.thread); + if (pieces.length) { + try { + rejoined = { pieces, ...(await rereadTake(project, hit, { without: pieces })) }; + } catch (e) { + throw e instanceof RereadError ? new CliError(e.message) : e; + } + } + } const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, hit.id, patch, { token: await manifestToken(project.dir) })); if (json) { - out(JSON.stringify({ ok: true, id: hit.id, entry: result.entry, token: result.token, editNotes }, null, 2)); + out(JSON.stringify({ ok: true, id: hit.id, entry: result.entry, token: result.token, editNotes, ...(rejoined ? { reread: { without: rejoined.pieces, take: rejoined.take.file } } : {}) }, null, 2)); return 0; } const { postItemSeconds } = await import("umtool-report-to-video/post-item"); + if (rejoined) out(`re-read ${hit.id} without ${rejoined.pieces.join(", ")}: ${rejoined.take.file} (${rejoined.take.seconds.toFixed(2)} s), picked -- no TTS`); out(`set ${hit.id}: ${postItemSeconds(result.entry).toFixed(1)} s${result.entry.hold ? ` (hold)` : ""}`); const refs = [["quoted", patch.quoted ? result.entry.quoted : null], ...Object.keys(patch.parents ?? {}).map((i) => [`parent ${i}`, result.entry.parents?.[Number(i)]])]; for (const [what, ref] of refs) if (ref) out(` ${what} (@${ref.handle ?? "?"}): ${ref.paraphrase ? `paraphrased -- "${ref.paraphrase}"` : "its own words"}`); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -148,7 +148,7 @@ export const TIMELINE_USAGE = [ " umtool timeline <project> threads --write [--conversation <id>] gather each conversation (or the one holding", " <id>: its root, a post or an item) at its first item's place in TREE order -- a post after what", " it answers, sibling branches by date, each branch depth first -- in ONE write (one undo point);", - " an item in another section than its conversation's first is reported and left where it is", + " nothing moves across a section boundary: a conversation spanning sections is gathered within each (said)", " umtool timeline <project> groups [ls] [--json] the claim groups, by section: id, claim, clips", " umtool timeline <project> groups import <file> [--skip-missing] [--drop-empty] a claim-groups file", " ({sections: [{label, groups: [{claim, ids}]}]}) in ONE write: the cut re-ordered to it, its", @@ -899,8 +899,8 @@ export async function threadsCommand(project, manifest, { write = false, only = const before = tl.map((e) => e?.id); const named = g.ids.filter((id, k) => id !== before[k]); if (!named.length) { - out(json ? JSON.stringify({ ok: true, written: false, moved: [], left: g.left }, null, 2) : `every conversation in ${project.id} is already together in tree order${g.left.length ? ` (${g.left.length} item(s) left in another section)` : ""}`); - for (const l of json ? [] : g.left) out(` left: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another section`); + out(json ? JSON.stringify({ ok: true, written: false, moved: [], left: g.left }, null, 2) : `every conversation in ${project.id} is already together in tree order${g.left.length ? ` (${g.left.length} item(s) in another section than their conversation's first)` : ""}`); + for (const l of json ? [] : g.left) out(` across a section: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another`); return 0; } const { orderEntries } = await import("./manifest.mjs"); @@ -910,8 +910,8 @@ export async function threadsCommand(project, manifest, { write = false, only = return 0; } out(`gathered ${g.moved.length} conversation(s) in ${project.id}, in tree order (one undo point: umtool timeline ${project.id} undo)`); - for (const mv of g.moved) out(` root ${mv.root}: ${mv.from.join(" ")} -> ${mv.to.join(" ")}`); - for (const l of g.left) out(` left: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another section`); + for (const mv of g.moved) out(` root ${mv.root}${mv.section !== undefined ? ` (section ${mv.section})` : ""}: ${mv.from.join(" ")} -> ${mv.to.join(" ")}`); + for (const l of g.left) out(` across a section: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another; gathered within its own section, never moved across`); return 0; } diff --git a/umtool/report-to-video/post-conversation.mjs b/umtool/report-to-video/post-conversation.mjs @@ -411,38 +411,43 @@ export function conversations(timeline, render = undefined) { * THE GATHERED ORDER (`threads --write`), pure: the timeline's ids with each * conversation's items gathered at its first item's place in TREE order -- * every entry between them after the conversation, in its order. `sectionOf` - * (id -> section, sectionEdit.mjs sectionModel's) leaves an item in another - * section than its conversation's first where it is (`left`). `only`: the + * (id -> section, sectionEdit.mjs sectionModel's): nothing moves across a + * section boundary -- a conversation that spans sections is gathered within + * each (its items there at their first place), and each item in another + * section than the conversation's first is reported (`left`). `only`: the * conversation holding that id (its root, a post of it, an item's id). - * Returns `{ ids, moved: [{ root, from: [ids], to: [ids] }], left: [{ id, root, section, first }] }`. + * Returns `{ ids, moved: [{ root, section?, from: [ids], to: [ids] }], left: [{ id, root, section, first }] }`. */ export function gatheredOrder(timeline, render = undefined, { sectionOf = null, only = null } = {}) { const tl = Array.isArray(timeline) ? timeline : []; let ids = tl.map((e) => e?.id); const moved = []; const left = []; + const sec = (id) => (sectionOf ? sectionOf.get(id) : undefined); for (const c of conversations(tl, render)) { if (only && !(c.root === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) continue; - const pos = new Map(ids.map((id, k) => [id, k])); - const first = c.items.reduce((a, b) => ((pos.get(a.id) ?? 0) <= (pos.get(b.id) ?? 0) ? a : b)); - const sec = (id) => (sectionOf ? sectionOf.get(id) : undefined); - const mine = c.order.filter((id) => { - if (sectionOf && sec(id) !== sec(first.id)) { - left.push({ id, root: c.root, section: sec(id), first: first.id }); - return false; - } - return true; - }); - if (mine.length < 2) continue; - const ats = mine.map((id) => pos.get(id)).sort((a, b) => a - b); - const lo = ats[0]; - const hi = ats[ats.length - 1]; - const span = ids.slice(lo, hi + 1); - const want = new Set(mine); - const next = [...mine, ...span.filter((id) => !want.has(id))]; - if (next.every((id, k) => id === span[k])) continue; - moved.push({ root: c.root, from: span.filter((id) => want.has(id)), to: mine }); - ids = [...ids.slice(0, lo), ...next, ...ids.slice(hi + 1)]; + const first = c.items[0]; + // One group a section (one group in all, with no sections), each in tree order. + const groups = new Map(); + for (const id of c.order) { + const k = sectionOf ? sec(id) : 0; + if (!groups.has(k)) groups.set(k, []); + groups.get(k).push(id); + if (sectionOf && k !== sec(first.id)) left.push({ id, root: c.root, section: k, first: first.id }); + } + for (const [k, mine] of groups) { + if (mine.length < 2) continue; + const pos = new Map(ids.map((id, n) => [id, n])); + const ats = mine.map((id) => pos.get(id)).sort((a, b) => a - b); + const lo = ats[0]; + const hi = ats[ats.length - 1]; + const span = ids.slice(lo, hi + 1); + const want = new Set(mine); + const next = [...mine, ...span.filter((id) => !want.has(id))]; + if (next.every((id, n) => id === span[n])) continue; + moved.push({ root: c.root, ...(sectionOf ? { section: k } : {}), from: span.filter((id) => want.has(id)), to: mine }); + ids = [...ids.slice(0, lo), ...next, ...ids.slice(hi + 1)]; + } } return { ids, moved, left }; } diff --git a/umtool/report-to-video/post-conversation.test.mjs b/umtool/report-to-video/post-conversation.test.mjs @@ -88,6 +88,11 @@ test("GATHERED in tree order (threads --write): at the first item's place, a pos const left = gatheredOrder([A, B, X, C], render, { sectionOf: sec }); assert.deepEqual(left.left, [{ id: "p-848", root: "771", section: 1, first: "p-776" }]); assert.deepEqual(left.ids, ["p-776", "p-779", "p-831", "p-848"]); + // A conversation across a boundary is gathered within each section, never across it. + const two = new Map([["p-776", 0], ["p-779", 1], ["p-831", 1], ["p-848", 1]]); + const within = gatheredOrder([A, B, X, C], render, { sectionOf: two }); + assert.deepEqual(within.ids, ["p-776", "p-848", "p-779", "p-831"]); + assert.deepEqual(within.moved, [{ root: "771", section: 1, from: ["p-779", "p-848"], to: ["p-848", "p-779"] }]); }); test("THE SCENE: each item opens on what its run left on screen -- an ancestor kept on top, the branch before collapsing away, the post the item before ended on in full", () => { diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -57,6 +57,8 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco * read as their source (takeSourceOf). */ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); +/** The ops umtool runs itself on a take's own file (no editor job): `rejoin` -- its kept parts cut out and joined again (lib/report/postReread.mjs). */ +export const POST_LOCAL_OPS = Object.freeze(["rejoin"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); @@ -169,7 +171,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]); -const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; @@ -616,8 +618,12 @@ export function validatePostNarration(e) { if (t.steps !== undefined) { if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`); else t.steps.forEach((st, k) => { - if (!isObj(st) || !POST_DERIVE_OPS.includes(st.op)) errors.push(`${tw}.steps[${k}].op must be one of ${POST_DERIVE_OPS.join(", ")}`); - else for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`); + else { + for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + // A re-join's record: what it left out (a piece, "part <n>", "url"). + if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`); + } }); } if (t.parts !== undefined) {