Archilyzer · Source

archilyzer

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

commit ec806eb251747dd6a91d68d5f045f1290d988491
parent efdc37ed31ce45e085c8cbaf332601413c638f2d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 23:06:36 -0500

umtool: a post item takes the quoted post and the parent its archive row lacks from the capture's context; umtool posts context

The capture now reads each X post's context (capture.json's `context`: the
post it quotes, the post it answers, as its page showed them). A post item
fills from it what the archive row lacks (postContext.mjs
applyCaptureContext): `quoted` where the entry has none, or a named one with
no words when it is the same post (its id, else its author); `parents` where
it has none. What the archive gave is never replaced.

Snapshotted when the entry is made: postReel.mjs's snapshot step (captureOf
returns the record's context; postEntryFrom calls the fill after its own
quoted/parents, the shown post's capture first, else the row's) -- so `posts
reel` and `timeline insert post:` take it. Refreshed by the new `umtool posts
context <project> [--dry-run] [--json]`: every post item at once, through a
new structural writer (manifest.mjs setPostItemsContext: quoted and parents
only, one write, one undo point, refused whole in the build's words); a re-run
with nothing new writes nothing, and the posts whose capture read no context
are listed with the capture-posts call that reads it ("contextOnly": true).

Card drawing is unchanged: the parents and the quote are drawn as before, and
the card's rule blurs every author but the subject unless gold- or
grey-checked (the badge the capture read is what it decides by).
postContext.test.mjs: the fill rule, the reel and the insert, the refresh,
its undo and CLI, the writer's refusals.

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

Diffstat:
Mumtool/lib/report/manifest.mjs | 40++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postContext.mjs | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postContext.test.mjs | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postReel.mjs | 13++++++++++---
Mumtool/lib/report/postsCli.mjs | 29+++++++++++++++++++++++++++++
5 files changed, 445 insertions(+), 3 deletions(-)

diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2397,6 +2397,46 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { }); } +/** What a context write may set on a post item (postContext.mjs). */ +export const POST_ITEM_CONTEXT_KEYS = Object.freeze(["quoted", "parents"]); + +/** + * 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 + * structural write for them all (one undo point), refused whole in the + * build's words (validatePostItem). Returns `{ ids }`. + * + * @param {string} dir + * @param {Record<string, Record<string, any>>} patches + * @param {{ token?: string | null }} [opts] + */ +export async function setPostItemsContext(dir, patches, { token = null } = {}) { + if (!isObj(patches) || !Object.keys(patches).length) throw new Error("nothing to set"); + for (const [id, p] of Object.entries(patches)) { + if (!isObj(p)) throw new Error(`${id}: a post item's context is an object`); + for (const k of Object.keys(p)) { + if (!POST_ITEM_CONTEXT_KEYS.includes(k)) throw new Error(`${k} is not a post item's context (${POST_ITEM_CONTEXT_KEYS.join(", ")})`); + } + } + return structural(dir, "post-context", token, (m) => { + const ids = []; + for (const [id, p] of Object.entries(patches)) { + const e = m.timeline[entryIndex(m.timeline, id)]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + for (const k of POST_ITEM_CONTEXT_KEYS) { + if (!(k in p)) continue; + if (p[k] === null || p[k] === undefined) delete e[k]; + else e[k] = structuredClone(p[k]); + } + const errors = validatePostItem(e); + if (errors.length) throw new StructureRefused(errors); + ids.push(id); + } + return { ids }; + }); +} + // ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) ----------- /** diff --git a/umtool/lib/report/postContext.mjs b/umtool/lib/report/postContext.mjs @@ -0,0 +1,190 @@ +// A POST ITEM's CONTEXT FROM ITS CAPTURE (umtool/docs/report-video.md, "Post +// items"): the post it quotes and the post it answers, as the post's page +// showed them -- `capture.json`'s `context`, read by the editor's +// capture-posts (common/social/xPostContext.ts) -- filled into the entry when +// the archive row lacks them. +// +// The archive often does: an X timeline read kept no quote until the fetcher +// asked for it, and a reply's parent is another account's post, never +// archived with the account's own. So a post item that the archive gives no +// `quoted` (or one with no words) and no `parents` takes the capture's: +// +// quoted <- context.quoted { id?, author?, handle?, badge?, date?, text, url? } +// parents <- [context.parent] (the post it answers; the capture reads one) +// +// SNAPSHOTTED like the rest of the entry: written into it when it is made +// (postReel.mjs postEntryFrom -- `posts reel`, `timeline insert post:`) or +// refreshed (`umtool posts context <project>`, every post item at once, one +// write). What the archive gives is never replaced: the capture only fills +// what is missing, and a ref the archive names is only completed by a context +// post that is the same post (its id, else its author). The card's own rule +// (post-item.mjs authorRedaction) decides whose name and face it shows -- a +// parent or a quoted author who is not the subject is blurred unless gold- or +// 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"; +import path from "node:path"; +import { channelsDirFor, readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, setPostItemsContext } from "./manifest.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; +const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; +const BADGES = new Set(["blue", "gold", "grey", "other"]); +/** The longest context text a ref takes (post-item.mjs refuses past 25,000). */ +const TEXT_MAX = 10000; +const POST_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +/** + * A post item ref from a capture's context post, kept to the shape the + * validator takes; null for nothing usable (no author and no words). + */ +export function contextRefOf(p) { + if (!isObj(p)) return null; + const handle = str(p.handle).replace(/^@/, ""); + const text = str(p.text).slice(0, TEXT_MAX); + const okHandle = HANDLE_RE.test(handle) ? handle : ""; + if (!okHandle && !text.trim()) return null; + const id = ID_RE.test(str(p.id)) ? str(p.id) : ""; + const url = /^https?:\/\//.test(str(p.url)) ? p.url : ""; + const date = str(p.date) && Number.isFinite(Date.parse(p.date)) ? p.date : ""; + return { + ...(id ? { id } : {}), + ...(str(p.author) ? { author: str(p.author).slice(0, 200) } : {}), + ...(okHandle ? { handle: okHandle } : {}), + ...(BADGES.has(p.badge) ? { badge: p.badge } : {}), + ...(date ? { date } : {}), + text, + ...(url ? { url } : {}), + }; +} + +const sameHandle = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase(); + +/** Whether `ref` (the archive's) and `ctx` (the capture's) are the same post: their ids, else their authors. */ +export function sameRef(ref, ctx) { + if (str(ref?.id) && str(ctx?.id)) return String(ref.id) === String(ctx.id); + if (str(ref?.handle) && str(ctx?.handle)) return sameHandle(ref.handle, ctx.handle); + return !str(ref?.id) && !str(ref?.handle); +} + +/** `ref` completed from `ctx`: every field the archive gave kept, the rest the capture's. */ +function completed(ref, ctx) { + const out = { ...ctx }; + for (const [k, v] of Object.entries(ref)) if (v !== undefined && v !== null && v !== "") out[k] = v; + return out; +} + +/** + * FILL `entry` (a post item, mutated) from its capture's `context`: the + * quoted post where the entry has none (or one with no words, the same post), + * the post it answers where it has no parents. Returns what it filled: + * a subset of ["quoted", "parents"]. + */ +export function applyCaptureContext(entry, context) { + const filled = []; + if (!isObj(entry) || !isObj(context)) return filled; + const q = contextRefOf(context.quoted); + if (q) { + if (!isObj(entry.quoted)) { + entry.quoted = q; + filled.push("quoted"); + } else if (!str(entry.quoted.text).trim() && sameRef(entry.quoted, q)) { + entry.quoted = completed(entry.quoted, q); + filled.push("quoted"); + } + } + const p = contextRefOf(context.parent); + if (p) { + const parents = Array.isArray(entry.parents) ? entry.parents.filter(isObj) : []; + if (!parents.length) { + entry.parents = [p]; + filled.push("parents"); + } else if (!str(parents[0].text).trim() && sameRef(parents[0], p)) { + entry.parents = [completed(parents[0], p), ...parents.slice(1)]; + filled.push("parents"); + } + } + return filled; +} + +/** + * 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. + */ +export async function readCaptureContext(channelsDir, slug, postId) { + if (!POST_KEY_RE.test(slug) || !ID_RE.test(String(postId)) || postId === "_avatars") return null; + try { + const cap = JSON.parse(await readFile(path.join(channelsDir, slug, "posts-media", String(postId), "capture.json"), "utf8")); + return isObj(cap?.context) ? cap.context : null; + } catch { + return null; + } +} + +/** The ops call that reads the context of `ids` (one channel's), ready to paste. */ +export function contextCaptureCall(slug, ids) { + return `pnpm ops capture-posts --json '${JSON.stringify({ slug, ids, contextOnly: true })}' --wait`; +} + +/** + * REFRESH EVERY POST ITEM's CONTEXT from its capture (`umtool posts context + * <project>`): each post item whose capture read a context it lacks gets it, + * in ONE write (one undo point), refused whole in the build's words. + * `dryRun`: nothing written. A post whose capture read none is listed with + * the capture-posts call that reads it (`missing`, by channel). + * + * @param {{ id: string, dir: string }} project + * @param {{ channelsDir?: string | null, dryRun?: boolean }} [o] + */ +export async function postsContext(project, { channelsDir = null, dryRun = false } = {}) { + const manifest = await readManifest(project.dir); + if (!manifest) throw new Error(`${project.id} has no manifest`); + const dir = channelsDir ?? channelsDirFor(project.dir, manifest); + const items = (Array.isArray(manifest.timeline) ? manifest.timeline : []).filter((e) => e?.type === "post" && typeof e.post === "string"); + /** @type {Record<string, { quoted?: any, parents?: any }>} */ + const patches = {}; + const report = []; + /** @type {Map<string, string[]>} */ + const missing = new Map(); + 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) { + 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; + } + patches[e.id] = { + ...(filled.includes("quoted") ? { quoted: copy.quoted } : {}), + ...(filled.includes("parents") ? { parents: copy.parents } : {}), + }; + report.push({ id: e.id, post: e.post, state: "filled", filled, ...patches[e.id] }); + } + const summary = { + items: items.length, + filled: Object.keys(patches).length, + complete: report.filter((r) => r.state === "complete").length, + noContext: report.filter((r) => r.state === "no-context").length, + channelsDir: dir, + report, + missing: [...missing].map(([slug, ids]) => ({ slug, ids, call: contextCaptureCall(slug, ids) })), + }; + if (dryRun || !summary.filled) return { ...summary, dryRun: dryRun === true, result: null, editNotes: null }; + const { result, editNotes } = await withEditNotes(project, async () => + setPostItemsContext(project.dir, patches, { token: await manifestToken(project.dir) }), + ); + return { ...summary, dryRun: false, result, editNotes }; +} diff --git a/umtool/lib/report/postContext.test.mjs b/umtool/lib/report/postContext.test.mjs @@ -0,0 +1,176 @@ +// postContext.mjs: a post item's quoted post and parent from its capture's +// `context` when the archive row lacks them -- the fill rule (pure), the +// snapshot when an entry is made (`posts reel`, `timeline insert post:`), and +// the refresh of every entry (`umtool posts context`): one write, an undo +// point, a re-run that does nothing, the posts with no context named with the +// capture call that reads it. +import assert from "node:assert/strict"; +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 { cardAuthors, validatePostItem } from "umtool-report-to-video/post-item"; +import { applyCaptureContext, contextCaptureCall, contextRefOf, postsContext, readCaptureContext, sameRef } from "./postContext.mjs"; +import { postItemFromArchive, postsReel } from "./postReel.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { setPostItemsContext, undoStructural } from "./manifest.mjs"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-context-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const CH = path.join(ROOT, "channels"); +const REPORTS = path.join(ROOT, "reports"); + +// The operator's case: his reply to Kirsche, archived with no replyTo, no +// quoted and no links -- the capture's page showed both. +const KIRSCHE = { + id: "1983200000000000001", url: "https://x.com/Kirsche/status/1983200000000000001", handle: "Kirsche", author: "Kirsche", + verified: true, badge: "blue", date: "2026-10-29T12:00:00.000Z", text: "Mr. Obvious is a leftist in disguise.", media: [], from: "above", +}; +const QUOTED = { + id: "1983100000000000003", url: "https://x.com/quoted_person/status/1983100000000000003", handle: "quoted_person", author: "Quoted Person", + date: "2026-10-28T09:00:00.000Z", text: "The receipt itself.", media: [{ kind: "image", url: "https://pbs.twimg.com/media/Q2.jpg" }], +}; +const CONTEXT = { readAt: "2026-11-02T20:00:00.000Z", quoted: QUOTED, parent: KIRSCHE }; + +const row = (id, o = {}) => ({ + id, slug: `obv-x/${id}`, channelSlug: "obv-x", author: "ObviousRises", authorName: "Mr. Obvious", createdAt: "2026-10-29T14:05:00.000Z", + text: `post ${id}`, url: `https://x.com/ObviousRises/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...o, +}); +async function archive(slug, rows) { + await mkdir(path.join(CH, slug, "posts"), { recursive: true }); + await writeFile(path.join(CH, slug, "config.json"), JSON.stringify({ socialHandle: "ObviousRises", platform: "twitter" })); + await writeFile(path.join(CH, slug, "posts", "2026-10.jsonl"), rows.map((r) => JSON.stringify({ ...r, channelSlug: slug })).join("\n") + "\n"); +} +async function capture(slug, id, context) { + const dir = path.join(CH, slug, "posts-media", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "capture.json"), JSON.stringify({ version: 1, id, state: "captured", mediaState: "skipped", media: [], ...(context ? { context } : {}) })); +} +async function project(name) { + const dir = path.join(REPORTS, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "obv-x", channelsDir: CH }, + render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { links: "original" } } } }, + timeline: [{ type: "clip", id: "c01", video: "v1", start: 1, end: 3 }], + }, null, 2)); + return { id: name, dir }; +} +const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); + +await archive("obv-x", [ + row("300", { text: "you called me a Leftist, so here is what you said" }), + // The archive names the quote but has no words for it (not archived). + row("301", { createdAt: "2026-10-29T15:00:00.000Z", text: "the receipt", quoted: { platform: "twitter", id: QUOTED.id, author: "quoted_person", url: QUOTED.url } }), + row("302", { createdAt: "2026-10-29T16:00:00.000Z", text: "no context captured yet" }), + // The archive has this reply's parent: its own wins. + row("303", { createdAt: "2026-10-29T17:00:00.000Z", author: "someone_private", authorName: "Private", text: "really?" }), + row("304", { createdAt: "2026-10-29T18:00:00.000Z", text: "@someone_private yes", isReply: true, replyTo: { platform: "twitter", id: "303", author: "someone_private" } }), +]); + +test("the fill rule: only what is missing, a named ref only completed by the same post; the card's blur rule still decides", () => { + assert.deepEqual(contextRefOf(KIRSCHE), { + id: KIRSCHE.id, author: "Kirsche", handle: "Kirsche", badge: "blue", date: KIRSCHE.date, text: KIRSCHE.text, url: KIRSCHE.url, + }); + assert.equal(contextRefOf({ handle: "no spaces allowed", text: " " }), null); + assert.equal(contextRefOf({ handle: "a", text: "x".repeat(30000) }).text.length, 10000); + + const bare = { type: "post", id: "p-1", handle: "ObviousRises", subjects: ["ObviousRises"] }; + assert.deepEqual(applyCaptureContext(bare, CONTEXT), ["quoted", "parents"]); + assert.equal(bare.parents[0].handle, "Kirsche"); + assert.equal(bare.quoted.text, "The receipt itself."); + // Blurred by the card's rule: neither author is the subject, and a blue check is bought. + assert.deepEqual(cardAuthors(bare).map((a) => [a.where, a.redact, a.reason]), [ + ["author", false, "subject"], + ["parents[0]", true, "blue-check"], + ["quoted", true, "private"], + ]); + + // The archive's own: kept; completed only by the same post. + const named = { quoted: { id: QUOTED.id, handle: "quoted_person", url: QUOTED.url }, parents: [{ id: "303", handle: "someone_private", text: "really?" }] }; + assert.deepEqual(applyCaptureContext(named, CONTEXT), ["quoted"]); + assert.equal(named.quoted.text, "The receipt itself."); + assert.equal(named.quoted.author, "Quoted Person"); + assert.equal(named.parents[0].id, "303", "the archive's parent stands"); + const other = { quoted: { id: "1", handle: "elsewhere" } }; + assert.deepEqual(applyCaptureContext(other, CONTEXT), ["parents"]); + assert.deepEqual(other.quoted, { id: "1", handle: "elsewhere" }); + assert.equal(sameRef({ handle: "Quoted_Person" }, { handle: "quoted_person" }), true); + assert.equal(sameRef({ id: "1", handle: "a" }, { id: "2", handle: "a" }), false); + // A context that read neither fills nothing. + assert.deepEqual(applyCaptureContext({}, { readAt: "t" }), []); + assert.deepEqual(applyCaptureContext({}, null), []); + assert.equal(contextCaptureCall("obv-x", ["302"]), `pnpm ops capture-posts --json '{"slug":"obv-x","ids":["302"],"contextOnly":true}' --wait`); +}); + +test("made with it: posts reel and timeline insert snapshot the capture's context where the archive lacks it", async () => { + await capture("obv-x", "300", CONTEXT); + await capture("obv-x", "301", { readAt: "t", quoted: { ...QUOTED, id: undefined } }); + const p = await project("ctx-reel"); + const r = await postsReel(p, { channels: ["obv-x"], until: "2026-10-29" }); + assert.equal(r.added, 5); + const by = new Map((await manifest(p)).timeline.filter((e) => e.type === "post").map((e) => [e.id, e])); + const e300 = by.get("p-300"); + assert.equal(e300.parents?.[0]?.handle, "Kirsche"); + assert.equal(e300.parents?.[0]?.text, KIRSCHE.text); + assert.equal(e300.quoted?.handle, "quoted_person"); + assert.deepEqual(validatePostItem(e300), []); + // The archive named 301's quote: completed with the words, its id kept. + assert.equal(by.get("p-301").quoted.id, QUOTED.id); + assert.equal(by.get("p-301").quoted.text, "The receipt itself."); + assert.equal(by.get("p-301").parents, undefined); + assert.equal(by.get("p-302").quoted, undefined); + assert.equal(by.get("p-304").parents[0].id, "303"); + + const one = await postItemFromArchive(p, await manifest(p), "obv-x", "300", { id: "again-300" }); + assert.equal(one.parents[0].handle, "Kirsche"); +}); + +test("refreshed: posts context fills every entry in one write, an undo point; a re-run does nothing; no context named with its call", async () => { + // A reel made before any capture read a context. + await archive("obv-y", [row("400", { channelSlug: "obv-y", slug: "obv-y/400" }), row("401", { channelSlug: "obv-y", slug: "obv-y/401", createdAt: "2026-10-29T15:00:00.000Z" })]); + const p = await project("ctx-refresh"); + await postsReel(p, { channels: ["obv-y"] }); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-400").parents, undefined); + + await capture("obv-y", "400", CONTEXT); + const dry = await postsContext(p, { dryRun: true }); + assert.equal(dry.filled, 1); + assert.equal((await manifest(p)).timeline.find((e) => e.id === "p-400").parents, undefined, "a dry run writes nothing"); + + const r = await postsContext(p); + assert.deepEqual([r.items, r.filled, r.complete, r.noContext], [2, 1, 0, 1]); + assert.deepEqual(r.report.find((x) => x.id === "p-400").filled, ["quoted", "parents"]); + assert.deepEqual(r.missing, [{ slug: "obv-y", ids: ["401"], call: contextCaptureCall("obv-y", ["401"]) }]); + assert.ok(r.result.snapshot?.rel, "an undo point"); + const e = (await manifest(p)).timeline.find((x) => x.id === "p-400"); + assert.equal(e.parents[0].handle, "Kirsche"); + assert.equal(e.quoted.handle, "quoted_person"); + + const again = await postsContext(p); + assert.deepEqual([again.filled, again.complete], [0, 1]); + assert.equal(again.result, null); + + await undoStructural(p.dir); + assert.equal((await manifest(p)).timeline.find((x) => x.id === "p-400").parents, undefined, "undone"); + + // The CLI. + const lines = []; + const code = await postsCommand(["context", p.dir], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + assert.equal(code, 0, lines.join("\n")); + assert.match(lines[0], /^filled the context of 1 of 2 post item\(s\)/); + assert.ok(lines.some((l) => /p-400 {2}quotes @quoted_person, answers @Kirsche/.test(l)), lines.join("\n")); + assert.ok(lines.some((l) => l.includes('"contextOnly":true')), lines.join("\n")); +}); + +test("the writer: only quoted and parents, refused whole in the build's words; the reader refuses what is no post", async () => { + const p = await project("ctx-writer"); + await postsReel(p, { channels: ["obv-x"], until: "2026-10-29" }); + await assert.rejects(setPostItemsContext(p.dir, { "p-300": { text: "rewritten" } }), /text is not a post item's context/); + await assert.rejects(setPostItemsContext(p.dir, { c01: { quoted: QUOTED } }), /not a post item/); + await assert.rejects(setPostItemsContext(p.dir, { "p-302": { parents: [{ handle: "bad handle!" }] } }), (e) => /handle must be a handle/.test(String(e.errors ?? e.message))); + assert.equal((await manifest(p)).timeline.find((x) => x.id === "p-302").parents, undefined, "refused whole"); + assert.equal(await readCaptureContext(CH, "obv-x", "../../etc"), null); + assert.equal(await readCaptureContext(CH, "obv-x", "302"), null); + assert.equal((await readCaptureContext(CH, "obv-x", "300")).parent.handle, "Kirsche"); +}); diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs @@ -42,6 +42,7 @@ import { channelsDirFor, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; +import { applyCaptureContext } from "./postContext.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; @@ -99,16 +100,20 @@ export async function channelHandle(channelsDir, slug) { /** * The files a post's capture holds (`posts-media/<postId>/`): capture.json's * `media` in its order (with each one's source url), else the folder's - * pictures and videos by name. Never `shot.png` or the thread shot. + * pictures and videos by name. Never `shot.png` or the thread shot. And the + * record's `context` (the quoted post and the parent its page showed; + * postContext.mjs), or null. * - * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null }>} + * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null, context: Record<string, any> | null }>} */ export async function captureOf(channelsDir, slug, postId) { const dir = path.join(channelsDir, slug, "posts-media", postId); const names = await readdir(dir).catch(() => []); let media = []; + let context = null; try { const cap = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")); + if (cap?.context && typeof cap.context === "object" && !Array.isArray(cap.context)) context = cap.context; if (Array.isArray(cap?.media)) { media = cap.media.filter((m) => typeof m?.name === "string" && names.includes(m.name)).map((m) => ({ name: m.name, url: typeof m.url === "string" ? m.url : null })); } @@ -121,7 +126,7 @@ export async function captureOf(channelsDir, slug, postId) { .sort() .map((name) => ({ name, url: null })); } - return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null }; + return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null, context }; } /** @@ -276,6 +281,8 @@ export async function postEntryFrom(row, { index, io, subjects = [] }) { const q = index.get(String(shown.quoted.id ?? "")) ?? null; entry.quoted = refOf(q ?? { ...shown.quoted, author: shown.quoted.author ?? shown.quoted.handle, authorName: shown.quoted.authorName ?? shown.quoted.name }, shown.quoted); } + // What the archive lacks of its context, from the capture's (postContext.mjs): the shown post's, else the row's. + applyCaptureContext(entry, (await io.capture(shownSlug, String(shown.id))).context ?? (shown !== row ? (await io.capture(slug, row.id)).context : null)); // Its attachments: the shown post's capture (a repost's original), else the row's own. let cap = await io.capture(shownSlug, String(shown.id)); let capSlug = shownSlug; diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -61,6 +61,10 @@ export const POSTS_USAGE = [ " [media.<i>.push=on|off] [media.<i>.trim=off] [--json]", " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,", " an attachment's trim, sound, crop (fractions of its picture) and push-in.", + " umtool posts context <project> [--dry-run] [--json]", + " every post item's CONTEXT from its capture (capture.json's `context`: the post it quotes, the post it answers, as", + " its page showed them) where the archive row lacks it -- one write (one undo point). A post whose capture read", + " none is listed with the call that reads it: pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}'.", ].join("\n"); const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after"]); @@ -336,6 +340,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con 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 === "context" && projectArg && !flags.has("--help")) return await contextCommand(projectArg, { root, json, dryRun, out }); if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) { err(POSTS_USAGE); return 2; @@ -529,6 +534,30 @@ export function postItemPatchOf(pairs) { return out; } +/** `posts context`: every post item's context from its capture (postContext.mjs postsContext). */ +async function contextCommand(projectArg, { root, json, dryRun, out }) { + const project = await projectOf(projectArg, root); + const { postsContext } = await import("./postContext.mjs"); + const r = await postsContext(project, { dryRun }); + if (json) { + out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2)); + return 0; + } + out(`${r.dryRun ? "would fill" : "filled"} the context of ${r.filled} of ${r.items} post item(s) in ${project.id} (${r.complete} complete, ${r.noContext} with no context captured)`); + 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.parents ? `answers ${x.parents[0]?.handle ? `@${x.parents[0].handle}` : x.parents[0]?.author ?? "?"}` : "", + ].filter(Boolean).join(", "); + out(` ${x.id} ${what}`); + } + for (const m of r.missing) out(` no context captured for ${m.ids.length} post(s) of ${m.slug}:\n ${m.call}\n then umtool posts context ${project.id} again`); + if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (r.editNotes) out(` edit noted for ${r.editNotes.generatedBy}`); + return 0; +} + /** `posts set-item`: a post item's knobs, through updatePostItem. */ async function setItemCommand(projectArg, ref, pairs, { root, json, out }) { const patch = postItemPatchOf(pairs);