commit 6ab038d5a9ce90c39e2411ec37a544619db713eb
parent 9d8fd941515c01c695d2e8ea6cb35a69e791c391
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 22:51:08 -0500
common: capture-posts reads each X post's context -- the quoted post and the parent, off the page it loads, into capture.json; contextOnly
The archive often names neither: a timeline read kept no quote, and a reply's
parent is another account's post (the operator's case, a 29 Oct reply to
Kirsche archived with replyTo, quoted and links all empty). The page shows
both, so the capture that loads it reads them (social/xPostContext.ts), with
no extra page load: the thread snapshot's own parent pick (the archive's
in-reply-to id, else the article directly above; an id not on the page is no
parent) and one evaluate reading that article and the post's quote card --
author, display name, check (the thread snapshot's badge rule, now shared as
BADGE_OF_JS), date, words, the media URLs the page drew, the status id when a
link names one (the archive's quoted id fills a card that names none, when
the authors agree). Recorded as capture.json's `context: {quoted?, parent?,
readAt}`; a read that found neither is still a read.
On by default for X ("context": false turns it off); a normal run reads it
from any page it loads and keeps the last one otherwise. "contextOnly": true
loads one page per post (one already read, or found deleted, not loaded
unless force), paced and stopped like every X contact, writes the context
into the post's record (merged, or a record of its own with nothing shot and
the media owed) and saves the avatars the page shows -- no shot, media,
article, thread shot or availability. X's only; refused with avatarsOnly
(two runs). The controller passes each post's archived replyTo and quoted ids.
Proved in a real headless Chromium against the recorded-style status page
(the fixture gains a quote card with its date and a picture whose link names
the quoted status, and a blue check by the parent's name): the parent and the
quote read exactly, a context-only run one page load with nothing shot
(xAvatarCapture.browser.test.ts); the parse, the record and both runs against
fakes (xPostContext.test.ts); the controller's options (capturePosts.test.ts).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 970 insertions(+), 32 deletions(-)
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/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("{{ORIGIN}}/profile_images/888/qq_mini.jpg");"></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("{{ORIGIN}}/profile_images/888/qq_mini.jpg");"></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&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/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 };
});