Archilyzer · Source

archilyzer

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

commit fb2f4abb4862233dfa493758d2525f8a0b84d2ce
parent 6e061e546639a75cd310b18921377e301d66eeea
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed,  4 Nov 2026 04:48:47 -0500

Merge lane/thread-tree: a thread is one scene, read in tree order, and nothing hidden or linked is ever said -- the root stays on top, a child's reply carries in, a sibling branch collapses as the next comes in (planContext, conv:<id> scene tiles; operator: "definitely would benefit from a full read thread progression", "this and the next are in wrong order?"); a quote read before his words opens in full as its own tile above his post, then shrinks and dims (operator: "you're reading hidden text before the main post again"); a tile read is shown whole; no URL is spoken (X's split links re-joined, then dropped; lint + posts roles; operator: "Don't read out a URL"); posts reread --without parent:0|quoted / --drop-urls re-joins a take's parts with no TTS, and set-item thread.parent.<i>=context runs it (operator: "This one can have the parent not read out"); timeline threads [--write] gathers each conversation in tree order within its section; posts context resolves a status link to its quote; a conversation scene wins the card over a media scene

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 21++++++++++++++-------
Mumtool/app/api/report/post-narration/route.ts | 16+++++++++++++++-
Mumtool/components/projects/PostBench.tsx | 8+++++---
Mumtool/components/projects/PostBenchPage.tsx | 8++++++--
Mumtool/components/projects/PostThreadPanel.tsx | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/docs/cli.md | 4+++-
Mumtool/docs/knobs.md | 13+++++++++++--
Mumtool/docs/report-video.md | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/e2e/thread-walk.spec.ts | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 13+++++++++----
Mumtool/lib/report/playView.mjs | 16++++++++++------
Mumtool/lib/report/postContext.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/postContext.test.mjs | 26+++++++++++++++++++++++++-
Aumtool/lib/report/postReread.mjs | 218+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postReread.test.mjs | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postThread.test.mjs | 33++++++++++++++++++++++++++++++++-
Mumtool/lib/report/postThreadCli.mjs | 26++++++++++++++++----------
Mumtool/lib/report/postsCli.mjs | 49++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/lib/report/timelineCli.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/report-to-video/build-video.mjs | 9++++++---
Mumtool/report-to-video/lint.mjs | 4+++-
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/post-conversation.mjs | 453+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-conversation.test.mjs | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-item.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/report-to-video/post-narration.mjs | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/post-narration.test.mjs | 17+++++++++++++++++
Mumtool/report-to-video/post-redact.mjs | 28++++++++++++++++++++++++++++
Mumtool/report-to-video/post-render.mjs | 16+++++++++-------
Mumtool/report-to-video/post-thread.mjs | 202++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/post-thread.test.mjs | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/read-follow.mjs | 46++++++++++++++++++++++++++++++++++------------
32 files changed, 2152 insertions(+), 127 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 { isNarrated, 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 { mediaSceneById, sceneEntry, sceneLayout } from "umtool-report-to-video/post-media-scene"; import { projectCombos } from "umtool-report-to-video/post-combo-prints"; import { channelsDirFor } from "@/lib/projects/report.mjs"; @@ -54,8 +55,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). */ @@ -187,9 +190,12 @@ export async function GET(request: Request) { const groups = besidePost ? ((await projectCombos(r.project.dir, found.manifest, { channelsDir: channelsDirFor(r.project.dir, found.manifest) }).catch(() => ({ groups: [] }))).groups as unknown[]) : []; - const scene = groups.length ? mediaSceneById(tl, found.item.id, groups as never, cutRender) : null; - const item = sceneEntry(found.item, scene) as Entry; - const tlayout = threadLayout(item, cutRender, { prev: found.prev }); + const media = groups.length ? mediaSceneById(tl, found.item.id, groups as never, cutRender) : null; + const item = sceneEntry(found.item, media) as Entry; + // THE THREAD SCENE WINS (post-media-scene.mjs's header): with the conversation's scene (post-conversation.mjs) the + // media scene keeps only the attachment (sceneEntry above), never the card. + const scene = found.ctx.scene ? null : media; + const tlayout = threadLayout(item, cutRender, found.ctx); const html = postCardHtml(item, { width: w, height: h, avatars, palette: (render.palette ?? {}) as Record<string, string>, @@ -198,8 +204,9 @@ export async function GET(request: Request) { parentShotUrl: parentShot, // 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 -- a media scene's - // earlier messages above them (a narrated item's thread read is its base; un-narrated, none). + // A threaded card (post-thread.mjs): its tiles, as the plan's follow.thread has them -- the conversation's scene + // (post-conversation.mjs) or, with none, a media scene's earlier messages above them (a narrated item's thread + // read is its base; un-narrated, none). thread: followOn ? (scene ? sceneLayout(isNarrated(item) ? tlayout : null, item, scene) ?? tlayout : tlayout) : null, redaction, }); diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -11,6 +11,7 @@ import { resolveReport } from "@/lib/report/serve.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { refuseCaller } from "@/lib/report/caller"; import { deleteTake, measureTake } from "@/lib/report/postNarrationCli.mjs"; +import { rereadTake } from "@/lib/report/postReread.mjs"; import { keepRecording, RECORD_LABEL_RE } from "@/lib/report/postRecord.mjs"; import { fitPostItem } from "@/lib/report/postFit.mjs"; import { projectRedaction } from "@/lib/report/postRedaction.mjs"; @@ -40,6 +41,8 @@ const benchVoice = (red: { slurs?: { voice?: string } | null } | null) => (red?. // (a job; kept by GET ?job&derive=<from>); `installed: false` // when the editor has no engine for it // POST {project, op: "delete", id, take} a take out of the list, its file to .trash/ (soft) +// POST {project, op: "reread", id, without?, dropParts?, dropUrls?} the picked take RE-JOINED without a piece +// (postReread.mjs: no TTS; a new take, picked, one undo point) // POST {project, op: "undo"} the last structural write undone const noStore = { "cache-control": "no-store" }; @@ -216,6 +219,17 @@ export async function POST(request: Request) { return Response.json({ error: msg }, { status }); } } + if (body.op === "reread") { + // The bench's "Read without it" (postReread.mjs): the picked take's kept parts cut and joined again, no TTS. + const list = (v: unknown) => (Array.isArray(v) ? v.map(String) : typeof v === "string" && v ? v.split(",") : []); + try { + const rr = await rereadTake(r.project, e, { without: list(body.without), dropParts: list(body.dropParts).map(Number), dropUrls: body.dropUrls === true }); + return Response.json({ ok: true, take: rr.take, entry: rr.result?.entry ?? null, token: rr.result?.token ?? null }, { headers: noStore }); + } catch (err) { + if ((err as Error)?.name === "RereadError") return Response.json({ error: (err as Error).message }, { status: 400 }); + throw err; + } + } if (body.op === "delete") { const { result } = { result: await deleteTake(r.project, e, Number(body.take)) }; return Response.json({ ok: true, entry: result.entry, token: result.token }, { headers: noStore }); @@ -229,7 +243,7 @@ export async function POST(request: Request) { const now = postsOf(after).find((x) => x.id === id); return Response.json({ ok: true, window: f.window, entry: now ?? null, token: result.token }, { headers: noStore }); } - return Response.json({ error: "op is set, take, derive, delete, fit or undo" }, { status: 400 }); + return Response.json({ error: "op is set, take, derive, reread, delete, fit or undo" }, { status: 400 }); } catch (err) { return fail(err); } diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -79,7 +79,7 @@ const CROPS: Array<{ label: string; crop: number[] | null }> = [ type Scene = { key: string; n: number; of: number; ids: string[]; media: number | null; anchor: { id: string; media: number; entry: { id: string; post: string; media: Array<Record<string, unknown>> } }; before: Array<Record<string, unknown>> } | null; export default function PostBench({ - project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene: savedScene = null, + project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene: savedScene = null, conversation = null, }: { project: string; entry: Entry; @@ -98,6 +98,8 @@ export default function PostBench({ before?: Record<string, unknown> | null; /** Its media scene (post-media-scene.mjs): the neighbours with the same attachment, as saved. */ scene?: Scene; + /** The posts its conversation's run leaves on screen (post-conversation.mjs planContext): kept on top or collapsed away. It wins the card over a media scene. */ + conversation?: Record<string, unknown> | null; }) { const router = useRouter(); const [entry, setEntry] = useState<Entry>(initial); @@ -118,7 +120,7 @@ export default function PostBench({ [entry, savedScene], ); const shown = useMemo(() => sceneEntry(entry, scene) as Entry, [entry, scene]); - const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, mediaScene: scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene]); + const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(shown, render, { prev: before, scene: conversation, mediaScene: conversation ? null : scene }) as PostPlan)), [entry, shown, initial, initialPlan, render, before, scene, conversation]); const total = plan.total; const [s, setS] = useState(0); const [playing, setPlaying] = useState(false); @@ -354,7 +356,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 project={project} entry={entry} plan={plan} render={render} before={before} scene={conversation} 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 { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; import type { ProjectRef } from "@/lib/project-types"; @@ -32,6 +33,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 counted = await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {}, groups: [] })); @@ -53,10 +56,11 @@ 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(sceneEntry(entry, scene), render, { prev: at > 0 ? tl[at - 1] : null, mediaScene: scene }) as unknown as PostPlan} + plan={postItemPlan(sceneEntry(entry, scene), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan} scene={scene} render={render} - before={at > 0 ? tl[at - 1] : null} + before={ctx.prev} + conversation={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 @@ -1,6 +1,6 @@ "use client"; -import { useMemo } from "react"; +import { useMemo, useState } from "react"; import { THREAD_DEFAULTS, THREAD_LIMITS, THREAD_MODES, partRoles, readPieces, threadKnobs, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; import { pickedTake } from "umtool-report-to-video/post-narration"; @@ -26,22 +26,46 @@ 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, + project = null, entry, plan, render, before, scene = null, setS, setEntry, }: { + /** The project (its "Read without it" re-joins the take through the post-narration route). */ + project?: string | null; entry: Entry; plan: PostPlan; render: Record<string, unknown>; 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; + // READ WITHOUT IT (lib/report/postReread.mjs): the picked take re-joined without a context piece it reads -- its + // kept parts cut from its own file, no TTS -- a new take picked (one undo point); the page reloads on it. + const [rereading, setRereading] = useState<string | null>(null); + const [rereadError, setRereadError] = useState<string | null>(null); + const reread = async (role: string) => { + if (!project) return; + setRereading(role); + setRereadError(null); + try { + const res = await fetch("/api/report/post-narration", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "reread", id: entry.id, without: [role] }) }); + const j = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; + if (!res.ok || !j.ok) throw new Error(j.error ?? `HTTP ${res.status}`); + window.location.reload(); + } catch (err) { + setRereadError(err instanceof Error ? err.message : String(err)); + setRereading(null); + } + }; const startOf = (part: number) => plan.follow?.blocks.find((b) => b.part === part)?.start ?? null; const setOwn = (patch: Thread) => setEntry((e) => { @@ -79,7 +103,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,14 +112,25 @@ 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(5)} 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) => { const at = startOf(p.parts[0]); const words = p.parts.map((n) => take?.parts?.[n]?.text ?? "").join(" ").trim(); return ( - <li key={i} data-post-thread-piece={p.role ?? "none"} data-source={roles[p.parts[0]]?.source}> - <button type="button" disabled={at === null} className="flex w-full gap-2 px-1 text-left disabled:opacity-60" onClick={() => at !== null && setS(at)} title={`parts ${p.parts.map((n) => n + 1).join(", ")}`}> + <li key={i} className="flex items-center gap-1" data-post-thread-piece={p.role ?? "none"} data-source={roles[p.parts[0]]?.source}> + <button type="button" disabled={at === null} className="flex min-w-0 flex-1 gap-2 px-1 text-left disabled:opacity-60" onClick={() => at !== null && setS(at)} title={`parts ${p.parts.map((n) => n + 1).join(", ")}`}> <span className="w-12 shrink-0 font-mono tabular-nums">{at === null ? "—" : `${at.toFixed(1)}s`}</span> <span className="w-32 shrink-0 text-text-2"> {ROLE_NAME(p.role)} @@ -103,6 +138,18 @@ export default function PostThreadPanel({ </span> <span className="min-w-0 truncate">{words.split(/\s+/).slice(0, 10).join(" ")}…</span> </button> + {project && p.role && (p.role === "quoted" || p.role.startsWith("parent:")) && ( + <button + type="button" + className="ink-link shrink-0 px-1 disabled:opacity-60" + disabled={rereading !== null} + onClick={() => void reread(p.role as string)} + data-post-thread-reread={p.role} + title="re-join the take without this piece (its own audio, no TTS): a new take, picked" + > + {rereading === p.role ? "re-joining…" : "Read without it"} + </button> + )} </li> ); })} @@ -157,6 +204,11 @@ export default function PostThreadPanel({ <p className="m-0 mt-1 text-text-2"> full: in full while read · excerpt: only what is read · context: small and dim · carry: the item before, giving way · hidden: not drawn (never read). Hidden and excerpt redraw the card once saved. </p> + {rereadError && ( + <p className="m-0 mt-1 text-[var(--color-bad,#e5484d)]" data-post-thread-reread-error=""> + {rereadError} + </p> + )} {errors.length > 0 && ( <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-thread-errors=""> {errors.map((er, i) => ( diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -84,6 +84,8 @@ Inbox cannot disagree about what is wrong with one. | `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) | | `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` | | `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [media.<i>.blur=on\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label="…"\|off] [media.<i>.blur.boxes=x,y,w,h;…\|off] [quoted.paraphrase="…"\|off] [parent.<i>.paraphrase="…"\|off] [follow=on\|off\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\|full\|excerpt\|context\|carry\|hidden] [thread.quoted=…] [thread.carry=auto\|on\|off] [thread.reveal=on\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a "paraphrased" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled "Censored"; the file untouched; merged key by key, `blur=off` keeps the settings) | +| `posts reread <project> <item> [--without parent:0\|parent:1\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]` | a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: "rejoin", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before) | +| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `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 `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item) at its first item's place in TREE order — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) | | `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) | | `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs=]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: @handles, links, emoji dropped; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) | | `posts fx <project> <item> [ls]` · `add word-zoom --match "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\|inOut\|snap] [--highlight #rrggbb\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]` | a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`) | @@ -91,7 +93,7 @@ Inbox cannot disagree about what is wrong with one. | `posts avatar <project> [<handle> <image-file> \| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]` | the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one | | `posts redact <project> ls \| add "<term>" [--substring] [--note "…"] \| remove <n> [--json]` | **REDACTED WORDS** ([knobs.md](knobs.md#redacted-words-blanked-from-what-is-published)): the project's list (`render.posts.redact`, `updatePostRedact`) of words or phrases blanked from everything the cut publishes -- a solid bar on the rendered card, left out of a synthesized read, a post's chapter line and an attachment's captions; matched without case, as whole words (`--substring`: inside words too), a phrase across any spaces or punctuation. The posts' words and the scripts are never rewritten. `ls` numbers the terms as `remove` takes them, and counts the corpus's (`transcripts/redactions.json`) and the posts marked up in the cut's channels (`posts-markup.json`). A term already listed is refused (**exit 1**) | | `posts slurs <project> [ls] \| on \| off \| level strong\|all \| visual blackout\|placeholder \| voice skip\|beep\|placeholder \| add <word> \| except <word> \| remove <word> [--json]` | **THE SLUR FILTER** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): `render.posts.slurs` (`updatePostSlurs`, one undo point each), on by default -- the slurs of the shipped list (`report-to-video/slurs.json`; `level strong`: only the strong ones) and the project's own (`add`; `except` never masks one) masked in everything the cut publishes: a dark pill with its mask (`visual placeholder`, the default, "f*****") or a bar (`blackout`) on the card; said and beeped by the take's word timings (`voice beep`, the default), left out of a synthesized read (`skip`), or its stand-in said (`placeholder`). `ls` counts what the cut masks per slur and per post -- masks only, never the word -- and names each narrated post whose take says one with no word timings (a censored build refuses it; `posts narrate <p> <item> --words`). `off` is the uncensored cut (the redaction stays). A word already on a list, or on neither for `remove`, is refused (**exit 1**); an unknown verb or value (**exit 2**) | -| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | +| `posts context <project> [--dry-run] [--json]` | every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `"contextOnly": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). An x.com/twitter.com **status link** in its words (or its row's links) is a quote: the post it names, from any channel's archive, fills `quoted` (`via: "link"`) when it has none; the row's `threadId` is snapshotted as the item's `conversation` (the thread walk reads it). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)) | | `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only | | `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words | | `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -801,7 +801,13 @@ A narrated post item that reads the post it answers or quotes draws the conversa (`updatePostNarrationRender`), one post's on the item (`updatePostItem`), each refused in the build's words (`threadKnobErrors`); a `thread`/`follow` change that would narrate a post the card hides is refused with the fix. Its bench is the post bench's **thread read** block; Play the cut -draws the same states the build shoots. +draws the same states the build shoots. A quoted post read before his words is its own tile above +his post; a tile that fits the window is shown whole while it is read. One conversation played +back to back is ONE SCENE (`report-to-video/post-conversation.mjs` planContext): the posts the +item before left on screen open this item's card, an ancestor kept on top as context, the branch +before collapsing away as this item's first piece comes in — automatic, no knob (a run is +consecutive narrated, read-following post items of one tree; `timeline <p> threads` lists and +gathers them). | Knob | In umtool | From a terminal | Route | |---|---|---|---| @@ -809,7 +815,10 @@ draws the same states the build shoots. | `render.postNarration.thread.carry` — carry a parent that is the item before: `auto` (default), `true`, `false` · `.reveal` — the post read next fades in under the one before (default true) | — | `umtool posts narrate <p> --cut thread.carry=off thread.reveal=off` | — | | `render.postNarration.thread.shrink` — a context post's size, 0.3–1 (default 0.62) · `.dim` — its opacity, 0.15–1 (default 0.5) · `.seconds` — the change, 0–3 s (default 0.7) · `.pan` — the column's move, 0.1–3 s (default 0.7) | — | `umtool posts narrate <p> --cut thread.shrink=0.55 thread.dim=0.4 thread.seconds=0.9 thread.pan=1` | — | | `thread` on a post item — `{parent?, quoted?, carry?, reveal?, shrink?, dim?, seconds?, pan?}` over the cut's (`parent` one mode, or a list, nearest parent first) | post bench, **thread read**: the post it answers / its parent / the quoted post (the cut's, or a mode), **carry**, **shrink**, **dim**, **over**, **pan**; the guard's refusals listed before Save | `umtool posts set-item <p> <item> thread.parent=excerpt` · `thread.parent.1=hidden` · `thread.quoted=context` · `thread.carry=off` · `thread.shrink=0.5` … · `thread=auto` (the cut's) | `POST /api/report/post-item {project, op: "set", id, patch: {thread}, token}` (an object merges; `null` clears) | -| a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) | +| a part's role — the text it reads: `parent:<i>`, `quoted`, `post`, `media:<i>` (stored, else inferred) | post bench, **thread read**: the read piece by piece (click one: the playhead at its start; `·` marks an inferred role) | `umtool posts roles <p> [<item> …]` (list, with the guard's verdict and the warnings: a link said aloud, a text cut short) · `--write` (store the inferred roles) · `<item> --set 3=parent:0,4=post` (`off`: inferred again) | — (`updatePostNarration {partRoles: {take, roles}}`) | +| a read RE-JOINED without a piece (no TTS) — the picked take's kept parts cut from its own file and joined with the read's pauses: a derived take (`steps: [{op: "rejoin", drop}]`), picked | post bench, **thread read**: **Read without it** on a context piece the take reads | `umtool posts reread <p> <item> --without parent:0` (`parent:1`, `quoted`) · `--drop-parts 3,4` · `--drop-urls` · `--dry-run`; `umtool posts set-item <p> <item> thread.parent.0=context` re-joins first when the take reads it (the knob alone when it does not; `--no-reread`: refused) | `POST /api/report/post-narration {project, op: "reread", id, without: ["parent:0"], dropParts?, dropUrls?}` | +| the cut's conversations — one run is one scene; `threads --write` gathers each in tree order (a post after what it answers, sibling branches by date, never across a section) | — | `umtool timeline <p> threads [--json]` · `threads --write [--conversation <id>]` (one undo point) | — (`orderEntries`) | +| a post item's `conversation` (the archive row's threadId) and `quoted.via: "link"` (a status link resolved to an archived post) | — | `umtool posts context <p> [--dry-run]` | — (`setPostItemsContext`) | ## The combo counter diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -789,7 +789,8 @@ picture, else no text's. Checked over the three Mr. Obvious cuts (395 reads): ev pieces in the batch's order, his words last. **The card.** Narrated, following (read-follow on), with a context post drawn, the card is a -column of TILES in one flow — the parents oldest first, his post, the quoted post inside it — +column of TILES in one flow — the parents oldest first, his post, the quoted post inside it (or +above it: see below) — each tile's words at the size that fits it alone in the card (at least 28 px of a 1080 frame), whole: no line clamp. read-follow's blocks span every tile (the parts matched to their roles' texts), and its pan moves the whole column. What each context post is on screen is its MODE: @@ -811,7 +812,68 @@ read. The column pans (`pan` s, eased, from the same moment) so a new piece sits (30 % of the window) of the post it answers, its first block whole in view; a later block running past the window's foot is brought up just far enough; a block taller than the window pans on through it. A conversation shorter than the window is centred in it. A part read off -an attachment lights no block (all dim: the picture is the thing being read). +an attachment lights no block (all dim: the picture is the thing being read). A tile that fits +the window is shown WHOLE while it is read — the strip of what it answers gives way rather than +its last lines running past the foot (operator, 4 Nov, p-2117359906164814087: "it must be in +full while read"); the first post read opens whole when it fits. + +**Quotes, read in place.** Read BEFORE his words, the quoted post is its own tile ABOVE his post +(`threadLayout(...).quotedAt === "above"`, labelled "quoted", at the size that fits it alone): +in full and lit while read, then shrunk and dimmed like a parent as his words are revealed under +it — the card no longer opens scrolled down to a quote drawn under his words (p-2116364553542070563, +p-2116651428425150687). Read after his words (or not at all) it stays inside his post. +Nothing read is clamped: the plain card's 4–5 line clamp on a context post, the strip's +one-line ellipsis and a long link's "…" only ever touch words no part reads. + +**Links are never spoken.** X draws a long link over lines ("https://" / "web.archive.org/web/2021…" +/ "1733/https://twitter.com/…" / "…"); `speakableText` puts a split link back together and drops +it whole (`joinSplitLinks`, `dropUrls`: a scheme, `www.`, a bare `host.tld/path`, `t.co`), so a +drafted script never says one. A take made before that may: the lint WARNS of every picked +take that says a link (`spokenUrls`; `posts roles` lists it per item) with the fix — `umtool posts +reread <p> <item> --drop-urls` when the links are whole parts, else a re-take. It also warns of a +text the read reads that the archive kept cut short (X's "…" or "Show more", not a link's). + +**A status link is a quote.** `umtool posts context <p>` resolves an x.com/twitter.com status +link in an item's words (or its archive row's links) to a post any channel's posts archive holds +(read lazily, only for a link) and fills `quoted` (`via: "link"`) when it has none; the same +pass snapshots the row's `threadId` as the item's `conversation`. + +**The thread walk: one conversation, one scene** (`report-to-video/post-conversation.mjs`; +operator, 4 Nov: p-2116779173746491646's tree, "weird thread progression", "wrong order"; +p-2117379128664236113, "a full read thread progression"). An item's CHAIN is the posts it answers +(oldest first) and its own post (plus its `conversation`); a RUN is consecutive narrated, +read-following post items whose chains share a post. `planContext(timeline, i, render)` → +`{ prev, scene }`: the SCENE is what the run had on screen as the item before ended — its drawn +ancestors and its post, and what its own scene kept — drawn first on this item's card as tiles +`conv:<id>`, in the tree's depth-first order (a branch in the order the run first showed it: the +root, the branch collapsing, the new branch). A scene post that is an ANCESTOR of this item is +kept on top as context; any other COLLAPSES away (scale 0, opacity 0, its gap closing) while +this item's first piece is revealed and the column pans, all at the first read's lead; the +opening frame is the post the item before ended on, in full. A post the item draws itself is its +own tile (a parent the item before ended on is carried; one the run showed earlier is context). +Scene tiles are never read (no blocks, no word spans), their words redacted by the terms of the +item they came from, their authors blurred by its rule; the slur filter masks them too. An item in both a +conversation's run and a media scene (post-media-scene.mjs) draws the CONVERSATION's scene: the media +scene keeps only the attachment (read-follow.mjs enforces it; the card route too). +`umtool timeline <p> threads` lists each conversation of two items or more (its root, its +items' places, one run or split, a reply placed before what it answers, an item re-reading a post +its run already read — with `posts set-item <p> <item> thread.parent.<i>=context`); +`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, a branch's date its earliest item's, each +depth first) in one undoable write — never across a section boundary (a conversation spanning +sections is gathered within each, and said). + +**A read without a piece, re-joined.** A context post the read reads that should not be read +("we don't need to read this context, or paraphrase it") is cut out of the take, not +re-synthesized: `umtool posts reread <p> <item> --without parent:0|parent:1|quoted [--drop-parts +3,4] [--drop-urls]` (`lib/report/postReread.mjs`) cuts the kept parts' spans out of the picked +take's own file, joins them with the read's pauses, measures it and adds it as a derived take +(`source: {kind: "take", from}`, `steps: [{op: "rejoin", drop, ranAt}]`) — its parts re-timed with +their roles stored, its word timings moved with them (bleeps and zooms still find their words), +its slurs state kept — and picks it, in one write. `posts set-item <p> <item> +thread.parent.<i>=context` (or `hidden`, or `thread.quoted=…`) on a piece the picked take reads +runs it first; on one it does not read it is the knob alone (`--no-reread`: refused, as before). +The post bench's **thread read** block offers **Read without it** on such a piece. ```jsonc "render": { "postNarration": { "thread": { "parent": "auto", "quoted": "auto", "carry": "auto", "reveal": true, @@ -830,8 +892,9 @@ post bench's **thread read** block shows the refusal before Save. opacity (`tiles`), the page's slots are closed up to match (`data-thread-slot`, `data-thread-tile`), the geometry is measured once at full size and worked out under the scales (threadGeoAt), and the build shoots each distinct state once. The plan's `follow.thread` is -the tiles' schedule; `postItemPlan(entry, render, { prev })` takes the item before it (the -build, Play, the bench and the card route pass it). Not narrated, or with no context post +the tiles' schedule; `postItemPlan(entry, render, { prev, scene })` takes the item before it and +the scene its run leaves on screen (`planContext`: the build, Play, the bench, the card route, the +writers' guard and the lint all pass it). Not narrated, or with no context post drawn, the card is as it was. ### The combo counter diff --git a/umtool/e2e/thread-walk.spec.ts b/umtool/e2e/thread-walk.spec.ts @@ -0,0 +1,181 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE THREAD WALK (report-to-video/post-conversation.mjs; knobs.md, "Thread +// reads"; operator, 4 Nov: "weird thread progression", "wrong order", "a full +// read thread progression"): one conversation played back to back is ONE +// scene. Fixture: e2e/fixtures/post-narration-fixture.mjs's three items made +// a tree here -- p-11 his reply under his root post (771), p-12 his answer to +// a stranger who answered p-11, p-13 his answer to a second stranger who +// answered the root (the sibling branch) -- and p-14 a post whose read reads +// the post it quotes first (its links among it). +// +// THREAD_WALK_SHOTS=<dir> screenshots there +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPORTS = path.join(HERE, "..", ".e2e-song", "reports"); +const DIR = path.join(REPORTS, "post-narration-fixture"); +const MANIFEST = path.join(DIR, "video.manifest.json"); +const PROJECT = "reports/post-narration-fixture"; +const SHOTS = process.env.THREAD_WALK_SHOTS ?? null; + +const ROOT = { id: "771", author: "Narr Subject", handle: "narrsubject", date: "2026-10-30T06:00:00.000Z", text: "Many have questioned my methods in dealing with the whole mess, and I will say it once more for everyone." }; +const A = "I can't help but feel like I've failed everyone, they all got exactly what they wanted out of it."; +const FOX = { id: "834", author: "Fox One", handle: "fox_one", date: "2026-10-30T07:00:00.000Z", text: "Far as people should be concerned you are no better than the people you criticised all week." }; +const C = "As far as people are concerned you are nobody at all, and that is the end of it."; +const DRAC = { id: "775", author: "Drac Two", handle: "drac_two", date: "2026-10-30T06:10:00.000Z", text: "Oh please, you were never going to change anything here by drawing all that attention to it." }; +const B = "I have fought them before, so who are you to tell me what fighting them is like."; +const QUOTED = { author: "Quoted Person", handle: "quoted_person", date: "2026-10-30T05:00:00.000Z", text: "Read the receipts before you say another word about it.\n\nhttps://\nweb.archive.org/web/2021032015\n1733/https://twitter.com/someone/status/1373102987070017537\n…" }; +const Q_REPLY = "I read them, and they say the opposite of what you think they say."; + +/** A take as the batch assembles one: its pieces in order (para = piece * 100), a part each, 3 words a second. */ +function takeOf(pieces: string[]) { + let at = 0; + const parts = pieces.map((text, pi) => { + const seconds = Math.round((text.split(/\s+/).length / 3) * 100) / 100; + if (pi) at += 0.6; + const p = { n: pi + 1, para: pi * 100, text, start: Math.round(at * 100) / 100, seconds }; + at += seconds; + return p; + }); + return { file: "narration/posts/11/take-1.orpheus-zac.wav", engine: "orpheus", voice: "leo+zac", seconds: Math.round(at * 100) / 100, script: pieces.join("\n\n"), parts }; +} +const STARTS = (pieces: string[]) => takeOf(pieces).parts.map((p) => 0.4 + p.start); + +test.beforeAll(() => { + if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); +}); +test.beforeEach(() => { + test.setTimeout(120_000); + copyFileSync(`${MANIFEST}.pristine`, MANIFEST); + rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); + rmSync(path.join(DIR, "notes.json"), { force: true }); + const m = JSON.parse(readFileSync(MANIFEST, "utf8")); + const byId = (id: string) => m.timeline.find((x: { id: string }) => x.id === id); + const narr = (e: Record<string, unknown>, text: string, pieces: string[]) => Object.assign(e, { text, narration: { script: text, takes: [takeOf(pieces)], pick: 0 } }); + const a = narr(byId("p-11"), A, [A]); + a.parents = [ROOT]; + const c = narr(byId("p-12"), C, [FOX.text, C]); + delete c.media; + c.date = "2026-10-30T07:10:00.000Z"; + c.parents = [FOX, { id: "11", author: "Narr Subject", handle: "narrsubject", date: "2026-10-30T10:00:00.000Z", text: A }]; + const b = narr(byId("p-13"), B, [DRAC.text, B]); + b.date = "2026-10-30T11:00:00.000Z"; + b.parents = [DRAC, ROOT]; + const q = narr({ ...structuredClone(b), id: "p-14", post: "narrchan-x/14", parents: undefined, date: "2026-10-30T12:00:00.000Z" }, Q_REPLY, [ + "Read the receipts before you say another word about it.", + "https://. web.archive.org slash web slash 2021032015. 1733/. …", + Q_REPLY, + ]); + delete q.parents; + q.quoted = QUOTED; + m.timeline = [a, c, b, q]; + writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); +}); + +/** Play opened paused `at` seconds into `id`; its frame once the card is threaded. */ +async function playAt(page: Page, id: string, at: number) { + await page.goto(urls.playHref(PROJECT, { bare: true, clip: id, at })); + const player = page.locator(`[data-post-play="${id}"]`); + await expect(player).toHaveAttribute("data-post-thread", /\d/, { timeout: 15_000 }); + const frame = page.frameLocator('[data-post-card-frame="read"]'); + await expect(frame.locator("body")).toHaveAttribute("data-post-thread", /\d/, { timeout: 15_000 }); + await expect.poll(async () => Math.abs(Number(await player.getAttribute("data-post-s")) - at)).toBeLessThan(0.3); + return { player, frame }; +} +const tilesOf = async (player: ReturnType<Page["locator"]>) => + Object.fromEntries(((await player.getAttribute("data-post-thread-tiles")) ?? "").split(" ").filter(Boolean).map((x) => { + const [sc, v] = x.split("="); + return [sc, v.split("/").map(Number)]; + })); +const slotTop = (frame: ReturnType<Page["frameLocator"]>, scope: string) => + frame.locator(`[data-thread-slot="${scope}"]`).evaluate((el) => el.getBoundingClientRect().top - document.querySelector("[data-post-words]")!.getBoundingClientRect().top); + +test("ONE SCENE: his answer to the stranger opens on his reply above it (carried, in full), the root kept on top as context; the stranger's post comes in lit while it is read", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + // At its first frame: the post p-11 ended on, in full; the root small and dim above it. + { + const { player, frame } = await playAt(page, "p-12", 0.05); + await expect(frame.locator('[data-thread-slot="conv:771"]')).toHaveAttribute("data-thread-scene", "keep"); + const t = await tilesOf(player); + // In full as the item opens (the change to it begins with the read, 0.4 s in less the pan's lead: at once). + expect(t["parent:1"][0]).toBeGreaterThan(0.9); + expect(t["parent:1"][1]).toBeGreaterThan(0.9); + expect(t["conv:771"][0]).toBeLessThan(1); + // The stranger's post not yet in (it fades in as the read begins). + expect(t["parent:0"][1]).toBeLessThan(0.2); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-open.png") }); + } + // The stranger's post read: in full and lit, the root still on top of the column. + { + const [fox] = STARTS([FOX.text, C]); + const { player, frame } = await playAt(page, "p-12", fox + 1.4); + const t = await tilesOf(player); + expect(t["parent:0"]).toEqual([1, 1]); + expect(t["conv:771"]).toEqual([0.62, 0.5]); + expect(t["parent:1"]).toEqual([0.62, 0.5]); + await expect.poll(async () => frame.locator('[data-thread-slot="parent:0"]').getAttribute("data-thread-state")).toBe("focus"); + expect(await slotTop(frame, "conv:771")).toBeLessThan(await slotTop(frame, "parent:1")); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-fox.png") }); + } +}); + +test("THE SIBLING SWAP: the next branch's item opens on the post the last one ended on; that branch collapses away (scale 0) as the second stranger comes in, lit -- the root stays on top", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + { + const { player, frame } = await playAt(page, "p-13", 0.05); + for (const sc of ["conv:11", "conv:834", "conv:12"]) await expect(frame.locator(`[data-thread-slot="${sc}"]`)).toHaveAttribute("data-thread-scene", "collapse"); + const t = await tilesOf(player); + // The post p-12 ended on, in full as the item opens (it collapses as the read begins: at once). + expect(t["conv:12"][0]).toBeGreaterThan(0.9); + expect(t["conv:12"][1]).toBeGreaterThan(0.9); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-swap-open.png") }); + } + { + const [drac] = STARTS([DRAC.text, B]); + const { player, frame } = await playAt(page, "p-13", drac + 1.4); + const t = await tilesOf(player); + for (const sc of ["conv:11", "conv:834", "conv:12"]) expect(t[sc].slice(0, 2)).toEqual([0, 0]); + expect(t["parent:0"]).toEqual([1, 1]); + expect(t["parent:1"]).toEqual([0.62, 0.5]); + await expect.poll(async () => frame.locator('[data-thread-slot="conv:12"]').getAttribute("data-thread-state")).toBe("hidden"); + await expect.poll(async () => frame.locator('[data-thread-slot="parent:0"]').getAttribute("data-thread-state")).toBe("focus"); + // The root on top, the new branch under it; the collapsed slots closed up. + expect(await slotTop(frame, "parent:1")).toBeLessThan(await slotTop(frame, "parent:0")); + await expect.poll(async () => frame.locator('[data-thread-slot="conv:12"]').evaluate((el) => el.getBoundingClientRect().height)).toBeLessThan(1); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-swap-drac.png") }); + } +}); + +test("A QUOTE READ FIRST is its own tile above his post, in full and lit while read -- his post not yet shown; the read's link is warned with its fix", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + const { player, frame } = await playAt(page, "p-14", 1.5); + const t = await tilesOf(player); + expect(t.quoted).toEqual([1, 1]); + expect(t.post[1]).toBe(0); + await expect(frame.locator('[data-thread-slot="quoted"]')).toHaveAttribute("data-thread-above", ""); + expect(await slotTop(frame, "quoted")).toBeLessThan(await slotTop(frame, "post")); + await expect.poll(async () => frame.locator('[data-thread-slot="quoted"]').getAttribute("data-thread-state")).toBe("focus"); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-quote.png") }); + // posts roles: the part that says a link, and the fix. + const roles = execFileSync(process.execPath, [path.join(HERE, "..", "bin", "umtool.mjs"), "posts", "roles", PROJECT, "p-14"], { env: { ...process.env, REPORTS_DIR: path.dirname(REPORTS) }, encoding: "utf8" }); + expect(roles).toMatch(/WARNING: timeline p-14: part 2 of its take says a link aloud .*umtool posts reread <p> p-14 --drop-urls/); +}); + +test("the bench: one scene with the item before (what stays on top, what collapses); a context piece the take reads offers \"Read without it\"", async ({ page }) => { + await page.setViewportSize({ width: 1500, height: 1100 }); + await page.goto(urls.postBenchHref(PROJECT, "p-13")); + const panel = page.locator("[data-post-thread-panel]"); + await expect(panel).toHaveAttribute("data-threaded", "1"); + await expect(panel.locator("[data-post-thread-scene]")).toHaveAttribute("data-post-thread-scene", "3"); + await expect(panel.locator('[data-post-thread-scene-tile="12"]')).toHaveAttribute("data-action", "collapse"); + await expect(panel.locator('[data-post-thread-reread="parent:0"]')).toHaveText("Read without it"); + await expect(panel.locator('[data-post-thread-piece="post"] [data-post-thread-reread]')).toHaveCount(0); + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "walk-bench.png") }); +}); 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"; @@ -2467,7 +2468,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); @@ -2871,12 +2875,13 @@ export async function fitPostItems(dir, fits, { token = null } = {}) { } /** What a context write may set on a post item (postContext.mjs). */ -export const POST_ITEM_CONTEXT_KEYS = Object.freeze(["quoted", "parents"]); +export const POST_ITEM_CONTEXT_KEYS = Object.freeze(["quoted", "parents", "conversation"]); /** * FILL POST ITEMS' CONTEXT (`umtool posts context`, postContext.mjs): `patches` - * is `{ <entry id>: { quoted?, parents? } }` -- the post it quotes and the posts - * it answers, snapshotted from each post's capture; a null clears one. ONE + * is `{ <entry id>: { quoted?, parents?, conversation? } }` -- the post it quotes, the posts + * it answers (snapshotted from each post's capture, or a status link's archived post) and + * the conversation it is part of (its archive row's threadId); a null clears one. ONE * structural write for them all (one undo point), refused whole in the * build's words (validatePostItem). Returns `{ ids }`. * 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"; @@ -40,11 +41,13 @@ 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) * @param {Record<string, any> | null} [mediaScene] its media scene (post-media-scene.mjs mediaSceneOf): `post` is - * the item as the scene plays it (the shared attachment the anchor's), its plan's card the scene's column + * the item as the scene plays it (the shared attachment the anchor's), its plan's card the scene's column -- unless + * the conversation's scene takes the card (it wins; the media scene keeps the attachment) */ -export function postPlayEntry(e, render = undefined, prev = null, mediaScene = null) { +export function postPlayEntry(e, render = undefined, ctx = null, mediaScene = 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(); @@ -58,8 +61,9 @@ export function postPlayEntry(e, render = undefined, prev = null, mediaScene = n date: day || null, quote: words || null, post: sceneEntry(e, mediaScene), - // `prev`: the item before it in the cut (post-thread.mjs: a parent that is that item is carried in). - postPlan: postItemPlan(sceneEntry(e, mediaScene), render, { prev, mediaScene }), + // `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) -- it wins the card. + postPlan: postItemPlan(sceneEntry(e, mediaScene), render, { prev: ctx?.prev ?? null, scene: ctx?.scene ?? null, mediaScene: ctx?.scene ? null : mediaScene }), ...(mediaScene ? { postScene: { key: mediaScene.key, n: mediaScene.n, of: mediaScene.of, ids: mediaScene.ids, anchor: mediaScene.anchor.id } } : {}), }; } @@ -120,7 +124,7 @@ export async function playView(project, { take = null, bare = false } = {}) { : { combos: {}, groups: [] }; const entries = await Promise.all( timeline.map(async (e, i) => { - if (e.type === "post") return postPlayEntry(e, render, timeline[i - 1] ?? null, mediaSceneOf(timeline, i, repeatGroups, render)); + if (e.type === "post") return postPlayEntry(e, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, 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/postContext.mjs b/umtool/lib/report/postContext.mjs @@ -23,11 +23,21 @@ // grey-checked; the badge the capture read is what it decides by. // // Plain ESM: the CLI runs it under bare node. -import { readFile } from "node:fs/promises"; +// +// A STATUS LINK IS A QUOTE (operator, 4 Nov: a post that embeds another by +// its link, not X's quote): a post item with no quoted post whose words (or +// its archive row's links) carry an x.com / twitter.com status link takes the +// post it names as its `quoted` (`via: "link"`) when any channel's posts +// archive holds it (read lazily, only for a link), else the capture's. The +// same pass snapshots the row's `threadId` as the entry's `conversation` +// (post-conversation.mjs reads a conversation by it). +import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; +import { joinSplitLinks } from "umtool-report-to-video/post-narration"; import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, setPostItemsContext } from "./manifest.mjs"; +import { findPostRow } from "./postsCli.mjs"; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const str = (v) => (typeof v === "string" ? v : ""); @@ -111,6 +121,65 @@ export function applyCaptureContext(entry, context) { return filled; } +/** An x.com / twitter.com status link: its handle and the post's id. */ +const STATUS_RE = /https?:\/\/(?:www\.|mobile\.)?(?:x|twitter)\.com\/([A-Za-z0-9_]{1,30})\/status(?:es)?\/(\d{5,25})/gi; + +/** + * The status links in a post's words (X's split links put back first) and in + * its archive row's `links`, in order, each once: `[{ handle, id }]`. Pure. + */ +export function statusLinksOf(text, links = []) { + const out = []; + const seen = new Set(); + const from = [joinSplitLinks(str(text)), ...(Array.isArray(links) ? links.map((l) => (typeof l === "string" ? l : str(l?.url) || str(l?.expanded))) : [])]; + for (const t of from) { + for (const m of t.matchAll(STATUS_RE)) { + if (seen.has(m[2])) continue; + seen.add(m[2]); + out.push({ handle: m[1], id: m[2] }); + } + } + return out; +} + +/** A post item ref from an archive row (postsCli.mjs findPostRow's), `via: "link"`; null for nothing usable. */ +export function refFromRow(row) { + if (!isObj(row)) return null; + const ref = contextRefOf({ id: str(row.id), author: str(row.authorName), handle: str(row.author), date: str(row.createdAt), text: str(row.text), url: str(row.url) }); + return ref ? { ...ref, via: "link" } : null; +} + +/** + * A RESOLVER of status ids to archived posts across every channel's posts + * archive (`channels/<slug>/posts/*.jsonl`), lazy: the channels are listed on + * the first call, a channel named for the link's handle read first, each id + * looked up once. + */ +export function statusResolver(channelsDir) { + let slugs = null; + const cache = new Map(); + return async function resolve({ handle, id }) { + if (cache.has(id)) return cache.get(id); + if (slugs === null) { + const names = await readdir(channelsDir).catch(() => []); + slugs = []; + for (const n of names) if (POST_KEY_RE.test(n) && (await stat(path.join(channelsDir, n, "posts")).catch(() => null))?.isDirectory()) slugs.push(n); + } + const h = str(handle).toLowerCase(); + const order = [...slugs.filter((s) => h && s.toLowerCase().startsWith(h)), ...slugs.filter((s) => !(h && s.toLowerCase().startsWith(h)))]; + let row = null; + for (const slug of order) { + const hit = await findPostRow(channelsDir, slug, id).catch(() => null); + if (hit?.row) { + row = hit.row; + break; + } + } + cache.set(id, row); + return row; + }; +} + /** * The `context` of a post's capture (`channels/<slug>/posts-media/<postId>/capture.json`), * or null when there is no capture or it read none. @@ -150,19 +219,38 @@ export async function postsContext(project, { channelsDir = null, dryRun = false const report = []; /** @type {Map<string, string[]>} */ const missing = new Map(); + const resolve = statusResolver(dir); for (const e of items) { const [slug, rowId] = e.post.split("/"); // A repost is drawn as its original: the original's capture first. const shownId = str(e.originalId) || rowId; const context = (await readCaptureContext(dir, slug, shownId)) ?? (shownId !== rowId ? await readCaptureContext(dir, slug, rowId) : null); - if (!context) { + const copy = structuredClone(e); + const filled = context ? applyCaptureContext(copy, context) : []; + // Its archive row: the conversation it is part of, and the links its words carry. + const row = ID_RE.test(String(shownId)) ? (await findPostRow(dir, slug, String(shownId)).catch(() => null))?.row ?? null : null; + // A status link is a quote, when it has none (or one with no words): the post it names, archived anywhere. + if (!isObj(copy.quoted) || !str(copy.quoted.text).trim()) { + for (const link of statusLinksOf(e.text, row?.links)) { + if (link.id === shownId || link.id === rowId) continue; + const ref = refFromRow(await resolve(link)); + if (!ref) continue; + copy.quoted = isObj(copy.quoted) && sameRef(copy.quoted, ref) ? completed(copy.quoted, ref) : ref; + if (!filled.includes("quoted")) filled.push("quoted"); + break; + } + } + const conv = str(row?.threadId); + if (!str(e.conversation) && ID_RE.test(conv)) { + copy.conversation = conv; + filled.push("conversation"); + } + if (!context && !filled.length) { report.push({ id: e.id, post: e.post, state: "no-context" }); if (!missing.has(slug)) missing.set(slug, []); missing.get(slug).push(shownId); continue; } - const copy = structuredClone(e); - const filled = applyCaptureContext(copy, context); if (!filled.length) { report.push({ id: e.id, post: e.post, state: "complete" }); continue; @@ -170,6 +258,7 @@ export async function postsContext(project, { channelsDir = null, dryRun = false patches[e.id] = { ...(filled.includes("quoted") ? { quoted: copy.quoted } : {}), ...(filled.includes("parents") ? { parents: copy.parents } : {}), + ...(filled.includes("conversation") ? { conversation: copy.conversation } : {}), }; report.push({ id: e.id, post: e.post, state: "filled", filled, ...patches[e.id] }); } diff --git a/umtool/lib/report/postContext.test.mjs b/umtool/lib/report/postContext.test.mjs @@ -10,7 +10,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { after, test } from "node:test"; import { cardAuthors, validatePostItem } from "umtool-report-to-video/post-item"; -import { applyCaptureContext, contextCaptureCall, contextRefOf, postsContext, readCaptureContext, sameRef } from "./postContext.mjs"; +import { applyCaptureContext, contextCaptureCall, contextRefOf, postsContext, readCaptureContext, refFromRow, sameRef, statusLinksOf } from "./postContext.mjs"; import { postItemFromArchive, postsReel } from "./postReel.mjs"; import { postsCommand } from "./postsCli.mjs"; import { setPostItemsContext, undoStructural } from "./manifest.mjs"; @@ -174,3 +174,27 @@ test("the writer: only quoted and parents, refused whole in the build's words; t assert.equal(await readCaptureContext(CH, "obv-x", "302"), null); assert.equal((await readCaptureContext(CH, "obv-x", "300")).parent.handle, "Kirsche"); }); + +test("A STATUS LINK IS A QUOTE: a post with no quoted post whose words link another (X's split link put back) takes it from any channel's archive (via: link); the row's threadId is its conversation", async () => { + assert.deepEqual(statusLinksOf("look\nhttps://\nx.com/OtherPerson/status/7770000000000001\n…", ["https://twitter.com/a_b/status/123456789"]), [{ handle: "OtherPerson", id: "7770000000000001" }, { handle: "a_b", id: "123456789" }]); + assert.deepEqual(statusLinksOf("no links here"), []); + assert.equal(refFromRow({ id: "1", author: "x_y", authorName: "X Y", createdAt: "2026-10-01T00:00:00.000Z", text: "hi", url: "https://x.com/x_y/status/1" }).via, "link"); + await archive("other-x", [row("7770000000000001", { channelSlug: "other-x", slug: "other-x/7770000000000001", author: "OtherPerson", authorName: "Other Person", text: "The post he linked to." })]); + await archive("obv-z", [ + row("500", { channelSlug: "obv-z", slug: "obv-z/500", text: "Read this\nhttps://\nx.com/OtherPerson/status/7770000000000001\n…", threadId: "499" }), + row("501", { channelSlug: "obv-z", slug: "obv-z/501", createdAt: "2026-10-29T15:00:00.000Z" }), + ]); + const p = await project("ctx-link"); + await postsReel(p, { channels: ["obv-z"] }); + const r = await postsContext(p); + const x = r.report.find((y) => y.id === "p-500"); + assert.deepEqual(x.filled, ["quoted", "conversation"]); + const e = (await manifest(p)).timeline.find((y) => y.id === "p-500"); + assert.deepEqual([e.quoted.handle, e.quoted.text, e.quoted.via, e.conversation], ["OtherPerson", "The post he linked to.", "link", "499"]); + assert.deepEqual(validatePostItem(e), []); + assert.equal(r.report.find((y) => y.id === "p-501").state, "no-context"); + // Re-run: nothing more to fill. + assert.equal((await postsContext(p)).filled, 0); + assert.match(validatePostItem({ ...e, conversation: 5 }).join(" "), /conversation must be/); + assert.match(validatePostItem({ ...e, quoted: { ...e.quoted, via: "guess" } }).join(" "), /via must be "link"/); +}); diff --git a/umtool/lib/report/postReread.mjs b/umtool/lib/report/postReread.mjs @@ -0,0 +1,218 @@ +// A READ WITHOUT A PIECE, RE-JOINED (umtool/docs/knobs.md, "Thread reads"; +// operator, 4 Nov, p-2117216053952655778 / p-2117259673917386879: "we don't +// need to read this context, or paraphrase it"; p-2116651428425150687: its +// quote's links read aloud): the picked take's kept parts cut out of its own +// file and joined again -- no TTS, nothing re-synthesized. +// +// umtool posts reread <p> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json] +// +// The parts dropped are those whose ROLE (post-thread.mjs partRoles) is a +// piece named by --without, the parts named by number, and (--drop-urls) the +// parts that are nothing but a link (post-narration.mjs isOnlyUrls). The kept +// parts' spans are cut from the take's file (ffmpeg atrim), joined with the +// pauses a read is assembled with (POST_PART_GAP: between paragraphs, inside +// one), measured, and added as a DERIVED take -- `source: {kind: "take", +// from}`, `steps: [{op: "rejoin", drop, ranAt}]` -- its parts re-timed (each +// with its role stored), its word timings moved with them (a word in a part +// dropped goes too: a beep, a zoom still find theirs), its slurs state kept; +// and picked, in ONE write (updatePostNarration: one undo point). The source +// take is never touched. +// +// Plain ESM: the CLI runs it under bare node. +import { execFile } from "node:child_process"; +import { mkdir, readdir, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { promisify } from "node:util"; +import { POST_PART_GAP, derivedFileOf, isOnlyUrls, nextTakeNumber, pickedTake, postIdOf, takeIdOf, takesDirOf } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostNarration } from "./manifest.mjs"; + +const execFileP = promisify(execFile); +const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; +const FFPROBE = () => process.env.FFPROBE_BIN ?? "ffprobe"; +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const r3 = (v) => Math.round(v * 1000) / 1000; + +export const REREAD_USAGE = [ + " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " A READ WITHOUT A PIECE, RE-JOINED (no TTS): the picked take's kept parts cut out of its own file and joined with", + " the read's pauses, as a NEW take (source: the take; steps: rejoin) that is picked -- one write, undoable. --without", + " drops the parts that read the post it answers (parent:0), that one's parent (parent:1) or the quoted post;", + " --drop-parts the parts by number (as posts roles lists them); --drop-urls the parts that are nothing but a link.", + " Its parts are re-timed (roles stored), its word timings moved with them, its slurs state kept.", +].join("\n"); + +export class RereadError extends Error { + constructor(message) { + super(message); + this.name = "RereadError"; + } +} + +const PIECE_RE = /^(parent:\d|quoted)$/; + +/** + * THE RE-JOIN's PLAN, pure: which parts of `entry`'s picked take are kept and + * where each lands in the new take -- `{ take, keep: [k…], drop: [{ k, why }], + * spans: [{ k, from, to, at }], parts, words, script, seconds, steps }`. + * `spans` are in the source take's seconds (`at` the kept part's start in + * the new one). Throws RereadError when there is nothing to drop, no part + * left, or the take has no parts timed. + * + * @param {Record<string, any>} entry + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean }} o + */ +export function rereadPlan(entry, { without = [], dropParts = [], dropUrls = false } = {}) { + const t = pickedTake(entry); + if (!t) throw new RereadError(`${entry?.id ?? "?"} has no take to re-join`); + const parts = Array.isArray(t.parts) ? t.parts : []; + if (!parts.length || !parts.every((p) => fin(p?.start) && fin(p?.seconds) && p.seconds > 0)) { + throw new RereadError(`${entry.id}'s picked take was read in one go (no timed parts): re-make it on a script without the piece (umtool posts narrate <p> ${entry.id} --take)`); + } + for (const w of without) if (!PIECE_RE.test(w)) throw new RereadError(`--without ${w}: a piece is parent:0, parent:1 or quoted`); + for (const n of dropParts) if (!(Number.isInteger(n) && n >= 1 && n <= parts.length)) throw new RereadError(`--drop-parts ${n}: ${entry.id}'s take has parts 1-${parts.length}`); + const roles = partRoles(entry); + const drop = []; + parts.forEach((p, k) => { + const role = roles[k]?.role ?? null; + if (role && without.includes(role)) drop.push({ k, why: role }); + else if (dropParts.includes(k + 1)) drop.push({ k, why: `part ${k + 1}` }); + else if (dropUrls && isOnlyUrls(p.text)) drop.push({ k, why: "url" }); + }); + if (!drop.length) throw new RereadError(`${entry.id}'s picked take reads none of that${without.length ? ` (${without.join(", ")})` : ""}: nothing to drop`); + const dropped = new Set(drop.map((d) => d.k)); + const keep = parts.map((_, k) => k).filter((k) => !dropped.has(k)); + if (!keep.length) throw new RereadError(`${entry.id}: that drops every part of its take -- nothing would be read`); + // The kept parts, joined with the read's pauses (a new paragraph's, a part inside one's). + const spans = []; + let cur = 0; + keep.forEach((k, j) => { + const p = parts[k]; + const gap = j === 0 ? 0 : p.para !== parts[keep[j - 1]].para ? POST_PART_GAP.para : POST_PART_GAP.inside; + const at = r3(cur + gap); + spans.push({ k, from: r3(p.start), to: r3(p.start + p.seconds), at, gap }); + cur = at + p.seconds; + }); + const newParts = spans.map((s, j) => { + const p = parts[s.k]; + const { gapBefore: _g, role: _r, ...rest } = p; + const role = roles[s.k]?.role ?? null; + return { ...rest, n: j + 1, start: s.at, seconds: r3(p.seconds), ...(role ? { role } : {}) }; + }); + // Its words moved with their parts (a word is its part's when it starts inside the part's span). + const words = Array.isArray(t.words) + ? t.words.flatMap((w) => { + const s = spans.find((x) => w.start >= x.from - 0.05 && w.start < x.to + 0.05); + if (!s) return []; + const d = s.at - s.from; + return [{ w: w.w, start: r3(Math.max(0, w.start + d)), end: r3(Math.max(0, w.end + d)) }]; + }) + : null; + const script = spans.reduce((acc, s, j) => { + const p = parts[s.k]; + const sep = j === 0 ? "" : p.para !== parts[spans[j - 1].k].para ? "\n\n" : " "; + return acc + sep + String(p.text ?? "").trim(); + }, ""); + return { take: t, keep, drop, spans, parts: newParts, words, script, seconds: r3(cur), steps: [{ op: "rejoin", drop: drop.map((d) => d.why).filter((v, i, a) => a.indexOf(v) === i), ranAt: new Date().toISOString() }] }; +} + +/** The ffmpeg arguments that cut the plan's spans out of `src` and join them with silence into `out`. */ +export function rejoinArgs(src, out, plan, { rate = 48000, layout = "mono" } = {}) { + const chains = []; + const labels = []; + plan.spans.forEach((s, j) => { + if (s.gap > 0) { + chains.push(`anullsrc=r=${rate}:cl=${layout},atrim=duration=${s.gap}[g${j}]`); + labels.push(`[g${j}]`); + } + chains.push(`[0:a]atrim=start=${s.from}:end=${s.to},asetpts=PTS-STARTPTS,aformat=sample_rates=${rate}:channel_layouts=${layout}[a${j}]`); + labels.push(`[a${j}]`); + }); + chains.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[out]`); + return ["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-filter_complex", chains.join(";"), "-map", "[out]", "-c:a", "pcm_s16le", out]; +} + +/** A file's sample rate and channel layout (ffprobe). */ +async function audioFormat(file) { + const { stdout } = await execFileP(FFPROBE(), ["-v", "error", "-select_streams", "a:0", "-show_entries", "stream=sample_rate,channels", "-of", "default=noprint_wrappers=1", file]); + const rate = Number(/sample_rate=(\d+)/.exec(String(stdout))?.[1]) || 48000; + const ch = Number(/channels=(\d+)/.exec(String(stdout))?.[1]) || 1; + return { rate, layout: ch >= 2 ? "stereo" : "mono" }; +} + +/** + * RE-JOIN post item `e`'s picked take without a piece (`opts` as rereadPlan + * takes them): the file written, measured, the take added and picked in one + * write. `dryRun`: the plan only. Returns `{ plan, take?, result? }`. + * + * @param {{ id: string, dir: string }} project + * @param {Record<string, any>} e + * @param {{ without?: string[], dropParts?: number[], dropUrls?: boolean, dryRun?: boolean, measure?: (file: string) => Promise<{ seconds: number|null, lufs: number|null }> }} [o] + */ +export async function rereadTake(project, e, { without = [], dropParts = [], dropUrls = false, dryRun = false, measure = undefined } = {}) { + const plan = rereadPlan(e, { without, dropParts, dropUrls }); + if (dryRun) return { plan }; + const t = plan.take; + const pid = postIdOf(e); + const dir = path.join(project.dir, ...takesDirOf(pid).split("/")); + await mkdir(dir, { recursive: true }); + const rel = derivedFileOf(pid, nextTakeNumber(e, await readdir(dir).catch(() => [])), "rejoin", t.engine === "derived" ? "take" : t.engine ?? "take"); + const abs = (r) => path.join(project.dir, ...String(r).split("/")); + const src = abs(t.file); + if (!(await stat(src).catch(() => null))?.isFile()) throw new RereadError(`${e.id}'s picked take is not on disk: ${t.file}`); + const fmt = await audioFormat(src); + try { + await execFileP(FFMPEG(), rejoinArgs(src, abs(rel), plan, fmt), { maxBuffer: 1 << 24 }); + } catch (err) { + await rm(abs(rel), { force: true }); + throw new RereadError(`ffmpeg could not re-join ${t.file}: ${String(err?.stderr ?? err?.message ?? err).trim().split("\n").pop()}`); + } + const m = await (measure ?? (await import("./postNarrationCli.mjs")).measureTake)(abs(rel)); + const take = { + file: rel, + engine: "derived", + voice: t.voice ?? "?", + seconds: fin(m.seconds) && m.seconds > 0 ? m.seconds : plan.seconds, + source: { kind: "take", from: takeIdOf(t) }, + steps: plan.steps, + script: plan.script, + at: new Date().toISOString(), + ...(fin(m.lufs) ? { lufs: m.lufs } : fin(t.lufs) ? { lufs: t.lufs } : {}), + ...(t.slurs ? { slurs: t.slurs } : {}), + ...(plan.words ? { words: plan.words } : {}), + parts: plan.parts, + }; + const { result } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, { addTake: take }, { token: await manifestToken(project.dir) })); + return { plan, take, result }; +} + +/** The pieces a set-item thread patch draws as context or hidden that `e`'s picked take reads (set-item's re-join). */ +export function piecesHidden(e, thread) { + if (!thread || typeof thread !== "object") return []; + const read = new Set(partRoles(e).map((r) => r.role).filter(Boolean)); + const out = []; + const off = (m) => m === "context" || m === "hidden"; + if (Array.isArray(thread.parent)) thread.parent.forEach((m, i) => off(m) && read.has(`parent:${i}`) && out.push(`parent:${i}`)); + else if (off(thread.parent)) for (const r of read) if (r.startsWith("parent:")) out.push(r); + if (off(thread.quoted) && read.has("quoted")) out.push("quoted"); + return out; +} + +/** `umtool posts reread <p> <item> …`. */ +export async function rereadCommand(project, ref, { without = [], dropParts = [], dropUrls = false, dryRun = false, json = false, out = (s) => console.log(s) } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new RereadError(`${project.id} has no manifest`); + const e = (manifest.timeline ?? []).find((x) => x?.type === "post" && (x.id === ref || postIdOf(x) === ref || x.id === `p-${ref}`)); + if (!e) throw new RereadError(`no post item ${ref} in ${project.id}`); + const r = await rereadTake(project, e, { without, dropParts, dropUrls, dryRun }); + const said = r.plan.drop.map((d) => `part ${d.k + 1} (${d.why})`).join(", "); + if (json) { + out(JSON.stringify({ ok: true, id: e.id, dryRun, drop: r.plan.drop.map((d) => ({ part: d.k + 1, why: d.why })), keep: r.plan.keep.map((k) => k + 1), seconds: r.take?.seconds ?? r.plan.seconds, take: r.take ?? null, token: r.result?.token ?? null }, null, 2)); + return 0; + } + out(`${dryRun ? "would re-join" : "re-joined"} ${e.id}'s take without ${said}: ${r.plan.keep.length} part(s), ${(r.take?.seconds ?? r.plan.seconds).toFixed(2)} s (was ${Number(r.plan.take.seconds).toFixed(2)} s)`); + if (r.take) out(` ${r.take.file} -- picked (one undo point: umtool timeline ${project.id} undo)`); + return 0; +} diff --git a/umtool/lib/report/postReread.test.mjs b/umtool/lib/report/postReread.test.mjs @@ -0,0 +1,132 @@ +// postReread.mjs: A READ WITHOUT A PIECE, RE-JOINED -- the picked take's kept +// parts cut from its own file and joined with the read's pauses (no TTS); the +// plan (spans, the parts re-timed with their roles, the words moved, the +// guard), the file (ffmpeg, measured), the one write (picked, undoable), and +// set-item's re-join: a piece drawn context that the take reads is re-joined +// first; one it does not read is the knob alone (idempotent). +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { validatePostItem } from "umtool-report-to-video/post-item"; +import { threadReadErrors } from "umtool-report-to-video/post-thread"; +import { piecesHidden, rejoinArgs, rereadPlan, rereadTake } from "./postReread.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { undoStructural } from "./manifest.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-reread-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const REPORTS = path.join(ROOT, "reports"); +const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning."; +const REPLY = "That is exactly what I was saying yesterday morning."; + +const parts = () => [ + { n: 1, para: 0, text: "The first thing anyone notices is the noise from the street.", start: 0, seconds: 3.6, file: "narration/parts-cache/a.wav" }, + { n: 2, para: 1, text: "Then the lights in the hall go out without warning.", start: 4.2, seconds: 3.2 }, + { n: 3, para: 100, text: REPLY, start: 8.2, seconds: 3.1 }, +]; +const words = () => [ + { w: "The", start: 0.1, end: 0.3 }, { w: "Then", start: 4.3, end: 4.6 }, { w: "That", start: 8.3, end: 8.5 }, { w: "morning", start: 10.9, end: 11.2 }, +]; +const item = (o = {}) => ({ + type: "post", id: "p-1", post: "subj-x/1", platform: "x", author: "THE SUBJECT", handle: "Subject", date: "2026-10-30T10:00:00.000Z", text: REPLY, + parents: [{ id: "900", author: "Neighbour", handle: "neighbour_one", date: "2026-10-29T10:00:00.000Z", text: PARENT }], + narration: { script: REPLY, takes: [{ file: "narration/posts/1/take-2.orpheus-thread.wav", engine: "orpheus", voice: "leo+zac", seconds: 11.3, slurs: "said", words: words(), parts: parts() }], pick: 0 }, + ...o, +}); + +test("THE PLAN: the parts reading the post it answers dropped; the rest re-timed with the read's pauses, their roles stored, the words moved with them", () => { + const p = rereadPlan(item(), { without: ["parent:0"] }); + assert.deepEqual(p.drop.map((d) => [d.k, d.why]), [[0, "parent:0"], [1, "parent:0"]]); + assert.deepEqual(p.keep, [2]); + assert.deepEqual(p.spans, [{ k: 2, from: 8.2, to: 11.3, at: 0, gap: 0 }]); + assert.deepEqual(p.parts, [{ n: 1, para: 100, text: REPLY, start: 0, seconds: 3.1, role: "post" }]); + assert.deepEqual(p.words, [{ w: "That", start: 0.1, end: 0.3 }, { w: "morning", start: 2.7, end: 3 }]); + assert.equal(p.script, REPLY); + assert.equal(p.seconds, 3.1); + assert.deepEqual(p.steps.map((s) => [s.op, s.drop]), [["rejoin", ["parent:0"]]]); + // A part by number: the pauses of a read (a paragraph's 0.6 s between pieces). + const q = rereadPlan(item(), { dropParts: [2] }); + assert.deepEqual(q.spans.map((s) => [s.k, s.at, s.gap]), [[0, 0, 0], [2, 4.2, 0.6]]); + assert.equal(q.parts[0].file, "narration/parts-cache/a.wav", "a part's own file kept"); + // Links: only the parts that are nothing but one. + const linked = item({ narration: { ...item().narration, takes: [{ ...item().narration.takes[0], parts: [...parts().slice(0, 2), { n: 3, para: 2, text: "https://. web.archive.org slash web slash 2021032015. 1733/. …", start: 8.2, seconds: 2 }, { ...parts()[2], n: 4, start: 10.8 }] }] } }); + assert.deepEqual(rereadPlan(linked, { dropUrls: true }).drop.map((d) => [d.k, d.why]), [[2, "url"]]); +}); + +test("the plan's refusals: nothing to drop (the take does not read it), every part dropped, a take read in one go", () => { + assert.throws(() => rereadPlan(item(), { without: ["quoted"] }), /reads none of that \(quoted\): nothing to drop/); + assert.throws(() => rereadPlan(item(), { dropParts: [1, 2, 3] }), /drops every part/); + assert.throws(() => rereadPlan(item(), { without: ["nonsense"] }), /a piece is parent:0, parent:1 or quoted/); + const oneGo = item({ narration: { script: REPLY, takes: [{ file: "narration/posts/1/take-1.orpheus-zac.wav", seconds: 3 }], pick: 0 } }); + assert.throws(() => rereadPlan(oneGo, { without: ["parent:0"] }), /read in one go/); + // set-item's pieces: only what the take reads, as context or hidden. + assert.deepEqual(piecesHidden(item(), { parent: ["context", "auto"] }), ["parent:0"]); + assert.deepEqual(piecesHidden(item(), { parent: "full" }), []); + assert.deepEqual(piecesHidden(item(), { quoted: "hidden" }), []); +}); + +test("the ffmpeg arguments: each kept span trimmed, the pauses silence, joined in order", () => { + const p = rereadPlan(item(), { dropParts: [2] }); + const argv = rejoinArgs("/in.wav", "/out.wav", p, { rate: 24000, layout: "mono" }); + const fc = argv[argv.indexOf("-filter_complex") + 1]; + assert.match(fc, /\[0:a\]atrim=start=0:end=3\.6,asetpts=PTS-STARTPTS,aformat=sample_rates=24000:channel_layouts=mono\[a0\]/); + assert.match(fc, /anullsrc=r=24000:cl=mono,atrim=duration=0\.6\[g1\]/); + assert.match(fc, /\[a0\]\[g1\]\[a1\]concat=n=3:v=0:a=1\[out\]/); +}); + +async function project(name, timeline) { + const dir = path.join(REPORTS, name); + await mkdir(path.join(dir, "narration", "posts", "1"), { recursive: true }); + // The take: 11.3 s of tone, as a read's file stands in for one. + execFileSync("ffmpeg", ["-nostdin", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=220:duration=11.3:sample_rate=24000", path.join(dir, "narration", "posts", "1", "take-2.orpheus-thread.wav")]); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "" }, render: { width: 1920, height: 1080, fps: 30 }, timeline }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +test("RE-JOINED: the file cut and joined (its length the kept parts'), a derived take (source, steps) picked in ONE write, undoable; the guard is satisfied once the parent is context", async () => { + const p = await project("rejoin", [item()]); + const e = (await manifest(p)).timeline[0]; + const r = await rereadTake(p, e, { without: ["parent:0"] }); + assert.match(r.take.file, /^narration\/posts\/1\/take-3\.rejoin-orpheus\.wav$/); + assert.ok(Math.abs(r.take.seconds - 3.1) < 0.06, `measured ${r.take.seconds}`); + const now = (await manifest(p)).timeline[0]; + assert.equal(now.narration.pick, 1); + const t = now.narration.takes[1]; + assert.deepEqual([t.engine, t.source, t.steps[0].op, t.steps[0].drop, t.slurs], ["derived", { kind: "take", from: "take-2.orpheus-thread" }, "rejoin", ["parent:0"], "said"]); + assert.deepEqual(t.parts.map((x) => x.role), ["post"]); + assert.deepEqual(validatePostItem(now), []); + assert.deepEqual(threadReadErrors({ ...now, thread: { parent: "context" } }), [], "the parent drawn as context, read by no part"); + await undoStructural(p.dir); + assert.equal((await manifest(p)).timeline[0].narration.takes.length, 1, "undone"); +}); + +test("set-item thread.parent.0=context on a piece the take reads RE-JOINS first (no TTS), then sets the knob; again: the knob alone; --no-reread: refused", async () => { + const p = await project("setitem", [item()]); + const cli = async (args) => { + const lines = []; + const errs = []; + const code = await postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => errs.push(s) }); + return { code, out: lines.join("\n"), err: errs.join("\n") }; + }; + const refused = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context", "--no-reread"]); + assert.notEqual(refused.code, 0); + assert.match(refused.err + refused.out, /drawn as context/); + const r = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context"]); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /re-read p-1 without parent:0: narration\/posts\/1\/take-3\.rejoin-orpheus\.wav/); + let e = (await manifest(p)).timeline[0]; + assert.deepEqual([e.narration.takes.length, e.narration.pick, e.thread.parent[0]], [2, 1, "context"]); + // Idempotent: the picked take reads no parent now -- the knob alone. + const again = await cli(["set-item", "setitem", "p-1", "thread.parent.0=context"]); + assert.equal(again.code, 0, again.err); + assert.doesNotMatch(again.out, /re-read/); + e = (await manifest(p)).timeline[0]; + assert.equal(e.narration.takes.length, 2); + // posts reread --dry-run: the plan only. + const dry = await cli(["reread", "setitem", "p-1", "--drop-parts", "1", "--dry-run"]); + assert.match(dry.err + dry.out, /only part|drops every part/); +}); diff --git a/umtool/lib/report/postThread.test.mjs b/umtool/lib/report/postThread.test.mjs @@ -70,7 +70,8 @@ test("set-item thread.*: the knobs merge; hiding a parent the read reads is REFU const ok = await cli(["set-item", "knobs", "p-1", "thread.shrink=0.5", "thread.dim=0.4"]); assert.equal(ok.code, 0, ok.err); assert.deepEqual((await manifest(p)).timeline[0].thread, { shrink: 0.5, dim: 0.4 }); - const bad = await cli(["set-item", "knobs", "p-1", "thread.parent=hidden"]); + // --no-reread keeps the guard's refusal (without it, set-item re-joins the take first: postReread.test.mjs). + const bad = await cli(["set-item", "knobs", "p-1", "thread.parent=hidden", "--no-reread"]); assert.notEqual(bad.code, 0); assert.match(bad.err, /part 1 reads the post it answers, which is drawn hidden.*thread\.parent=full/); assert.equal((await manifest(p)).timeline[0].thread.parent, undefined); @@ -100,6 +101,36 @@ test("the cut's thread knobs (posts narrate --cut thread.*), and the import stor 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"); +}); + test("set-item's censor knobs: a band in one knob, its edge, its style; off clears them", () => { assert.deepEqual(postItemPatchOf(["media.0.censor=below:0.38:blur"]).media, { 0: { blur: { on: true, band: { below: 0.38 }, style: "blur" } } }); assert.deepEqual(postItemPatchOf(["media.1.censor=between:0.2,0.6:pixelate:8"]).media, { 1: { blur: { on: true, band: { between: [0.2, 0.6] }, style: "pixelate", strength: 8 } } }); diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs @@ -13,8 +13,9 @@ // // Plain ESM: the CLI runs under bare node. import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; -import { partRoles, readPieces, threadLayout, threadReadErrors } from "umtool-report-to-video/post-thread"; +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 }) }; + 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,12 +112,12 @@ 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 }, null, 2)); + 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; } - out(`${project.id}: ${rows.length} narrated item(s) read in parts, ${rows.filter((r) => r.threaded).length} threaded, ${rows.filter((r) => r.errors.length).length} refused`); + out(`${project.id}: ${rows.length} narrated item(s) read in parts, ${rows.filter((r) => r.threaded).length} threaded, ${rows.filter((r) => r.errors.length).length} refused, ${rows.filter((r) => r.warnings.length).length} warned`); out(lines(rows).join("\n")); return 0; } @@ -124,6 +129,7 @@ function lines(rows) { for (const p of r.pieces) out.push(` parts ${p.parts.join(",")} ${p.role ?? "(no text on the card)"} ${p.source}${p.mode ? ` shown ${p.mode}` : ""} ${p.words} words`); for (const u of r.unread) out.push(` not read: ${u.scope} shown ${u.mode}`); for (const er of r.errors) out.push(` REFUSED: ${er}`); + for (const w of r.warnings ?? []) out.push(` WARNING: ${w}`); } return out; } diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -44,6 +44,14 @@ const ROLES_LINES = [ " words, an attachment's), stored or inferred, what the card shows for each, and the guard (umtool posts roles --help).", ]; +// `umtool posts reread` (postReread.mjs REREAD_USAGE): its lines, kept here so the usage is one block. +const REREAD_LINES = [ + " umtool posts reread <project> <item> [--without parent:0|parent:1|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]", + " a READ RE-JOINED without a piece (no TTS): the picked take's kept parts cut from its own file and joined again, a new", + " take that is picked (one undo point) -- the post it answers or quotes left unread, a part by number, a part that is", + " only a link. set-item thread.parent.<i>|quoted=context|hidden on a piece the take reads runs it first (--no-reread: refused).", +]; + // `umtool posts slurs` (postSlursCli.mjs SLURS_USAGE): its lines, kept here so the usage is one block. const SLURS_USAGE_LINES = [ " umtool posts slurs <project> [ls] | on | off | level strong|all | visual blackout|placeholder", @@ -101,6 +109,7 @@ export const POSTS_USAGE = [ " on screen (auto: full when read, carried in when it is the item before, else context), the shrink, dim and their", " seconds, the pan's seconds. A setting that would narrate a post the card hides is refused (umtool posts roles).", ...ROLES_LINES, + ...REREAD_LINES, " umtool posts narrate <project> … a post item's narration: script, takes (the editor's tts), pick, approve, mix", " (umtool posts narrate --help)", " umtool posts fit <project> [--all|<item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part", @@ -129,7 +138,7 @@ export const POSTS_USAGE = [ " umtool posts scenes <project> [on|off] [--json] the MEDIA SCENES: neighbours with the same attachment", ].join("\n"); -const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker"]); +const VALUED = new Set(["--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -401,7 +410,20 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); - if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out }); + if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out, reread: !flags.has("--no-reread") }); + if (verb === "reread") { + // A read re-joined without a piece (postReread.mjs): no TTS, a new take picked in one write. + const { REREAD_USAGE, rereadCommand } = await import("./postReread.mjs"); + if (!projectArg || !ref || flags.has("--help")) { + err(REREAD_USAGE); + return 2; + } + const list = (v) => (v === null ? [] : String(v).split(",").map((x) => x.trim()).filter(Boolean)); + const dropParts = list(flags.has("--drop-parts") ? str("--drop-parts") : null).map(Number); + return await rereadCommand(await projectOf(projectArg, root), ref, { without: list(flags.has("--without") ? str("--without") : null), dropParts, dropUrls: flags.has("--drop-urls"), dryRun, json, out }).catch((e) => { + throw e?.name === "RereadError" ? new CliError(e.message) : e; + }); + } if (verb === "narrate") { const { NARRATE_USAGE, narrateCommand } = await import("./postNarrationCli.mjs"); if (!projectArg || flags.has("--help")) { @@ -768,8 +790,9 @@ async function contextCommand(projectArg, { root, json, dryRun, out }) { for (const x of r.report) { if (x.state !== "filled") continue; const what = [ - x.quoted ? `quotes ${x.quoted.handle ? `@${x.quoted.handle}` : x.quoted.author ?? "?"}` : "", + x.quoted ? `quotes ${x.quoted.handle ? `@${x.quoted.handle}` : x.quoted.author ?? "?"}${x.quoted.via === "link" ? " (its status link, archived)" : ""}` : "", x.parents ? `answers ${x.parents[0]?.handle ? `@${x.parents[0].handle}` : x.parents[0]?.author ?? "?"}` : "", + x.conversation ? `conversation ${x.conversation}` : "", ].filter(Boolean).join(", "); out(` ${x.id} ${what}`); } @@ -780,7 +803,7 @@ async function contextCommand(projectArg, { root, json, dryRun, out }) { } /** `posts set-item`: a post item's knobs, through updatePostItem (`fit=read[:linger]`: posts fit, on this item). */ -async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { +async function setItemCommand(projectArg, ref, pairs, { root, json, out, reread = true }) { const fitPair = pairs.find((p) => /^fit=/.test(p)); if (fitPair) { if (pairs.length > 1) throw new CliError("fit= goes alone (it is posts fit on this item)"); @@ -820,12 +843,28 @@ async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref)); if (!hit) throw new CliError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + // A piece drawn context or hidden that its take READS (operator, 4 Nov: "we don't need to read this context"): the + // take re-joined without it first (postReread.mjs, no TTS) -- then the knob; one the take does not read: the knob alone. + // --no-reread keeps the guard's refusal. + let rejoined = null; + if (reread && patch.thread) { + const { piecesHidden, rereadTake, RereadError } = await import("./postReread.mjs"); + const pieces = piecesHidden(hit, patch.thread); + if (pieces.length) { + try { + rejoined = { pieces, ...(await rereadTake(project, hit, { without: pieces })) }; + } catch (e) { + throw e instanceof RereadError ? new CliError(e.message) : e; + } + } + } const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, hit.id, patch, { token: await manifestToken(project.dir) })); if (json) { - out(JSON.stringify({ ok: true, id: hit.id, entry: result.entry, token: result.token, editNotes }, null, 2)); + out(JSON.stringify({ ok: true, id: hit.id, entry: result.entry, token: result.token, editNotes, ...(rejoined ? { reread: { without: rejoined.pieces, take: rejoined.take.file } } : {}) }, null, 2)); return 0; } const { postItemSeconds } = await import("umtool-report-to-video/post-item"); + if (rejoined) out(`re-read ${hit.id} without ${rejoined.pieces.join(", ")}: ${rejoined.take.file} (${rejoined.take.seconds.toFixed(2)} s), picked -- no TTS`); out(`set ${hit.id}: ${postItemSeconds(result.entry).toFixed(1)} s${result.entry.hold ? ` (hold)` : ""}`); const refs = [["quoted", patch.quoted ? result.entry.quoted : null], ...Object.keys(patch.parents ?? {}).map((i) => [`parent ${i}`, result.entry.parents?.[Number(i)]])]; for (const [what, ref] of refs) if (ref) out(` ${what} (@${ref.handle ?? "?"}): ${ref.paraphrase ? `paraphrased -- "${ref.paraphrase}"` : "its own words"}`); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -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);", + " nothing moves across a section boundary: a conversation spanning sections is gathered within each (said)", " umtool timeline <project> groups [ls] [--json] the claim groups, by section: id, claim, clips", " umtool timeline <project> groups import <file> [--skip-missing] [--drop-empty] a claim-groups file", " ({sections: [{label, groups: [{claim, ids}]}]}) in ONE write: the cut re-ordered to it, its", @@ -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) in another section than their conversation's first)` : ""}`); + for (const l of json ? [] : g.left) out(` across a section: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another`); + return 0; + } + const { orderEntries } = await import("./manifest.mjs"); + 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.section !== undefined ? ` (section ${mv.section})` : ""}: ${mv.from.join(" ")} -> ${mv.to.join(" ")}`); + for (const l of g.left) out(` across a section: ${l.id} (section ${l.section}) -- its conversation's first, ${l.first}, is in another; gathered within its own section, never moved across`); + return 0; +} + 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"; @@ -6433,9 +6434,11 @@ 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, - // Its media scene (post-media-scene.mjs): neighbours with the same attachment, over the WHOLE cut's groups. + // 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), + // Its media scene (post-media-scene.mjs): neighbours with the same attachment, over the WHOLE cut's groups -- + // its attachment always, its card only when the conversation has no scene (read-follow.mjs: that one wins). mediaScene: mediaSceneById(manifest.timeline, entry.id, postGroups, render), }); if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr }); diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -89,7 +89,7 @@ import { wordZoomTimes } from "./word-zoom.mjs"; import { postAvatarFiles, validatePostAvatars } from "./post-avatars.mjs"; import { validatePostNarrationRender } from "./post-narration.mjs"; import { validatePostCombos } from "./post-combo.mjs"; -import { validateThreadReads } from "./post-thread.mjs"; +import { validateThreadReadWarnings, validateThreadReads } from "./post-thread.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -410,6 +410,8 @@ export function lintManifest(manifest, { if (!only) warnings.push(...deckClaimNotes(whole)); // Room at the clips' edges (render.room): a fetched window it can reach past. warnings.push(...roomWindowWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest)); + // A narrated post's read that says a link aloud (post-thread.mjs threadReadWarnings), with its fix. + warnings.push(...validateThreadReadWarnings(only ? { ...manifest, timeline: (manifest.timeline ?? []).filter((e) => e?.id === only) } : manifest)); for (const { where, src } of imageSrcsOf(manifest, { only })) { if (path.isAbsolute(src) || src.startsWith("~")) { diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -72,6 +72,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,453 @@ +// 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(5), 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): nothing moves across a + * section boundary -- a conversation that spans sections is gathered within + * each (its items there at their first place), and each item in another + * section than the conversation's first is reported (`left`). `only`: the + * conversation holding that id (its root, a post of it, an item's id). + * Returns `{ ids, moved: [{ root, section?, from: [ids], to: [ids] }], left: [{ id, root, section, first }] }`. + */ +export function gatheredOrder(timeline, render = undefined, { sectionOf = null, only = null } = {}) { + const tl = Array.isArray(timeline) ? timeline : []; + let ids = tl.map((e) => e?.id); + const moved = []; + const left = []; + const sec = (id) => (sectionOf ? sectionOf.get(id) : undefined); + for (const c of conversations(tl, render)) { + if (only && !(c.root === only || c.items.some((it) => it.id === only || it.post === only || it.chain.includes(only)))) continue; + const first = c.items[0]; + // One group a section (one group in all, with no sections), each in tree order. + const groups = new Map(); + for (const id of c.order) { + const k = sectionOf ? sec(id) : 0; + if (!groups.has(k)) groups.set(k, []); + groups.get(k).push(id); + if (sectionOf && k !== sec(first.id)) left.push({ id, root: c.root, section: k, first: first.id }); + } + for (const [k, mine] of groups) { + if (mine.length < 2) continue; + const pos = new Map(ids.map((id, n) => [id, n])); + const ats = mine.map((id) => pos.get(id)).sort((a, b) => a - b); + const lo = ats[0]; + const hi = ats[ats.length - 1]; + const span = ids.slice(lo, hi + 1); + const want = new Set(mine); + const next = [...mine, ...span.filter((id) => !want.has(id))]; + if (next.every((id, n) => id === span[n])) continue; + moved.push({ root: c.root, ...(sectionOf ? { section: k } : {}), from: span.filter((id) => want.has(id)), to: mine }); + ids = [...ids.slice(0, lo), ...next, ...ids.slice(hi + 1)]; + } + } + return { ids, moved, left }; +} diff --git a/umtool/report-to-video/post-conversation.test.mjs b/umtool/report-to-video/post-conversation.test.mjs @@ -0,0 +1,227 @@ +// 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"]); + // A conversation across a boundary is gathered within each section, never across it. + const two = new Map([["p-776", 0], ["p-779", 1], ["p-831", 1], ["p-848", 1]]); + const within = gatheredOrder([A, B, X, C], render, { sectionOf: two }); + assert.deepEqual(within.ids, ["p-776", "p-848", "p-779", "p-831"]); + assert.deepEqual(within.moved, [{ root: "771", section: 1, from: ["p-779", "p-848"], to: ["p-848", "p-779"] }]); +}); + +test("THE SCENE: each item opens on what its run left on screen -- an ancestor kept on top, the branch before collapsing away, the post the item before ended on in full", () => { + 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]), [["conv: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], ["conv:776", "scene", "collapse"], ["conv:834", "scene", "collapse"], ["conv: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("conv:848").from, row("conv:848").to], [[1, 1], [0, 0]]); + assert.deepEqual([row("conv:776").from, row("conv: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("conv:848").t0, row("parent:0").t0); + assert.equal(row("conv: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("conv:") ? { 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("conv:"), `${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("conv:") && 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", "conv:776", "conv:834", "conv:848", "parent:0", "post"]) assert.ok(at(sc) > 0, sc); + assert.ok(at("parent:1") < at("conv:776") && at("conv:776") < at("conv:834") && at("conv:834") < at("conv:848") && at("conv:848") < at("parent:0") && at("parent:0") < at("post"), "the tree's order"); + assert.match(html, /data-thread-slot="conv:848" data-thread-scene="collapse"/); + const scene = html.slice(at("conv: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="conv:848"'), red.indexOf('data-thread-slot="parent:0"')), /worthless/); + const fox = red.slice(red.indexOf('data-thread-slot="conv:834"'), red.indexOf('data-thread-slot="conv:848"')); + assert.match(fox, /data-redacted=""/); + assert.doesNotMatch(fox, /fox_one/); +}); + +test("A THREAD SCENE AND A MEDIA SCENE on one item: the conversation's scene wins the card; the media scene keeps only the attachment (post-media-scene.mjs's header)", async () => { + const { repeatGroups } = await import("./post-combo.mjs"); + const { mediaSceneOf, sceneEntry } = await import("./post-media-scene.mjs"); + const gif = (id) => [{ src: `posts-media/acct-x/${id}/${id}_1.mp4`, kind: "gif", seconds: 0.8, width: 500, height: 280 }]; + // A and C, one conversation (its id snapshotted on both; C's card shows only the stranger it answers), carrying + // the same GIF (the same bytes): both scenes want C's card. + const a = { ...A, conversation: "771", media: gif("776") }; + const c = { ...C, conversation: "771", parents: [FOX], media: gif("848") }; + const tl = [a, c]; + const groups = repeatGroups(tl, () => ({ sha256: "same" })); + const ms = mediaSceneOf(tl, 1, groups, render); + assert.ok(ms, "C is in a media scene with A"); + const ctx = planContext(tl, 1, render); + assert.ok(ctx.scene, "and in A's conversation's run"); + const shown = sceneEntry(c, ms); + assert.equal(shown.media[0].src, a.media[0].src, "the media scene keeps the attachment: the anchor's"); + const plan = postItemPlan(shown, render, { ...ctx, mediaScene: ms }); + const scopes = plan.follow.thread.tiles.map((t) => t.scope); + assert.ok(scopes.includes("conv:776"), "the conversation's scene draws the card (A's post, collapsing)"); + assert.ok(!scopes.some((sc) => sc.startsWith("scene:")), "no media-scene tile on it"); + // With no conversation scene, the media scene's column is drawn as before. + const alone = postItemPlan(shown, render, { prev: a, scene: null, mediaScene: ms }); + assert.ok(alone.follow.thread.tiles.some((t) => t.scope.startsWith("scene:")), "the media scene's earlier message above it"); +}); 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"; @@ -229,15 +229,17 @@ export function postItemSeconds(entry, render = undefined) { * scene's earlier messages in its card's column (`follow.thread`). The entry * is the one the scene plays (sceneEntry: the shared attachment the * anchor's): the caller makes it, so a channel's markup is laid on first. + * `scene` (post-conversation.mjs planContext): the posts its conversation's + * run left on screen -- it wins the card over a media scene. * * @param {Record<string, any>} entry * @param {Record<string, any>} [render] - * @param {{ prev?: Record<string, any> | null, mediaScene?: 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, mediaScene?: Record<string, any> | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it) * @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, mediaScene = null } = {}) { +export function postItemPlan(entry, render = undefined, { prev = null, scene = null, mediaScene = null } = {}) { const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; - return planOf(entry, render, hold, prev, mediaScene); + return planOf(entry, render, hold, prev, scene, mediaScene); } /** @@ -245,15 +247,16 @@ export function postItemPlan(entry, render = undefined, { prev = null, mediaScen * @param {Record<string, any> | undefined} render * @param {number | null} hold * @param {Record<string, any> | null} [prev] + * @param {Record<string, any> | null} [scene] * @param {Record<string, any> | null} [mediaScene] */ -function planOf(entry, render, hold, prev = null, mediaScene = null) { +function planOf(entry, render, hold, prev = null, scene = null, mediaScene = 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, mediaScene }); + const follow = followSchedule(entry, render, { hold, narration: sch, prev, scene, mediaScene }); const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) }; if (sch && k.attach === "after") { const voiceOnly = round3(sch.at + sch.seconds + k.tail); @@ -421,6 +424,8 @@ function refErrors(r, where) { } if (r.handle !== undefined && (typeof r.handle !== "string" || !HANDLE_RE.test(r.handle))) errors.push(`${where}.handle must be a handle`); if (r.badge !== undefined && r.badge !== null && !BADGES.includes(r.badge)) errors.push(`${where}.badge must be one of ${BADGES.join(", ")}`); + // How it was found: "link" -- a status link in the post's words, resolved to an archived post (postContext.mjs). + if (r.via !== undefined && r.via !== "link") errors.push(`${where}.via must be "link" (a status link resolved to an archived post)`); if (typeof r.text === "string" && r.text.length > TEXT_MAX) errors.push(`${where}.text is longer than ${TEXT_MAX} characters`); if (r.paraphrase !== undefined) { if (typeof r.paraphrase !== "string") errors.push(`${where}.paraphrase must be a string (your retelling of its words; absent: its own words)`); @@ -456,6 +461,8 @@ export function validatePostItem(e) { if (!isObj(e.repostedBy) || typeof e.repostedBy.handle !== "string" || !HANDLE_RE.test(e.repostedBy.handle)) errors.push(`${w}.repostedBy must be { author?, handle }`); } if (e.quoted !== undefined) errors.push(...refErrors(e.quoted, `${w}.quoted`)); + // The conversation it is part of (postContext.mjs: the archive row's threadId, snapshotted; post-conversation.mjs). + if (e.conversation !== undefined && !(typeof e.conversation === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(e.conversation))) errors.push(`${w}.conversation must be the conversation's id (a string)`); if (e.parents !== undefined) { if (!Array.isArray(e.parents)) errors.push(`${w}.parents must be a list (the posts it answers, nearest first)`); else { @@ -914,7 +921,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) }; // A MEDIA SCENE (post-media-scene.mjs): the scene's earlier messages, oldest first, each drawn as its own post tile was. for (const t of tiles) { if (t.scope.startsWith("scene:") && isObj(t.entry)) tileHtml.push(sceneTileHtml(t, { k, pal, size: (text) => sizeFor(text, innerW, innerH - 170 * k), redaction, avatars })); @@ -933,11 +942,19 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p ); } const qmode = q ? tmode("quoted") : null; + // Read before his words, the quoted post is its own tile ABOVE his post (post-thread.mjs threadLayout's + // quotedAt), labelled, at the size that fits it alone; read after them (or not), inside his post. + const qabove = !!tiles.find((t) => t.scope === "quoted")?.above; let quotedTile = ""; if (q && qmode && qmode !== "hidden") { const qsize = sizeFor(contextText(q), innerW - Math.round(36 * k), innerH - 140 * k); for (const kk of cut("quoted") ?? []) cutCss.push(`[data-thread-tile="quoted"] [data-post-block="${kk}"]`); - quotedTile = `<div class="tslot" data-thread-slot="quoted"><div class="tile quoted" data-thread-tile="quoted" data-thread-mode="${qmode}" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(36 * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${qmode === "excerpt" ? '<span class="plabel" data-thread-excerpt="">excerpt</span>' : ""}${paraLabel(q)}</div><div class="qtext tt"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""} style="font-size:${Math.round(qsize * 0.9)}px">${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"), blk("quoted"))}</div></div></div>`; + const label = qabove ? '<span class="plabel" data-thread-quoted-label="">quoted</span>' : ""; + quotedTile = `<div class="tslot" data-thread-slot="quoted"${qabove ? ' data-thread-above=""' : ""}><div class="tile quoted${qabove ? " tabove" : ""}" data-thread-tile="quoted" data-thread-mode="${qmode}" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round((qabove ? 44 : 36) * k), img: pic(q) })}${nameHtml(q, { redact: red("quoted"), cls: qabove ? "big" : "" })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span>${label}${qmode === "excerpt" ? '<span class="plabel" data-thread-excerpt="">excerpt</span>' : ""}${paraLabel(q)}</div><div class="qtext tt"${isParaphrased(q) ? ' data-post-paraphrase=""' : ""} style="font-size:${qabove ? qsize : Math.round(qsize * 0.9)}px">${wordsHtml(contextText(q), blurred, "quoted", hlOf("quoted"), blk("quoted"))}</div></div></div>`; + } + if (qabove && quotedTile) { + tileHtml.push(quotedTile); + quotedTile = ""; } const own = cardText(entry); const psize = own.trim() ? sizeFor(own, innerW, innerH - 170 * k) : size; @@ -945,11 +962,28 @@ 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(5))}"${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; }` : "", }; }; + // NOTHING READ IS CLAMPED (post-thread.mjs): a context post's 4-5 line clamp (.ptext/.qtext) is on the plain + // card only, where no part reads it (a read one makes the card threaded, its tiles unclamped -- .tt -- or the + // guard refuses it with follow off); the strip's one-line ellipsis and a long link's "…" only touch words no + // part reads (links are never read: post-narration.mjs dropUrls). const tc = threaded ? threadCard(L.card) : null; const body = strip ? `${stripHtml}${slot}` : `${tc ? tc.html : card(L.card)}${slot}`; const minSize = tc ? size : follow ? followMin : Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k); @@ -1011,7 +1045,8 @@ b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } .tpost { display: flex; flex-direction: column; gap: ${Math.round(16 * k)}px; } .tile .tt { display: block; -webkit-line-clamp: none; overflow: visible; line-height: ${LINE}; color: ${pal.fg}; margin-top: ${Math.round(6 * k)}px; } .twords { line-height: ${LINE}; overflow-wrap: anywhere; } -.tile.quoted .tt { color: ${mixHex(pal.fg, pal.bg, 0.08)}; }${tc.css}` : ""}${highlight ? ` +.tile.quoted .tt { color: ${mixHex(pal.fg, pal.bg, 0.08)}; } +.tile.quoted.tabove .tt { color: ${pal.fg}; }${tc.css}` : ""}${highlight ? ` [data-w-hl] { background: ${rgbaOf(highlight.color, WORD_ZOOM_HIGHLIGHT_ALPHA)}; box-shadow: inset 0 -0.12em 0 ${highlight.color}; border-radius: 0.16em; padding: 0 0.08em; margin: 0 -0.08em; -webkit-box-decoration-break: clone; box-decoration-break: clone; }` : ""} ${BAR_CSS(pal.fg)} </style></head> diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -57,6 +57,8 @@ export const POST_TAKE_ENGINES = Object.freeze([...POST_NARRATION_ENGINES, "reco * read as their source (takeSourceOf). */ export const POST_DERIVE_OPS = Object.freeze(["enhance", "convert"]); +/** The ops umtool runs itself on a take's own file (no editor job): `rejoin` -- its kept parts cut out and joined again (lib/report/postReread.mjs). */ +export const POST_LOCAL_OPS = Object.freeze(["rejoin"]); /** The editor's op route for each. */ export const POST_DERIVE_ROUTES = Object.freeze({ enhance: "/api/ops/voice-enhance", convert: "/api/ops/voice-convert" }); @@ -169,7 +171,7 @@ const MIX_KEYS = ["lead", "tail", "ramp", "linger", "clip", "wet", "lowpassHz", const RENDER_KEYS = new Set([...MIX_KEYS.filter((k) => k !== "attach"), "engine", "voice", "follow", "thread"]); const ITEM_KEYS = new Set([...MIX_KEYS, "script", "excerpt", "engine", "voice", "speed", "takes", "pick", "approved", "off", "window"]); const TAKE_KEYS = new Set(["file", "engine", "voice", "seconds", "script", "at", "note", "speed", "lufs", "jobId", "parts", "label", "source", "steps", "words", "slurs"]); -const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job"]); +const STEP_KEYS = new Set(["op", "engine", "voice", "params", "ranAt", "job", "drop"]); // `role` (post-thread.mjs): the text a part reads -- "post", "quoted", "parent:<i>", "media:<i>"; `voice`, `piece`: the batch's. const PART_KEYS = new Set(["n", "para", "text", "file", "start", "seconds", "gapBefore", "note", "at", "jobId", "role", "voice", "piece"]); const VOICE_RE = /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/; @@ -394,10 +396,87 @@ export function speakShouts(script) { }).join(""); } +// --------------------------------------------------------------------------- +// LINKS ARE NEVER SPOKEN (operator, 4 Nov: a quoted post's links were read +// aloud -- "https://. web.archive.org slash web slash 2021032015 ..."). X +// draws a long link over lines ("https://" / "web.archive.org/web/2021…" / +// "1733/https://twitter.com/…" / "…"), so the old `https?://\S+` ate only its +// first line. The link is put back together first, then dropped whole. +// --------------------------------------------------------------------------- + +/** The top-level domains a bare `host.tld/…` link is recognised by (no scheme, no www.). */ +const URL_TLDS = "com|org|net|io|co|tv|gg|me|ly|be|us|uk|ca|de|fr|ru|jp|app|dev|xyz|info|live|link|news|site|online|social|art|fm|to|is|ph|li|gl|eu|au|nz|in|sh|so|ai|cc|ws|biz|edu|gov"; +/** A host as a voice would say it (no path): a domain on one of those. */ +const HOST_RE = new RegExp(`\\b(?:[a-z0-9-]+\\.)+(?:${URL_TLDS})\\b`, "gi"); +/** A link as written: a scheme, a www., a bare host.tld/path, or X's t.co. */ +const URL_RE = new RegExp(`(?:https?:\\/\\/\\S*|\\bwww\\.[^\\s]+|\\b(?:[a-z0-9-]+\\.)+(?:${URL_TLDS})\\/\\S*|\\bt\\.co\\/\\S+)`, "gi"); +/** A line ending in a link (its last token one). */ +const ENDS_IN_LINK = /(?:https?:\/\/|\bwww\.|\b(?:[a-z0-9-]+\.)+(?:com|org|net|io|co|tv|gg|me|ly|be|app|dev|xyz)\/)\S*$/i; +/** What a link's continuation line looks like: one token of a link's characters. */ +const LINK_TAIL = /^[\w\-./?=&%#:~+@!,;]+$/; +/** X's "…" after a link cut short. */ +const ELLIPSIS_LINE = /^(?:…|\.{3})$/; + +/** + * A text with X's SPLIT LINKS put back on one line: "https://" and the host on + * the next line joined, a link's continuation lines (one token, a link's + * characters, with a "/" or all digits) joined onto it, and a lone "…" line + * after a link dropped. Pure. + */ +export function joinSplitLinks(text) { + const lines = String(text ?? "").replace(/(https?:\/\/)[ \t]*\n[ \t]*(?=\S)/gi, "$1").split("\n"); + const out = []; + for (const raw of lines) { + const line = raw.trim(); + const last = out.length ? out[out.length - 1] : null; + const linked = last !== null && ENDS_IN_LINK.test(last.trim()); + if (linked && line && LINK_TAIL.test(line) && (line.includes("/") || /^\d+$/.test(line))) { + out[out.length - 1] = `${last.replace(/\s+$/, "")}${line}`; + continue; + } + if (linked && ELLIPSIS_LINE.test(line)) continue; + out.push(raw); + } + return out.join("\n"); +} + +/** A text with every link dropped (joinSplitLinks first). */ +export function dropUrls(text) { + return joinSplitLinks(text).replace(URL_RE, " "); +} + +/** + * WHAT A READ WOULD SAY THAT IS A LINK, pure: the links (and the pieces a + * voice reads of one -- "https:", "web.archive.org", "1733/") in `text`, a + * script or a part's words. Empty: nothing a voice would say is a link. + */ +export function spokenUrls(text) { + // A voice's "slash" put back, so a spelled-out link is one again. + const t = joinSplitLinks(String(text ?? "")).replace(/\s+slash\s+/gi, "/"); + const out = []; + for (const m of t.matchAll(URL_RE)) out.push(m[0]); + // A link a script already spelled out ("https://. web.archive.org slash web slash …"): its scheme, a host. + const rest = t.replace(URL_RE, " "); + for (const m of rest.matchAll(/\bhttps?:\/*/gi)) out.push(m[0]); + for (const m of rest.matchAll(HOST_RE)) if (!/^(?:e\.g|i\.e)$/i.test(m[0])) out.push(m[0]); + return out; +} + +/** Whether `text` is only links (and the dots, slashes and digits a split link leaves): a part that is nothing but one. */ +export function isOnlyUrls(text) { + const t = joinSplitLinks(String(text ?? "")).replace(/\s+slash\s+/gi, "/"); + if (!spokenUrls(t).length) return false; + return !t + .replace(URL_RE, " ") + .replace(/\bhttps?:\/*/gi, " ") + .replace(HOST_RE, " ") + .replace(/[\d\s./:…,;!?\-]+/g, "") + .trim(); +} + export function speakableText(text) { - const clean = String(text ?? "") + const clean = dropUrls(String(text ?? "")) .replace(/^RT @[A-Za-z0-9_]+:\s*/, "") - .replace(/https?:\/\/\S+/g, " ") .replace(/(^|[\s(])@[A-Za-z0-9_]{1,30}\b/g, "$1") .replace(/[\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}\u{FE0F}\u{200D}\u{20E3}]/gu, "") .replace(/\b(\w+)\(s\)/g, "$1s") @@ -543,8 +622,12 @@ export function validatePostNarration(e) { if (t.steps !== undefined) { if (!Array.isArray(t.steps) || t.steps.length > 20) errors.push(`${tw}.steps must be a list (at most 20)`); else t.steps.forEach((st, k) => { - if (!isObj(st) || !POST_DERIVE_OPS.includes(st.op)) errors.push(`${tw}.steps[${k}].op must be one of ${POST_DERIVE_OPS.join(", ")}`); - else for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + if (!isObj(st) || !(POST_DERIVE_OPS.includes(st.op) || POST_LOCAL_OPS.includes(st.op))) errors.push(`${tw}.steps[${k}].op must be one of ${[...POST_DERIVE_OPS, ...POST_LOCAL_OPS].join(", ")}`); + else { + for (const key of Object.keys(st)) if (!STEP_KEYS.has(key)) errors.push(`${tw}.steps[${k}].${key} is not a step key`); + // A re-join's record: what it left out (a piece, "part <n>", "url"). + if (st.drop !== undefined && !(Array.isArray(st.drop) && st.drop.length <= 200 && st.drop.every((d) => typeof d === "string"))) errors.push(`${tw}.steps[${k}].drop must be a list of what it left out`); + } }); } if (t.parts !== undefined) { diff --git a/umtool/report-to-video/post-narration.test.mjs b/umtool/report-to-video/post-narration.test.mjs @@ -7,6 +7,7 @@ import { POST_NARRATION_DEFAULTS, draftScript, dryGainAt, isNarrated, mixPhaseAt, narrationLevelDb, narrationSchedule, nextTakeNumber, pickedTake, speakShouts, postNarrationDisclosure, postNarrationFilters, postNarrationKnobs, readSpanSeconds, speakableText, takeFileOf, validatePostNarration, validatePostNarrationRender, wetGainAt, narrationRateOf, partAt, partStartOnItem, readSecondsOf, + dropUrls, isOnlyUrls, joinSplitLinks, spokenUrls, } from "./post-narration.mjs"; import { POST_PICTURE_MIN, mediaTimeAt, postItemFiles, postItemPlan, postItemSeconds, postLayout, ruleSeconds, validatePostItem } from "./post-item.mjs"; import { postSegmentArgs } from "./post-render.mjs"; @@ -237,6 +238,22 @@ test("SCRIPTS ARE THE POST, VERBATIM: cleaned for pronunciation only, never an e assert.equal(draftScript("RT @someone: hello there").script, "hello there"); }); +test("LINKS ARE NEVER SPOKEN: X's link split over lines is put back together and dropped whole -- its \"…\" line too; a spelled-out link is still found", () => { + const q = "THIS IS THE FINDING OUT STAGE STRAWB.\n\nhttps://\nweb.archive.org/web/2021032015\n1733/https://twitter.com/someone/status/1373102987070017537\n…\n\nhttps://\nweb.archive.org/web/2021032004\n0213/https://twitter.com/other/status/1373122620334477314\n…"; + assert.equal(joinSplitLinks(q), "THIS IS THE FINDING OUT STAGE STRAWB.\n\nhttps://web.archive.org/web/20210320151733/https://twitter.com/someone/status/1373102987070017537\n\nhttps://web.archive.org/web/20210320040213/https://twitter.com/other/status/1373122620334477314"); + assert.equal(speakableText(q), "this is the finding out stage strawb!"); + assert.deepEqual(spokenUrls(speakableText(q)), []); + // www., a bare host with a path, X's t.co: gone; "e.g." and a name with a dot are words. + assert.equal(dropUrls("go to www.foo.com/bar, t.co/abc or kiwifarms.net/threads/1 e.g. Mr.Obvious").replace(/\s+/g, " "), "go to or e.g. Mr.Obvious"); + // A script that already says one (the old draft's): found, and a part that is nothing else is whole. + const said = "https://. web.archive.org slash web slash 2021032015. 1733/. …"; + assert.deepEqual(spokenUrls(said), ["https://.", "web.archive.org/web/2021032015."]); + assert.equal(isOnlyUrls(said), true); + assert.equal(isOnlyUrls("read this https://x.com/a/b before you go"), false); + assert.equal(isOnlyUrls("no link here at all"), false); + assert.deepEqual(spokenUrls("I said it twice, e.g. here and there."), []); +}); + test("the validator: shapes, tags, takes, the pick, the cut's knobs; the build's files", () => { assert.deepEqual(validatePostNarration(post({ narration: narr(5) })), []); const bad = validatePostNarration(post({ narration: { script: "hi <whisper>", takes: [{ file: "/abs.wav", seconds: -1 }], pick: 3, wet: 2, short: "freeze", bogus: 1 } })); 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 @@ -442,12 +442,13 @@ 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), `prev` the timeline entry - * before it (post-thread.mjs carries a parent that is it), and `mediaScene` - * its media scene (post-media-scene.mjs mediaSceneOf: the attachment the - * anchor's, the scene's earlier messages above its card). Returns the - * segment's path. + * before it (post-thread.mjs carries a parent that is it), `scene` the posts + * its conversation's run left on screen (post-conversation.mjs planContext), + * and `mediaScene` its media scene (post-media-scene.mjs mediaSceneOf: the + * attachment the anchor's, the scene's earlier messages above its card -- not + * drawn when `scene` is). 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, mediaScene = null }) { +export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {}, avatars = {}, redaction = null, prev = null, scene = null, mediaScene = 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); // In a media scene (post-media-scene.mjs) the shared attachment is the anchor's -- its markup laid on too. @@ -456,8 +457,9 @@ export async function buildPostSegment(entry, { render, outDir, manifestDir, box 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, mediaScene }); + // `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) -- in plan.follow, so in the segment's key; a media scene too. + const plan = postItemPlan(entry, render, { prev, scene, mediaScene }); 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 @@ -49,9 +49,10 @@ // bench, the writers and the lint all read the same rules from here. import { cardText, contextText, parentsOf } from "./post-item.mjs"; -import { draftScript, isNarrated, pickedTake, scriptParts } from "./post-narration.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 + * `conv:<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) { @@ -269,13 +277,71 @@ export function threadLayout(entry, render = undefined, { prev = null } = {}) { if (mode === "carry" && isRead) mode = "full"; tiles.push({ scope, mode, read: isRead }); } - tiles.push({ scope: "post", mode: "full", read: read.has("post") }); + // THE QUOTED POST (operator, 4 Nov: the quote read first while it sat under his words -- "the card opens + // scrolled down"): read BEFORE his words, it is its own tile ABOVE his post, read in full and lit, then + // shrunk and dimmed like a parent as his words come in; read after them (or not at all), inside his post. + const postAt = roles.findIndex((r) => r.role === "post"); + const quotedFirst = roles.findIndex((r) => r.role === "quoted"); + const quotedAt = quotedFirst >= 0 && (postAt < 0 || quotedFirst < postAt) ? "above" : "inside"; + const post = { scope: "post", mode: "full", read: read.has("post") }; if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) { const m = k.quoted === "auto" ? (read.has("quoted") ? "full" : "context") : k.quoted; - tiles.push({ scope: "quoted", mode: m, read: read.has("quoted") }); - } - const on = isNarrated(entry) && tiles.some((t) => t.scope !== "post" && t.mode !== "hidden"); - return { on, tiles, roles }; + const q = { scope: "quoted", mode: m, read: read.has("quoted"), ...(quotedAt === "above" && m !== "hidden" && m !== "context" ? { above: true } : {}) }; + if (q.above) tiles.push(q, post); + else tiles.push(post, q); + } else tiles.push(post); + 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: `conv:${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(5)) ?? 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). */ @@ -294,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)`; @@ -350,9 +416,9 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { const ts = p.parts.map((n) => startOfPart.get(n)).filter(fin); return { ...p, start: ts.length ? Math.min(...ts) : null }; }).filter((p) => p.start !== null && p.role); - // A tile's pieces (the quoted post reads inside his post's tile: the post tile shows for both). - const tileOf = (role) => (role === "quoted" ? "quoted" : role); - const firstRead = (scope) => pieces.find((p) => tileOf(p.role) === scope || (scope === "post" && p.role === "quoted"))?.start ?? null; + // A tile's pieces (a quoted post inside his post's tile: the post tile shows for both; above it, its own). + const above = layout.quotedAt === "above"; + const firstRead = (scope) => pieces.find((p) => p.role === scope || (scope === "post" && p.role === "quoted" && !above))?.start ?? null; /** The start of the first piece after the last piece of `scope` that is of another tile. */ const after = (scope) => { let last = -1; @@ -369,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) { @@ -379,10 +446,19 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { if (t.scope === "post") { // His post: revealed when its first piece (or the quoted post inside it) starts, when something else is read first. const T = firstRead("post"); - if (revealed("post", T) && (carried || first.role !== "quoted")) { + if (revealed("post", T) && (carried || above || first.role !== "quoted")) { 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; @@ -396,20 +472,23 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4 }) { // Read: in full while it is read, then small and dim (a quoted post only dims) as the next piece starts. const T = after(t.scope); const T0 = firstRead(t.scope); - if (t.scope !== "quoted" && revealed(t.scope, T0)) { + // A quoted post above his: a top-level tile like a parent (revealed, shrunk); inside his: it only dims. + const own = t.scope !== "quoted" || !!t.above; + if (own && revealed(t.scope, T0)) { // Revealed when its read comes (an older post read before it). row.from = [1, 0]; row.to = [1, 1]; Object.assign(row, win(T0)); if (T !== null) row.then = { to: small, ...win(T) }; } else if (T !== null) { - row.to = t.scope === "quoted" ? [1, k.dim] : small; + row.to = own ? small : [1, k.dim]; Object.assign(row, win(T)); } } + if (t.above) row.above = true; tiles.push(row); } - return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, tiles }; + return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, quotedAt: above ? "above" : "inside", tiles }; } /** inOut cubic over [0, 1]. */ @@ -469,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("conv:") && y >= t.top - 0.5) d += (1 - t.s) * t.gap; } return y - d; }; @@ -479,6 +560,70 @@ export function threadGeoAt(geo, scales) { return { C: shift(geo?.C ?? 0), blocks, tiles: tileTops }; } +// --------------------------------------------------------------------------- +// THE WARNINGS: what a read says that is not on its card, short of the guard. +// --------------------------------------------------------------------------- + +/** + * WHERE A PICKED TAKE SAYS A LINK (post-narration.mjs spokenUrls), pure: + * `{ parts: [k…], words: [link…], whole, script }` -- the parts that say one + * (k from 0), what they say, and whether each of them is nothing but links + * (`whole`: dropping them is the fix, `posts reread … --drop-urls`; else a + * re-take). A take read in one go: its script (`script` true, no parts). + * Null when it says none. + */ +export function urlParts(entry) { + const t = pickedTake(entry); + if (!t) return null; + const parts = Array.isArray(t.parts) ? t.parts : []; + if (parts.length) { + const hit = parts.map((p, k) => ({ k, urls: spokenUrls(p?.text) })).filter((x) => x.urls.length); + if (!hit.length) return null; + return { parts: hit.map((x) => x.k), words: hit.flatMap((x) => x.urls), whole: hit.every((x) => isOnlyUrls(parts[x.k].text)), script: false }; + } + const urls = spokenUrls(str(t.script).trim() ? t.script : entry?.narration?.script); + return urls.length ? { parts: [], words: urls, whole: false, script: true } : null; +} + +/** + * Post item `entry`'s read WARNINGS (the build's lint says them, never + * refuses): a take that says a link aloud, with its fix. + */ +export function threadReadWarnings(entry) { + if (!isNarrated(entry)) return []; + const id = entry?.id ?? "?"; + const out = []; + const u = urlParts(entry); + if (u) { + const said = [...new Set(u.words)].slice(0, 2).map((w) => `"${w.length > 40 ? `${w.slice(0, 39)}…` : w}"`).join(", "); + const where = u.script ? "its read says" : `part${u.parts.length === 1 ? "" : "s"} ${u.parts.map((k) => k + 1).join(", ")} of its take say${u.parts.length === 1 ? "s" : ""}`; + const fix = u.whole + ? `drop ${u.parts.length === 1 ? "it" : "them"} (umtool posts reread <p> ${id} --drop-urls)` + : `re-make the take on a script without it (umtool posts narrate <p> ${id} --take; a drafted script drops links)`; + out.push(`timeline ${id}: ${where} a link aloud (${said}) -- ${fix}`); + } + // A text the archive kept cut short (X's "…" or "Show more", not a link's): the read and the card stop mid-thought. + const roles = new Set(partRoles(entry).map((r) => r.role).filter(Boolean)); + const texts = [["post", "his words", entry?.text], ["quoted", "the post it quotes", entry?.quoted?.text], ...parentsOf(entry).map((p, i) => [`parent:${i}`, i ? "the post that one answers" : "the post it answers", p?.text])]; + for (const [scope, name, text] of texts) { + if ((scope !== "post" && !roles.has(scope)) || !isTruncated(text)) continue; + out.push(`timeline ${id}: ${name} (${scope}) ends cut short in the archive ("…") -- the read stops mid-thought; re-fetch the post (umtool posts context <p>, or the editor's capture) or paraphrase it`); + } + return out; +} + +/** Whether an archived text ends CUT SHORT: X's "…" or "Show more" at its end that is not a link's (joinSplitLinks drops those). */ +export function isTruncated(text) { + const t = joinSplitLinks(str(text)).trim(); + return /…$/.test(t) || /\bshow more$/i.test(t); +} + +/** THE WARNINGS over a cut (the build's lint): every narrated post item's (threadReadWarnings). */ +export function validateThreadReadWarnings(manifest) { + const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + return tl.filter((e) => e?.type === "post").flatMap((e) => threadReadWarnings(e)); +} + /** * THE GUARD over a cut (the build's lint): every post item's read against * what its card shows (threadReadErrors), each with the item before it. @@ -488,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 @@ -10,6 +10,7 @@ import { validatePostNarrationRender } from "./post-narration.mjs"; import { followPath, followStateAt, followStateKey } from "./read-follow.mjs"; import { THREAD_DEFAULTS, partRoles, readPieces, threadGeoAt, threadKnobs, threadLayout, threadReadErrors, threadStateAt, tileStateAt, validateThreadReads, + threadReadWarnings, urlParts, validateThreadReadWarnings, isTruncated, } from "./post-thread.mjs"; const PARENT = "The first thing anyone notices is the noise from the street.\n\nThen the lights in the hall go out without warning.\n\nNobody had planned for any of this at all."; @@ -160,6 +161,7 @@ test("THE INVARIANT: every part's time span lies inside its block's on-screen, h ["a quoted post read first", narrate(base({ quoted: { author: "Other", handle: "other", text: `${QUOTED}\n\n${PARENT}` } }), [[`${QUOTED}\n\n${PARENT}`], [REPLY]]), null], ["two parents, then him", narrate(base({ parents: [parentRef({ id: "901", handle: "second_one", text: "Is anyone else hearing the street noise again tonight?" }), parentRef()] }), [[PARENT], ["Is anyone else hearing the street noise again tonight?"], [REPLY]]), null], ["a carried parent", narrate(base({ parents: [parentRef()] }), [[REPLY]]), { post: "acct-x/900" }], + ["a quoted post read after his words", narrate(base({ quoted: { author: "Other", handle: "other", text: QUOTED } }), [[REPLY], [QUOTED]]), null], ]; for (const [what, e, prev] of cases) { const render = { postNarration: { lead: 0.4 } }; @@ -178,13 +180,17 @@ test("THE INVARIANT: every part's time span lies inside its block's on-screen, h const st = followStateAt(plan.follow, path, s); const [sc, op] = st.tiles[blk.scope]; assert.equal(sc, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile (${blk.scope}) in full`); - if (blk.scope !== "quoted") assert.equal(op, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile at full strength`); + // A quoted post read first is its own tile above his post: at full strength like any other. + if (blk.scope !== "quoted" || plan.follow.thread.quotedAt === "above") assert.equal(op, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its tile at full strength`); else assert.equal(st.tiles.post[1], 1, `${what}: the post the quoted post is in, shown`); assert.equal(st.op[blk.k] ?? 1, 1, `${what}: part ${k + 1} at ${s.toFixed(2)} s -- its block lit`); assert.equal(st.current, blk.k, `${what}: part ${k + 1} is the block being read`); 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. @@ -220,3 +226,61 @@ test("a take read in one go (no parts): its script's paragraphs carry the roles assert.deepEqual(plan.follow.thread.tiles.map((t) => [t.scope, t.mode]), [["parent:0", "full"], ["post", "full"]]); assert.deepEqual(threadReadErrors(e), []); }); + +test("A READ NEVER SAYS A LINK: a take whose parts say one is warned, with the fix -- drop the parts that are nothing but links, else a re-take", () => { + const quoted = { author: "Other", handle: "other", text: `${QUOTED}\n\nhttps://\nweb.archive.org/web/2021032015\n1733/https://twitter.com/x/status/1\n…` }; + const e = narrate(base({ quoted }), [[`${QUOTED}\n\nhttps://. web.archive.org slash web slash 2021032015. 1733/. …`], [REPLY]]); + const u = urlParts(e); + assert.deepEqual(u.parts, [1]); + assert.equal(u.whole, true); + assert.match(threadReadWarnings(e)[0], /timeline p-1: part 2 of its take says a link aloud \("https:\/\/\.", .*umtool posts reread <p> p-1 --drop-urls/); + // A link inside words: a re-take. + const mixed = narrate(base({ quoted }), [[`${QUOTED} See https://x.com/a/b for more.`], [REPLY]]); + assert.match(threadReadWarnings(mixed)[0], /part 1 of its take says a link aloud.*re-make the take/); + // None: no warning; over a cut, every narrated post item's. + assert.deepEqual(threadReadWarnings(narrate(base({ quoted }), [[QUOTED], [REPLY]])), []); + assert.equal(validateThreadReadWarnings({ timeline: [e, base({ id: "p-2" })] }).length, 1); +}); + +test("QUOTES READ IN PLACE: read before his words, the quoted post is its own tile ABOVE his post -- in full and lit, then shrunk and dimmed as his words come in under it; read after them, inside his post", () => { + const quoted = { author: "Other", handle: "other", text: QUOTED }; + const first = narrate(base({ quoted }), [[QUOTED], [REPLY]]); + const L = threadLayout(first); + assert.equal(L.quotedAt, "above"); + assert.deepEqual(L.tiles.map((t) => [t.scope, t.mode, !!t.above]), [["quoted", "full", true], ["post", "full", false]]); + const plan = postItemPlan(first, { postNarration: { lead: 0.4 } }); + const th = plan.follow.thread; + assert.equal(th.quotedAt, "above"); + const q = th.tiles.find((t) => t.scope === "quoted"); + const post = th.tiles.find((t) => t.scope === "post"); + assert.deepEqual([q.from, q.to], [[1, 1], [THREAD_DEFAULTS.shrink, THREAD_DEFAULTS.dim]]); + assert.deepEqual([post.from, post.to], [[1, 0], [1, 1]]); + // The card opens on the quoted post: his post not yet shown, the flow not panned down to it. + assert.deepEqual(threadStateAt(th, 0.5), { quoted: [1, 1], post: [1, 0] }); + const html = postCardHtml(first, { width: 1600, height: 900, follow: true, thread: th }); + assert.ok(html.indexOf('data-thread-slot="quoted"') < html.indexOf('data-thread-slot="post"'), "the quoted tile is above his post's"); + assert.match(html, /data-thread-slot="quoted" data-thread-above=""><div class="tile quoted tabove"/); + assert.match(html, /data-thread-quoted-label="">quoted</); + // His tile closes the flow up under the quoted post as it shrinks (followStateAt's height counts it). + const geo = fakeGeo(plan); + const fp = followPath(plan.follow, geo); + assert.ok(fp.start < geo.tiles.quoted.top + 100 && fp.start < geo.tiles.post.top, "it opens on the quoted post, not scrolled down to his"); + // Read after his words: inside his post, as before. + const afterIt = narrate(base({ quoted }), [[REPLY], [QUOTED]]); + assert.equal(threadLayout(afterIt).quotedAt, "inside"); + const html2 = postCardHtml(afterIt, { width: 1600, height: 900, follow: true, thread: postItemPlan(afterIt, {}).follow.thread }); + assert.ok(html2.indexOf('data-thread-slot="quoted"') > html2.indexOf('data-thread-slot="post"'), "inside his post"); + assert.doesNotMatch(html2, /data-thread-above/); +}); + +test("TRUNCATED archive text: a text the read reads that ends in X's \"…\" (not a link's) is warned, naming the item and the piece", () => { + assert.equal(isTruncated("He said this and then…"), true); + assert.equal(isTruncated("Look\nhttps://\nx.com/a/status/1\n…"), false, "a link's ellipsis"); + assert.equal(isTruncated("Read the rest. Show more"), true); + assert.equal(isTruncated("A whole post."), false); + const cut = parentRef({ text: "The first thing anyone notices is the noise from the street and then…" }); + const e = narrate(base({ parents: [cut] }), [[cut.text], [REPLY]]); + assert.match(threadReadWarnings(e).join(" "), /timeline p-1: the post it answers \(parent:0\) ends cut short/); + // Not read, not warned (a context post shows only a strip of it). + assert.deepEqual(threadReadWarnings(narrate(base({ parents: [cut] }), [[REPLY]])), []); +}); diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -316,10 +316,13 @@ const wordsIn = (t) => scriptWordsOf(t).length; * @param {Record<string, any>} [render] * `o.mediaScene` (post-media-scene.mjs mediaSceneOf): the item's media scene -- * the scene's earlier messages drawn above the card as tiles of the column. + * `o.scene` (post-conversation.mjs planContext): the posts its conversation's + * run left on screen. A conversation scene WINS the card: with one, the media + * scene is not drawn (it keeps only the attachment, sceneEntry). * - * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] + * @param {{ hold?: number | null, narration?: Record<string, any> | null, prev?: Record<string, any> | null, scene?: Record<string, any> | null, mediaScene?: Record<string, any> | null }} [o] */ -export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, mediaScene = null } = {}) { +export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, scene = null, mediaScene = null } = {}) { const k = followKnobs(entry, render); if (!k.on) return null; const map = followBlocks(entry); @@ -367,12 +370,15 @@ 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 base = 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. + // THE THREAD SCENE WINS (post-media-scene.mjs's header): with one, no media scene is drawn on the card. + const ms = Array.isArray(scene?.tiles) && scene.tiles.length ? null : mediaScene; + const base = isNarrated(entry) ? threadLayout(entry, render, { prev, scene }) : null; // A MEDIA SCENE (post-media-scene.mjs): the scene's earlier messages above the card's own tiles -- a narrated // item's on its thread read's schedule, an un-narrated one's on the scene's. - const layout = mediaScene ? sceneLayout(base, entry, mediaScene) : base; + const layout = ms ? sceneLayout(base, entry, ms) : base; const own = !layout?.on ? null : base ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead }) : sceneSchedule(threadKnobs(entry, render), { layout, blocks, lead: FOLLOW_PAN.lead }); - const thread = mediaScene ? sceneRows(own, layout) : own; + const thread = ms ? sceneRows(own, layout) : own; return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}) }; } @@ -464,8 +470,9 @@ 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] && th.scene) { @@ -476,7 +483,9 @@ export function threadPath(follow, geo) { } else 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 = []; @@ -503,6 +512,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); @@ -577,8 +589,12 @@ 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]; - if (sc < 0.9995 && scope !== "quoted") C -= (1 - sc) * h; + // A scene tile (post-conversation.mjs) collapsing away takes the gap above it with it. + const gap = scope.startsWith("conv:") ? 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; } const below = C - (path?.H ?? 0) - offset; return { @@ -622,8 +638,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 = ""; @@ -647,12 +664,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; @@ -679,6 +698,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;