Archilyzer · Source

archilyzer

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

commit fd2d4b34bb5287e7d62b938232eb90c0f5f2ff81
parent 9d8fd941515c01c695d2e8ea6cb35a69e791c391
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 23:18:25 -0500

Merge lane/capture-context: a post's context from the page capture-posts loads -- the quoted post and the reply parent into capture.json (contextOnly: one page per post); the X fetcher keeps quoted posts; umtool fills a post item's missing quote and parents from it (posts context)

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

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 20++++++++++++++++++++
Mcommon/controller/capturePosts.test.ts | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/capturePosts.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/report/draft/research/tools.ts | 6+++---
Acommon/social/__fixtures__/gallery-dl-timeline-quotes.jsonl | 10++++++++++
Mcommon/social/__fixtures__/x-post-avatars.html | 25+++++++++++++++++--------
Mcommon/social/fetchers.ts | 15+++++++++++++++
Mcommon/social/postCapture.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/social/xAvatarCapture.browser.test.ts | 51+++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/social/xGalleryDlFetcher.test.ts | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 70+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/social/xNormalize.ts | 33++++++++++++++++++++++++++++++++-
Mcommon/social/xPostCapture.ts | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Acommon/social/xPostContext.test.ts | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xPostContext.ts | 254+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xThreadShot.ts | 24++++++++++++++----------
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/capture-posts/route.test.ts | 21+++++++++++++++++++++
Meditor/app/api/ops/capture-posts/route.ts | 18+++++++++++++++---
Meditor/app/channels/[slug]/socialActions.ts | 25+++++++++++++++++++++----
Meditor/app/jobs/jobReplayRegistry.ts | 2++
Meditor/e2e/capture-posts.spec.ts | 11+++++++++++
Mscripts/archilyzer-ops.mjs | 7+++++++
Mumtool/docs/cli.md | 3++-
Mumtool/docs/knobs.md | 1+
Mumtool/docs/report-video.md | 6+++++-
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+++++++++++++++++++++++++++++
32 files changed, 1730 insertions(+), 56 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -146,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). A forum thread keeps two positions: a run catches up from the last page, then continues the history where it stopped; "full": true is its full re-walk (every page, edits updated). "retryOnBlock": {"minutes": 30, "max": 12} (or true: the forum default in settings) waits out a challenge or refusal page and runs again, max tries in all. "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | -| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. Paced like a post fetch, on its queue. | | +| `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. "thread": true (X; default the channel's postCaptureThread) also shoots each reply with the post it answers above it, as shot-thread.png beside shot.png (a post shot before gets only that); the replied-to author's avatar, name and handle are blurred unless verified or the reply's own. "threadRedact": false turns the blur off, true blurs any author; {"&lt;id&gt;": false} sets it per post. X also keeps each author's avatar, read off the page the shot loads (with "thread", the replied-to and quoted authors' too), in posts-media/\_avatars/&lt;handle&gt;.&lt;ext&gt; + avatars.json; an author already stored is not fetched again unless "force". "avatars": false turns that off. "avatarsOnly": true (X) loads ONE post page per distinct archived author for the avatars alone -- no shot, media, article or thread shot, no capture record, no availability: one author's avatar is {"slug", "ids": \["&lt;one of their post ids&gt;"\], "avatarsOnly": true}. X also reads each post's CONTEXT off the same page -- the post it quotes and the post it answers (its author, check, date, words, media links) -- into its capture.json's "context"; "context": false turns that off. "contextOnly": true (X) loads ONE page per post for that alone (and the avatars it shows): the context written into capture.json, nothing shot, no media, article, thread shot or availability; a post whose context is already read is skipped unless "force". Not with "avatarsOnly". Paced like a post fetch, on its queue. | | | `publish` | publish runs publish stages on the editor's publish queue, one at a time, under one run id: {"verb": …}. "index" updates the index; "build" builds "siteId"/"siteIds" (forced; the index first when stale; "runner": "docker" builds every site in containers; "allowMissingMedia": true lets a report citation with no prepared media through compose, local builds only); "deploy" ships their built bundles (production, "preview": "&lt;branch&gt;", or "to": "local"; "force" redeploys a bundle already shipped there); "hub" / "homepage" build them, {"deploy": true} deploys after; "now" is Publish now (the stale index, then each policy target); "stale" builds every stale site. The answer lists every job ({target, kind, jobId}) and --wait follows them all. A site never built is refused: "no build of &lt;id&gt; in &lt;dir&gt; — archilyzer publish build &lt;id&gt;". `get publish` is the status. | | | `build-index`, `build-site`, `build-deploy`, `deploy-site`, `build-hub`, `deploy-hub`, `build-homepage`, `deploy-homepage` | build-index, build-site, build-deploy, deploy-site, build-hub, deploy-hub, build-homepage and deploy-homepage are publish's aliases, with their old bodies and answers ("skipData" is accepted and ignored). | `pnpm ops build-deploy --json '{"siteIds":["anilyzer","jeralyzer"]}' --wait`<br>`pnpm ops build-site --json '{"siteId":"anilyzer"}' --wait`<br>`pnpm ops deploy-site --json '{"siteId":"anilyzer","preview":"tags-exclude"}' --wait`<br>`pnpm ops build-hub --wait`<br>`pnpm ops build-hub --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-hub --wait`<br>`pnpm ops build-homepage --json '{"deploy":true}' --wait`<br>`pnpm ops deploy-homepage --json '{"preview":"refresh"}' --wait` | | `build-site`, `build-deploy`, `deploy-site` | build-site, build-deploy and deploy-site all take "siteId" (one) or "siteIds" (a list). | | diff --git a/OPERATING.md b/OPERATING.md @@ -427,6 +427,26 @@ pnpm ops capture-posts --json '{"slug":"example-x","ids":["<postId>"]}' --wait channels/<slug>/posts-media/_avatars/<handle>.<ext> # jpg | png | webp | gif channels/<slug>/posts-media/_avatars/avatars.json # { "<handle>": { "file", "url" (the _400x400), "capturedAt", "postId" } } ``` +- **A post's context (X): what it quotes and what it answers.** The archive often names neither — a timeline + read kept no quote until the fetcher asked gallery-dl for them (it does now: a quote becomes the post's + `quoted`, never one of the account's posts), and a reply's parent is another account's post, never archived + with the account's. Every X capture that loads a post page reads both off it — the parent (the archive's + in-reply-to id, else the post directly above it; read even when the archive calls the post no reply) and the + quote card: author, display name, check, date, words, the media links the page drew, the status id when the + page names it — into `capture.json`'s `context: {quoted?, parent?, readAt}`, with no extra page load; + `"context": false` turns that off. For a list of posts already captured (or not), `"contextOnly": true` loads + ONE page per post for its context (and the avatars it shows) and writes nothing else — no shot, media, article, + thread shot or availability; a post whose context is already read is skipped unless `"force": true`: + + ```sh + pnpm ops capture-posts --json '{"slug":"ObviousRises-x","ids":["<postId>","<postId>"],"contextOnly":true}' --wait + umtool posts context <project> # every post item of the cut takes the quoted post / parent it lacks + ``` + + A post video draws them on the card (`quoted`, `parents`), blurring every author but the subject unless + gold- or grey-checked. `umtool posts reel` and `timeline insert post:` fill them when the entry is made; + `umtool posts context` refreshes a cut made before the capture, in one write (one undo point), and names the + posts with no context yet with the call above. Keys keep the handle's case as X prints it; lookups ignore case. X's default "egg" picture is not stored. - A **forum thread** keeps two positions (`posts-state.json` `forum`): **Fetch posts** catches up from the last page diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -202,7 +202,7 @@ test("the articles: on by default, refused alone only when not asked for by name assert.deepEqual(archived.get("222"), { text: "a plain post", links: ["https://example.com/page"] }); calls = []; - assert.equal((await run("demo-x", ["111"], { articles: false })).ok, true); + assert.equal((await run("demo-x", ["111"], { articles: false, context: false })).ok, true); assert.equal(calls[0].articles, false); assert.equal(calls[0].archived, undefined); @@ -245,9 +245,9 @@ test("the thread shots (X): off by default, the run's word or the channel's, eac answer = { outcomes: [] }; calls = []; - assert.equal((await run("demo-x-replies", ["501"], { articles: false })).ok, true); + assert.equal((await run("demo-x-replies", ["501"], { articles: false, context: false })).ok, true); assert.equal(calls[0].thread, false); - assert.equal(calls[0].archived, undefined, "nothing read for a run with no articles and no thread"); + assert.equal(calls[0].archived, undefined, "nothing read for a run with no articles, no thread and no context"); calls = []; assert.equal((await run("demo-x-replies", ["501", "502"], { thread: true, threadRedact: { "501": false } })).ok, true); @@ -413,3 +413,74 @@ test("avatars (X): on by default, off by word; avatarsOnly is its own run, X's o assert.equal(calls.length, 0); answer = { outcomes: [] }; }); + +test("context (X): read by default with each post's archived parent and quoted ids; contextOnly is its own run, X's only, nothing recorded", async () => { + const root = path.join(channelsDir, "demo-x-context"); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "twitter", + postFetcher: "test-capture-x", + socialHandle: "ObviousRises", + name: "Example (X context)", + url: "https://x.com/ObviousRises", + }), + ); + const base = { + channelSlug: "demo-x-context", author: "ObviousRises", createdAt: "2026-10-29T04:34:32.000Z", uploadDate: "20261029", + platform: "twitter" as const, isRepost: false, links: [], + }; + await writePosts(root, [ + { + ...base, id: "701", slug: "demo-x-context/701", text: "a reply quoting", url: "https://x.com/ObviousRises/status/701", isReply: true, + replyTo: { platform: "twitter" as const, id: "700", author: "Kirsche" }, + quoted: { platform: "twitter" as const, id: "699", author: "someone" }, + }, + // The archive names neither (the operator's case): the page is the word. + { ...base, id: "702", slug: "demo-x-context/702", text: "you called me a Leftist", url: "https://x.com/ObviousRises/status/702", isReply: false }, + ]); + + // A normal run: on by default (the fetcher's), the archive's ids passed. + calls = []; + answer = { outcomes: [] }; + await run("demo-x-context", ["701", "702"], { articles: false }); + assert.equal(calls[0].context, undefined); + assert.equal(calls[0].contextOnly, undefined); + assert.deepEqual(calls[0].archived?.get("701")?.replyTo, { id: "700", author: "Kirsche" }); + assert.deepEqual(calls[0].archived?.get("701")?.quoted, { id: "699", author: "someone" }); + assert.equal(calls[0].archived?.get("702")?.replyTo, undefined); + calls = []; + await run("demo-x-context", ["701"], { articles: false, context: false }); + assert.equal(calls[0].context, false); + + // contextOnly: a run even with both halves off; the summary is the result's, + // and an outcome the fetcher (wrongly) returns is not recorded. + calls = []; + answer = { + outcomes: [{ id: "701", state: "deleted", availability: "deleted", files: 0 }], + context: { read: 2, quoted: 1, parents: 2, skipped: 0, pages: 2, failed: [] }, + }; + const res = await run("demo-x-context", ["701", "702"], { contextOnly: true, shots: false, media: false, articles: false }); + assert.equal(res.ok, true); + assert.deepEqual(res.outcomes, []); + assert.equal(res.context?.parents, 2); + assert.equal(calls[0].contextOnly, true); + assert.deepEqual(await readPostAvailability(root), {}); + + // With avatarsOnly: two runs, refused; another platform reads none. + calls = []; + assert.match( + (await run("demo-x-context", ["701"], { contextOnly: true, avatarsOnly: true })).error ?? "", + /^"contextOnly" and "avatarsOnly" are two runs/, + ); + await makeChannel("demo-social-context"); + assert.equal( + (await run("demo-social-context", ["aaa"], { contextOnly: true })).error, + "Post context is X's only; Test capture reads none.", + ); + assert.equal(calls.length, 0); + answer = { outcomes: [] }; +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -18,6 +18,12 @@ // in `posts-media/_avatars/` (social/xAvatars.ts has the store): on by // default (`avatars: false` turns it off), and `avatarsOnly` loads one page // per archived author for that alone, recording nothing about the posts. +// +// And X reads each post's CONTEXT off the same page -- the post it quotes and +// the post it answers, which the archive often lacks -- into its capture.json +// (social/xPostContext.ts): on by default (`context: false` turns it off), and +// `contextOnly` loads one page per post for that alone (and the avatars it +// shows), writing the context into the record and nothing about availability. import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; @@ -45,6 +51,7 @@ import { } from "../social/fetchers"; import { postsMediaDir } from "../social/postCapture"; import type { XAvatarRunSummary } from "../social/xAvatarCapture"; +import type { XContextRunSummary } from "../social/xPostContext"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { captureWaybackPageRecords, @@ -85,6 +92,12 @@ export type CapturePostsOptions = { // media, article or thread shot, no capture record, no availability. avatars?: boolean; avatarsOnly?: boolean; + // X: read each post's context (the quoted post, the parent) off the pages + // the shots load (default true), or ONLY it -- one page per post, the + // context written into its capture.json, the avatars it shows saved; no + // shot, media, article, thread shot or availability. + context?: boolean; + contextOnly?: boolean; onLog?: (line: string) => void; signal?: AbortSignal; // The job's drain: stop between posts. @@ -101,6 +114,8 @@ export type CapturePostsResult = { error?: string; // X: what the run did about avatars, when it did anything. avatars?: XAvatarRunSummary; + // X: what the run read of the posts' context, when it read any. + context?: XContextRunSummary; }; // Why this fetcher cannot capture posts, or null when it can. Shared with the @@ -119,15 +134,16 @@ export const NOTHING_TO_CAPTURE = // Both halves off is nothing to do — unless the articles or the thread shots // were asked for by name: their defaults alone do not make a run. An -// avatars-only run is a run of its own, whatever the halves say. +// avatars-only or context-only run is a run of its own, whatever the halves say. export function nothingToCapture(o: { shots?: boolean; media?: boolean; articles?: boolean; thread?: boolean; avatarsOnly?: boolean; + contextOnly?: boolean; }): boolean { - if (o.avatarsOnly === true) return false; + if (o.avatarsOnly === true || o.contextOnly === true) return false; return o.shots === false && o.media === false && o.articles !== true && o.thread !== true; } @@ -136,6 +152,17 @@ export function avatarsOnlyProblem(platform: string | undefined, label: string): return platform === "twitter" ? null : `Avatars are X's only; ${label} keeps none.`; } +// The refusal for a context-only run asked of a platform that reads none, or +// asked together with an avatars-only one (it keeps the avatars itself). +export function contextOnlyProblem( + platform: string | undefined, + label: string, + o: { avatarsOnly?: boolean } = {}, +): string | null { + if (o.avatarsOnly) return '"contextOnly" and "avatarsOnly" are two runs; a context-only run keeps the avatars it shows too.'; + return platform === "twitter" ? null : `Post context is X's only; ${label} reads none.`; +} + // The thread shot's blur knob as a caller wrote it: a boolean for the run, or // { "<post id>": boolean }. Returns the knob, or the sentence refusing it. export type ThreadRedactKnob = boolean | Record<string, boolean>; @@ -186,6 +213,7 @@ export async function capturePosts( // rendered from its capture's replay, its images from the archive. if (isWaybackPagesChannel(config)) { if (opts.avatarsOnly) return fail(avatarsOnlyProblem(undefined, "a Wayback pages channel")!); + if (opts.contextOnly) return fail(contextOnlyProblem(undefined, "a Wayback pages channel", opts)!); return captureChannelPageRecords(opts, channelRoot, ids); } @@ -198,6 +226,13 @@ export async function capturePosts( const nope = avatarsOnlyProblem(fetcher.platform, fetcher.label); if (nope) return fail(nope); } + const contextOnly = opts.contextOnly === true; + if (contextOnly) { + const nope = contextOnlyProblem(fetcher.platform, fetcher.label, opts); + if (nope) return fail(nope); + } + // The context read (X): what the archive says each post answers and quotes. + const contextWanted = fetcher.platform === "twitter" && (contextOnly || opts.context !== false); // An X search channel has no account (release 38): its posts are any // author's, and the X capture opens each by its status id alone. @@ -221,11 +256,12 @@ export async function capturePosts( author?: string; isReply?: boolean; replyTo?: { id: string; author?: string }; + quoted?: { id: string; author?: string }; }; let archived: Map<string, Archived> | undefined; const forum = fetcher.platform === "xenforo"; const bluesky = fetcher.platform === "bluesky"; - if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky || avatarsOnly) { + if ((opts.articles !== false && fetcher.platform === "twitter") || thread || forum || bluesky || avatarsOnly || contextWanted) { const wanted = new Set(ids); archived = new Map(); for (const p of await readAllPosts(channelRoot)) { @@ -238,6 +274,14 @@ export async function capturePosts( ...(bluesky ? { url: p.url, author: p.author } : {}), // An avatars-only run loads one page per author. ...(avatarsOnly ? { author: p.author } : {}), + // The context read tells the parent by the id the reply answers, and + // fills a quote card's missing id from the quoted one. + ...(contextWanted + ? { + ...(p.replyTo ? { replyTo: { id: p.replyTo.id, ...(p.replyTo.author ? { author: p.replyTo.author } : {}) } } : {}), + ...(p.quoted ? { quoted: { id: p.quoted.id, ...(p.quoted.author ? { author: p.quoted.author } : {}) } } : {}), + } + : {}), // The thread shot tells the parent by the id the reply answers. ...(thread ? { @@ -256,7 +300,14 @@ export async function capturePosts( ? await resolveXCookieSourceFor(paths, settings, policy.cookies) : undefined; - if (avatarsOnly) { + if (contextOnly) { + log( + `Reading the context (the quoted post, the post answered) of ${ids.length} post(s) of ${slug} via ${fetcher.label}` + + (opts.avatars === false ? "" : ", and the avatars it shows") + + (opts.force ? ", again where already read" : "") + + ".", + ); + } else if (avatarsOnly) { log( `Capturing the authors' avatars of ${ids.length} post(s) of ${slug} via ${fetcher.label}` + (thread ? " (with the replied-to and quoted authors')" : "") + @@ -271,6 +322,7 @@ export async function capturePosts( opts.articles === false || fetcher.platform !== "twitter" ? "" : " articles", thread ? ` thread shots${opts.threadRedact === false ? " (no blur)" : ""}` : "", fetcher.platform === "twitter" && opts.avatars !== false ? " avatars" : "", + contextWanted ? " context" : "", ].join("") + (opts.force ? ", again where already captured" : "") + ".", @@ -295,6 +347,8 @@ export async function capturePosts( ...(opts.threadRedact !== undefined ? { threadRedact: opts.threadRedact } : {}), ...(opts.avatars !== undefined ? { avatars: opts.avatars } : {}), ...(avatarsOnly ? { avatarsOnly: true } : {}), + ...(opts.context !== undefined ? { context: opts.context } : {}), + ...(contextOnly ? { contextOnly: true } : {}), archived, cookies: alwaysCookies(policy), cookieSource: xLogin?.source, @@ -309,8 +363,11 @@ export async function capturePosts( return fail(message); } - const avatars = result.avatars ? { avatars: result.avatars } : {}; - if (avatarsOnly) { + const avatars = { + ...(result.avatars ? { avatars: result.avatars } : {}), + ...(result.context ? { context: result.context } : {}), + }; + if (avatarsOnly || contextOnly) { // Nothing about the posts was learned or written: no sidecar, no records. if (result.needsCookies) { return { ok: false, outcomes: [], needsCookies: true, error: result.stoppedEarly ?? "The capture needs an X login.", ...avatars }; diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts @@ -128,10 +128,10 @@ export const ACTION_SPECS: Record<AcquisitionAction, ActionSpec> = { action: "capture-posts", editorAction: "capture-posts", description: - "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified); X keeps each author's avatar (posts-media/_avatars/); avatarsOnly: only the avatars, one page per author.", - properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool, avatarsOnly: bool }, + "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified); X keeps each author's avatar (posts-media/_avatars/) and each post's context (the post it quotes, the post it answers) in its capture.json; avatarsOnly: only the avatars, one page per author; contextOnly: only the context, one page per post.", + properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool, avatarsOnly: bool, contextOnly: bool }, required: ["slug", "ids"], - body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread", "avatarsOnly"]), + body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread", "avatarsOnly", "contextOnly"]), }, "import-post": { action: "import-post", diff --git a/common/social/__fixtures__/gallery-dl-timeline-quotes.jsonl b/common/social/__fixtures__/gallery-dl-timeline-quotes.jsonl @@ -0,0 +1,10 @@ +[2, {"tweet_id": 1983300000000000001, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000001, "source_id": 0, "date": "2026-10-29 14:05:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "you called me a Leftist, so here is what you said", "count": 0, "category": "twitter", "subcategory": "timeline"}] +[2, {"tweet_id": 1983200000000000007, "retweet_id": 0, "quote_id": 1983300000000000001, "reply_id": 0, "conversation_id": 1983200000000000007, "source_id": 0, "date": "2026-10-29 12:00:00", "author": {"id": 2222222222, "name": "Kirsche", "nick": "Kirsche", "location": "", "date": "2019-03-01 10:00:00", "verified": true, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/2222222222/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "Mr. Obvious is a leftist in disguise.", "count": 0, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[2, {"tweet_id": 1983300000000000002, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000002, "source_id": 0, "date": "2026-10-28 09:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "the receipt", "count": 1, "category": "twitter", "subcategory": "timeline"}] +[3, "https://pbs.twimg.com/media/T2pic.jpg?name=orig", {"tweet_id": 1983300000000000002, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000002, "source_id": 0, "date": "2026-10-28 09:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "the receipt", "count": 1, "category": "twitter", "subcategory": "timeline", "num": 1, "filename": "T2pic", "extension": "jpg"}] +[2, {"tweet_id": 1983100000000000003, "retweet_id": 0, "quote_id": 1983300000000000002, "reply_id": 0, "conversation_id": 1983100000000000003, "source_id": 0, "date": "2026-10-27 18:30:00", "author": {"id": 3333333333, "name": "quoted_person", "nick": "Quoted Person", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/3333333333/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "The receipt itself.", "count": 1, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[3, "https://pbs.twimg.com/media/Q2pic.jpg?name=orig", {"tweet_id": 1983100000000000003, "retweet_id": 0, "quote_id": 1983300000000000002, "reply_id": 0, "conversation_id": 1983100000000000003, "source_id": 0, "date": "2026-10-27 18:30:00", "author": {"id": 3333333333, "name": "quoted_person", "nick": "Quoted Person", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/3333333333/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "The receipt itself.", "count": 1, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises", "num": 1, "filename": "Q2pic", "extension": "jpg"}] +[2, {"tweet_id": 1983300000000000003, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1983300000000000003, "source_id": 0, "date": "2026-10-27 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "as I said last week", "count": 0, "category": "twitter", "subcategory": "timeline"}] +[2, {"tweet_id": 1981000000000000005, "retweet_id": 0, "quote_id": 1983300000000000003, "reply_id": 0, "conversation_id": 1981000000000000005, "source_id": 0, "date": "2026-10-20 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "an older post of my own", "count": 0, "category": "twitter", "subcategory": "timeline", "quote_by": "ObviousRises"}] +[2, {"tweet_id": 1983300000000000004, "retweet_id": 0, "quote_id": 0, "reply_id": 1983200000000000001, "conversation_id": 1983200000000000001, "source_id": 0, "date": "2026-10-26 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "@Kirsche no", "count": 0, "category": "twitter", "subcategory": "timeline", "reply_to": "Kirsche"}] +[2, {"tweet_id": 1981000000000000005, "retweet_id": 0, "quote_id": 0, "reply_id": 0, "conversation_id": 1981000000000000005, "source_id": 0, "date": "2026-10-20 08:00:00", "author": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "user": {"id": 1111111111, "name": "ObviousRises", "nick": "Mr. Obvious", "location": "", "date": "2019-03-01 10:00:00", "verified": false, "protected": false, "profile_banner": "", "profile_image": "https://pbs.twimg.com/profile_images/1111111111/x.jpg", "favourites_count": 10, "followers_count": 100, "friends_count": 50, "listed_count": 1, "media_count": 3, "statuses_count": 1000, "description": ""}, "lang": "en", "source": "Twitter Web App", "sensitive": false, "sensitive_flags": null, "favorite_count": 7, "quote_count": 1, "reply_count": 2, "retweet_count": 3, "bookmark_count": 0, "view_count": 900, "content": "an older post of my own", "count": 0, "category": "twitter", "subcategory": "timeline"}] diff --git a/common/social/__fixtures__/x-post-avatars.html b/common/social/__fixtures__/x-post-avatars.html @@ -1,9 +1,11 @@ <!doctype html> <!-- An X status page as X draws it (2026-11), cut to what the capture reads: - the reply's parent above it, the post itself (its author's avatar, a - quoted post's card with its own avatar), and a reply under it. Every - picture is on {{ORIGIN}}, the test's loopback server, at X's - profile_images path. Recorded-style, hand-trimmed; no live X. --> + the reply's parent above it (a blue check by its name), the post itself + (its author's avatar, a quoted post's card with its own avatar, its + words, date and a picture whose link names the quoted status), and a + reply under it. Every picture is on {{ORIGIN}}, the test's loopback + server, at X's profile_images (and media) paths. Recorded-style, + hand-trimmed; no live X. --> <html lang="en"> <head> <meta charset="utf-8"> @@ -41,6 +43,7 @@ <div class="body"> <div data-testid="User-Name"> <a href="/parent_person" role="link"><span>A Private Person</span></a> + <svg data-testid="icon-verified" viewBox="0 0 22 22" width="16" height="16" fill="#1d9bf0" aria-label="Verified account"><path d="M0 0h22v22H0z"></path></svg> <a href="/parent_person" role="link" tabindex="-1"><span class="handle">@parent_person</span></a> <a href="/parent_person/status/1849999999999999990" role="link"><time datetime="2026-10-30T12:00:00.000Z">Oct 30</time></a> </div> @@ -67,13 +70,19 @@ <div data-testid="tweetText" lang="en"><span>It is obvious, and here is the receipt.</span></div> <div class="quote" role="link" tabindex="0"> <div data-testid="User-Name"> - <div data-testid="UserAvatar-Container-quoted_person"> - <div class="bg" style="background-image: url(&quot;{{ORIGIN}}/profile_images/888/qq_mini.jpg&quot;);"></div> - <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/888/qq_mini.jpg"> + <div> + <div data-testid="UserAvatar-Container-quoted_person"> + <div class="bg" style="background-image: url(&quot;{{ORIGIN}}/profile_images/888/qq_mini.jpg&quot;);"></div> + <img alt="" draggable="true" src="{{ORIGIN}}/profile_images/888/qq_mini.jpg"> + </div> + <span>Quoted Person</span> </div> - <span>Quoted Person</span> <span class="handle">@quoted_person · Oct 29</span> + <div><span class="handle">@quoted_person</span> <span class="handle">·</span> <time datetime="2026-10-29T08:00:00.000Z">Oct 29</time></div> </div> <div data-testid="tweetText" lang="en"><span>The receipt itself.</span></div> + <a href="/quoted_person/status/1849000000000000005/photo/1" role="link"> + <div data-testid="tweetPhoto"><img alt="Image" src="{{ORIGIN}}/media/QQ_receipt.jpg?format=jpg&amp;name=small"></div> + </a> </div> <div role="group" aria-label="3 replies, 5 reposts, 40 likes"><button data-testid="reply" type="button"><span>3</span></button></div> </div> diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -19,6 +19,7 @@ import type { ForumWalkState } from "../lib/forumWalk"; import type { XCookieSource } from "./xCookieSource"; import type { PostCaptureState } from "./postCapture"; import type { XAvatarRunSummary } from "./xAvatarCapture"; +import type { XContextRunSummary } from "./xPostContext"; export type PostFetchInput = { // The account's canonical URL as configured on the channel. @@ -265,6 +266,15 @@ export type PostCaptureInput = Pick< // shot, no media, no article, no thread shot, and no capture record or // availability observation written. Defaults to false. avatarsOnly?: boolean; + // X: read the post's CONTEXT off the page the shot loads -- the post it + // quotes and the post it answers -- into its capture.json's `context` + // (xPostContext.ts). Defaults to true. + context?: boolean; + // X: ONLY the context — one post page per post (one already read, or + // deleted, not loaded unless `force`), the context written into its + // capture.json and the avatars the page shows saved; no shot, no media, no + // article, no thread shot, no availability observation. Defaults to false. + contextOnly?: boolean; // What the posts archive holds for each id — its text and expanded links — // for the links a capture follows (an X Article's). Ids absent are read // from the page alone. @@ -284,6 +294,9 @@ export type PostCaptureInput = Pick< // parent is told by this id). isReply?: boolean; replyTo?: { id: string; author?: string }; + // What it quotes, as archived (X: the context read fills a quote + // card's missing id from it). + quoted?: { id: string; author?: string }; } >; // A soft stop: no new post is started once it fires, and the one in hand @@ -312,6 +325,8 @@ export type PostCaptureResult = { stoppedEarly?: string; // X: what the run did about avatars, when it did anything. avatars?: XAvatarRunSummary; + // X: what the run read of the posts' context, when it read any. + context?: XContextRunSummary; }; // Input for importing ONE post by its URL (`SocialFetcher.fetchOne`, release diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts @@ -175,6 +175,40 @@ export type ThreadCaptureRecord = CapturedFile & { }; }; +// THE POST'S CONTEXT as its page showed it (X, xPostContext.ts): the post it +// quotes and the post it answers, read off the page the capture loaded -- the +// archive often names neither (a timeline read keeps no quote, and a reply's +// parent is another account's post). What a card needs to draw them: who, +// their check, when, the words, the status link and the media URLs the page +// drew. `readAt` is when the page was read; a read that found neither is +// still a read (`{ readAt }` alone), so a context-only run does not load it +// again. Editor-only, like the rest of the record: never published. +export type PostContextPost = { + // The status id and link, when the page names them (a quote card often + // does not: the archive's quoted id fills it, when it agrees). + id?: string; + url?: string; + handle?: string; + // The display name. + author?: string; + verified?: boolean; + badge?: "blue" | "gold" | "grey" | "other"; + // ISO, from the post's <time>. + date?: string; + text: string; + // The pictures and videos it carries, as the page drew them (a video by its + // poster): links, never downloaded. + media: { kind: "image" | "video"; url: string }[]; +}; + +export type PostContextRecord = { + readAt: string; + quoted?: PostContextPost; + // How the parent was told: its status link matched the archive's + // in-reply-to id, or (the archive not saying) the post directly above. + parent?: PostContextPost & { from: "reply-to" | "above" }; +}; + export type PostCaptureRecord = { version: 1; id: string; @@ -204,6 +238,8 @@ export type PostCaptureRecord = { // is `threadError` instead, and owed again. threadNone?: string; threadError?: string; + // X: the quoted post and the parent, read off the page (xPostContext.ts). + context?: PostContextRecord; error?: string; }; diff --git a/common/social/xAvatarCapture.browser.test.ts b/common/social/xAvatarCapture.browser.test.ts @@ -11,7 +11,10 @@ // ONCE per author through the page's own request context (it carries the // context's cookie), with no second page load and the page left where it was; // an avatars-only run writes no capture record; a normal run shoots the post -// and reads the avatars from the same load. +// and reads the avatars from the same load. And the post's CONTEXT +// (xPostContext.ts) off the same page: the parent's and the quoted post's +// author, check, date, words and media, into capture.json -- on a normal run, +// and on a context-only one (one page load, nothing shot). // // Skips where Playwright or its Chromium is not installed. With // AVATAR_PROOF_DIR set, it leaves a screenshot, the store and a log there. @@ -29,7 +32,7 @@ import { fileURLToPath } from "node:url"; import { importPlaywright, type PageLike } from "./playwrightRuntime"; import { captureXPosts, type XCaptureDeps } from "./xPostCapture"; import { AVATARS_DIRNAME, readXAvatarIndex } from "./xAvatars"; -import { SHOT_FILENAME } from "./postCapture"; +import { CAPTURE_FILENAME, readPostCapture, SHOT_FILENAME } from "./postCapture"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIX = path.join(HERE, "__fixtures__"); @@ -204,6 +207,50 @@ test("in a real Chromium: the avatars read off a recorded-style X page and fetch assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`]); const shot = await readFile(path.join(out, POST_ID, SHOT_FILENAME)); assert.equal(shot.readUInt32BE(0), 0x89504e47); + // The context, read off the same load: the archive not saying, the + // parent is the article above. + const ctx = (await readPostCapture(path.join(out, POST_ID)))?.context; + assert.ok(ctx, log.join("\n")); + assert.deepEqual(ctx.parent, { + id: PARENT_ID, + url: `https://x.com/parent_person/status/${PARENT_ID}`, + handle: "parent_person", + author: "A Private Person", + verified: true, + badge: "blue", + date: "2026-10-30T12:00:00.000Z", + text: "So what happened next?", + media: [], + from: "above", + }); + assert.deepEqual(ctx.quoted, { + id: "1849000000000000005", + url: "https://x.com/quoted_person/status/1849000000000000005", + handle: "quoted_person", + author: "Quoted Person", + date: "2026-10-29T08:00:00.000Z", + text: "The receipt itself.", + media: [{ kind: "image", url: `${fx.origin}/media/QQ_receipt.jpg?format=jpg&name=small` }], + }); + + // 3. contextOnly, into a channel with no capture yet: one page load, + // nothing shot, the context and the avatars only; the archive's parent id. + const out3 = path.join(path.dirname(out), "posts-media-context"); + const res3 = await captureXPosts( + { ids: [POST_ID], handle: "ObviousRises", outDir: out3, signal: new AbortController().signal, contextOnly: true, archived, onLog }, + deps, + ); + assert.deepEqual(res3.outcomes, []); + assert.equal(res3.context?.read, 1, log.join("\n")); + assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`, `/i/status/${POST_ID}`]); + assert.deepEqual(await readdir(path.join(out3, POST_ID)), [CAPTURE_FILENAME]); + const rec3 = await readPostCapture(path.join(out3, POST_ID)); + assert.equal(rec3?.shot, undefined); + assert.equal(rec3?.context?.parent?.from, "reply-to"); + assert.equal(rec3?.context?.parent?.id, PARENT_ID); + assert.equal(rec3?.context?.quoted?.handle, "quoted_person"); + assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out3, AVATARS_DIRNAME))), ["ObviousRises", "parent_person", "quoted_person"]); + assert.deepEqual(blocked, []); if (proofDir) { await mkdir(proofDir, { recursive: true }); diff --git a/common/social/xGalleryDlFetcher.test.ts b/common/social/xGalleryDlFetcher.test.ts @@ -416,3 +416,101 @@ test("the capture's gap before each contact is the reads' 4–10 s, drawn fresh" assert.equal(xRequestPauseMs(() => 1), 10_000); assert.equal(xRequestPauseMs(() => 0.5), 7_000); }); + +// --------------------------------------------------------------------------- +// Quoted posts (gallery-dl's twitter `quoted` option) +// --------------------------------------------------------------------------- +// +// __fixtures__/gallery-dl-timeline-quotes.jsonl is a timeline read in +// gallery-dl 1.32.9's --dump-json/output.jsonl shape, as its twitter +// extractor writes it (extractor/twitter.py _transform_tweet: bare 64-bit +// ids, `quote_id` set on the QUOTED tweet's record naming the one quoting it, +// `quote_by`, a [3, url, kwdict] record per file): built to that shape by +// hand -- the suite never contacts X. Lines: a post quoting Kirsche and the +// quote; a post with a picture quoting one with a picture (each with its file +// record); a post quoting the account's OWN older post, that post met first +// as the quote; a reply; and the older post again as a post of the timeline +// (gallery-dl's dedupe is off, so the walk still archives it). + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { normalizeXTweets } from "./xNormalize"; +import { parseGalleryDlOutput } from "./xGalleryDlFetcher"; + +const QUOTES_JSONL = readFileSync( + fileURLToPath(new URL("./__fixtures__/gallery-dl-timeline-quotes.jsonl", import.meta.url)), + "utf8", +); +const T1 = "1983300000000000001"; // quotes Kirsche's Q1 +const Q1 = "1983200000000000007"; +const T2 = "1983300000000000002"; // quotes quoted_person's Q2 +const Q2 = "1983100000000000003"; +const T3 = "1983300000000000003"; // quotes his own T5 +const T5 = "1981000000000000005"; +const T4 = "1983300000000000004"; // a reply + +test("every read keeps quoted posts and turns gallery-dl's own dedupe off; the media capture does neither", () => { + const timeline = buildGalleryDlArgs({ accountUrl: ACCOUNT, stream: true }); + const search = buildGalleryDlSearchArgs({ handle: "example_user", position: { since: "2020-12-11", until: "2021-03-11" } }); + for (const argv of [timeline, search]) { + assert.ok(argv.includes("extractor.twitter.quoted=true")); + assert.ok(argv.includes("extractor.twitter.unique=false")); + } + const capture = buildGalleryDlCaptureArgs({ id: "123", dir: "/corpus/x/posts-media/123" }); + assert.equal(capture.some((a) => a.startsWith("extractor.twitter.quoted=")), false, "a capture downloads the post's own media only"); +}); + +test("stream: a quoted tweet's record becomes the quoting post's `quoted`, never a post of the account's", () => { + const s = newStream({ channelSlug: "ObviousRises-x" }); + for (const line of QUOTES_JSONL.split("\n")) s.pushStdout(line); + const posts = s.finish(); + assert.deepEqual(posts.map((p) => p.id), [T1, T2, T3, T4, T5]); + const by = new Map(posts.map((p) => [p.id, p])); + assert.deepEqual(by.get(T1)?.quoted, { platform: "twitter", id: Q1, author: "Kirsche", url: `https://x.com/Kirsche/status/${Q1}` }); + assert.deepEqual(by.get(T2)?.quoted, { platform: "twitter", id: Q2, author: "quoted_person", url: `https://x.com/quoted_person/status/${Q2}` }); + // His own older post: the quote of the newer one, and archived as his post when the walk reaches it. + assert.equal(by.get(T3)?.quoted?.id, T5); + assert.equal(by.get(T3)?.quoted?.author, "ObviousRises"); + assert.equal(by.get(T5)?.text, "an older post of my own"); + assert.equal(by.get(T5)?.quoted, undefined); + assert.equal(by.get(T4)?.quoted, undefined); + assert.equal(by.get(T4)?.replyTo?.author, "Kirsche"); + assert.equal(by.get(T2)?.mediaCount, 1); + // Counted: 5 posts, 3 given their quote; gallery-dl yielded 8 tweets + // toward --post-range (each quote, and T5 twice — as a quote and as itself). + assert.equal(s.distinct, 5); + assert.equal(s.newPosts, 5); + assert.equal(s.quotesLinked, 3); + assert.equal(s.yielded, 8); +}); + +test("stream: a quote is no resume point and no stop — and is linked whichever of the two arrives first", () => { + const lines = QUOTES_JSONL.split("\n").filter(Boolean); + // T1 then Q1: Q1's id is OLDER than T1's, and must not become the walk's + // oldest post (a search window resumes below it). + const a = newStream(); + a.pushStdout(lines[0]); + a.pushStdout(lines[1]); + assert.equal(a.oldestId, T1); + // The quote first. + const b = newStream(); + b.pushStdout(lines[1]); + b.pushStdout(lines[0]); + const [post] = b.finish(); + assert.equal(post.quoted?.id, Q1); + // A quoting post already archived: not re-written, the quote not a post. + const c = newStream({ seenIds: new Set([T1]) }); + c.pushStdout(lines[0]); + c.pushStdout(lines[1]); + assert.deepEqual(c.finish(), []); + assert.equal(c.known, 1); + assert.equal(c.quotesLinked, 0); +}); + +test("normalizeXTweets (the Playwright fallback's batch) links quotes the same way", () => { + const posts = normalizeXTweets(parseGalleryDlOutput(QUOTES_JSONL), "ObviousRises-x"); + assert.deepEqual(posts.map((p) => p.id).sort(), [T5, T4, T3, T2, T1].sort()); + assert.equal(posts.find((p) => p.id === T1)?.quoted?.id, Q1); + assert.equal(posts.find((p) => p.id === T3)?.quoted?.id, T5); + assert.ok(!posts.some((p) => p.id === Q1 || p.id === Q2)); +}); diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -33,9 +33,9 @@ import { getPaths } from "../lib/paths"; import { noteXServiceOutcome } from "../lib/serviceCookies-server"; import { looksLikeXAuthFailure, xBlockKind, xBlockLine } from "./xGalleryDlSignals"; import { cookieArgs } from "../lib/cookiePolicy"; -import type { Post } from "../lib/posts"; +import type { Post, PostRef } from "../lib/posts"; import type { OlderBackfillPosition } from "../lib/posts-server"; -import { normalizeXTweet, xCreatedAt, type XTweetRaw } from "./xNormalize"; +import { normalizeXTweet, xCreatedAt, xIdOf, xQuoteOf, type XTweetRaw } from "./xNormalize"; import { OLDER_MAX_EMPTY_WINDOWS, OLDER_WINDOW_MONTHS, @@ -191,6 +191,21 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { "extractor.twitter.retweets=true", "-o", "extractor.twitter.replies=true", + // QUOTED POSTS: gallery-dl yields the post a tweet quotes as a record of + // its own, right after the tweet (its `quote_id` naming the quoting one) -- + // the only way a read learns what a post quotes, since its flat record of + // the quoting tweet names none. The stream (GalleryDlStream) turns it into + // the quoting post's `quoted` and never archives it as the account's own. + // On the timeline it costs no request: the quote is already inside the + // page X returned. + "-o", + "extractor.twitter.quoted=true", + // …and gallery-dl's own "previously seen" dedupe off: with quotes on, the + // account's OWN older post, met first as the quote of a newer one, would + // otherwise be skipped when the walk reaches it as a post of the timeline, + // and never archived. The stream dedupes by id itself. + "-o", + "extractor.twitter.unique=false", // Media is counted, not archived. "-o", "extractor.twitter.videos=false", @@ -201,7 +216,9 @@ function galleryDlCommonArgs(opts: GalleryDlLoginAndCap): string[] { ]; // A cap on POSTS. `--range` counts files, and with downloads off most tweets // yield none, so it never stopped the walk: a 400-post fetch of a new - // channel read 3,803. `--post-range` counts the tweets themselves. + // channel read 3,803. `--post-range` counts the tweets themselves -- the + // quoted ones and any repeat among them (GalleryDlStream.yielded is what + // a capped run is told by). if (opts.limit && opts.limit > 0) { args.push("--post-range", `1-${Math.floor(opts.limit)}`); } @@ -583,6 +600,12 @@ export type GalleryDlCheckpoint = { posts: Post[]; cursor: string }; export class GalleryDlStream { // Every distinct post seen this run, new or not. distinct = 0; + // Every record gallery-dl counted toward --post-range: each tweet it + // yielded, quoted ones and repeats included (a tweet's directory record and + // its per-URL records are one). What tells a capped run from a finished one. + yielded = 0; + // Posts read this run that a quoted record gave their `quoted`. + quotesLinked = 0; newPosts = 0; known = 0; older = 0; @@ -600,6 +623,11 @@ export class GalleryDlStream { private savedCursor?: string; private pending: Post[] = []; private ids = new Set<string>(); + private yieldedKeys = new Set<string>(); + // The new posts of this run by id, for a quote met after its quoting post. + private newById = new Map<string, Post>(); + // Quoting id → the quoted ref, for a quoting post met after its quote. + private quotedBy = new Map<string, PostRef>(); private knownRun = 0; private tail: string[] = []; private unparsed: string[] = []; @@ -697,6 +725,26 @@ export class GalleryDlStream { } private addRecord(rec: XTweetRaw): void { + const link = xQuoteOf(rec); + const rawId = xIdOf(rec); + // One tweet's directory record and its per-URL records are one post to + // --post-range; the same tweet quoted by two posts is two. + const tweetKey = rawId ? `${rawId}:${link?.quoterId ?? ""}` : ""; + if (tweetKey && !this.yieldedKeys.has(tweetKey)) { + this.yieldedKeys.add(tweetKey); + this.yielded++; + } + // A QUOTED tweet's own record: the quote of the post quoting it, never a + // post of this account's. Not counted, not a resume point, not a stop. + if (link) { + if (!this.quotedBy.has(link.quoterId)) this.quotedBy.set(link.quoterId, link.quoted); + const quoter = this.newById.get(link.quoterId); + if (quoter && !quoter.quoted) { + quoter.quoted = link.quoted; + this.quotesLinked++; + } + return; + } const post = normalizeXTweet(rec, this.opts.channelSlug); // gallery-dl can emit a tweet more than once (a directory record, then one // per media URL); count it once. @@ -729,6 +777,12 @@ export class GalleryDlStream { } this.knownRun = 0; this.newPosts++; + const quoted = this.quotedBy.get(post.id); + if (quoted && !post.quoted) { + post.quoted = quoted; + this.quotesLinked++; + } + this.newById.set(post.id, post); this.pending.push(post); } } @@ -1122,7 +1176,8 @@ async function walkSearchWindows( } onLog?.( `${windowStart.since} – ${windowStart.until}: read ${stream.distinct} post(s), ${stream.newPosts} new` + - (stream.known ? `, ${stream.known} already archived` : ""), + (stream.known ? `, ${stream.known} already archived` : "") + + (stream.quotesLinked ? `, ${stream.quotesLinked} with the post it quotes` : ""), ); if (stream.challengeLine) { @@ -1148,7 +1203,7 @@ async function walkSearchWindows( error: `gallery-dl exited ${res.exitCode ?? res.signal ?? "abnormally"}: ${tail || "(no output)"}`, }); } - if (remainingLimit !== undefined && stream.distinct >= remainingLimit) { + if (remainingLimit !== undefined && stream.yielded >= remainingLimit) { return stopped(here); } @@ -1393,7 +1448,8 @@ export const xGalleryDlFetcher: SocialFetcher = { onLog?.( `gallery-dl read ${stream.distinct} post(s): ${stream.newPosts} new` + (stream.known ? `, ${stream.known} already archived` : "") + - (stream.older ? `, ${stream.older} older than the watermark` : ""), + (stream.older ? `, ${stream.older} older than the watermark` : "") + + (stream.quotesLinked ? `, ${stream.quotesLinked} new with the post it quotes` : ""), ); // Where the next run should pick up when this one did not finish: the last @@ -1460,7 +1516,7 @@ export const xGalleryDlFetcher: SocialFetcher = { // A clean exit walked everything it was given: gallery-dl waits out rate // limits rather than skipping pages. Only a --post-range cap leaves history // behind — resume from the last page it finished. - const capped = Boolean(limit && stream.distinct >= limit); + const capped = Boolean(limit && stream.yielded >= limit); return capped ? { posts, complete: false, cursor: resumeAt } : { posts, complete: true }; diff --git a/common/social/xNormalize.ts b/common/social/xNormalize.ts @@ -144,6 +144,25 @@ function refFrom( return ref; } +// THE QUOTED TWEET AS gallery-dl YIELDS IT. With its twitter `quoted` option +// on (every read here turns it on, xGalleryDlFetcher.ts), gallery-dl yields a +// quoted tweet as a record of its own, right after the tweet quoting it, its +// `quote_id` naming the QUOTING tweet (and `quote_by` that tweet's author) -- +// the reverse link: X's timeline carries the quote inside the quoting tweet, +// and gallery-dl's flat record of the quoting tweet names no quote at all. +// Such a record is not one of the account's posts: it says what ANOTHER post +// quotes. This is the link it carries -- the quoting tweet's id, and the ref +// the quoting post's `quoted` should hold -- or null for any other record. +export function xQuoteOf(rec: XTweetRaw): { quoterId: string; quoted: PostRef } | null { + const quoterId = refId(rec.quote_id); + if (!quoterId) return null; + const id = xIdOf(rec); + if (!id || id === quoterId) return null; + const handle = xAuthor(rec).handle; + const quoted = refFrom(id, handle || undefined); + return quoted ? { quoterId, quoted } : null; +} + // Normalize one tweet record into a Post. Returns null when the record has no // resolvable id or timestamp — a shape we don't understand is skipped rather // than stored as a corrupt entry. @@ -244,15 +263,27 @@ export function normalizeXTweet( } // Normalize a batch, dropping unparseable records and deduping by id (a -// timeline page can repeat a tweet across a cursor boundary). +// timeline page can repeat a tweet across a cursor boundary). A quoted tweet's +// own record (xQuoteOf) is not a post of the batch: it becomes the `quoted` of +// the post quoting it, where that post names none. export function normalizeXTweets( records: ReadonlyArray<XTweetRaw>, channelSlug: string, ): Post[] { const byId = new Map<string, Post>(); + const quotes = new Map<string, PostRef>(); for (const rec of records) { + const link = xQuoteOf(rec); + if (link) { + if (!quotes.has(link.quoterId)) quotes.set(link.quoterId, link.quoted); + continue; + } const post = normalizeXTweet(rec, channelSlug); if (post && !byId.has(post.id)) byId.set(post.id, post); } + for (const [quoterId, quoted] of quotes) { + const post = byId.get(quoterId); + if (post && !post.quoted) post.quoted = quoted; + } return [...byId.values()]; } diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -37,6 +37,12 @@ // page per distinct archived author for that alone, and writes no capture // record. // +// The post's CONTEXT -- the post it quotes and the post it answers, as the +// page shows them -- is read off the same page too (xPostContext.ts) and kept +// in capture.json's `context`, unless `context` is off. `contextOnly` loads +// one page per post for that alone (and the avatars it shows), and writes the +// context into the post's record, nothing else. +// // NOT VERIFIED AGAINST LIVE X. The page markers below are X's as of this // writing and are tested against recorded snapshots, never x.com; the first // real run is the check. @@ -62,6 +68,7 @@ import { type CaptureMediaState, type PostCaptureRecord, type PostCaptureState, + type PostContextRecord, } from "./postCapture"; import { xArticleLinkFromArchive, type XArticleLink } from "./xArticle"; import { captureXArticle, xArticleLinkFromCard } from "./xArticleCapture"; @@ -77,6 +84,14 @@ import { type XAvatarRunSummary, } from "./xAvatarCapture"; import { lookupXAvatar, readXAvatarIndex, xAvatarsDir } from "./xAvatars"; +import { + describeContext, + describeContextSummary, + emptyContextSummary, + noteContext, + readXPostContext, + type XContextReadOptions, +} from "./xPostContext"; // The post's own article, marked by the snapshot. const CAPTURE_SELECTOR = "[data-archilyzer-capture]"; @@ -228,6 +243,9 @@ export type XShotResult = XPostVerdict & { thread?: ThreadShotResult; // The avatars read off the page, when asked for and the post rendered. avatars?: XAvatarCandidate[]; + // The quoted post and the parent, read off the page, when asked for and + // the post rendered (null: the page could not be read for them). + context?: PostContextRecord | null; }; export type XShotOptions = { @@ -239,6 +257,8 @@ export type XShotOptions = { // Read the authors' avatars off the page (xAvatarCapture.ts): nothing is // fetched here, the caller saves them through the same page. avatars?: XAvatarReadOptions | null; + // Read the post's context (xPostContext.ts): the quoted post, the parent. + context?: XContextReadOptions | null; }; // One post's screenshot: load, read the page, open a sensitive cover, shoot @@ -287,7 +307,8 @@ export async function shootXPost( // Before any shot: the thread shot's blur is a CSS filter, but the read // should see the page as X drew it. const avatars = opts.avatars ? await readXAvatarCandidates(page, opts.avatars) : undefined; - const found = avatars ? { avatars } : {}; + const context = opts.context ? await readXPostContext(page, opts.context) : undefined; + const found = { ...(avatars ? { avatars } : {}), ...(context !== undefined ? { context } : {}) }; if (opts.own === false) { const thread = opts.thread ? await shootXThread(page, id, dir, { ...opts.thread, url, onLog }) : undefined; return { ...verdict, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found }; @@ -369,12 +390,15 @@ export async function captureXPosts( articles: input.articles ?? true, thread: input.thread ?? false, avatars: input.avatars ?? true, + context: input.context ?? true, }; + if (input.contextOnly) return captureXContextOnly(input, deps); if (input.avatarsOnly) return captureXAvatarsOnly(input, deps); const now = deps.now ?? (() => new Date()); const avatarDir = xAvatarsDir(input.outDir); const avatarSeen = new Set<string>(); const avatarSummary = emptyAvatarSummary(); + const contextSummary = emptyContextSummary(); const outcomes: PostCaptureOutcome[] = []; let contacts = 0; let errorsInARow = 0; @@ -389,9 +413,14 @@ export async function captureXPosts( onLog?.(describeAvatarSummary(s)); return { avatars: s }; }; + const withContext = (): Partial<PostCaptureResult> => { + if (!contextSummary.read && !contextSummary.failed.length) return {}; + onLog?.(describeContextSummary(contextSummary)); + return { context: contextSummary }; + }; const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => { onLog?.(why); - return { outcomes, stoppedEarly: why, ...extra, ...withAvatars() }; + return { outcomes, stoppedEarly: why, ...extra, ...withAvatars(), ...withContext() }; }; try { @@ -429,6 +458,8 @@ export async function captureXPosts( let state: PostCaptureState | undefined = work.shot ? undefined : existing?.state; let sensitive = work.shot ? undefined : existing?.sensitive; let shot = work.shot ? undefined : existing?.shot; + // The context is read from any page this run loads; else the last one's stands. + let context = existing?.context; let error: string | undefined; let stop: string | undefined; @@ -442,7 +473,12 @@ export async function captureXPosts( ? { replyTo: arch?.replyTo ?? null, ownHandle: arch?.author, redact: threadRedactFor(input.threadRedact, id) } : null, avatars: wanted.avatars ? avatarReadOptions(wanted.thread, arch) : null, + context: wanted.context ? contextReadOptions(arch, now) : null, }); + if (res.context) { + context = res.context; + noteContext(contextSummary, res.context); + } if (res.avatars?.length) { await saveXAvatars(browser.page, res.avatars, { dir: avatarDir, @@ -542,6 +578,7 @@ export async function captureXPosts( ...(thread ? { thread } : {}), ...(threadNone && !thread ? { threadNone } : {}), ...(threadError && !thread ? { threadError } : {}), + ...(context ? { context } : {}), ...(error ? { error } : {}), }; await writePostCapture(dir, record); @@ -565,6 +602,7 @@ export async function captureXPosts( (work.thread && !thread && (threadNone || threadError) ? `, no thread shot: ${threadNone ?? threadError}` : "") + (mediaState === "ok" ? `, ${media.length} media file(s)` : mediaState === "none" ? ", no media" : "") + (article && article !== existing?.article ? `, ${describeArticle(article)}` : "") + + (context && context !== existing?.context ? `, ${describeContext(context)}` : "") + (error ? ` — ${error}` : ""), ); @@ -580,13 +618,22 @@ export async function captureXPosts( ); } } - return { outcomes, ...withAvatars() }; + return { outcomes, ...withAvatars(), ...withContext() }; } finally { await browser?.close().catch(() => {}); } } type ArchivedForAvatars = { author?: string; isReply?: boolean; replyTo?: { id: string } } | undefined; +type ArchivedForContext = + | { replyTo?: { id: string; author?: string }; quoted?: { id: string; author?: string } } + | undefined; + +// What the context read is told by the archive: the id the post answers (its +// parent is that article), and the id it quotes (for a card that names none). +function contextReadOptions(arch: ArchivedForContext, now: () => Date): XContextReadOptions { + return { replyTo: arch?.replyTo ?? null, quoted: arch?.quoted ?? null, now }; +} // What the avatar read looks for on one post's page: its author's always; // with the thread on, the post it answers (unless the archive says it is no @@ -681,6 +728,122 @@ async function captureXAvatarsOnly(input: PostCaptureInput, deps: XCaptureDeps): } } +// `contextOnly`: one post page per post, its CONTEXT read off it (the post it +// quotes, the post it answers) and written into the post's capture.json -- +// merged into the record there, or a record of its own (state "captured", +// nothing shot, media owed) when there is none -- and the avatars the page +// shows saved (unless `avatars` is off). No shot, no media, no article, no +// thread shot, no availability: `outcomes` stays empty. A post whose context +// is already recorded, or that a capture found deleted, is not loaded unless +// `force`. Paced like every other X contact, and stopped like one. +async function captureXContextOnly(input: PostCaptureInput, deps: XCaptureDeps): Promise<PostCaptureResult> { + const { signal, onLog } = input; + const force = input.force ?? false; + const avatarsOn = input.avatars ?? true; + const now = deps.now ?? (() => new Date()); + const avatarDir = xAvatarsDir(input.outDir); + const summary = emptyContextSummary(); + const avatarSummary = emptyAvatarSummary(); + const avatarSeen = new Set<string>(); + + const picks: { id: string; existing: PostCaptureRecord | null }[] = []; + for (const id of input.ids) { + const existing = await readPostCapture(postCaptureDir(input.outDir, id)); + if (!force && existing?.context) { + summary.skipped++; + onLog?.(`${id}: context already read (${existing.context.readAt}) — skipped (no page load).`); + continue; + } + if (!force && existing?.state === "deleted") { + summary.skipped++; + onLog?.(`${id}: captured as deleted — skipped.`); + continue; + } + picks.push({ id, existing }); + } + onLog?.(`Context only: ${picks.length} post page(s) to load.`); + + let contacts = 0; + let errorsInARow = 0; + let browser: { page: PageLike; close: () => Promise<void> } | undefined; + const done = (extra: Partial<PostCaptureResult> = {}): PostCaptureResult => { + onLog?.(describeContextSummary(summary)); + const avatars = avatarSummary.stored.length || avatarSummary.skipped.length || avatarSummary.failed.length; + if (avatars) onLog?.(describeAvatarSummary(avatarSummary)); + return { outcomes: [], context: summary, ...(avatars ? { avatars: avatarSummary } : {}), ...extra }; + }; + const stopped = (why: string, extra: Partial<PostCaptureResult> = {}) => { + onLog?.(why); + return done({ stoppedEarly: why, ...extra }); + }; + try { + for (const [i, { id, existing }] of picks.entries()) { + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run."); + if (contacts++ > 0) await deps.pause(deps.pauseMs(), signal); + if (signal.aborted) return stopped("Cancelled; the rest are left for a later run."); + onLog?.(`[${i + 1}/${picks.length}] ${id} (for its context)`); + browser ??= await deps.openPage(); + summary.pages++; + const arch = input.archived?.get(id); + const dir = postCaptureDir(input.outDir, id); + const res = await shootXPost(browser.page, id, dir, onLog, { + own: false, + thread: null, + avatars: avatarsOn ? { parent: true, quotes: true, parentId: arch?.replyTo?.id ?? null } : null, + context: contextReadOptions(arch, now), + }); + if (res.state !== "captured") { + const why = res.error ?? `the page showed the post as ${res.state}`; + onLog?.(`${id}: no context read — ${why}.`); + summary.failed.push({ id, error: why }); + if (res.stop) { + return stopped(`${res.stop} Stopped at ${id}; the rest are left for a later run.`, { + needsCookies: res.state === "login-wall", + }); + } + errorsInARow = res.state === "error" ? errorsInARow + 1 : 0; + if (errorsInARow >= STOP_AFTER_ERRORS) { + return stopped(`${STOP_AFTER_ERRORS} pages in a row failed; stopping rather than paging through the rest.`); + } + continue; + } + errorsInARow = 0; + if (res.avatars?.length) { + await saveXAvatars(browser.page, res.avatars, { + dir: avatarDir, postId: id, force, seen: avatarSeen, summary: avatarSummary, now, onLog, + }); + } + if (!res.context) { + summary.failed.push({ id, error: "the page could not be read for its context" }); + onLog?.(`${id}: the page could not be read for its context.`); + continue; + } + // Re-read: a capture that ran meanwhile wrote the rest of the record. + const base = (await readPostCapture(dir)) ?? existing; + const record: PostCaptureRecord = base + ? { ...base, context: res.context } + : { + version: 1, + id, + url: xStatusUrl(id), + capturedAt: now().toISOString(), + state: "captured", + ...(res.sensitive ? { sensitive: true } : {}), + mediaState: "skipped", + media: [], + context: res.context, + }; + await writePostCapture(dir, record); + noteContext(summary, res.context); + onLog?.(`${id}: ${describeContext(res.context)}.`); + } + return done(); + } finally { + await browser?.close().catch(() => {}); + } +} + // The blur knob for one post: the run's, or the post's own entry of it. export function threadRedactFor( knob: PostCaptureInput["threadRedact"], diff --git a/common/social/xPostContext.test.ts b/common/social/xPostContext.test.ts @@ -0,0 +1,282 @@ +// The context half of the X capture (the quoted post, the parent), against +// fakes only: the parse of the in-page read's answer, the record built from +// it, and the run (a normal capture and contextOnly) over a page that answers +// the capture's evaluates. The in-page read itself is proved in a real +// Chromium by xAvatarCapture.browser.test.ts, against the recorded-style page. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xPostContext.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { PageLike } from "./playwrightRuntime"; +import { captureXPosts, type XCaptureDeps, type XPostSnapshot } from "./xPostCapture"; +import { + CONTEXT_SCRIPT_MARKER, + CONTEXT_TEXT_MAX, + contextRecordFrom, + contextScript, + parseContextPost, + readXPostContext, +} from "./xPostContext"; +import { THREAD_SNAPSHOT_MARKER, type ThreadSnapshot } from "./xThreadShot"; +import { AVATARS_SCRIPT_MARKER } from "./xAvatarCapture"; +import { VIEW_SCRIPT_MARKER } from "./viewportShot"; +import { readPostCapture, writePostCapture } from "./postCapture"; +import type { PostCaptureInput } from "./fetchers"; + +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 9, 9]); +const RECT = { x: 10, y: 120, width: 598, height: 300 }; +const snap = (id: string): XPostSnapshot => ({ path: `/ObviousRises/status/${id}`, text: "the post", article: { rect: RECT, sensitive: false } }); + +// What the read returns for the operator's case: a reply to Kirsche, quoting +// a third post. +const KIRSCHE = { + id: "1983000000000000001", + handle: "Kirsche", + author: "Kirsche", + verified: true, + badge: "blue", + date: "2026-10-29T13:00:00.000Z", + text: "Your whole channel is grift.", + media: [], +}; +const QUOTED = { + id: null, + handle: "quoted_person", + author: "Quoted Person", + verified: false, + badge: null, + date: "2026-10-28T09:00:00.000Z", + text: "The receipt itself.", + media: [{ kind: "image", url: "https://pbs.twimg.com/media/QQ1.jpg?format=jpg&name=small" }], +}; +const THREAD: ThreadSnapshot = { + own: 1, + articles: [ + { id: KIRSCHE.id, handle: "Kirsche", verified: true, badge: "blue", top: 0, bottom: 200 }, + { id: "1983000000000000002", handle: "ObviousRises", verified: false, top: 200, bottom: 500 }, + ], +}; + +test("parse: the read's post kept to the shape — ids are digits, the date ISO, the media http(s) and at most four, the text capped", () => { + const p = parseContextPost({ + ...KIRSCHE, + handle: "@Kirsche", + date: "2026-10-29T13:00:00Z", + badge: "platinum", + media: [ + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "gif", url: "https://pbs.twimg.com/media/b.jpg" }, + { kind: "video", url: "javascript:alert(1)" }, + { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, + ], + }); + assert.deepEqual(p, { + id: KIRSCHE.id, + url: `https://x.com/Kirsche/status/${KIRSCHE.id}`, + handle: "Kirsche", + author: "Kirsche", + verified: true, + date: "2026-10-29T13:00:00.000Z", + text: "Your whole channel is grift.", + media: [ + { kind: "image", url: "https://pbs.twimg.com/media/a.jpg" }, + { kind: "video", url: "https://pbs.twimg.com/ext_tw_video_thumb/1/pu/img/c.jpg" }, + ], + }); + assert.equal(parseContextPost({ ...KIRSCHE, id: "../etc", handle: "not a handle!" })?.id, undefined); + assert.equal(parseContextPost({ ...KIRSCHE, text: "x".repeat(CONTEXT_TEXT_MAX + 50) })?.text.length, CONTEXT_TEXT_MAX); + // Nobody and nothing said is no post. + assert.equal(parseContextPost({ handle: null, text: " " }), null); + assert.equal(parseContextPost("a string"), null); + assert.equal(parseContextPost(null), null); +}); + +test("record: the quote and the parent with how the parent was told; the archive's quoted id fills a card that names none, only when the authors agree", () => { + const rec = contextRecordFrom({ quoted: QUOTED, parent: KIRSCHE }, { from: "above" }, { + quoted: { id: "1982000000000000009", author: "quoted_person" }, + readAt: "2026-11-02T20:00:00.000Z", + }); + assert.equal(rec?.readAt, "2026-11-02T20:00:00.000Z"); + assert.equal(rec?.parent?.from, "above"); + assert.equal(rec?.parent?.handle, "Kirsche"); + assert.equal(rec?.parent?.badge, "blue"); + assert.equal(rec?.quoted?.id, "1982000000000000009"); + assert.equal(rec?.quoted?.url, "https://x.com/quoted_person/status/1982000000000000009"); + assert.equal(rec?.quoted?.media.length, 1); + + const other = contextRecordFrom({ quoted: QUOTED, parent: null }, null, { quoted: { id: "1982000000000000009", author: "someone_else" }, readAt: "t" }); + assert.equal(other?.quoted?.id, undefined, "another author's id is not this card's"); + // No pick: no parent, whatever the page answered. + assert.equal(contextRecordFrom({ quoted: null, parent: KIRSCHE }, null, { readAt: "t" })?.parent, undefined); + // Neither: still a read. + assert.deepEqual(contextRecordFrom({ quoted: null, parent: null }, null, { readAt: "t" }), { readAt: "t" }); + // Not the read's shape: not read. + assert.equal(contextRecordFrom(snap("1"), null, { readAt: "t" }), null); + assert.equal(contextRecordFrom(null, null, { readAt: "t" }), null); +}); + +test("script: carries its marker; reads the parent at the picked index, or none", () => { + assert.ok(contextScript(0).includes(CONTEXT_SCRIPT_MARKER)); + assert.match(contextScript(3), /all\[3\] \|\| null/); + assert.match(contextScript(null), /const parent = null;/); + assert.ok(contextScript(null).includes("badgeOf"), "the badge is told as the thread snapshot tells it"); +}); + +function contextPage(answer: { quoted: unknown; parent: unknown }, thread: ThreadSnapshot = THREAD) { + const reads: string[] = []; + const gotos: string[] = []; + let current = ""; + const page: PageLike & { reads: string[]; gotos: string[]; shots: number } = { + reads, + gotos, + shots: 0, + goto: async (url: string) => { + gotos.push(url); + current = /status\/(\d+)/.exec(url)?.[1] ?? ""; + }, + waitForSelector: async () => undefined, + waitForTimeout: async () => undefined, + on: () => {}, + evaluate: async (script: string) => { + if (script.includes(THREAD_SNAPSHOT_MARKER)) { + reads.push("thread"); + return thread; + } + if (script.includes(CONTEXT_SCRIPT_MARKER)) { + reads.push(`context ${/all\[(\d+)\]/.exec(script)?.[1] ?? "none"}`); + return answer; + } + if (script.includes(AVATARS_SCRIPT_MARKER)) return []; + if (script.includes(VIEW_SCRIPT_MARKER)) return null; + if (script.includes("imgs.length")) return 0; + return snap(current); + }, + screenshot: async () => { + page.shots++; + return PNG; + }, + }; + return page; +} + +test("read: the parent is the archive's in-reply-to id when it says, else the article above; an id not on the page is no parent", async () => { + const page = contextPage({ quoted: null, parent: KIRSCHE }); + const told = await readXPostContext(page, { replyTo: { id: KIRSCHE.id }, now: () => new Date("2026-11-02T00:00:00Z") }); + assert.equal(told?.parent?.from, "reply-to"); + assert.deepEqual(page.reads, ["thread", "context 0"]); + // The archive says nothing (the operator's case): the article above. + assert.equal((await readXPostContext(page, { replyTo: null }))?.parent?.from, "above"); + // An id not on the page: the article above is not taken for it. + page.reads.length = 0; + const wrong = await readXPostContext(page, { replyTo: { id: "1" } }); + assert.equal(wrong?.parent, undefined); + assert.deepEqual(page.reads, ["thread", "context none"]); +}); + +const deps = (page: PageLike, pauses: number[] = []): XCaptureDeps => ({ + openPage: async () => ({ page, close: async () => {} }), + downloadMedia: async () => ({ ok: true, files: [] }), + pauseMs: () => 5000, + pause: async (ms) => void pauses.push(ms), + now: () => new Date("2026-11-02T20:00:00.000Z"), +}); + +const input = async (over: Partial<PostCaptureInput> = {}): Promise<PostCaptureInput> => ({ + ids: ["1983000000000000002"], + handle: "ObviousRises", + outDir: path.join(await mkdtemp(path.join(os.tmpdir(), "xcontext-")), "posts-media"), + signal: new AbortController().signal, + media: false, + articles: false, + avatars: false, + ...over, +}); + +test("run: a normal capture writes the context it read into capture.json, from the page it shot — one load", async () => { + const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); + const inp = await input(); + const res = await captureXPosts(inp, deps(page)); + assert.equal(res.outcomes[0]?.state, "captured"); + assert.equal(page.gotos.length, 1); + assert.equal(page.shots, 1); + const rec = await readPostCapture(path.join(inp.outDir, "1983000000000000002")); + assert.equal(rec?.context?.readAt, "2026-11-02T20:00:00.000Z"); + assert.equal(rec?.context?.parent?.handle, "Kirsche"); + assert.equal(rec?.context?.quoted?.text, "The receipt itself."); + assert.deepEqual(res.context, { read: 1, quoted: 1, parents: 1, skipped: 0, pages: 0, failed: [] }); + + // context: false reads none, and keeps the one on disk. + const again = contextPage({ quoted: null, parent: null }); + const res2 = await captureXPosts({ ...inp, force: true, context: false }, deps(again)); + assert.equal(res2.context, undefined); + assert.ok(!again.reads.includes("thread")); + assert.equal((await readPostCapture(path.join(inp.outDir, "1983000000000000002")))?.context?.parent?.handle, "Kirsche"); +}); + +test("contextOnly: one page per post, paced, no shot, the context merged into the record — or a record of its own; read ones and deleted ones not loaded", async () => { + const page = contextPage({ quoted: QUOTED, parent: KIRSCHE }); + const inp = await input({ ids: ["11", "22", "33", "44"], contextOnly: true, shots: false }); + // 22 was shot before; 33's context is already read; 44 was found deleted. + const shot = { name: "shot.png", bytes: 6, sha256: "ab" }; + await writePostCapture(path.join(inp.outDir, "22"), { + version: 1, id: "22", url: "https://x.com/i/status/22", capturedAt: "2026-10-01T00:00:00.000Z", state: "captured", + shot, mediaState: "ok", media: [shot], + }); + await writePostCapture(path.join(inp.outDir, "33"), { + version: 1, id: "33", url: "https://x.com/i/status/33", capturedAt: "x", state: "captured", mediaState: "none", media: [], + context: { readAt: "2026-10-30T00:00:00.000Z" }, + }); + await writePostCapture(path.join(inp.outDir, "44"), { + version: 1, id: "44", url: "https://x.com/i/status/44", capturedAt: "x", state: "deleted", mediaState: "skipped", media: [], + }); + const pauses: number[] = []; + const res = await captureXPosts(inp, deps(page, pauses)); + assert.deepEqual(res.outcomes, []); + assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); + assert.deepEqual(pauses, [5000], "paced before every page after the first"); + assert.equal(page.shots, 0); + assert.deepEqual(res.context, { read: 2, quoted: 2, parents: 2, skipped: 2, pages: 2, failed: [] }); + + const fresh = (await readPostCapture(path.join(inp.outDir, "11")))!; + assert.equal(fresh.state, "captured"); + assert.equal(fresh.shot, undefined); + assert.equal(fresh.mediaState, "skipped", "the media is still owed"); + assert.equal(fresh.context?.parent?.id, KIRSCHE.id); + assert.deepEqual(await readdir(path.join(inp.outDir, "11")), ["capture.json"]); + const merged = (await readPostCapture(path.join(inp.outDir, "22")))!; + assert.deepEqual(merged.shot, shot); + assert.equal(merged.capturedAt, "2026-10-01T00:00:00.000Z"); + assert.equal(merged.context?.quoted?.handle, "quoted_person"); + assert.equal((await readPostCapture(path.join(inp.outDir, "33")))?.context?.readAt, "2026-10-30T00:00:00.000Z"); + + // force reads again. + const page2 = contextPage({ quoted: null, parent: null }); + await captureXPosts({ ...inp, ids: ["33"], force: true }, deps(page2)); + assert.deepEqual((await readPostCapture(path.join(inp.outDir, "33")))?.context, { readAt: "2026-11-02T20:00:00.000Z" }); +}); + +test("contextOnly: a login wall stops the run with needsCookies, the rest left; a page that is not the post writes nothing", async () => { + let n = 0; + const page = contextPage({ quoted: null, parent: null }); + const inner = page.evaluate; + page.evaluate = async (s: string) => { + if (!s.includes(CONTEXT_SCRIPT_MARKER) && !s.includes(THREAD_SNAPSHOT_MARKER) && !s.includes("imgs.length")) { + n++; + if (n === 1) return { path: "/i/status/11", text: "This post was deleted", article: null }; + return { path: "/i/flow/login", text: "", article: null }; + } + return inner(s); + }; + const inp = await input({ ids: ["11", "22", "33"], contextOnly: true }); + const res = await captureXPosts(inp, deps(page)); + assert.equal(res.needsCookies, true); + assert.match(res.stoppedEarly ?? "", /Stopped at 22/); + assert.deepEqual(page.gotos, ["https://x.com/i/status/11", "https://x.com/i/status/22"]); + assert.deepEqual(await readdir(inp.outDir).catch(() => []), []); + assert.equal(res.context?.failed.length, 2); +}); diff --git a/common/social/xPostContext.ts b/common/social/xPostContext.ts @@ -0,0 +1,254 @@ +// Reading an X post's CONTEXT off the post page capture-posts has ALREADY +// loaded: the post it QUOTES (the card inside its own article) and the post it +// ANSWERS (the article above it), into capture.json's `context` +// (postCapture.ts has the record's shape). +// +// Why: the archive often names neither. A timeline read keeps no quoted post +// unless gallery-dl is asked to (xGalleryDlFetcher.ts now asks), and a reply's +// parent is another account's post, never archived with the account's own -- +// so a post video drew "you called me a Leftist…" with nothing it answered. +// The page shows both, so the capture that loads it reads them. +// +// NO EXTRA PAGE LOAD. Two evaluates over the page as it stands, before any +// shot (the thread shot's blur is a CSS filter; the read sees X's drawing): +// 1. the thread snapshot (xThreadShot.ts) and its pick of the IMMEDIATE +// parent -- the article whose status link is the archive's in-reply-to +// id, else (the archive not saying) the article directly above the post; +// an archive id not on the page is no parent at all. Read whether or not +// the archive calls the post a reply: X draws only a status's ancestors +// above it, and the archive is often what is wrong; +// 2. the context read: that parent article's author, check, date, words and +// media, and the post's own quote card (a `div[role="link"]` inside its +// article holding a User-Name) -- the same fields, and its status id when +// a link inside the card names one (a quote card often has none: the +// archive's quoted id fills it, when its author agrees). +// +// The words are kept whole; the people are not judged here. Whose name a card +// may show is the card's rule (umtool post-item.mjs authorRedaction), which +// blurs every author but the subject unless gold- or grey-checked -- the +// badge recorded here is what it decides by. capture.json is editor-only. +// +// NOT VERIFIED AGAINST LIVE X: the markup is X's as of 2026-11, proved against +// a recorded-style fixture page in a real Chromium +// (xAvatarCapture.browser.test.ts); the first real run is the check. + +import type { PageLike } from "./playwrightRuntime"; +import type { PostContextPost, PostContextRecord } from "./postCapture"; +import { BADGE_OF_JS, pickThreadParent, threadSnapshotScript, type ThreadSnapshot } from "./xThreadShot"; + +export const CONTEXT_SCRIPT_MARKER = "__archilyzerContext"; + +// The longest text kept of one context post (a long post's whole body is a +// note-tweet's 25,000; a card never draws more than a few lines of context). +export const CONTEXT_TEXT_MAX = 10_000; +const MEDIA_MAX = 4; + +// The in-page read: the parent article at `parentIndex` (among +// `article[data-testid="tweet"]`, the thread snapshot's order) and the quote +// card inside the marked own article. Each as { id, handle, author, verified, +// badge, date, text, media }; null where there is none. Null altogether when +// the own article is not marked. +export const contextScript = (parentIndex: number | null) => `(() => { + const ${CONTEXT_SCRIPT_MARKER} = true; + const badgeOf = ${BADGE_OF_JS}; + const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); + const own = document.querySelector("[data-archilyzer-capture]"); + if (!own) return null; + const HANDLE = /^[A-Za-z0-9_]{1,30}$/; + // A quote card: a div link inside an article, holding a User-Name. + const inCard = (el, root) => { const q = el.closest('div[role="link"]'); return !!q && root.contains(q) && q !== root; }; + const cardOf = (a) => Array.from(a.querySelectorAll('div[role="link"]')).find((q) => q.querySelector('[data-testid="User-Name"]')) || null; + const read = (root, isCard) => { + // An article's own parts, never its quote card's; a card's, all of them. + const pick = (sel) => Array.from(root.querySelectorAll(sel)).filter((el) => isCard || !inCard(el, root)); + const un = pick('[data-testid="User-Name"]')[0] || null; + let handle = null, id = null; + const links = pick('a[href*="/status/"]'); + const timed = links.filter((l) => l.querySelector("time")); + for (const l of [...timed, ...(isCard ? links : [])]) { + const m = /^(?:https:\\/\\/(?:x|twitter)\\.com)?\\/([A-Za-z0-9_]{1,30})\\/status\\/(\\d+)/.exec(l.getAttribute("href") || ""); + if (m) { handle = m[1]; id = m[2]; break; } + } + if (!handle) { + const c = pick('[data-testid^="UserAvatar-Container-"]')[0]; + const t = c ? (c.getAttribute("data-testid") || "").replace(/^UserAvatar-Container-/, "") : ""; + if (HANDLE.test(t)) handle = t; + } + const lines = un ? (un.innerText || "").split("\\n").map((s) => s.trim()).filter((s) => s && s !== "·") : []; + if (!handle) { + const at = lines.map((s) => /(?:^|\\s)@([A-Za-z0-9_]{1,30})\\b/.exec(s)).find(Boolean); + if (at) handle = at[1]; + } + let author = null; + if (un && handle) { + for (const l of un.querySelectorAll("a[href]")) { + const h = (l.getAttribute("href") || "").split(/[?#]/)[0].toLowerCase(); + const t = (l.innerText || "").trim(); + if (h === "/" + handle.toLowerCase() && t && !t.startsWith("@")) { author = t; break; } + } + } + if (!author && lines[0] && !lines[0].startsWith("@")) author = lines[0].split(/\\s+@[A-Za-z0-9_]/)[0].trim() || null; + const icon = un && un.querySelector('[data-testid="icon-verified"]'); + const time = (timed[0] && timed[0].querySelector("time[datetime]")) || pick("time[datetime]")[0] || null; + const words = pick('[data-testid="tweetText"]')[0]; + const media = []; + for (const img of pick('[data-testid="tweetPhoto"] img[src]')) media.push({ kind: "image", url: img.src }); + for (const v of pick("video")) { const u = v.poster || v.currentSrc || v.src; if (u) media.push({ kind: "video", url: new URL(u, location.href).href }); } + return { + id, handle, author, + verified: !!icon, badge: icon ? badgeOf(icon) : null, + date: time ? time.getAttribute("datetime") : null, + text: words ? (words.innerText || "").trim() : "", + media, + }; + }; + const card = cardOf(own); + const parent = ${parentIndex === null ? "null" : `all[${Math.floor(parentIndex)}] || null`}; + return { quoted: card ? read(card, true) : null, parent: parent && parent !== own ? read(parent, false) : null }; +})()`; + +const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/; +const ID_RE = /^\d{1,25}$/; +const BADGES = new Set(["blue", "gold", "grey", "other"]); + +function statusUrl(id: string | undefined, handle: string | undefined): string | undefined { + if (!id) return undefined; + return handle ? `https://x.com/${handle}/status/${id}` : `https://x.com/i/status/${id}`; +} + +// One post of what the read returned, kept to the shape (null: not a post — +// no author and no words is nothing to draw). +export function parseContextPost(raw: unknown): PostContextPost | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record<string, unknown>; + const s = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined); + const id = s(r.id) && ID_RE.test(s(r.id)!) ? s(r.id) : undefined; + const handle = s(r.handle)?.replace(/^@/, ""); + const okHandle = handle && HANDLE_RE.test(handle) ? handle : undefined; + const text = typeof r.text === "string" ? r.text.trim().slice(0, CONTEXT_TEXT_MAX) : ""; + if (!okHandle && !text) return null; + const author = s(r.author)?.slice(0, 200); + const dateRaw = s(r.date); + const date = dateRaw && Number.isFinite(Date.parse(dateRaw)) ? new Date(Date.parse(dateRaw)).toISOString() : undefined; + const badge = typeof r.badge === "string" && BADGES.has(r.badge) ? (r.badge as PostContextPost["badge"]) : undefined; + const media: PostContextPost["media"] = []; + const seen = new Set<string>(); + for (const m of Array.isArray(r.media) ? r.media : []) { + if (!m || typeof m !== "object") continue; + const { kind, url } = m as Record<string, unknown>; + if ((kind !== "image" && kind !== "video") || typeof url !== "string" || !/^https?:\/\//.test(url) || seen.has(url)) continue; + seen.add(url); + media.push({ kind, url }); + if (media.length >= MEDIA_MAX) break; + } + const url = statusUrl(id, okHandle); + return { + ...(id ? { id } : {}), + ...(url ? { url } : {}), + ...(okHandle ? { handle: okHandle } : {}), + ...(author ? { author } : {}), + ...(r.verified === true ? { verified: true } : {}), + ...(badge ? { badge } : {}), + ...(date ? { date } : {}), + text, + media, + }; +} + +export type XContextReadOptions = { + // What the archive says the post answers, when it says (the parent is the + // article with this status id; not on the page means no parent). + replyTo?: { id?: string; author?: string } | null; + // What the archive says it quotes: its id fills a quote card that names + // none, when the authors agree. + quoted?: { id?: string; author?: string } | null; + now?: () => Date; +}; + +const sameHandle = (a?: string, b?: string) => + !!a && !!b && a.replace(/^@/, "").toLowerCase() === b.replace(/^@/, "").toLowerCase(); + +// The whole record from the read's answer and the parent pick. Pure. Null +// when the answer is not the read's shape (the page could not be read: a +// later run reads it again). +export function contextRecordFrom( + raw: unknown, + pick: { from: "reply-to" | "above" } | null, + o: Pick<XContextReadOptions, "quoted"> & { readAt: string }, +): PostContextRecord | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw) || !("quoted" in raw) || !("parent" in raw)) return null; + const r = raw as { quoted: unknown; parent: unknown }; + const record: PostContextRecord = { readAt: o.readAt }; + const quoted = parseContextPost(r.quoted); + if (quoted) { + const arch = o.quoted; + if (!quoted.id && arch?.id && ID_RE.test(arch.id) && (!arch.author || !quoted.handle || sameHandle(arch.author, quoted.handle))) { + quoted.id = arch.id; + quoted.url = statusUrl(arch.id, quoted.handle ?? arch.author?.replace(/^@/, "")); + } + record.quoted = quoted; + } + const parent = pick ? parseContextPost(r.parent) : null; + if (parent && pick) record.parent = { ...parent, from: pick.from }; + return record; +} + +// The read, in the page shot — never throws: an unreadable page is null. +export async function readXPostContext(page: PageLike, o: XContextReadOptions = {}): Promise<PostContextRecord | null> { + try { + const snap = (await page.evaluate(threadSnapshotScript()).catch(() => null)) as ThreadSnapshot | null; + let parentIndex: number | null = null; + let pick: { from: "reply-to" | "above" } | null = null; + if (snap && Array.isArray(snap.articles) && typeof snap.own === "number") { + const got = pickThreadParent(snap, o.replyTo ?? null); + if ("index" in got) { + parentIndex = got.index; + pick = { from: got.from }; + } + } + const raw = await page.evaluate(contextScript(parentIndex)); + return contextRecordFrom(raw, pick, { quoted: o.quoted, readAt: (o.now ?? (() => new Date()))().toISOString() }); + } catch { + return null; + } +} + +export type XContextRunSummary = { + // Posts whose context was read and recorded this run. + read: number; + // Of them, how many showed a quoted post / a parent. + quoted: number; + parents: number; + // Posts not loaded for it: a context already recorded, or a deleted post. + skipped: number; + // Post pages loaded for the context alone (contextOnly). + pages: number; + failed: { id: string; error: string }[]; +}; + +export function emptyContextSummary(): XContextRunSummary { + return { read: 0, quoted: 0, parents: 0, skipped: 0, pages: 0, failed: [] }; +} + +export function noteContext(s: XContextRunSummary, c: PostContextRecord): void { + s.read++; + if (c.quoted) s.quoted++; + if (c.parent) s.parents++; +} + +export function describeContextSummary(s: XContextRunSummary): string { + return ( + `Context: ${s.read} read (${s.quoted} quoting a post, ${s.parents} answering one)` + + (s.skipped ? `, ${s.skipped} already read or deleted` : "") + + (s.failed.length ? `, ${s.failed.length} failed (${s.failed.map((f) => f.id).join(", ")})` : "") + + (s.pages ? `; ${s.pages} page(s) loaded for it` : "") + + "." + ); +} + +// A one-line account of one post's context, for the run's log. +export function describeContext(c: PostContextRecord): string { + const who = (p: PostContextPost) => (p.handle ? `@${p.handle}` : p.author ?? "?") + (p.id ? ` ${p.id}` : ""); + const parts = [c.parent ? `answers ${who(c.parent)}` : "", c.quoted ? `quotes ${who(c.quoted)}` : ""].filter(Boolean); + return parts.length ? `context: ${parts.join(", ")}` : "context: no quote, no parent"; +} diff --git a/common/social/xThreadShot.ts b/common/social/xThreadShot.ts @@ -81,8 +81,21 @@ export type ThreadSnapshot = { articles: ThreadArticle[]; }; +// Which check an `icon-verified` element is, in the page: gold is drawn with a +// gradient; blue and grey are one fill, X's own colours. Shared by the in-page +// reads that name a badge (the thread snapshot, the post context). +export const BADGE_OF_JS = `(icon) => { + const paint = [getComputedStyle(icon).color, icon.getAttribute("fill") || "", + ...Array.from(icon.querySelectorAll("[fill]")).map((e) => e.getAttribute("fill") || "")].join(" "); + return /linearGradient/i.test(icon.outerHTML) ? "gold" + : /29,\\s*155,\\s*240|#1d9bf0/i.test(paint) ? "blue" + : /130,\\s*154,\\s*171|#829aab/i.test(paint) ? "grey" + : "other"; +}`; + export const threadSnapshotScript = () => `(() => { const ${THREAD_SNAPSHOT_MARKER} = true; + const badgeOf = ${BADGE_OF_JS}; const all = Array.from(document.querySelectorAll('article[data-testid="tweet"]')); const own = all.findIndex((a) => a.hasAttribute("data-archilyzer-capture")); const articles = all.map((a) => { @@ -95,16 +108,7 @@ export const threadSnapshotScript = () => `(() => { const name = un ? ((un.innerText || "").split("\\n")[0] || "").trim() : ""; const icon = un && un.querySelector('[data-testid="icon-verified"]'); const verified = !!icon; - let badge; - if (icon) { - // Gold is drawn with a gradient; blue and grey are one fill, X's own colours. - const paint = [getComputedStyle(icon).color, icon.getAttribute("fill") || "", - ...Array.from(icon.querySelectorAll("[fill]")).map((e) => e.getAttribute("fill") || "")].join(" "); - badge = /linearGradient/i.test(icon.outerHTML) ? "gold" - : /29,\\s*155,\\s*240|#1d9bf0/i.test(paint) ? "blue" - : /130,\\s*154,\\s*171|#829aab/i.test(paint) ? "grey" - : "other"; - } + const badge = icon ? badgeOf(icon) : undefined; const r = a.getBoundingClientRect(); return { id, handle, name: name || undefined, verified, badge, top: r.top + window.scrollY, bottom: r.bottom + window.scrollY }; }); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **X post captures keep the post's context: what it quotes and what it answers.** A post video drew a reply ("you called me a Leftist…") with nothing it answered, because the archive row named no parent, no quote and no links. `capture-posts` on an X channel now reads, off the page it already loads, the post it answers (the archive's in-reply-to id, else the post directly above it) and the post it quotes — author, display name, check, date, words and media links — into the post's `capture.json` as `context`, with no extra page load (`"context": false` turns it off). `"contextOnly": true` loads one page per post for that alone (and the avatars it shows) and writes nothing else: `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<post id>", …],"contextOnly":true}' --wait`. Not verified against live X yet; the first run is the check. Needs a restart of the editor. +- **The X fetcher keeps quoted posts.** A timeline read never recorded what a post quotes (gallery-dl drops the quoted tweet unless asked). Every read now asks for it, and a quote becomes the quoting post's `quoted` — never archived as one of the account's own posts; an account quoting its own older post still archives that post when the walk reaches it. Posts already archived keep what they have (a re-fetch does not rewrite them; their context comes from `contextOnly`). Needs a restart of the editor. +- **`umtool posts context <project>`** fills every post item's quoted post and parent from its capture's `context` where the archive row lacks them, in one write (one undo point), and names the posts with no context yet with the capture call that reads it; `umtool posts reel` and `timeline insert post:` fill them when the entry is made. Needs a restart of umtool. - **X post captures keep the authors' avatars.** A post card showed an initial letter because the posts archive keeps no profile pictures. `capture-posts` on an X channel now reads the post author's avatar off the page it already loads for the shot (with `"thread": true`, the replied-to and quoted authors' too) and saves it at 400×400, fetched through the same browser context with no extra page load, into `posts-media/_avatars/<handle>.<ext>` and `avatars.json` — once per author, an author already stored skipped unless `"force": true`; `"avatars": false` turns it off. `"avatarsOnly": true` loads one post page per distinct archived author for the avatars alone and writes nothing else (no shot, media, record or availability): `pnpm ops capture-posts --json '{"slug":"<x-channel>","ids":["<one post id>"],"avatarsOnly":true}' --wait`. X's default picture is not stored. Needs a restart of the editor. - **A research case can be verified, its leads decided and its evidence captured, all in umtool.** The case pipeline page gains **7 Verify**, **8 Leads** and **10 Evidence**. **Verify** shows each finding's moment in every caption track side by side — the original audio's captions beside the uploaded `en` ones, the quote's words lit where they land and "holds the quote" or "4 of 5 words" on each — and an **Audio check** that has the editor transcribe the window on a local worker (its held media, or a clip fetched through it; **Run even while transcription is paused** for a pause-all) and diffs what was heard with the quote ("Heard 9 of 9 words"). A finding is marked Verified, Corrected, Disputed, Unverified or Quarantined (one first seen on a forum says so); **Correct by hand** keeps the reader's words ("The reader wrote: …"). **Leads** lists the accounts and pages a forum or posts channel links most, counted by post, with the posts around each on demand; **Never archive** makes the lead's name one of the case's private names — stored as its hash, never as text, and withheld from then on — and **Archive** creates its channel through the editor on no site and starts its first fetch (**Older walk** after). **Evidence** takes Wayback captures of a list of pages at chosen dates (a page the Wayback Machine will not show is the row "excluded from the Wayback Machine (cause unknown)") and a forum post's attachments and screenshot, shown everywhere as "forum attachment, post #N, unverified", attached to the findings they back and listed in the exported report's Evidence section. Any quote, note or role typed by hand that holds one of the case's private names is refused by the privacy gate, with the row and a count, never the name. Needs a restart of umtool. - **Newgrounds pages are read whole.** A Wayback capture of a 2014 Newgrounds user page used to come out as one small block of it: the page keeps its profile, stats, links and news in many small boxes the generic extractor dropped. A user page (`<user>.newgrounds.com/`) is now read box by box — "Profile", "Location: …", "Joined on: …", its links — and an art page or a movie page is one record per work (its title, author, comments, image or file, tags, credits and date) that later captures update. A channel imported before this is put right by **Re-extract** (`reextract-pages`), from the captures it already keeps; nothing is fetched. Needs a restart of the editor. diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts @@ -194,3 +194,24 @@ test("avatars and avatarsOnly: booleans; avatarsOnly is a run of its own, X's on assert.match(bsky.error, /^Avatars are X's only; .* keeps none\.$/); assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); }); + +test("context and contextOnly: booleans; contextOnly is a run of its own, X's only, not with avatarsOnly — refused before any job", async () => { + for (const key of ["context", "contextOnly"]) { + const bad = await post({ slug: SLUG, ids: ["111"], [key]: "yes" }); + assert.equal(bad.status, 400, key); + assert.match(bad.error, new RegExp(`"${key}" must be a boolean`)); + } + // Both halves off is no refusal for a context-only run: past it, to the + // next one (an id not archived). + const stray = await post({ slug: SLUG, ids: ["999"], shots: false, media: false, contextOnly: true }); + assert.equal(stray.status, 400); + assert.equal(stray.error, "1 id(s) not in demo-x's posts archive: 999"); + const both = await post({ slug: SLUG, ids: ["111"], contextOnly: true, avatarsOnly: true }); + assert.equal(both.status, 400); + assert.match(both.error, /^"contextOnly" and "avatarsOnly" are two runs/); + // Another platform reads none (the channel the avatars test made). + const bsky = await post({ slug: "example-bsky-avatars", ids: ["1"], contextOnly: true }); + assert.equal(bsky.status, 400); + assert.match(bsky.error, /^Post context is X's only; .* reads none\.$/); + assert.deepEqual(await readdir(path.join(ROOT, ".jobs")).catch(() => []), []); +}); diff --git a/editor/app/api/ops/capture-posts/route.ts b/editor/app/api/ops/capture-posts/route.ts @@ -10,7 +10,7 @@ import { export const dynamic = "force-dynamic"; -// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, queueKey? } -> { ok: true, jobId } +// POST { slug, ids, shots?, media?, force?, articles?, thread?, threadRedact?, avatars?, avatarsOnly?, context?, contextOnly?, queueKey? } -> { ok: true, jobId } // // Capture specific archived posts of a social channel: a screenshot of each // (`shots`, default true) and its attached media (`media`, default true), into @@ -34,14 +34,24 @@ export const dynamic = "force-dynamic"; // skipped unless `force`. One author's avatar is one page load: // {"slug":"ObviousRises-x","ids":["<one of his post ids>"],"avatarsOnly":true} // +// X also reads each post's CONTEXT off the page the shot loads -- the post it +// quotes and the post it answers (the archive often names neither) -- into +// its capture.json's `context`; `context: false` turns that off. +// `contextOnly: true` loads ONE page per post for that alone (and the avatars +// it shows): the context written into the post's capture.json, nothing shot, +// no media, article or thread shot, no availability; a post whose context is +// already read is skipped unless `force`: +// {"slug":"ObviousRises-x","ids":["<post id>", …],"contextOnly":true} +// // Every refusal is the action's own sentence: both halves off (an // articles-only run names `articles: true`), a channel that // is not a social one, a fetcher that cannot capture, an id not in the -// channel's posts archive, `avatarsOnly` on a channel that is not X. +// channel's posts archive, `avatarsOnly` or `contextOnly` on a channel that +// is not X, both of them at once. export async function POST(request: Request) { return ops( request, - ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "queueKey"], + ["slug", "ids", "shots", "media", "force", "articles", "thread", "threadRedact", "avatars", "avatarsOnly", "context", "contextOnly", "queueKey"], async (body) => { const slug = reqSlug(body, "slug"); return jobResponse( @@ -58,6 +68,8 @@ export async function POST(request: Request) { threadRedact: body.threadRedact as boolean | Record<string, boolean> | undefined, avatars: optBool(body, "avatars"), avatarsOnly: optBool(body, "avatarsOnly"), + context: optBool(body, "context"), + contextOnly: optBool(body, "contextOnly"), }, ), ); diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts @@ -45,6 +45,7 @@ import { import { avatarsOnlyProblem, capturePosts, + contextOnlyProblem, capturePostsProblem, NOTHING_TO_CAPTURE, nothingToCapture, @@ -306,7 +307,9 @@ export async function fetchPostsAction( // by the rule unless `threadRedact` says otherwise. X keeps the authors' // avatars from the pages it loads (`avatars: false` turns that off); // `avatarsOnly` loads one page per archived author for them alone (X only, -// refused here elsewhere). +// refused here elsewhere). X reads each post's context (the quoted post, the +// parent) off the same pages (`context: false` turns that off); `contextOnly` +// loads one page per post for it alone (X only; not with avatarsOnly). export async function capturePostsAction( slug: string, ids: string[], @@ -315,13 +318,20 @@ export async function capturePostsAction( media?: boolean, force?: boolean, articles?: boolean, - more: { thread?: boolean; threadRedact?: ThreadRedactKnob; avatars?: boolean; avatarsOnly?: boolean } = {}, + more: { + thread?: boolean; + threadRedact?: ThreadRedactKnob; + avatars?: boolean; + avatarsOnly?: boolean; + context?: boolean; + contextOnly?: boolean; + } = {}, ): Promise<StreamActionResult> { - const { thread, avatars, avatarsOnly } = more; + const { thread, avatars, avatarsOnly, context, contextOnly } = more; const redact = parseThreadRedact(more.threadRedact); if (!redact.ok) return { ok: false, error: redact.error }; const threadRedact = redact.value; - if (nothingToCapture({ shots, media, articles, thread, avatarsOnly })) return { ok: false, error: NOTHING_TO_CAPTURE }; + if (nothingToCapture({ shots, media, articles, thread, avatarsOnly, contextOnly })) return { ok: false, error: NOTHING_TO_CAPTURE }; const wanted = [...new Set(ids)]; if (wanted.length === 0) return { ok: false, error: "No post ids to capture." }; const paths = getPaths(); @@ -334,6 +344,7 @@ export async function capturePostsAction( // their captures, on archive.org's queue (release 37 S4). const pages = isWaybackPagesChannel(config); if (pages && avatarsOnly) return { ok: false, error: avatarsOnlyProblem(undefined, "a Wayback pages channel")! }; + if (pages && contextOnly) return { ok: false, error: contextOnlyProblem(undefined, "a Wayback pages channel", { avatarsOnly })! }; if (!pages) { await registerBuiltinSocialFetchers(); const fetcher = resolveSocialFetcher(config.postFetcher, config.url); @@ -341,6 +352,8 @@ export async function capturePostsAction( if (problem) return { ok: false, error: problem }; const nope = avatarsOnly ? avatarsOnlyProblem(fetcher?.platform, fetcher?.label ?? "") : null; if (nope) return { ok: false, error: nope }; + const noContext = contextOnly ? contextOnlyProblem(fetcher?.platform, fetcher?.label ?? "", { avatarsOnly }) : null; + if (noContext) return { ok: false, error: noContext }; } const stray = strayCaptureIds( wanted, @@ -363,6 +376,8 @@ export async function capturePostsAction( ...(threadRedact !== undefined ? { threadRedact } : {}), ...(avatars !== undefined ? { avatars } : {}), ...(avatarsOnly ? { avatarsOnly } : {}), + ...(context !== undefined ? { context } : {}), + ...(contextOnly ? { contextOnly } : {}), }, }, fn: async (onLog, signal, _progress, ctx) => { @@ -379,6 +394,8 @@ export async function capturePostsAction( threadRedact, avatars, avatarsOnly, + context, + contextOnly, onLog, signal, drain: ctx.drainSignal, diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -445,6 +445,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { threadRedact: p.threadRedact as boolean | Record<string, boolean> | undefined, avatars: bool(p.avatars), avatarsOnly: bool(p.avatarsOnly), + context: bool(p.context), + contextOnly: bool(p.contextOnly), }, ); }, diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts @@ -133,6 +133,17 @@ test("capture-posts on a Bluesky channel: shots cropped to the post, its images, }); expect(av.status()).toBe(400); expect(((await av.json()) as { error?: string }).error).toMatch(/^Avatars are X's only; .* keeps none\.$/); + + // So is a post's context (the quoted post, the parent): a Bluesky + // record carries none, and a context-only run is refused by name. + const textRecord = JSON.parse(await readFile(path.join(media, textOnly, "capture.json"), "utf8")) as { context?: unknown }; + expect(textRecord.context).toBeUndefined(); + const ctx = await request.post(`${baseUrl}/api/ops/capture-posts`, { + headers: AUTH, + data: { slug: SLUG, ids, contextOnly: true }, + }); + expect(ctx.status()).toBe(400); + expect(((await ctx.json()) as { error?: string }).error).toMatch(/^Post context is X's only; .* reads none\.$/); } finally { await rm(originFile, { force: true }); await bsky.close(); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1544,6 +1544,13 @@ export function usage() { ' author for the avatars alone -- no shot, media, article or thread shot,', ' no capture record, no availability: one author\'s avatar is', ' {"slug", "ids": ["<one of their post ids>"], "avatarsOnly": true}.', + ' X also reads each post\'s CONTEXT off the same page -- the post it quotes', + ' and the post it answers (its author, check, date, words, media links) --', + ' into its capture.json\'s "context"; "context": false turns that off.', + ' "contextOnly": true (X) loads ONE page per post for that alone (and the', + ' avatars it shows): the context written into capture.json, nothing shot,', + ' no media, article, thread shot or availability; a post whose context is', + ' already read is skipped unless "force". Not with "avatarsOnly".', ' Paced like a post fetch, on its queue.', "", 'persist-videos saves specific videos, across channels, to the saved-video', diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -81,8 +81,9 @@ Inbox cannot disagree about what is wrong with one. | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | | `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). 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 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] [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] [--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 | +| `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)) | | `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters | | `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one | | `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -657,6 +657,7 @@ its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused |---|---|---|---| | a posts reel: the archive's posts as post items, re-run to add only what is new (one write, one undo point) | — | `umtool posts reel <p> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run]` | — | | one post item among clips | — | `umtool timeline <p> insert --after <id\|-> post:<channel>/<postId> [--id ID]` (or `--to-section N`, `--group G`) | `POST /api/report/timeline {op: "insert", …}` with an entry | +| its `quoted` and `parents` the archive row lacks, from the capture's `context` (the post's page, read by `capture-posts`): filled when the entry is made, and into a cut made before (one write, one undo point; the archive's own never replaced) | — | `umtool posts context <p> [--dry-run]` (no context yet: `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"contextOnly":true}' --wait` first) | — | | move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's | | the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -493,7 +493,11 @@ plays skipped — by its id, as a repost's original, or reposted by one — so a adds only what is new, and the rest put in through ONE write (`insertEntries`: one undo point, refused whole in the build's words). A reply's parents come from the archive (the replies channel carries the posts he answered), else from the capture's -`shot-thread.png`, else a "Replying to" line. The attachments are COPIED into the +`shot-thread.png`, else a "Replying to" line. The quoted post and the parent the +archive lacks come from the capture's `context` (the post's page, read by +`capture-posts`; `"contextOnly": true` reads it alone) -- snapshotted when the entry is +made, and filled into a cut made before by `umtool posts context <p>` (one write, one +undo point; what the archive gave is never replaced). The attachments are COPIED into the project's `posts-media/` and measured (ffprobe: pixels, length, sound; X serves a GIF as a silent mp4 from `tweet_video/`). `umtool new <p> --from-posts <slug>` scaffolds a posts reel (the deck on; with no `siteOrigin` each QR opens the post), and `umtool 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);