// 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

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, ownPictureOnly, parentsOf, refPictureOnly } from "./post-item.mjs"; import { pictureMediaOf, pictureRuleEntry } from "./post-picture.mjs"; import { isNarrated } from "./post-narration.mjs"; import { followKnobs } from "./read-follow.mjs"; import { joinKnobs } from "./post-join.mjs"; import { groupOf, 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)); // A MANUAL THREAD (`thread.group`): its items are one conversation whether X links them or not. if (groupOf(e)) out.add(`group:${groupOf(e)}`); return out; } /** * Whether an item plays in a run: a narrated post item that read-follows (its card can carry a scene) -- or any * read-following post item of a manual thread (`thread.group`: the post that opens it may be shown, not read). */ export const runsIn = (e, render) => e?.type === "post" && (isNarrated(e) || !!groupOf(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` -- 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); // A manual thread takes its own items only: consecutive items of one group are one run (in timeline order). const g = groupOf(e); const joins = cur && (g || cur.group ? g === cur.group : [...keys].some((k) => cur.keys.has(k))); if (joins) { cur.items.push(i); for (const k of keys) cur.keys.add(k); } else { cur = { items: [i], keys, group: g }; runs.push(cur); } runOf[i] = runs.length - 1; }); return { runOf, runs: runs.map((r) => { const tree = treeOf(r.items.map((i) => tl[i])); // A manual thread is stacked in the order its posts came on screen ("as if a thread"), not the tree's. const rank = r.group ? new Map([...tree.seen.entries()].sort((a, b) => a[1] - b[1] || idCmp(a[0], b[0])).map(([id], n) => [id, n])) : treeRank(tree, "seen"); return { items: r.items, tree, rank, group: r.group ?? null }; }), }; } /** 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, // An anonymous author (post-anon.mjs) stays one in another item's scene. ...(e?.anonymous === true ? { anonymous: true } : {}), date: str(e?.date) || undefined, text: cardText(e), redact: authors.find((a) => a.where === "author")?.redact === true, ...(parentsOf(e)[0] ? { replyTo: { id: str(parentsOf(e)[0].id), handle: str(parentsOf(e)[0].handle) } } : str(e?.replyingTo) ? { replyTo: { id: "", handle: str(e.replyingTo) } } : {}), src: { post: str(e?.post), scope: "text" }, // A PICTURE-ONLY post (post-picture.mjs) keeps its picture as context, as a text post keeps its words. ...(ownPictureOnly(e) ? { pictureOnly: true, media: pictureMediaOf(e) } : {}), }; } 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, ...(p.anonymous === true ? { anonymous: true } : {}), 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, ...(parentsOf(e)[i + 1] ? { replyTo: { id: str(parentsOf(e)[i + 1].id), handle: str(parentsOf(e)[i + 1].handle) } } : {}), src: { post: str(e?.post), scope: "parent", index: i }, ...(refPictureOnly(p) ? { pictureOnly: true, media: pictureMediaOf(p) } : {}), }; } 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); // A manual thread keeps every earlier post on screen (stacked, small and dim): none collapses away. scene = { tiles: end.map((t) => ({ id: t.id, ref: t.ref, from: t.id === prevId ? "full" : "small", action: run.group || anc.has(t.id) ? "keep" : "collapse" })), rank: Object.fromEntries(run.rank), ...(run.group ? { group: run.group } : {}), }; } // THE JOIN (post-join.mjs): an item of a run opens on the item before as it ended, its card morphing into its own. const join = r >= 0 && i > 0 && runOf[i - 1] === r && joinKnobs(e, render).on ? { seconds: joinKnobs(e, render).seconds } : null; const ctx = { prev, scene, join }; 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 = []; // An item that draws no scene (one shown, not read, in a manual thread): what the run had stays for the next. if (!isNarrated(e) && scene) for (const t of scene.tiles) if (t.action === "keep") end.push({ id: t.id, ref: t.ref }); 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:")) { // (The cut's picture-only rule laid on: off, a picture-only post is carried as its words alone, as before.) const ref = sceneRefOf(pictureRuleEntry(e, render), t.scope); // What it answers, from the run's tree when its own item does not carry it (the branch map's lines). const up = ref?.id ? runs[r].tree.parentOf.get(ref.id) : undefined; if (ref && !ref.replyTo && up) ref.replyTo = { id: up, handle: "" }; if (ref?.id && (str(ref.text).trim() || ref.pictureOnly)) 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>} timeline * @param {number} i * @param {Record} [render] * @returns {{ prev: Record | null, scene: { tiles: Array>, rank: Record, group?: string } | null, join: { seconds: 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, join: null }; const c = contextsOf(tl, render)[i]; return { prev: c.prev, scene: c.scene, join: c.join }; } /** 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, join: null } : planContext(tl, i, render); } // --------------------------------------------------------------------------- // The cut's conversations (`umtool timeline

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>} timeline * @param {Record} [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; } // A manual thread (`thread.group`) is gathered by its posts' DATES ("include the whole thread chronologically"). const grouped = members.some((x) => groupOf(x.e)); const dateOf = (x) => Date.parse(str(x.e?.date)); const order = grouped ? [...members].sort((a, b) => (dateOf(a) || Infinity) - (dateOf(b) || Infinity) || a.at - b.at).map((x) => x.e.id) : [...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

${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, ...(grouped ? { group: groupOf(members.find((x) => groupOf(x.e)).e) } : {}) }); } 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.group === 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 }; }