commit 7341475ec38923eb963758fb621e94c8f07e353e parent 16716b18ae5bf2c9d57632f8a3e11d012c78accd Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 4 Nov 2026 02:26:25 -0500 umtool: the thread walk -- one conversation played back to back is one scene, not cold cuts (operator, 4 Nov: p-2116779173746491646's tree, "weird thread progression", "wrong order"; p-2117379128664236113, "a full read thread progression"). New pure post-conversation.mjs: an item's chain (the posts it answers and its own, plus its `conversation`), a RUN of consecutive narrated, read-following items of one tree, and planContext(timeline, i, render) -> { prev, scene }: the posts the run had on screen as the item before ended, each with its ref (words, author blurred by its own item's rule) -- an ancestor kept on top as context, the branch before collapsing away (scale 0, opacity 0, its gap closing) while the new branch is revealed and the pan moves, all at the first read's lead; the opening frame is the post the item before ended on. threadLayout/threadSchedule/threadPath take the scene (tiles `scene:<id>` in the tree's depth-first order), the card draws them never read (no blocks, no word spans) and redacted by their own item's terms (post-redact.mjs redactSceneRef); every caller passes planContext where it passed { prev } (the build's segment, Play, the card route, the bench, the writers' guard, posts roles, the lint). A post tile that fits the window is shown WHOLE while it is read (p-2117359906164814087's parent ran past the foot). `umtool timeline <p> threads [--json]`: each conversation of two items or more -- root, places, one run or split, a reply placed before what it answers, a re-read with its fix; `threads --write [--conversation <id>]` gathers them at the first item's place in tree order (a post after what it answers; sibling branches by date, each depth first) in one undoable orderEntries write, an item in another section reported and left Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
19 files changed, 979 insertions(+), 68 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -9,6 +9,7 @@ import { pickedTake } from "umtool-report-to-video/post-narration"; import { scriptWordTimes } from "umtool-report-to-video/word-zoom"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { threadLayout } from "umtool-report-to-video/post-thread"; +import { planContext } from "umtool-report-to-video/post-conversation"; import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs"; import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs"; @@ -51,8 +52,10 @@ async function itemOf(project: { dir: string }, manifest: Record<string, unknown if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>; const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[]; const at = tl.findIndex((e) => e?.type === "post" && e.id === id); - // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - return { item: at >= 0 ? tl[at] : null, prev: at > 0 ? tl[at - 1] : null, manifest: m }; + // `ctx`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in) and the scene its + // run leaves on screen (post-conversation.mjs), as Play's plan has them. + const ctx = planContext(tl, at, (m.render ?? {}) as Record<string, unknown>) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null }; + return { item: at >= 0 ? tl[at] : null, prev: ctx.prev, ctx, manifest: m }; } /** A project file under posts-media/, never outside it (its real path checked). */ @@ -183,7 +186,7 @@ export async function GET(request: Request) { // Its read-follow (read-follow.mjs): the blocks and the flow Play lights and pans, as the build's page has them. follow: followOn, // A threaded card (post-thread.mjs): its tiles, as the plan's follow.thread has them. - thread: followOn ? threadLayout(found.item, (found.manifest.render ?? render) as Record<string, unknown>, { prev: found.prev }) : null, + thread: followOn ? threadLayout(found.item, (found.manifest.render ?? render) as Record<string, unknown>, found.ctx) : null, redaction, }); return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } }); diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -59,7 +59,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ ]; export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene = null, }: { project: string; entry: Entry; @@ -76,6 +76,8 @@ export default function PostBench({ combo?: ComboInfo | null; /** The timeline entry before it in the cut (post-thread.mjs: a parent that is that item is carried in). */ before?: Record<string, unknown> | null; + /** The posts its run leaves on screen (post-conversation.mjs planContext): kept on top or collapsed away. */ + scene?: Record<string, unknown> | null; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -83,7 +85,7 @@ export default function PostBench({ const [token, setToken] = useState(initialToken); const [status, setStatus] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); - const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render, { prev: before }) as PostPlan)), [entry, initial, initialPlan, render, before]); + const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry, render, { prev: before, scene }) as PostPlan)), [entry, initial, initialPlan, render, before, scene]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -315,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} 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)} /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -6,6 +6,7 @@ import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; import { postItemPlan } from "umtool-report-to-video/post-item"; +import { planContext } from "umtool-report-to-video/post-conversation"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import type { ProjectRef } from "@/lib/project-types"; import type { PostPlan } from "./review/PostItemPlayer"; @@ -31,6 +32,8 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) }; const neighbours = tl.filter((e) => e?.type === "post").map((e) => e.id); const k = neighbours.indexOf(id); + // What it opens on (post-conversation.mjs): the item before it and the scene its run leaves on screen. + const ctx = planContext(tl, at, render) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null }; const fromPlay = search.from === "play"; // Its combo (post-combo.mjs): counted over the whole cut, as the build counts it. const combos = (await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {} }))).combos as Record<string, ComboInfo>; @@ -49,9 +52,10 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj entry={entry} token={await manifestToken(project.dir)} box={{ width: box.width, height: box.height }} - plan={postItemPlan(entry, render, { prev: at > 0 ? tl[at - 1] : null }) as unknown as PostPlan} + plan={postItemPlan(entry, render, ctx) as unknown as PostPlan} render={render} - before={at > 0 ? tl[at - 1] : null} + before={ctx.prev} + scene={ctx.scene} combo={combo} back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }} prev={k > 0 ? neighbours[k - 1] : null} diff --git a/umtool/components/projects/PostThreadPanel.tsx b/umtool/components/projects/PostThreadPanel.tsx @@ -26,21 +26,25 @@ 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, setS, setEntry, + entry, plan, render, before, scene = null, setS, setEntry, }: { entry: Entry; plan: PostPlan; render: Record<string, unknown>; before: Record<string, unknown> | null; + /** The posts its run leaves on screen (post-conversation.mjs planContext). */ + scene?: Record<string, unknown> | null; setS: (s: number) => void; setEntry: (f: (e: Entry) => Entry) => void; }) { const own = (entry.thread ?? undefined) as Thread | undefined; const k = threadKnobs(entry, render) as Required<Thread>; - const layout = useMemo(() => threadLayout(entry, render, { prev: before }), [entry, render, before]); + const layout = useMemo(() => threadLayout(entry, render, { prev: before, scene }), [entry, render, before, scene]); const roles = useMemo(() => partRoles(entry) as Array<{ role: string | null; source: string }>, [entry]); const pieces = useMemo(() => readPieces(entry, roles) as Array<{ role: string | null; parts: number[] }>, [entry, roles]); - const errors = useMemo(() => threadReadErrors(entry, render, { prev: before, followOn: (followKnobs(entry, render) as { on: boolean }).on }) as string[], [entry, render, before]); + const errors = useMemo(() => threadReadErrors(entry, render, { prev: before, scene, followOn: (followKnobs(entry, render) as { on: boolean }).on }) as string[], [entry, render, before, scene]); + // 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; const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null; const setOwn = (patch: Thread) => @@ -79,7 +83,7 @@ export default function PostThreadPanel({ /> </label> ); - if (!parents.length && !entry.quoted) return null; + if (!parents.length && !entry.quoted && !sceneTiles.length) return null; return ( <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-thread-panel="" data-threaded={layout.on ? "1" : "0"}> <div className="mb-2 flex flex-wrap items-center gap-2"> @@ -88,6 +92,17 @@ export default function PostThreadPanel({ {layout.on ? "the card draws the conversation: each post read is shown in full, then shrinks and dims as the next comes in" : roles.length ? "his words only: the posts it answers are context" : "not narrated: the card as it is"} </span> </div> + {sceneTiles.length > 0 && ( + <p className="m-0 mb-2 text-text-2" data-post-thread-scene={sceneTiles.length}> + one scene with the item before:{" "} + {sceneTiles.map((t, i) => ( + <span key={t.scope} data-post-thread-scene-tile={t.scope.slice(6)} data-action={t.action}> + {i ? ", " : ""} + {t.ref?.redact ? "a post" : `@${t.ref?.handle ?? "?"}`} {t.action === "keep" ? "stays on top (context)" : "collapses away"} + </span> + ))} + </p> + )} {pieces.length > 0 && ( <ol className="m-0 mb-2 list-none space-y-0.5 p-0" data-post-thread-pieces=""> {pieces.map((p, i) => { diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -59,6 +59,7 @@ import { import { validateNarration } from "umtool-report-to-video/narration"; import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; import { threadReadErrors } from "umtool-report-to-video/post-thread"; +import { planContext } from "umtool-report-to-video/post-conversation"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { AVATARS_DIR, avatarEntryOf, handleKey, validatePostAvatars } from "umtool-report-to-video/post-avatars"; import { POST_NARRATION_DEFAULTS, validatePostNarrationRender } from "umtool-report-to-video/post-narration"; @@ -2466,7 +2467,10 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { // NEVER NARRATE HIDDEN TEXT (post-thread.mjs): a change to what the card shows that leaves a part of its read // off the screen is refused, with the fix (one it had before is the guard's, not this write's). if ("thread" in patch || "follow" in patch) { - const guard = (x) => threadReadErrors(x, m.render, { prev: m.timeline[i - 1] ?? null, followOn: followKnobs(x, m.render).on }); + // With the item before it and the scene its run leaves on screen (post-conversation.mjs; a fresh list, so never + // a context worked out before this write). + const ctx = planContext(m.timeline.slice(), i, m.render); + const guard = (x) => threadReadErrors(x, m.render, { ...ctx, followOn: followKnobs(x, m.render).on }); const had = new Set(guard(was)); const now = guard(e).filter((x) => !had.has(x)); if (now.length) throw new StructureRefused(now); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -15,6 +15,7 @@ import { channelsDirFor, clipDateKey, readManifest } from "../projects/report.mj import { rejectionOf } from "./rejectReasons.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { postDay, postItemPlan } from "umtool-report-to-video/post-item"; +import { planContext } from "umtool-report-to-video/post-conversation"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; @@ -39,9 +40,10 @@ export function headingOf(e) { * * @param {Record<string, any>} e * @param {Record<string, any>} [render] - * @param {Record<string, any> | null} [prev] the item before it in the cut + * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null } | null} [ctx] the item before it + * in the cut and the scene its run leaves on screen (post-conversation.mjs planContext) */ -export function postPlayEntry(e, render = undefined, prev = null) { +export function postPlayEntry(e, render = undefined, ctx = null) { const day = postDay(e.date); const dateKey = day ? Number(day.replace(/-/g, "")) : null; const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim(); @@ -55,8 +57,9 @@ export function postPlayEntry(e, render = undefined, prev = null) { date: day || null, quote: words || null, post: e, - // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - postPlan: postItemPlan(e, render, { prev }), + // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: the + // posts its run left on screen (post-conversation.mjs: one conversation played as one scene). + postPlan: postItemPlan(e, render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null }), }; } @@ -111,7 +114,7 @@ export async function playView(project, { take = null, bare = false } = {}) { const cache = await projectCache(project, manifest); const entries = await Promise.all( timeline.map(async (e, i) => { - if (e.type === "post") return postPlayEntry(e, render, timeline[i - 1] ?? null); + if (e.type === "post") return postPlayEntry(e, render, planContext(timeline, i, render)); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); const dateKey = clipDateKey(e); diff --git a/umtool/lib/report/postThread.test.mjs b/umtool/lib/report/postThread.test.mjs @@ -99,3 +99,33 @@ test("the cut's thread knobs (posts narrate --cut thread.*), and the import stor const got = (await manifest(p)).timeline[0].narration.takes[0].parts; assert.deepEqual(got.map((x) => [x.role, x.voice]), [["parent:0", "leo"], ["parent:0", "leo"], ["post", "zac"]]); }); + +test("timeline threads: the cut's conversations (split, tree order, a re-read with its fix); --write gathers one in tree order in ONE write, undoable", async () => { + const { timelineCommand } = await import("./timelineCli.mjs"); + const reply = (id, parents, text, date) => item(id, { text, date, parents, narration: { script: text, takes: [{ file: `narration/posts/${id}/take-1.orpheus-zac.wav`, engine: "orpheus", voice: "zac", seconds: 4, parts: [{ n: 1, para: 0, text, start: 0, seconds: 3.6 }] }], pick: 0 } }); + const root = { id: "771", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T06:00:00.000Z", text: "The root of it all, said once and for everyone." }; + const a = reply("776", [root], "His own reply under the root, the first branch.", "2026-10-30T06:20:00.000Z"); + const b = reply("779", [{ id: "775", handle: "drac_two", text: "A stranger answering the root." }, root], "His answer to the stranger, the second branch.", "2026-10-30T06:27:00.000Z"); + const x = reply("831", [{ id: "825", handle: "saber", text: "Another conversation entirely." }], "A reply in another conversation.", "2026-10-30T06:40:00.000Z"); + const c = reply("848", [{ id: "834", handle: "fox_one", text: "A stranger answering his own reply." }, { id: "776", author: "THE SUBJECT", handle: "Subject", text: "His own reply under the root, the first branch." }], "His answer to the fox, under the first branch.", "2026-10-30T07:10:00.000Z"); + const p = await project("threads", [a, b, x, c]); + const run = async (args) => { + const lines = []; + const errs = []; + const code = await timelineCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; + }; + const ls = await run(["threads", "threads"]); + assert.equal(ls.code, 0, ls.err); + assert.match(ls.out, /1 conversation\(s\)/); + assert.match(ls.out, /root 771 {2}3 items {2}SPLIT into 2 runs/); + assert.match(ls.out, /tree order: p-776 p-848 p-779 {2}\(umtool timeline threads threads --write --conversation 771\)/); + const w = await run(["threads", "threads", "--write", "--conversation", "p-848"]); + assert.equal(w.code, 0, w.err); + assert.match(w.out, /gathered 1 conversation\(s\)/); + assert.deepEqual((await manifest(p)).timeline.map((e) => e.id), ["p-776", "p-848", "p-779", "p-831"]); + assert.match((await run(["threads", "threads", "--write"])).out, /already together in tree order/); + assert.notEqual((await run(["threads", "threads", "--write", "--conversation", "nope"])).code, 0); + await run(["threads", "undo"]); + assert.deepEqual((await manifest(p)).timeline.map((e) => e.id), ["p-776", "p-779", "p-831", "p-848"], "one undo point"); +}); diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs @@ -15,6 +15,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { partRoles, readPieces, threadLayout, threadReadErrors, threadReadWarnings } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; +import { planContext } from "umtool-report-to-video/post-conversation"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarrations } from "./manifest.mjs"; @@ -38,11 +39,14 @@ export class RolesError extends Error { const ROLE_RE = /^(post|quoted|parent:\d|media:\d)$/; -/** A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. */ -export function readListing(e, render, prev) { +/** + * A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. + * `ctx`: what it opens on (post-conversation.mjs planContext: the item before it, its run's scene). + */ +export function readListing(e, render, ctx) { const t = pickedTake(e); const roles = partRoles(e); - const L = threadLayout(e, render, { prev }); + const L = threadLayout(e, render, ctx ?? {}); const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === role)?.mode ?? "absent"); const pieces = readPieces(e, roles).map((p) => ({ role: p.role, @@ -52,7 +56,7 @@ export function readListing(e, render, prev) { words: p.parts.map((k) => String(t.parts[k]?.text ?? "")).join(" ").split(/\s+/).filter(Boolean).length, })); const tiles = L.tiles.filter((x) => !x.read && x.scope !== "post").map((x) => ({ scope: x.scope, mode: x.mode })); - return { id: e.id, take: t?.file ?? null, parts: t?.parts?.length ?? 0, pieces, unread: tiles, threaded: L.on && followKnobs(e, render).on, errors: threadReadErrors(e, render, { prev, followOn: followKnobs(e, render).on }), warnings: threadReadWarnings(e) }; + return { id: e.id, take: t?.file ?? null, parts: t?.parts?.length ?? 0, pieces, unread: tiles, threaded: L.on && followKnobs(e, render).on, errors: threadReadErrors(e, render, { ...(ctx ?? {}), followOn: followKnobs(e, render).on }), warnings: threadReadWarnings(e) }; } /** @@ -66,7 +70,7 @@ export async function rolesCommand(project, ids, { write = false, set = null, js const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; const want = new Set(ids); const hit = (e) => !want.size || want.has(e.id) || want.has(String(e.post ?? "").split("/")[1]); - const items = tl.map((e, i) => ({ e, prev: tl[i - 1] ?? null })).filter(({ e }) => e?.type === "post" && isNarrated(e) && hit(e) && pickedTake(e)?.parts?.length); + const items = tl.map((e, i) => ({ e, ctx: planContext(tl, i, manifest.render) })).filter(({ e }) => e?.type === "post" && isNarrated(e) && hit(e) && pickedTake(e)?.parts?.length); for (const id of want) if (!tl.some((e) => e?.type === "post" && (e.id === id || String(e.post ?? "").split("/")[1] === id))) throw new RolesError(`no post item ${id} in ${project.id}`); if (set !== null) { if (items.length !== 1) throw new RolesError("--set names one item's parts: give exactly one narrated item with parts"); @@ -86,7 +90,8 @@ export async function rolesCommand(project, ids, { write = false, set = null, js const { result } = await withEditNotes(project, async () => updatePostNarrations(project.dir, [{ id: e.id, patch: { partRoles: { take, roles } } }], { token: await manifestToken(project.dir) })); const now = await readManifest(project.dir); const after = (now?.timeline ?? []).find((x) => x?.id === e.id) ?? e; - const row = readListing(after, now?.render ?? manifest.render, items[0].prev); + const ntl = Array.isArray(now?.timeline) ? now.timeline : []; + const row = readListing(after, now?.render ?? manifest.render, planContext(ntl, ntl.indexOf(after), now?.render ?? manifest.render)); out(json ? JSON.stringify({ ok: true, item: row, token: result.token }, null, 2) : lines([row]).join("\n")); return 0; } @@ -107,7 +112,7 @@ export async function rolesCommand(project, ids, { write = false, set = null, js out(json ? JSON.stringify({ ok: true, written: patches.length, token: result.token }, null, 2) : `stored the roles of ${patches.length} read(s) in ${project.id}`); return 0; } - const rows = items.map(({ e, prev }) => readListing(e, manifest.render, prev)); + const rows = items.map(({ e, ctx }) => readListing(e, manifest.render, ctx)); if (json) { out(JSON.stringify({ ok: true, items: rows, refused: rows.filter((r) => r.errors.length).length, warned: rows.filter((r) => r.warnings.length).length }, null, 2)); return 0; diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -26,6 +26,7 @@ // umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start]) // [--move] [--quote Q] [--id ID] // umtool timeline <project> order <file|@file|id…> +// umtool timeline <project> threads [--write [--conversation <id>]] [--json] // umtool timeline <project> groups [ls] | import <file> [--skip-missing] [--drop-empty] // | set <gid|-> <id…> [--claim C] | move <gid> (--to <index> | --to after <gid>) // | label <gid> <claim…> | promote <gid> [--label L] | remove <gid> @@ -140,6 +141,14 @@ export const TIMELINE_USAGE = [ " places the named entries hold, in that order (name them all for the whole order); every", " clip keeps its section (an order across a boundary is refused); a JSON list, {order}, a", " claim-groups file or ids by spaces, commas or lines; one undo point", + " umtool timeline <project> threads [--json] THE CONVERSATIONS (post-conversation.mjs): each tree of two post", + " items or more -- its root, its items' places, whether they play as one run (one scene) or are", + " split by other entries, a reply placed before the post it answers, an item re-reading a post", + " its run already read (with the fix: posts set-item <p> <item> thread.parent.<i>=context)", + " 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", " 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", @@ -162,9 +171,9 @@ export const TIMELINE_USAGE = [ ].join("\n"); const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"]; -const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups"]; +const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"]; const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"]; -const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim"]); +const VALUED = new Set(["--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo"]; @@ -491,6 +500,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => return 0; } + if (verb === "threads") return await threadsCommand(project, manifest, { write: flags.has("--write"), only: flags.has("--conversation") ? String(flags.get("--conversation")) : null, json, out }); + if (verb === "ls") { const rows = timelineRows(manifest); if (json) { @@ -855,6 +866,55 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) { } /** `sections`, one line each: §, its marker, colour, label, its clips. */ +/** + * `umtool timeline <p> threads [--write [--conversation <id>]]`: the cut's conversations + * (post-conversation.mjs conversations), and their gathering in tree order (gatheredOrder) as ONE + * orderEntries write -- only the entries whose place changes are named, so every other keeps its slot. + */ +export async function threadsCommand(project, manifest, { write = false, only = null, json = false, out = (s) => console.log(s) } = {}) { + const { conversations, gatheredOrder } = await import("umtool-report-to-video/post-conversation"); + const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; + const convs = conversations(tl, manifest.render); + if (only && !convs.some((c) => c.root === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) { + throw new CliError(`no conversation of two post items or more holds ${only} in ${project.id}`); + } + if (!write) { + if (json) { + out(JSON.stringify({ ok: true, project: project.id, conversations: convs }, null, 2)); + return 0; + } + out(`${project.id}: ${convs.length} conversation(s) of two post items or more`); + for (const c of convs) { + out(` root ${c.root ?? "?"} ${c.items.length} items ${c.split ? `SPLIT into ${c.runs} runs` : "one run"}`); + out(` in the cut: ${c.items.map((it) => `${it.id}@${it.at}`).join(" ")}`); + const inOrder = c.items.map((it) => it.id).join(" ") === c.order.join(" "); + if (!inOrder) out(` tree order: ${c.order.join(" ")} (umtool timeline ${project.id} threads --write --conversation ${c.root ?? c.items[0].id})`); + for (const m of c.misplaced) out(` MISPLACED: ${m.id} (at ${m.at}) answers ${m.answers}, placed after it (at ${m.answersAt})`); + for (const r of c.rereads) out(` RE-READ: ${r.id} reads ${r.scope} (${r.post}), which ${r.by} already read -- ${r.fix.replace("<p>", project.id)}`); + } + return 0; + } + const model = sectionModel(manifest); + const g = gatheredOrder(tl, manifest.render, { sectionOf: model.sectionOf, 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`); + return 0; + } + const { orderEntries } = await import("./manifest.mjs"); + const { result, editNotes } = await withEditNotes(project, async () => orderEntries(project.dir, named, { token: await manifestToken(project.dir) })); + if (json) { + out(JSON.stringify({ ok: true, written: true, moved: g.moved, left: g.left, token: result.token, editNotes }, null, 2)); + 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`); + return 0; +} + export function sectionLines(sections) { return sections.map((s) => { const clips = s.clips.length > 6 ? `${s.clips.slice(0, 3).join(" ")} … ${s.clips.slice(-2).join(" ")}` : s.clips.join(" "); diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -216,6 +216,7 @@ import { // The snap itself (a montage's window snaps with it too), re-exported for the tests. import { snap } from "./snap.mjs"; import { buildPostSegment } from "./post-render.mjs"; +import { planContextOf } from "./post-conversation.mjs"; import { readPostRedaction } from "./post-redact-files.mjs"; import { dropMarks, redactEntry } from "./post-redact.mjs"; import { avatarUrls } from "./post-avatars.mjs"; @@ -6432,8 +6433,9 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // The authors' pictures (post-avatars.mjs), as files of the project. avatars: avatarUrls(manifest, (src) => path.resolve(manifestDir, src)), redaction: POST_REDACTION, - // The item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to). - prev: manifest.timeline[manifest.timeline.findIndex((x) => x?.id === entry.id) - 1] ?? null, + // The item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to) and + // the scene its run leaves on screen (post-conversation.mjs: one conversation played as one scene). + ...planContextOf(manifest.timeline, entry.id, render), }); if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr }); // Its combo badge (post-combo-render.mjs): a pass over the segment when its attachment repeats an earlier one's. diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -71,6 +71,7 @@ "./post-redact-files": "./post-redact-files.mjs", "./post-slurs": "./post-slurs.mjs", "./post-thread": "./post-thread.mjs", + "./post-conversation": "./post-conversation.mjs", "./post-render": "./post-render.mjs", "./word-zoom": "./word-zoom.mjs", "./read-follow": "./read-follow.mjs", diff --git a/umtool/report-to-video/post-conversation.mjs b/umtool/report-to-video/post-conversation.mjs @@ -0,0 +1,448 @@ +// THE THREAD WALK (umtool/docs/report-video.md, "Thread reads"; operator, +// 4 Nov 2026, of p-2116779173746491646's tree: "weird thread progression", +// "wrong order"; p-2117379128664236113: "definitely would benefit from a full +// read thread progression"): the post items of ONE CONVERSATION played back +// to back are one scene, not cold cuts. +// +// identity an item's CHAIN is the posts it answers (oldest first) and its +// own post (a repost's: the original), plus its `conversation` +// (postContext.mjs: the archive row's threadId) when it has one. +// Two items are of one TREE when their chains share an id. +// a RUN consecutive narrated, read-following post items of one tree. +// +// planContext(timeline, i, render) -> { prev, scene }: what item i opens on. +// `scene.tiles` are the posts its run had on screen as the item before ended +// (that item's drawn ancestors and its post, and what its own scene kept), +// each with its `ref` (what it draws: author, handle, words, date -- the +// author blurred or not by its own item's rule, post-item.mjs cardAuthors) +// and how it opens (`from` "full" when it was the item before's post, else +// "small": shrunk and dimmed as it ended); `action` "keep" when it is an +// ancestor of item i (the root stays on top as context), else "collapse" +// (the branch it was on collapses away -- scale 0, opacity 0, the flow +// closing up -- as item i's own posts come in). A post item i draws itself +// is left to its own tile (post-thread.mjs threadLayout): a parent the item +// before ended on is carried, one the run showed earlier is context. +// `scene.rank` orders every post of the run's tree (depth first, a branch in +// the order the run first showed it: the root, the branch collapsing, the new +// branch). +// +// conversations(timeline, render) is the cut's conversations (any post items, +// in any order) for `umtool timeline <p> threads`: each tree with two items or +// more, whether they play as one run, a reply placed before the post it +// answers, a post re-read that the run already read -- and treeOrder, the +// order `threads --write` gathers them in (a post after what it answers; +// sibling branches by date, each branch depth first). +// +// PURE and dependency-free (but its siblings): the build, Play, the bench, +// the route, the writers' guard and the lint read the same context from here. + +import { cardAuthors, cardText, contextText, isParaphrased, parentsOf } from "./post-item.mjs"; +import { isNarrated } from "./post-narration.mjs"; +import { followKnobs } from "./read-follow.mjs"; +import { partRoles, shownIdOf, threadLayout } from "./post-thread.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); + +// --------------------------------------------------------------------------- +// Identity: chains, trees. +// --------------------------------------------------------------------------- + +/** An item's CHAIN: the ids of the posts it answers, oldest first, then its own post's (blank ids kept as ""). */ +export function chainOf(e) { + return [...parentsOf(e).map((p) => str(p?.id)).reverse(), shownIdOf(e)]; +} + +/** The keys an item joins a tree by: its chain's ids and its conversation. */ +export function treeKeysOf(e) { + const out = new Set(chainOf(e).filter(Boolean)); + if (str(e?.conversation)) out.add(str(e.conversation)); + return out; +} + +/** Whether an item plays in a run: a narrated post item that read-follows (its card can carry a scene). */ +export const runsIn = (e, render) => e?.type === "post" && isNarrated(e) && followKnobs(e, render).on; + +/** Compare two post ids: snowflakes by number (their time), else as strings. */ +function idCmp(a, b) { + if (/^\d{1,25}$/.test(a) && /^\d{1,25}$/.test(b)) { + const x = BigInt(a); + const y = BigInt(b); + return x < y ? -1 : x > y ? 1 : 0; + } + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * A TREE of items (in the order given): `{ parentOf, children, roots, seen, + * date }` -- each post's parent (from the chains), its children, the posts + * with none, the place each post was first seen (the index of the item that + * first drew it), its date. + */ +export function treeOf(items) { + const parentOf = new Map(); + const seen = new Map(); + const date = new Map(); + items.forEach((e, k) => { + const ids = chainOf(e); + const refs = [...parentsOf(e)].reverse(); + ids.forEach((id, j) => { + if (!id) return; + if (!seen.has(id)) seen.set(id, k); + const d = j < refs.length ? str(refs[j]?.date) : str(e?.date); + if (d && !date.has(id)) date.set(id, d); + if (j > 0 && ids[j - 1] && !parentOf.has(id) && ids[j - 1] !== id) parentOf.set(id, ids[j - 1]); + }); + }); + // A cycle (bad data) is cut where it closes. + for (const id of [...parentOf.keys()]) { + const path = new Set([id]); + let cur = parentOf.get(id); + while (cur !== undefined) { + if (path.has(cur)) { + parentOf.delete(id); + break; + } + path.add(cur); + cur = parentOf.get(cur); + } + } + const children = new Map(); + for (const [c, p] of parentOf) { + if (!children.has(p)) children.set(p, []); + children.get(p).push(c); + } + const all = new Set([...seen.keys(), ...parentOf.values()]); + const roots = [...all].filter((id) => !parentOf.has(id)); + return { parentOf, children, roots, seen, date }; +} + +/** The ancestors of post `id` in a tree (nearest first). */ +export function ancestorsOf(tree, id) { + const out = []; + let cur = tree.parentOf.get(id); + while (cur !== undefined && !out.includes(cur)) { + out.push(cur); + cur = tree.parentOf.get(cur); + } + return out; +} + +/** + * The tree's DEPTH-FIRST ORDER: `Map<id, place>` -- a post before what + * answers it, each branch whole before the next. `by`: "seen" (siblings in + * the order the items first drew them -- a scene's order) or "date" + * (sibling branches by date -- a branch's date its earliest item's, `items` + * the posts the items draw -- then id: the order `threads --write` gathers in). + */ +export function treeRank(tree, by = "seen", items = null) { + // A branch's date (by "date"): its earliest item's (`items`: the ids of the posts the items draw), else its earliest post's. + const mine = items ? new Set(items) : null; + const branchDate = new Map(); + const dateOf = (id) => { + if (branchDate.has(id)) return branchDate.get(id); + branchDate.set(id, Infinity); + const own = Date.parse(tree.date.get(id) ?? ""); + let best = !mine || mine.has(id) ? (Number.isFinite(own) ? own : Infinity) : Infinity; + for (const c of tree.children.get(id) ?? []) best = Math.min(best, dateOf(c)); + if (best === Infinity && Number.isFinite(own) && mine && !mine.has(id)) best = own + 1e12; + branchDate.set(id, best); + return best; + }; + const cmp = (a, b) => { + if (by === "seen") { + const x = tree.seen.get(a) ?? Infinity; + const y = tree.seen.get(b) ?? Infinity; + if (x !== y) return x - y; + } + const da = by === "date" ? dateOf(a) : Date.parse(tree.date.get(a) ?? ""); + const db = by === "date" ? dateOf(b) : Date.parse(tree.date.get(b) ?? ""); + if (Number.isFinite(da) && Number.isFinite(db) && da !== db) return da - db; + return idCmp(a, b); + }; + const rank = new Map(); + const visit = (id) => { + if (rank.has(id)) return; + rank.set(id, rank.size); + for (const c of [...(tree.children.get(id) ?? [])].sort(cmp)) visit(c); + }; + for (const r of [...tree.roots].sort(cmp)) visit(r); + return rank; +} + +// --------------------------------------------------------------------------- +// Runs and the scene. +// --------------------------------------------------------------------------- + +/** + * THE RUNS of a timeline: `{ runOf: number[], runs: [{ items: [i…], tree, + * rank }] }` -- runOf[i] the run item i plays in (-1: none). A run starts at + * any item that runs in one and takes the items after it while each shares a + * key with the run so far. + */ +export function conversationRuns(timeline, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const runOf = new Array(tl.length).fill(-1); + const runs = []; + let cur = null; + tl.forEach((e, i) => { + if (!runsIn(e, render)) { + cur = null; + return; + } + const keys = treeKeysOf(e); + if (cur && [...keys].some((k) => cur.keys.has(k))) { + cur.items.push(i); + for (const k of keys) cur.keys.add(k); + } else { + cur = { items: [i], keys }; + runs.push(cur); + } + runOf[i] = runs.length - 1; + }); + return { + runOf, + runs: runs.map((r) => { + const tree = treeOf(r.items.map((i) => tl[i])); + return { items: r.items, tree, rank: treeRank(tree, "seen") }; + }), + }; +} + +/** A tile's REF from item `e`'s card: what it draws, its author blurred by `e`'s rule. */ +export function sceneRefOf(e, scope) { + const authors = cardAuthors(e); + if (scope === "post") { + return { + id: shownIdOf(e), + author: str(e?.author) || undefined, + handle: str(e?.handle) || undefined, + date: str(e?.date) || undefined, + text: cardText(e), + redact: authors.find((a) => a.where === "author")?.redact === true, + src: { post: str(e?.post), scope: "text" }, + }; + } + const i = Number(/^parent:(\d)$/.exec(scope)?.[1] ?? -1); + const p = parentsOf(e)[i]; + if (!p) return null; + return { + id: str(p.id), + author: str(p.author) || undefined, + handle: str(p.handle) || undefined, + date: str(p.date) || undefined, + ...(p.badge ? { badge: p.badge } : {}), + text: contextText(p), + ...(isParaphrased(p) ? { paraphrased: true } : {}), + redact: authors.find((a) => a.where === `parents[${i}]`)?.redact === true, + src: { post: str(e?.post), scope: "parent", index: i }, + }; +} + +const memo = new WeakMap(); +const NO_RENDER = {}; + +/** + * Every item's context, worked out once per timeline and render (each item's + * scene is the end of the one before): `[{ prev, scene }]`. + */ +function contextsOf(tl, render) { + const byRender = memo.get(tl) ?? new WeakMap(); + memo.set(tl, byRender); + const rk = isObj(render) ? render : NO_RENDER; + const hit = byRender.get(rk); + if (hit && hit.length === tl.length && hit.every((c, i) => c.entry === tl[i])) return hit; + const { runOf, runs } = conversationRuns(tl, render); + const out = []; + let end = null; + tl.forEach((e, i) => { + const prev = i > 0 ? tl[i - 1] ?? null : null; + const r = runOf[i]; + let scene = null; + if (r >= 0 && i > 0 && runOf[i - 1] === r && end?.length) { + const run = runs[r]; + const anc = new Set([...ancestorsOf(run.tree, shownIdOf(e)), ...chainOf(e).slice(0, -1).filter(Boolean)]); + const prevId = shownIdOf(prev); + scene = { + tiles: end.map((t) => ({ id: t.id, ref: t.ref, from: t.id === prevId ? "full" : "small", action: anc.has(t.id) ? "keep" : "collapse" })), + rank: Object.fromEntries(run.rank), + }; + } + const ctx = { prev, scene }; + out.push({ entry: e, ...ctx }); + // What this item leaves on screen for the next: the scene's posts it kept, its drawn parents, its post. + end = null; + if (r >= 0) { + const L = threadLayout(e, render, ctx); + end = []; + for (const t of L.tiles) { + if (t.mode === "hidden") continue; + if (t.mode === "scene") { + if (t.action === "keep") end.push({ id: t.scope.slice(6), ref: t.ref }); + } else if (t.scope === "post" || t.scope.startsWith("parent:")) { + const ref = sceneRefOf(e, t.scope); + if (ref?.id && str(ref.text).trim()) end.push({ id: ref.id, ref }); + } + } + } + }); + byRender.set(rk, out); + return out; +} + +/** + * WHAT ITEM i OPENS ON, pure (memoised per timeline): `{ prev, scene }` -- + * the item before it, and the scene its run leaves on screen (null: none; see + * the head of this file). Every caller that plans, draws or guards a post + * item passes this where it passed `{ prev }`. + * + * @param {Array<Record<string, any>>} timeline + * @param {number} i + * @param {Record<string, any>} [render] + * @returns {{ prev: Record<string, any> | null, scene: { tiles: Array<Record<string, any>>, rank: Record<string, number> } | null }} + */ +export function planContext(timeline, i, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + if (!(i >= 0 && i < tl.length)) return { prev: i > 0 ? tl[i - 1] ?? null : null, scene: null }; + const c = contextsOf(tl, render)[i]; + return { prev: c.prev, scene: c.scene }; +} + +/** The context of the item with id `id` (planContext; `{ prev: null, scene: null }` when there is none). */ +export function planContextOf(timeline, id, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const i = tl.findIndex((e) => e?.id === id); + return i < 0 ? { prev: null, scene: null } : planContext(tl, i, render); +} + +// --------------------------------------------------------------------------- +// The cut's conversations (`umtool timeline <p> threads`). +// --------------------------------------------------------------------------- + +/** + * THE CUT's CONVERSATIONS, pure: each tree of two post items or more, + * `{ root, items: [{ id, at, post, chain }], runs, split, order, misplaced, + * rereads }` -- its root post, its items in cut order (`at` the index), the + * runs it plays in (`split`: other entries between them), `order` its items' + * ids in TREE order (a post after what it answers; sibling branches by date, + * each depth first), `misplaced` each reply placed before the post it answers + * (`{ id, answers, at, answersAt }`), `rereads` each item whose read reads a + * post its run already read (`{ id, scope, post, by, fix }`). + * + * @param {Array<Record<string, any>>} timeline + * @param {Record<string, any>} [render] + */ +export function conversations(timeline, render = undefined) { + const tl = Array.isArray(timeline) ? timeline : []; + const posts = tl.map((e, at) => ({ e, at })).filter((x) => x.e?.type === "post"); + // Union-find over the items, by their keys. + const parent = posts.map((_, k) => k); + const find = (k) => (parent[k] === k ? k : (parent[k] = find(parent[k]))); + const owner = new Map(); + posts.forEach((x, k) => { + for (const key of treeKeysOf(x.e)) { + if (owner.has(key)) parent[find(k)] = find(owner.get(key)); + else owner.set(key, k); + } + }); + const groups = new Map(); + posts.forEach((x, k) => { + const g = find(k); + if (!groups.has(g)) groups.set(g, []); + groups.get(g).push(x); + }); + const { runOf } = conversationRuns(tl, render); + const out = []; + for (const members of groups.values()) { + if (members.length < 2) continue; + const tree = treeOf(members.map((x) => x.e)); + const byDate = treeRank(tree, "date", members.map((x) => shownIdOf(x.e))); + const root = [...tree.roots].sort((a, b) => (byDate.get(a) ?? 0) - (byDate.get(b) ?? 0))[0] ?? null; + const items = members.map((x) => ({ id: x.e.id, at: x.at, post: shownIdOf(x.e), chain: chainOf(x.e) })); + // Runs: maximal stretches of its items with nothing else between them. + let runs = 0; + let lastAt = -2; + for (const it of items) { + if (it.at !== lastAt + 1) runs += 1; + lastAt = it.at; + } + const order = [...items].sort((a, b) => (byDate.get(a.post) ?? Infinity) - (byDate.get(b.post) ?? Infinity) || a.at - b.at).map((x) => x.id); + const atOfPost = new Map(); + for (const it of items) if (!atOfPost.has(it.post)) atOfPost.set(it.post, it); + const misplaced = []; + for (const it of items) { + for (const a of ancestorsOf(tree, it.post)) { + const y = atOfPost.get(a); + if (y && y.at > it.at) { + misplaced.push({ id: it.id, answers: y.id, at: it.at, answersAt: y.at }); + break; + } + } + } + // Re-reads: in a run, a part of an item's read reading a post the run already read (or drew in full as an item's post). + const rereads = []; + const readBy = new Map(); + let runAt = -1; + for (const it of items) { + const e = tl[it.at]; + if (runOf[it.at] !== runAt) { + readBy.clear(); + runAt = runOf[it.at]; + } + if (runAt < 0) continue; + const roles = new Set(partRoles(e).map((r) => r.role).filter(Boolean)); + parentsOf(e).forEach((p, i) => { + const pid = str(p?.id); + if (pid && roles.has(`parent:${i}`) && readBy.has(pid)) { + rereads.push({ id: e.id, scope: `parent:${i}`, post: pid, by: readBy.get(pid), fix: `umtool posts set-item <p> ${e.id} thread.parent.${i}=context` }); + } + }); + if (roles.has("post") || isNarrated(e)) readBy.set(it.post, e.id); + parentsOf(e).forEach((p, i) => { + if (str(p?.id) && roles.has(`parent:${i}`) && !readBy.has(str(p.id))) readBy.set(str(p.id), e.id); + }); + } + out.push({ root, items, runs, split: runs > 1, order, misplaced, rereads }); + } + return out.sort((a, b) => a.items[0].at - b.items[0].at); +} + +/** + * 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 + * 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 }] }`. + */ +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 = []; + 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)]; + } + return { ids, moved, left }; +} diff --git a/umtool/report-to-video/post-conversation.test.mjs b/umtool/report-to-video/post-conversation.test.mjs @@ -0,0 +1,197 @@ +// post-conversation.mjs: THE THREAD WALK -- the post items of one conversation +// played back to back are one scene. The fixture is the operator's tree +// (p-2116779173746491646's, 4 Nov): his root post, his own reply under it (A), +// a stranger's answer to A with his reply (C), and a second stranger's answer +// to the root with his reply (B) -- the sibling branch. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan } from "./post-item.mjs"; +import { followPath, followStateAt } from "./read-follow.mjs"; +import { THREAD_DEFAULTS, threadGeoAt, threadLayout, threadReadErrors, validateThreadReads } from "./post-thread.mjs"; +import { ancestorsOf, chainOf, conversationRuns, conversations, gatheredOrder, planContext, treeOf, treeRank } from "./post-conversation.mjs"; + +const ROOT = { id: "771", author: "Subject", handle: "subject", date: "2026-11-01T06:00:00.000Z", text: "Many have questioned my methods in dealing with the whole mess.\n\nThey are all jumping for joy because the moment they have it, it is already too late." }; +const A_TEXT = "I can't help but feel like I've failed, everyone gave them exactly what they wanted.\n\nRegardless of what happens now, I know I'm going to blame myself."; +const FOX = { id: "834", author: "Fox", handle: "fox_one", date: "2026-11-01T07:00:00.000Z", text: "Far as people should be concerned you are no better than the people you criticised." }; +const C_TEXT = "As far as people are concerned you're nobody at all.\n\nIn short, go away you worthless loser."; +const DRAC = { id: "775", author: "Drac", handle: "drac_two", date: "2026-11-01T06:10:00.000Z", text: "Oh please you were not going to affect anything on this.\n\nYou don't fight them by drawing attention to it, that is the last thing you want to do." }; +const B_TEXT = "I have fought them though.\n\nWho are you to speak about what fighting them is like."; + +const post = (id, text, o = {}) => ({ type: "post", id: `p-${id}`, post: `acct-x/${id}`, platform: "x", author: "Subject", handle: "subject", date: o.date ?? "2026-11-01T06:20:00.000Z", text, ...o }); +/** A take as the batch assembles one: pieces in order (para = piece * 100 + paragraph), each paragraph a part. */ +function take(pieces) { + const parts = []; + let at = 0; + pieces.forEach((text, pi) => { + text.split(/\n\n/).forEach((para, k) => { + const seconds = Math.round((para.split(/\s+/).length / 3) * 100) / 100; + at += parts.length ? (k === 0 ? 0.8 : 0.6) : 0; + parts.push({ n: parts.length + 1, para: pi * 100 + k, text: para, start: Math.round(at * 100) / 100, seconds }); + at += seconds; + }); + }); + return { file: "narration/posts/x/take-1.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(at * 100) / 100, script: pieces.join("\n\n"), parts }; +} +const narrate = (e, pieces) => ({ ...e, narration: { script: e.text, takes: [take(pieces)], pick: 0 } }); + +const A = narrate(post("776", A_TEXT, { date: "2026-11-01T06:20:00.000Z", parents: [ROOT] }), [A_TEXT]); +const B = narrate(post("779", B_TEXT, { date: "2026-11-01T06:27:00.000Z", parents: [DRAC, ROOT] }), [DRAC.text, B_TEXT]); +const X = narrate(post("831", "Something else entirely, another conversation.", { date: "2026-11-01T06:40:00.000Z", parents: [{ id: "825", handle: "saber", text: "A different question about a different thing." }] }), ["Something else entirely, another conversation."]); +const C = narrate(post("848", C_TEXT, { date: "2026-11-01T07:10:00.000Z", parents: [FOX, { id: "776", author: "Subject", handle: "subject", date: A.date, text: A_TEXT }] }), [FOX.text, C_TEXT]); +const render = { postNarration: { lead: 0.4 } }; + +test("identity: an item's chain (oldest first), the tree its chains make, its ancestors and the depth-first order -- by first sight, or by date (a branch's date its earliest item's)", () => { + assert.deepEqual(chainOf(C), ["776", "834", "848"]); + assert.deepEqual(chainOf({ ...A, originalId: "999" }), ["771", "999"], "a repost draws its original"); + const tree = treeOf([A, B, C]); + assert.deepEqual(tree.roots, ["771"]); + assert.deepEqual(ancestorsOf(tree, "848"), ["834", "776", "771"]); + assert.deepEqual([...treeRank(tree, "seen").keys()], ["771", "776", "834", "848", "775", "779"]); + // By date: the root's branches by their earliest ITEM -- his own reply (06:20) before the stranger's branch (06:27), + // though the stranger's post itself (06:10) is older. + assert.deepEqual([...treeRank(tree, "date", ["776", "779", "848"]).keys()], ["771", "776", "834", "848", "775", "779"]); +}); + +test("the runs: consecutive narrated, read-following post items of one tree; another conversation between them splits them", () => { + const r = conversationRuns([A, B, X, C], render); + assert.deepEqual(r.runOf, [0, 0, 1, 2]); + const g = conversationRuns([A, C, B, X], render); + assert.deepEqual(g.runOf, [0, 0, 0, 1]); + // Un-narrated or follow off: in no run. + assert.deepEqual(conversationRuns([A, { ...C, follow: false }], render).runOf, [0, -1]); +}); + +test("THE CUT's CONVERSATIONS: the tree, its items' places, split or one run, tree order, a reply placed before what it answers, a re-read", () => { + const [c] = conversations([A, B, X, C], render); + assert.equal(c.root, "771"); + assert.deepEqual(c.items.map((it) => [it.id, it.at]), [["p-776", 0], ["p-779", 1], ["p-848", 3]]); + assert.equal(c.split, true); + assert.deepEqual(c.order, ["p-776", "p-848", "p-779"]); + assert.deepEqual(c.misplaced, []); + // His reply to Fox before his own reply A that Fox answered: misplaced. + const [m] = conversations([C, A], render); + assert.deepEqual(m.misplaced, [{ id: "p-848", answers: "p-776", at: 0, answersAt: 1 }]); + // C reading A again (its parent:1) right after A was read: a re-read, with the fix. + const again = narrate(C, [A_TEXT, FOX.text, C_TEXT]); + const [rr] = conversations([A, again], render); + assert.equal(rr.rereads.length, 1); + assert.deepEqual([rr.rereads[0].id, rr.rereads[0].scope, rr.rereads[0].post, rr.rereads[0].by], ["p-848", "parent:1", "776", "p-776"]); + assert.match(rr.rereads[0].fix, /set-item <p> p-848 thread\.parent\.1=context/); +}); + +test("GATHERED in tree order (threads --write): at the first item's place, a post after what it answers, branches by date; another section's item is left", () => { + const g = gatheredOrder([A, B, X, C], render); + assert.deepEqual(g.ids, ["p-776", "p-848", "p-779", "p-831"]); + assert.deepEqual(g.moved, [{ root: "771", from: ["p-776", "p-779", "p-848"], to: ["p-776", "p-848", "p-779"] }]); + assert.deepEqual(gatheredOrder([A, C, B, X], render).moved, [], "already gathered"); + const sec = new Map([["p-776", 0], ["p-779", 0], ["p-831", 0], ["p-848", 1]]); + 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"]); +}); + +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", () => { + const tl = [A, C, B, X]; + assert.equal(planContext(tl, 0, render).scene, null); + // C after A: A's root stays on top (an ancestor of C); A's post is C's own parent (carried), not a scene tile. + const c = planContext(tl, 1, render); + assert.equal(c.prev, A); + assert.deepEqual(c.scene.tiles.map((t) => [t.id, t.action, t.from]), [["771", "keep", "small"], ["776", "keep", "full"]]); + const Lc = threadLayout(C, render, c); + assert.deepEqual(Lc.tiles.map((t) => [t.scope, t.mode]), [["scene:771", "scene"], ["parent:1", "carry"], ["parent:0", "full"], ["post", "full"]]); + // B after C: the root is B's own (context); C's branch (A, Fox, C) collapses -- in the tree's order, between the root and B's branch. + const b = planContext(tl, 2, render); + assert.deepEqual(b.scene.tiles.map((t) => [t.id, t.action, t.from]), [["771", "keep", "small"], ["776", "collapse", "small"], ["834", "collapse", "small"], ["848", "collapse", "full"]]); + const Lb = threadLayout(B, render, b); + assert.deepEqual(Lb.tiles.map((t) => [t.scope, t.mode, t.action ?? null]), [["parent:1", "context", null], ["scene:776", "scene", "collapse"], ["scene:834", "scene", "collapse"], ["scene:848", "scene", "collapse"], ["parent:0", "full", null], ["post", "full", null]]); + // Another conversation: no scene. + assert.equal(planContext(tl, 3, render).scene, null); + // The schedule: the branch collapses (scale 0, opacity 0) as the stranger's post is revealed, all at the first read's lead. + const plan = postItemPlan(B, render, b); + const th = plan.follow.thread; + const row = (sc) => th.tiles.find((t) => t.scope === sc); + assert.deepEqual([row("scene:848").from, row("scene:848").to], [[1, 1], [0, 0]]); + assert.deepEqual([row("scene:776").from, row("scene:776").to], [[THREAD_DEFAULTS.shrink, THREAD_DEFAULTS.dim], [0, 0]]); + assert.deepEqual([row("parent:0").from, row("parent:0").to], [[1, 0], [1, 1]]); + assert.equal(row("scene:848").t0, row("parent:0").t0); + assert.equal(row("scene:848").ref.handle, "subject"); + assert.deepEqual(threadReadErrors(B, render, b), []); + assert.deepEqual(validateThreadReads({ render, timeline: tl }), []); +}); + +/** A page's geometry for a plan: each tile a head and its blocks (scene tiles: a head and a paragraph). */ +function fakeGeo(plan, { H = 520, line = 44 } = {}) { + const blocks = {}; + const tiles = {}; + let y = 0; + for (const t of plan.follow.thread.tiles) { + const top = y; + y += 70; + const mine = plan.follow.blocks.filter((x) => x.scope === t.scope); + if (!mine.length) y += 3 * line; + for (const b of mine) { + const h = Math.max(1, Math.ceil((b.to - b.from + 1) / 6)) * line; + blocks[b.k] = { top: y, bottom: y + h }; + y += h + line; + } + tiles[t.scope] = { top, height: y - top, ...(t.scope.startsWith("scene:") ? { gap: 22 } : {}) }; + y += 22; + } + return { H, C: y, blocks, tiles }; +} + +test("THE INVARIANT, in a scene: every part of each item's read is on screen while it is said -- its tile in full and lit, its block in the window -- and the scene's posts are never read", () => { + const tl = [A, C, B]; + for (let i = 1; i < tl.length; i += 1) { + const e = tl[i]; + const ctx = planContext(tl, i, render); + const plan = postItemPlan(e, render, ctx); + const geo = fakeGeo(plan); + const path = followPath(plan.follow, geo); + const t = e.narration.takes[0]; + const settle = Math.max(THREAD_DEFAULTS.pan, THREAD_DEFAULTS.seconds) + plan.follow.ease / 2 + 0.02; + t.parts.forEach((p, k) => { + const blk = plan.follow.blocks.find((b) => b.part === k); + assert.ok(blk && !blk.scope.startsWith("scene:"), `${e.id} part ${k + 1}: a block of its own`); + const to = (t.parts[k + 1] ? plan.follow.blocks.find((b) => b.part === k + 1).start : plan.follow.readEnd) - 0.45; + for (let s = blk.start + settle; s <= to; s += 0.1) { + const st = followStateAt(plan.follow, path, s); + assert.deepEqual(st.tiles[blk.scope].slice(0, 2), [1, 1], `${e.id} part ${k + 1} at ${s.toFixed(2)} s: its tile in full`); + assert.equal(st.op[blk.k] ?? 1, 1); + const g = threadGeoAt(geo, Object.fromEntries(Object.entries(st.tiles).map(([x, v]) => [x, v[0]]))); + const bb = g.blocks[blk.k]; + assert.ok(bb.top - st.offset >= -1 && bb.bottom - st.offset <= geo.H + 1, `${e.id} part ${k + 1} at ${s.toFixed(2)} s: in the window (${(bb.top - st.offset).toFixed(0)}–${(bb.bottom - st.offset).toFixed(0)})`); + // A collapsed branch is gone (scale 0), its gap closed. + for (const [sc, v] of Object.entries(st.tiles)) if (sc.startsWith("scene:") && plan.follow.thread.tiles.find((x) => x.scope === sc).action === "collapse") assert.equal(v[0], 0, `${sc} collapsed`); + } + }); + // The opening frame is the one the item before ended on: the post it ended on in full, at the top of the window. + const st0 = followStateAt(plan.follow, path, 0); + const endedOn = plan.follow.thread.tiles.find((x) => x.wasPost || x.mode === "carry"); + assert.ok(endedOn, `${e.id}: opens on the post the item before ended on`); + assert.deepEqual(st0.tiles[endedOn.scope].slice(0, 2), [1, 1]); + const g0 = threadGeoAt(geo, Object.fromEntries(Object.entries(st0.tiles).map(([x, v]) => [x, v[0]]))); + const want = Math.min(Math.max(0, g0.tiles[endedOn.scope].top - Math.round(geo.H * 0.1)), Math.max(0, g0.C - geo.H)); + assert.ok(Math.abs(path.start - want) < 1, `${e.id}: framed on it (${path.start} vs ${want})`); + } +}); + +test("the card page draws the scene's posts as they were -- in the tree's order, never read (no blocks, no word spans), their words redacted by their own item's terms, their authors blurred by its rule", () => { + const tl = [A, C, B]; + const ctx = planContext(tl, 2, render); + const plan = postItemPlan(B, render, ctx); + const html = postCardHtml(B, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + const at = (sc) => html.indexOf(`data-thread-slot="${sc}"`); + for (const sc of ["parent:1", "scene:776", "scene:834", "scene:848", "parent:0", "post"]) assert.ok(at(sc) > 0, sc); + assert.ok(at("parent:1") < at("scene:776") && at("scene:776") < at("scene:834") && at("scene:834") < at("scene:848") && at("scene:848") < at("parent:0") && at("parent:0") < at("post"), "the tree's order"); + assert.match(html, /data-thread-slot="scene:848" data-thread-scene="collapse"/); + const scene = html.slice(at("scene:848"), at("parent:0")); + assert.doesNotMatch(scene, /data-w=|data-post-block=/, "never read"); + assert.match(scene, /worthless loser/); + // Redacted as published: a term of the project's, and a stranger (no badge) blurred by C's rule. + const red = postCardHtml(B, { width: 1600, height: 900, follow: true, thread: plan.follow.thread, redaction: { terms: [{ term: "worthless", wholeWord: true }] } }); + assert.doesNotMatch(red.slice(red.indexOf('data-thread-slot="scene:848"'), red.indexOf('data-thread-slot="parent:0"')), /worthless/); + const fox = red.slice(red.indexOf('data-thread-slot="scene:834"'), red.indexOf('data-thread-slot="scene:848"')); + assert.match(fox, /data-redacted=""/); + assert.doesNotMatch(fox, /fox_one/); +}); diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -32,7 +32,7 @@ import { isNarrated, narrationSchedule, postNarrationFiles, postNarrationKnobs, validatePostNarration, } from "./post-narration.mjs"; -import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactionOn, validatePostsRender } from "./post-redact.mjs"; +import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactSceneRef, redactionOn, validatePostsRender } from "./post-redact.mjs"; import { blurErrors } from "./post-censor.mjs"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs"; import { FOLLOW_MIN_SIZE, followBlocks, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; @@ -224,12 +224,13 @@ export function postItemSeconds(entry, render = undefined) { * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it) + * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs + * carries a parent that is it) and the scene its run leaves on screen (post-conversation.mjs planContext) * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number, narration?: Record<string, any>, follow?: Record<string, any> }} */ -export function postItemPlan(entry, render = undefined, { prev = null } = {}) { +export function postItemPlan(entry, render = undefined, { prev = null, scene = null } = {}) { const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; - return planOf(entry, render, hold, prev); + return planOf(entry, render, hold, prev, scene); } /** @@ -237,14 +238,15 @@ export function postItemPlan(entry, render = undefined, { prev = null } = {}) { * @param {Record<string, any> | undefined} render * @param {number | null} hold * @param {Record<string, any> | null} [prev] + * @param {Record<string, any> | null} [scene] */ -function planOf(entry, render, hold, prev = null) { +function planOf(entry, render, hold, prev = null, scene = null) { const narrated = isNarrated(entry); const k = postNarrationKnobs(entry, render); const sch = narrated ? narrationSchedule(entry, render) : null; // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off. `prev`: the // item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to). - const follow = followSchedule(entry, render, { hold, narration: sch, prev }); + const follow = followSchedule(entry, render, { hold, narration: sch, prev, scene }); const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) }; if (sch && k.attach === "after") { const voiceOnly = round3(sch.at + sch.seconds + k.tail); @@ -907,7 +909,9 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p const av = Math.round(56 * k); const cut = (scope) => (tmode(scope) === "excerpt" && fmap ? new Set(fmap.blocks.filter((b) => b.scope === scope && b.part === null).map((b) => b.k)) : null); const cutCss = []; - const tileHtml = []; + // Each tile's HTML by its scope, then drawn in the layout's order (the tree's: a scene's posts among his own). + const byScope = new Map(); + const tileHtml = { push: (h) => byScope.set(/data-thread-slot="([^"]+)"/.exec(h)?.[1] ?? `x${byScope.size}`, h) }; for (let i = parents.length - 1; i >= 0; i -= 1) { const scope = `parent:${i}`; const mode = tmode(scope); @@ -942,8 +946,21 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p tileHtml.push( `<div class="tslot" data-thread-slot="post"><div class="tile tpost" data-thread-tile="post">${repost}${lead}${head}<div class="twords" style="font-size:${psize}px">${wordsHtml(own, blurred, "post", hlOf("post"), blk("post"))}</div>${quotedTile}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div></div>`, ); + // THE SCENE (post-conversation.mjs): the posts the run left on screen, drawn as they were -- never read (no + // blocks, no word spans), their words redacted by the same terms, their authors blurred by their own item's rule. + for (const t of tiles) { + if (t.mode !== "scene" || !isObj(t.ref)) continue; + const ref = redactSceneRef(t.ref, redaction); + const r = ref.redact === true; + const text = str(ref.text); + const tsize = sizeFor(text || " ", innerW - av - Math.round(16 * k), innerH - 90 * k); + tileHtml.push( + `<div class="tslot" data-thread-slot="${esc(t.scope)}" data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"><div class="tile tparent tscene" data-thread-tile="${esc(t.scope)}" data-thread-mode="scene" data-post-scene="${esc(t.scope.slice(6))}"${r ? ' data-redacted=""' : ""}>${avatarHtml(ref, { redact: r, size: av, img: pic(ref) })}<div class="pbody"><div class="phead">${nameHtml(ref, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(ref.date).split(" · ")[0])}</span>${ref.paraphrased ? '<span class="plabel" data-post-paraphrased="">paraphrased</span>' : ""}</div><div class="ptext tt" style="font-size:${tsize}px">${wordsHtml(text, r && ref.handle ? [...blurred, ref.handle] : blurred)}</div></div></div></div>`, + ); + } + const order = [...tiles.map((t) => t.scope).filter((sc) => byScope.has(sc)), ...[...byScope.keys()].filter((sc) => !tiles.some((t) => t.scope === sc))]; return { - html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${tileHtml.join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div></div>`, + html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${order.map((sc) => byScope.get(sc)).join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div></div>`, css: cutCss.length ? `\n${cutCss.join(", ")} { display: none; }` : "", }; }; diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -280,6 +280,34 @@ export function redactEntry(entry, red) { } /** + * A SCENE TILE's post (post-conversation.mjs: a post the run left on screen, + * drawn on the next item's card) AS PUBLISHED: its words marked by the terms + * of the item it came from (`ref.src`: `{ post, scope: "text"|"parent"|"quoted", + * index }`) -- the same marks that item's card drew -- its name and handle by + * the project's, its slurs masked. A copy; the ref itself with nothing to do. + * + * @param {Record<string, any>} ref + * @param {Redaction|null|undefined} red + */ +export function redactSceneRef(ref, red) { + if (!isObj(ref)) return ref; + let out = ref; + if (redactionOn(red)) { + const src = isObj(ref.src) ? ref.src : {}; + const from = { post: str(src.post) }; + const scope = ["text", "parent", "quoted"].includes(src.scope) ? src.scope : "text"; + const all = redactPattern(termsFor(from, red)); + const re = redactPattern(termsFor(from, red, scope)); + // A paraphrase is not the words a span was marked on: its terms only. + const spans = ref.paraphrased ? [] : spansFor(from, red, scope, Number.isInteger(src.index) ? src.index : 0); + const mark = (v, p, sp = []) => (typeof v === "string" ? redactText(v, p, { spans: sp }).text : v); + out = { ...ref, author: mark(ref.author, all), handle: mark(ref.handle, all), text: mark(ref.text, re, spans) }; + } + if (slursOn(red?.slurs)) out = { ...out, text: maskSlurs(str(out.text), red.slurs).text, ...(typeof out.author === "string" ? { author: maskSlurs(out.author, red.slurs).text } : {}) }; + return out; +} + +/** * A post item's words with every SLUR masked (post-slurs.mjs maskSlurs) as * the filter's `visual` draws them: its words, its author's name, the repost * line's, the posts it answers and quotes (their words, a paraphrase, their diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -441,18 +441,20 @@ export function postZoomPlan(entry, render, total = Infinity) { * (`{ <handle>: absolute file }`, post-avatars.mjs), the redaction it is * published with (`{ terms, markup }`, post-redact-files.mjs: its matches * drawn as bars, dropped from its captions), and `prev` the timeline entry - * before it (post-thread.mjs carries a parent that is it). Returns the - * segment's path. + * before it (post-thread.mjs carries a parent that is it) and `scene` the + * posts its run left on screen (post-conversation.mjs planContext). Returns + * the segment's path. */ -export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null, scene = null }) { // A channel's markup may censor an attachment for every project (post-censor.mjs); the item's own blur wins. entry = censorEntry(entry, redaction); // A word zoom on a redacted word is refused in the build's words (the corpus's terms and the markup included). const fxRed = fxRedactionErrors(entry, redaction); if (fxRed.length) throw new Error(fxRed.join("; ")); const seg = path.join(outDir, "segments", `${entry.id}.mp4`); - // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - const plan = postItemPlan(entry, render, { prev }); + // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in); `scene`: what + // its run left on screen (post-conversation.mjs) -- both in plan.follow, so in the segment's key. + const plan = postItemPlan(entry, render, { prev, scene }); const layout = postLayout(entry, box); const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src)); for (const [i, f] of files.entries()) { diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -52,6 +52,7 @@ import { cardText, contextText, parentsOf } from "./post-item.mjs"; import { draftScript, isNarrated, isOnlyUrls, joinSplitLinks, pickedTake, scriptParts, spokenUrls } from "./post-narration.mjs"; import { normWord, scriptWordsOf } from "./word-zoom.mjs"; import { followKnobs } from "./read-follow.mjs"; +import { planContext } from "./post-conversation.mjs"; /** What a context tile may be. */ export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]); @@ -237,24 +238,31 @@ export function readPieces(entry, roles = partRoles(entry)) { /** The archive id of an item's post (`<channel>/<postId>` → `<postId>`). */ const postIdOf = (e) => String(e?.post ?? "").split("/")[1] ?? ""; +/** The id of the post an item's card shows (a repost shows its original). */ +export const shownIdOf = (e) => str(e?.originalId) || postIdOf(e); /** - * THE THREAD LAYOUT, pure: `{ on, tiles: [{ scope, mode, read }], roles }` -- - * the tiles top to bottom (the parents oldest first, "post", then "quoted" - * inside it), each with its resolved mode (never "auto") and whether the read - * reads it. `on`: the card is threaded (a narrated item with a context tile - * drawn; read-follow on is the caller's to require). `prev`: the item before - * it in the cut (a parent that is that item is carried). + * THE THREAD LAYOUT, pure: `{ on, tiles: [{ scope, mode, read }], roles, + * quotedAt }` -- the tiles top to bottom (the parents oldest first, a quoted + * post read first, "post", a quoted post inside it), each with its resolved + * mode (never "auto") and whether the read reads it. `on`: the card is + * threaded (a narrated item with a context tile drawn; read-follow on is the + * caller's to require). `prev`: the item before it in the cut (a parent that + * is that item is carried). `scene` (post-conversation.mjs planContext): the + * posts the run had on screen as the item before ended -- each a tile + * `scene:<id>` (mode "scene", never read, `ref` what it draws), kept on top as + * context when it is an ancestor of this item, else collapsed away; one this + * item draws itself is its own tile. Every tile in the tree's order. * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null }} [o] + * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null }} [o] */ -export function threadLayout(entry, render = undefined, { prev = null } = {}) { +export function threadLayout(entry, render = undefined, { prev = null, scene = null } = {}) { const k = threadKnobs(entry, render); const roles = isNarrated(entry) ? partRoles(entry) : []; const read = new Set(roles.map((r) => r.role).filter(Boolean)); - const prevId = prev ? postIdOf(prev) : ""; + const prevId = prev ? shownIdOf(prev) : ""; const tiles = []; const parents = parentsOf(entry); for (let i = parents.length - 1; i >= 0; i -= 1) { @@ -282,8 +290,58 @@ export function threadLayout(entry, render = undefined, { prev = null } = {}) { if (q.above) tiles.push(q, post); else tiles.push(post, q); } else tiles.push(post); - const on = isNarrated(entry) && tiles.some((t) => t.scope !== "post" && t.mode !== "hidden"); - return { on, tiles, roles, quotedAt: tiles.some((t) => t.above) ? "above" : "inside" }; + const quotedAtOut = tiles.some((t) => t.above) ? "above" : "inside"; + // THE SCENE (post-conversation.mjs): what the run had on screen, in the tree's order with this item's own tiles. + const scened = isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles; + const on = isNarrated(entry) && scened.some((t) => t.scope !== "post" && t.mode !== "hidden"); + return { on, tiles: scened, roles, quotedAt: quotedAtOut }; +} + +/** The id a tile of `entry` draws (a parent's, his post's; null: a quoted post, a scene tile's own). */ +function tileIdOf(entry, t) { + if (t.scope === "post") return shownIdOf(entry) || null; + const m = /^parent:(\d)$/.exec(t.scope); + return m ? str(parentsOf(entry)[Number(m[1])]?.id) || null : null; +} + +/** + * The layout's tiles with the SCENE's (planContext's `scene.tiles`: `{ id, + * ref, from: "full"|"small", action: "keep"|"collapse" }`) merged in, in the + * tree's order (`scene.rank`, id → place): a scene post this item draws + * itself is left to its own tile. + */ +function sceneTiles(entry, tiles, scene, k) { + const list = Array.isArray(scene?.tiles) ? scene.tiles : []; + if (!list.length) return tiles; + const own = new Set(tiles.filter((t) => t.mode !== "hidden").map((t) => tileIdOf(entry, t)).filter(Boolean)); + const extra = list + .filter((t) => isObj(t) && str(t.id) && isObj(t.ref) && !own.has(str(t.id))) + .map((t) => ({ + scope: `scene:${t.id}`, + mode: "scene", + read: false, + action: t.action === "keep" ? "keep" : "collapse", + from: t.from === "full" ? [1, 1] : [k.shrink, k.dim], + ...(t.from === "full" ? { wasPost: true } : {}), + ref: t.ref, + })); + if (!extra.length) return tiles; + const rank = isObj(scene.rank) ? scene.rank : {}; + const rankOf = (id) => (id && fin(rank[id]) ? rank[id] : null); + // His own tiles keep their order; one with no place in the tree sits just after the one before it. + const mine = tiles.map((t) => ({ t, r: rankOf(tileIdOf(entry, t)) })); + let last = null; + mine.forEach((x, i) => { + if (x.r === null) { + const next = mine.slice(i + 1).find((y) => y.r !== null); + x.r = last !== null ? last + 0.001 : next ? next.r - 0.5 + i * 0.001 : -1 + i * 0.001; + } + // A quoted post rides with his post (above it or inside it). + if (x.t.scope === "quoted") x.r = (mine.find((y) => y.t.scope === "post")?.r ?? x.r) + (x.t.above ? -0.0005 : 0.0005); + last = x.r; + }); + const theirs = extra.map((t, i) => ({ t, r: rankOf(t.scope.slice(6)) ?? 1e9 + i })); + return [...mine, ...theirs].map((x, i) => ({ ...x, i })).sort((a, b) => a.r - b.r || a.i - b.i).map((x) => x.t); } /** A tile's mode in a layout (null: no such tile). */ @@ -302,12 +360,12 @@ const ROLE_NAME = (r) => (r === "post" ? "his words" : r === "quoted" ? "the pos * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null, followOn?: boolean }} [o] + * @param {{ prev?: Record<string, any> | null, scene?: Record<string, any> | null, followOn?: boolean }} [o] */ -export function threadReadErrors(entry, render = undefined, { prev = null, followOn = true } = {}) { +export function threadReadErrors(entry, render = undefined, { prev = null, scene = null, followOn = true } = {}) { if (!isNarrated(entry)) return []; const w = `timeline ${entry?.id ?? "?"}`; - const L = threadLayout(entry, render, { prev }); + const L = threadLayout(entry, render, { prev, scene }); const errors = []; const fix = `umtool posts set-item <p> ${entry?.id ?? "<item>"}`; const remake = `or re-make the read without it (umtool posts narrate <p> ${entry?.id ?? "<item>"} --take, a script that leaves it out)`; @@ -377,8 +435,9 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { return { t0, t1: r3(t0 + k.seconds) }; }; const small = [k.shrink, k.dim]; - // A carried parent opens the item alone: what the read reads first comes in under it as it gives way. - const carried = layout.tiles.some((t) => t.mode === "carry"); + // A carried parent (or a scene the run left on screen) opens the item: what the read reads first comes in + // under it as it gives way. + const carried = layout.tiles.some((t) => t.mode === "carry" || t.mode === "scene"); const revealed = (scope, T0) => !!k.reveal && !!first && T0 !== null && (first.start < T0 - 1e-6 ? first.role !== scope : carried) && !first.role.startsWith("media:"); const tiles = []; for (const t of layout.tiles) { @@ -391,6 +450,15 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { row.from = [1, 0]; Object.assign(row, win(T)); } + } else if (t.mode === "scene") { + // A post the run left on screen (post-conversation.mjs): it opens as the item before ended, and as the + // read begins an ancestor of this item stays on top as context, any other post collapses away. + row.from = t.from; + row.to = t.action === "keep" ? small : [0, 0]; + if (row.to[0] !== row.from[0] || row.to[1] !== row.from[1]) Object.assign(row, win(first ? first.start : lead)); + row.action = t.action; + row.ref = t.ref; + if (t.wasPost) row.wasPost = true; } else if (t.mode === "context") { row.from = t.scope === "quoted" ? [1, k.dim] : small; row.to = row.from; @@ -480,6 +548,8 @@ export function threadGeoAt(geo, scales) { if (t.s >= 0.9995) continue; if (y >= t.top + t.height - 0.5) d += (1 - t.s) * t.height; else if (y > t.top) d += (1 - t.s) * (y - t.top); + // A scene tile collapsing away (post-conversation.mjs) closes the gap above it too. + if (t.gap > 0 && t.scope.startsWith("scene:") && y >= t.top - 0.5) d += (1 - t.s) * t.gap; } return y - d; }; @@ -563,7 +633,8 @@ export function validateThreadReads(manifest) { const errors = []; tl.forEach((e, i) => { if (e?.type !== "post") return; - errors.push(...threadReadErrors(e, manifest?.render, { prev: tl[i - 1] ?? null, followOn: followKnobs(e, manifest?.render).on })); + // Each with the item before it and the scene its run leaves on screen (post-conversation.mjs). + errors.push(...threadReadErrors(e, manifest?.render, { ...planContext(tl, i, manifest?.render), followOn: followKnobs(e, manifest?.render).on })); }); return errors; } diff --git a/umtool/report-to-video/post-thread.test.mjs b/umtool/report-to-video/post-thread.test.mjs @@ -188,6 +188,9 @@ test("THE INVARIANT: every part's time span lies inside its block's on-screen, h const g = threadGeoAt(geo, Object.fromEntries(Object.entries(st.tiles).map(([x, v]) => [x, v[0]]))); const bb = g.blocks[blk.k]; assert.ok(bb.top - st.offset >= -1 && bb.bottom - st.offset <= geo.H + 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its block in the window (${(bb.top - st.offset).toFixed(0)}–${(bb.bottom - st.offset).toFixed(0)} of ${geo.H})`); + // Its tile WHOLE in the window while it is read, when it fits (a tile is read in full, not clipped at the foot). + const tt = g.tiles[blk.scope]; + if (tt && tt.bottom - tt.top <= geo.H - Math.round(geo.H * 0.1)) assert.ok(tt.top - st.offset >= -1 && tt.bottom - st.offset <= geo.H + 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile whole in the window (${(tt.top - st.offset).toFixed(0)}–${(tt.bottom - st.offset).toFixed(0)} of ${geo.H})`); } }); // A transition draws a different card every frame; a still read, one. diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -313,9 +313,9 @@ const wordsIn = (t) => scriptWordsOf(t).length; * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null }} [o] + * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, scene?: Record<string, any> | null }} [o] */ -export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null } = {}) { +export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, scene = null } = {}) { const k = followKnobs(entry, render); if (!k.on) return null; const map = followBlocks(entry); @@ -363,7 +363,8 @@ export function followSchedule(entry, render = undefined, { hold = null, narrati for (const b of blocks) if (b.start === null) b.end = null; // THREADED (post-thread.mjs): a narrated read of the post it answers or quotes -- the card a column of tiles, // each shown in full while it is read, then shrunk and dimmed as the next piece comes in. - const layout = isNarrated(entry) ? threadLayout(entry, render, { prev }) : null; + // `scene` (post-conversation.mjs planContext): the posts its run left on screen, kept on top or collapsed away. + const layout = isNarrated(entry) ? threadLayout(entry, render, { prev, scene }) : null; const thread = layout?.on ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : null; return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}) }; } @@ -456,14 +457,17 @@ export function threadPath(follow, geo) { return Math.round(clamp(want, 0, max) * 100) / 100; }; const read = (follow.blocks ?? []).filter((b) => b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start || a.k - b.k); - // The opening frame: a carried post framed as the item before left it; else the first block's place. - const carry = (th.tiles ?? []).find((t) => t.mode === "carry"); + // The opening frame: a carried post (or the scene's post the item before ended on) framed as the item before + // left it; else the first block's place. + const carry = (th.tiles ?? []).find((t) => t.mode === "carry") ?? (th.tiles ?? []).find((t) => t.mode === "scene" && t.wasPost); const g0 = at(0); let off; if (carry && g0.tiles[carry.scope]) off = placed(g0, g0.tiles[carry.scope].top - m); else if (read.length) { const g = at(read[0].start - lead + span); - off = placed(g, g.blocks[read[0].k].top - m); + // The first post read, whole when it fits the window; else its first block a margin from the top. + const tile = g.tiles[tileScopeOf(read[0].scope)]; + off = placed(g, tile && tile.bottom - tile.top <= H - m ? tile.top - Math.min(m / 2, tile.top) : g.blocks[read[0].k].top - m); } else off = placed(g0, 0); const start = off; const segments = []; @@ -490,6 +494,9 @@ export function threadPath(follow, geo) { const tile = g.tiles[tileScopeOf(b.scope)]; const top = tile ? tile.top : bb.top; let want = top - Math.min(H * (th.contextRoom ?? 0.3), top); + // THE POST BEING READ IN FULL (operator, 4 Nov, p-2117359906164814087: "it must be in full while read"): a + // tile that fits the window is shown whole while it is read -- the strip of what it answers above giving way. + if (tile && tile.bottom - tile.top <= H - m && tile.bottom > want + H - m / 2) want = Math.min(top, tile.bottom - H + m / 2); // Its first block whole in view, as much of what it answers kept above as that leaves. if (bb.bottom > want + H - m) want = Math.min(bb.top - m, bb.bottom - H + m); moveTo(placed(g, want), b.start - lead, th.pan); @@ -564,7 +571,10 @@ export function followStateAt(follow, path, s) { let C = fin(path?.C) ? path.C : 0; for (const [scope, [sc, o]] of Object.entries(ts)) { const h = path?.tiles?.[scope]?.height ?? 0; - tiles[scope] = [sc, o, Math.round(h * 100) / 100]; + // A scene tile (post-conversation.mjs) collapsing away takes the gap above it with it. + const gap = scope.startsWith("scene:") ? path?.tiles?.[scope]?.gap ?? 0 : 0; + tiles[scope] = gap > 0 ? [sc, o, Math.round(h * 100) / 100, Math.round(gap * 100) / 100] : [sc, o, Math.round(h * 100) / 100]; + if (sc < 0.9995 && gap > 0) C -= (1 - sc) * gap; // A tile closes the flow up under it as it shrinks -- a quoted post inside his post never shrinks; one above it does. if (sc < 0.9995 && (scope !== "quoted" || follow.thread.quotedAt === "above")) C -= (1 - sc) * h; } @@ -610,8 +620,9 @@ export function measureFollow(doc = document) { const slots = Array.from(flow.querySelectorAll("[data-thread-slot]")); const kept = slots.map((el) => { const tile = el.querySelector("[data-thread-tile]"); - const k = { el, tile, h: el.style.height, t: tile ? tile.style.transform : "", o: tile ? tile.style.opacity : "" }; + const k = { el, tile, h: el.style.height, mt: el.style.marginTop, t: tile ? tile.style.transform : "", o: tile ? tile.style.opacity : "" }; el.style.height = ""; + el.style.marginTop = ""; if (tile) { tile.style.transform = ""; tile.style.opacity = ""; @@ -635,12 +646,14 @@ export function measureFollow(doc = document) { const tiles = {}; for (const el of slots) { const r = el.getBoundingClientRect(); - tiles[el.getAttribute("data-thread-slot")] = { top: Math.round((r.top - fr.top) * 100) / 100, height: Math.round(r.height * 100) / 100 }; + const gap = parseFloat(getComputedStyle(el).marginTop) || 0; + tiles[el.getAttribute("data-thread-slot")] = { top: Math.round((r.top - fr.top) * 100) / 100, height: Math.round(r.height * 100) / 100, ...(gap > 0 ? { gap: Math.round(gap * 100) / 100 } : {}) }; } out.tiles = tiles; } for (const k of kept) { k.el.style.height = k.h; + k.el.style.marginTop = k.mt; if (k.tile) { k.tile.style.transform = k.t; k.tile.style.opacity = k.o; @@ -667,6 +680,9 @@ export function applyFollowState(state, doc = document) { const o = v && typeof v[1] === "number" ? v[1] : 1; const h = sc < 0.9995 && v && v[2] > 0 ? `${Math.round(v[2] * sc * 100) / 100}px` : ""; if (el.style.height !== h) el.style.height = h; + // A scene tile collapsing away (post-conversation.mjs): the gap above it closes with it. + const mt = sc < 0.9995 && v && v[3] > 0 ? `${Math.round(v[3] * sc * 100) / 100}px` : ""; + if (el.style.marginTop !== mt) el.style.marginTop = mt; if (tile) { const tf = sc < 0.9995 ? `scale(${sc})` : ""; if (tile.style.transform !== tf) tile.style.transform = tf;