commit cbf8eaff774744bbbceb96b7777fd20614f77a97
parent 0ebae7ef80803254df52dd778c0a01abb4aafd2d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 19:26:54 -0400
Merge main (lane D: cite) into r37/archive-sources
D's pageCopyLinks names archive.today for its records ("archive.today copy, <date>") and
the view carries page.source; the records table shows the source; umtool's evidence rail
labels an archive.today fallback copy. The channel page keeps D's rows plus the archive
session. The citation fallback is unchanged: its archiveUrl names its source by its URL.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
58 files changed, 3558 insertions(+), 111 deletions(-)
diff --git a/CITATIONS.md b/CITATIONS.md
@@ -78,6 +78,16 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `channel` | yes | The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule). |
| `id` | yes | The post's id. A path segment of the moment page. |
| `thread` | no | True to show the post with the thread it belongs to. Absent = the post alone. |
+| `fallback` | no | The `page` citation this one replaced (`{kind: "page", url, title?, archiveUrl?}`): a page citation whose Wayback copy was imported as a page record (umtool's **Import this capture**) becomes a `post` citation of that record, its page facts kept here so the page can still be shown where the post is not resolved. Absent = the citation was always a post. |
+
+#### `fallback` (post)
+
+| Key | Required | Description |
+|---|---|---|
+| `kind` | yes | `"page"`. |
+| `url` | yes | The page's address, as the page citation named it. |
+| `title` | no | The page's title, as the page citation named it. |
+| `archiveUrl` | no | The archived copy the page citation named (the capture imported). |
#### `"source"`
diff --git a/OPERATING.md b/OPERATING.md
@@ -198,6 +198,35 @@ pnpm ops find-copy --json '{"siteId":"<site>","pages":true,"channel":"old-bl
citation, the record to cite (`pointTo`) and the citation as a `post` citation of it (`as`); the report itself
is not rewritten. Dry run first: it asks the same paced questions and imports nothing.
+### Shoot and cite a capture
+
+```sh
+pnpm ops capture-posts --json '{"slug":"old-blog","ids":["<recordId>"]}' --wait
+pnpm ops capture-posts --json '{"slug":"old-blog","ids":["<recordId>"],"media":false,"force":true}' --wait
+```
+
+- `capture-posts` on a Wayback pages channel shoots each record from its capture's replay (`if_`, no toolbar) in a
+ headless Chromium with JavaScript off and nothing but the archive reachable: a whole-page record full page (cut at
+ 8000 px), a tweet / Tumblr post / forum post clipped to its own element (the whole page when the render cannot find
+ it). Its images are saved through their own Wayback URLs (`im_`). Into `posts-media/<id>/` like any post capture;
+ on archive.org's queue and pace; the channel page's **Capture** button is the same (picked records, or every
+ record without a shot). It says nothing about whether the original is still up.
+- Every surface that shows a page record says what the capture is: the kind, "Original (may be gone)" + "Wayback
+ Machine copy, <date>", "N captures of this page; text changed on …", a capture that holds no content, and the
+ note when a site's reader failed and the generic one read the page — the report site's moment page and citation
+ card, the corpus viewer, the editor's channel page, umtool's evidence rail, `get_post`.
+- **Cite a capture:** a report's `page` citation whose `archiveUrl` is a Wayback capture gets **Import this
+ capture** in umtool's evidence rail: pick a Wayback pages channel (or name a new one, scoped on the page's host),
+ Import (the editor's `import-page`), then **Cite this** on the record it made. A store article's citation becomes a
+ `post` citation of the record, the page kept as its `fallback` (CITATIONS.md), written as a hand iteration — its
+ quote checked against the record first. A site report is built from its draft, so umtool shows the replacement
+ citation to put there. `reports-prepare` then copies the record's shot like any post capture. find-copy's page
+ mode builds its `as` with the same function, so both paths write the same citation (the page as its `fallback`).
+- A page record whose original the liveness check found gone is labelled "Original gone — the Wayback Machine copy
+ is the only copy" everywhere its links are shown.
+- The MCP: `get_post` prints a page record's capture (kind, date, the original, the Wayback copy);
+ `search_transcripts` takes `platforms: ["webpage"]` (with `content_types: ["post"]` for page records only).
+
## Fetch and capture posts
```sh
diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts
@@ -69,6 +69,7 @@ import {
type ArchiveManifestEntry,
} from "../lib/archiveOptions";
import { readChannelConfig } from "../controller/channels";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
import { builtSiteIdIn } from "../lib/builtExport";
import { publishedMemberSlugs } from "../lib/postsVisibility";
import { isCitedSite, isPrivateSite } from "../lib/siteSchema";
@@ -279,6 +280,14 @@ export async function emitAiFiles(
/* no digests manifest for this site */
}
+ // Which posts channels are Wayback pages channels (release 37 S4): corpus.json
+ // names the kind, so a reader knows its records are page captures.
+ const channelKinds: Record<string, "wayback-pages"> = {};
+ for (const slug of Object.keys(postCounts)) {
+ const config = await readChannelConfig(paths, slug).catch(() => null);
+ if (config && isWaybackPagesChannel(config)) channelKinds[slug] = "wayback-pages";
+ }
+
// Whether this site published a curated vocabulary. Presence of the file is
// the fact — it was written (or removed) just above, by the same rule that
// decides whether any tag means anything on this site.
@@ -287,6 +296,7 @@ export async function emitAiFiles(
const corpus = buildSiteCorpus(descriptor, {
hasArchives,
postCounts,
+ channelKinds,
digestCounts,
hasTags,
// A private site says so in its own corpus.json — the bundle's word that
diff --git a/common/components/PageCaptureFacts.test.ts b/common/components/PageCaptureFacts.test.ts
@@ -0,0 +1,40 @@
+// PageCaptureFacts (release 37 S4): a page record's capture in plain words.
+//
+// Run with: node_modules/.bin/tsx --test components/PageCaptureFacts.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { PageCaptureFacts } from "./PageCaptureFacts";
+import { pageCaptureView, PAGE_NO_CONTENT_LINE } from "../lib/waybackPages/view";
+
+(globalThis as { React?: typeof React }).React = React;
+
+test("a shell capture: the kind, no content, the fallback note, both links", () => {
+ const url = "https://x.example/someone";
+ const v = pageCaptureView({
+ id: "20220101000000-0123456789ab",
+ text: "",
+ page: {
+ originalUrl: url,
+ captureTs: "20220101000000",
+ waybackUrl: `https://web.archive.org/web/20220101000000/${url}`,
+ rawUrl: `https://web.archive.org/web/20220101000000id_/${url}`,
+ kind: "x-profile",
+ noContent: true,
+ extractor: "generic",
+ extractorVersion: 1,
+ extractorFallback: { from: "x", fromVersion: 1, error: "boom" },
+ },
+ })!;
+ const html = renderToStaticMarkup(React.createElement(PageCaptureFacts, { view: v }));
+ assert.match(html, /data-page-capture="x-profile"/);
+ assert.match(html, /X\/Twitter profile · captured 2022-01-01/);
+ assert.ok(html.includes(PAGE_NO_CONTENT_LINE));
+ assert.match(html, /data-page-fallback/);
+ assert.match(html, /Original \(may be gone\)/);
+ assert.match(html, /Wayback Machine copy, 2022-01-01/);
+ const bare = renderToStaticMarkup(React.createElement(PageCaptureFacts, { view: v, links: false }));
+ assert.doesNotMatch(bare, /may be gone/);
+});
diff --git a/common/components/PageCaptureFacts.tsx b/common/components/PageCaptureFacts.tsx
@@ -0,0 +1,68 @@
+// WHAT A PAGE RECORD'S CAPTURE IS (release 37 S4), from its view
+// (lib/waybackPages/view.ts): the kind and capture date, a capture that holds
+// no content, the extractor-fallback note, the version list, and — unless the
+// surface prints them itself — "Original (may be gone)" and "Wayback Machine
+// copy, <date>". The same words on a report site's moment page, the corpus
+// viewer's post modal and the editor's Wayback pages panel.
+
+import { pageCaptureLine, pageVersionsLine, PAGE_NO_CONTENT_LINE, type PageCaptureView } from "../lib/waybackPages/view";
+
+const link = "underline underline-offset-2";
+
+export function PageCaptureFacts({
+ view,
+ links = true,
+ className = "",
+}: {
+ view: PageCaptureView;
+ // Print the original and the Wayback copy (off where the surface's own
+ // links line carries them).
+ links?: boolean;
+ className?: string;
+}) {
+ return (
+ <div data-page-capture={view.kind} className={`flex flex-col gap-1 text-sm ${className}`}>
+ <p className="font-mono text-xs text-muted-foreground">{pageCaptureLine(view)}</p>
+ {view.noContent && (
+ <p data-page-no-content="" className="text-muted-foreground">
+ {PAGE_NO_CONTENT_LINE}
+ </p>
+ )}
+ {view.fallbackNote && (
+ <p data-page-fallback="" className="text-xs text-muted-foreground">
+ {view.fallbackNote}
+ </p>
+ )}
+ {links && (
+ <p className="flex flex-wrap gap-x-4 gap-y-1">
+ <a href={view.links.original.url} target="_blank" rel="noreferrer" className={link}>
+ {view.links.original.label}
+ </a>
+ <a href={view.links.copy.url} target="_blank" rel="noreferrer" className={link}>
+ {view.links.copy.label}
+ </a>
+ </p>
+ )}
+ {view.versions && (
+ <div data-page-versions={view.versions.count} className="flex flex-col gap-1">
+ <p className="text-muted-foreground">{pageVersionsLine(view.versions)}</p>
+ <ol className="flex flex-wrap gap-x-3 gap-y-1 font-mono text-xs">
+ {view.versions.captures.map((c) => (
+ <li key={c.id}>
+ {c.current ? (
+ <span aria-current="true" className="font-semibold">
+ {c.date}
+ </span>
+ ) : (
+ <a href={c.waybackUrl} target="_blank" rel="noreferrer" className={link}>
+ {c.date}
+ </a>
+ )}
+ </li>
+ ))}
+ </ol>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/common/components/PostModal.tsx b/common/components/PostModal.tsx
@@ -15,6 +15,8 @@ import { Button } from "./ui/button";
import { useUrlParams, writeUrlParams } from "./urlState";
import { fetchPost, fetchThread } from "./postsCache";
import { postPlatformLabel, type Post } from "../lib/posts";
+import { pageCaptureView } from "../lib/waybackPages/view";
+import { PageCaptureFacts } from "./PageCaptureFacts";
function formatWhen(iso: string): string {
const ms = Date.parse(iso);
@@ -168,6 +170,9 @@ function PostBody({
}) {
const links = useMemo(() => post.links ?? [], [post.links]);
const capturedMedia = capture?.media.length ?? 0;
+ // A page record (a Wayback capture, release 37 S4): what the capture is,
+ // and the original named as possibly gone beside the Wayback copy.
+ const page = useMemo(() => pageCaptureView(post), [post]);
return (
<article
data-post-id={post.id}
@@ -215,6 +220,8 @@ function PostBody({
{capture && <PostCapturePanel capture={capture} />}
+ {page && !compact && <PageCaptureFacts view={page} links={false} className="mt-2" />}
+
{post.forum?.threadTitle && !compact && (
<p className="mt-1 text-xs text-muted-foreground">
In thread: {post.forum.threadTitle}
@@ -263,14 +270,25 @@ function PostBody({
)}
<footer className="mt-2 flex flex-wrap items-center gap-x-3 text-xs text-muted-foreground">
- <a
- href={post.url}
- target="_blank"
- rel="noopener noreferrer"
- className="underline"
- >
- {post.isDeleted ? "Original (deleted)" : "Open original"}
- </a>
+ {page ? (
+ <>
+ <a href={page.links.original.url} target="_blank" rel="noopener noreferrer" className="underline">
+ {post.isDeleted ? "Original (deleted)" : page.links.original.label}
+ </a>
+ <a href={page.links.copy.url} target="_blank" rel="noopener noreferrer" className="underline">
+ {page.links.copy.label}
+ </a>
+ </>
+ ) : (
+ <a
+ href={post.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline"
+ >
+ {post.isDeleted ? "Original (deleted)" : "Open original"}
+ </a>
+ )}
{post.engagement?.likes != null && (
<span>{post.engagement.likes} likes</span>
)}
diff --git a/common/components/citations/CitationCard.tsx b/common/components/citations/CitationCard.tsx
@@ -178,7 +178,12 @@ function PostLinks({ c }: { c: PostCitationView }) {
<a href={c.href} className={linkClass}>
Open post
</a>
- {c.record.originalUrl && <ExternalA href={c.record.originalUrl}>Original</ExternalA>}
+ {c.record.originalUrl && <ExternalA href={c.record.originalUrl}>{c.record.originalLabel ?? "Original"}</ExternalA>}
+ {c.record.downloads?.map((d) => (
+ <ExternalA key={d.url} href={d.url}>
+ {d.label}
+ </ExternalA>
+ ))}
</>
);
}
diff --git a/common/components/citations/citations.test.ts b/common/components/citations/citations.test.ts
@@ -220,3 +220,22 @@ test("the reference list: number order as given, anchors c-<id>, none when asked
assert.ok(!render(h(ReferenceList, { citations: all, anchors: false })).includes('id="c-'));
assert.equal(render(h(ReferenceList, { citations: [] })), "");
});
+
+test("a page record's card (release 37 S4): the original named as possibly gone, and the Wayback copy", () => {
+ const pageRecord: PostCitationView = {
+ ...post,
+ record: {
+ ...post.record,
+ originalUrl: "https://blog.example/a.html",
+ originalLabel: "Original (may be gone)",
+ downloads: [{ label: "Wayback Machine copy, 2014-03-05", url: "https://web.archive.org/web/20140305120000/https://blog.example/a.html" }],
+ },
+ };
+ const html = render(h(CitationCard, { citation: pageRecord }));
+ assert.match(html, /Original \(may be gone\)/);
+ assert.match(html, /href="https:\/\/web\.archive\.org\/web\/20140305120000\/https:\/\/blog\.example\/a\.html"/);
+ assert.match(html, /Wayback Machine copy, 2014-03-05/);
+ // An ordinary post keeps its "Original".
+ const plain = render(h(CitationCard, { citation: post }));
+ assert.doesNotMatch(plain, /may be gone|Wayback/);
+});
diff --git a/common/components/report/MomentArticle.page.test.ts b/common/components/report/MomentArticle.page.test.ts
@@ -0,0 +1,68 @@
+// A page record's moment page (release 37 S4): the shot named as the Wayback
+// copy, the capture's kind and date, the version list, the two links.
+//
+// Run with: node_modules/.bin/tsx --test components/report/MomentArticle.page.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import MomentArticle from "./MomentArticle";
+import { MOMENT_PAGE_FORMAT, REPORT_VIEWS_VERSION, type MomentPageView } from "../../lib/report/views";
+import { pageCaptureView } from "../../lib/waybackPages/view";
+import type { Post } from "../../lib/posts";
+
+(globalThis as { React?: typeof React }).React = React;
+
+const URL_A = "https://blog.example/a.html";
+const rec = (id: string, ts: string, text: string): Post => ({
+ id,
+ slug: `pages/${id}`,
+ channelSlug: "pages",
+ author: "blog.example",
+ createdAt: "2014-03-04T18:30:00.000Z",
+ uploadDate: "20140304",
+ text,
+ url: URL_A,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page: {
+ originalUrl: URL_A,
+ captureTs: ts,
+ waybackUrl: `https://web.archive.org/web/${ts}/${URL_A}`,
+ rawUrl: `https://web.archive.org/web/${ts}id_/${URL_A}`,
+ kind: "generic",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+});
+
+test("a page record's moment page: the capture, its versions, the original and the Wayback copy", () => {
+ const a = rec("20140305120000-0123456789ab", "20140305120000", "First.");
+ const b = rec("20150611090000-0123456789ab", "20150611090000", "Second.");
+ const view: MomentPageView = {
+ format: MOMENT_PAGE_FORMAT,
+ version: REPORT_VIEWS_VERSION,
+ key: `pages/${b.id}`,
+ kind: "post",
+ record: {
+ channel: "pages",
+ id: b.id,
+ title: "A Post",
+ originalUrl: URL_A,
+ originalLabel: "Original (may be gone)",
+ downloads: [{ label: "Wayback Machine copy, 2015-06-11", url: b.page!.waybackUrl }],
+ },
+ quote: "Second.",
+ post: { author: "blog.example", text: "Second.", shot: "/media/posts/pages/x/shot.png", page: pageCaptureView(b, [a]) },
+ citedIn: [],
+ };
+ const html = renderToStaticMarkup(React.createElement(MomentArticle, { view }));
+ assert.match(html, /alt="Screenshot of the Wayback Machine copy, 2015-06-11"/);
+ assert.match(html, /Web page · captured 2015-06-11/);
+ assert.match(html, /2 captures of this page; text changed on 2015-06-11\./);
+ assert.match(html, />Original \(may be gone\)</);
+ assert.match(html, /Wayback Machine copy, 2015-06-11/);
+});
diff --git a/common/components/report/MomentArticle.tsx b/common/components/report/MomentArticle.tsx
@@ -4,6 +4,7 @@ import { formatTimestamp } from "../../lib/vtt";
import { CITATION_KIND_LABELS, spanLabel, type MomentPageView, type RecordView } from "../../lib/report/views";
import { ExternalLinkText, Eyebrow, dateLabel, textLink } from "./parts";
import { SOURCE_GONE_LABELS } from "../../lib/sourceGone";
+import { PageCaptureFacts } from "../PageCaptureFacts";
// ONE CITED MOMENT, from its view (common/lib/report/views.ts): a span's
// self-hosted evidence clip (video, or audio with its poster) or a post's
@@ -87,10 +88,15 @@ export default function MomentArticle({
// eslint-disable-next-line @next/next/no-img-element -- a published file of unknown size; the export serves images unoptimized
<img
src={view.post.shot}
- alt={`Screenshot of the post${view.post.author ? ` by ${view.post.author}` : ""}`}
+ alt={
+ view.post.page
+ ? `Screenshot of the Wayback Machine copy, ${view.post.page.captureDate}`
+ : `Screenshot of the post${view.post.author ? ` by ${view.post.author}` : ""}`
+ }
className="w-full max-w-xl rounded-lg border border-border"
/>
)}
+ {view.post?.page && <PageCaptureFacts view={view.post.page} links={false} />}
<div className="flex flex-col gap-2">
<blockquote className="border-l-4 border-brand pl-4 text-lg leading-relaxed text-foreground">
@@ -153,7 +159,7 @@ export default function MomentArticle({
<ExternalLinkText href={r.originalUrl}>
{isSpan && view.start !== undefined
? `${r.originalLabel ?? "Original"} at ${formatTimestamp(view.start)}`
- : "Original post"}
+ : (r.originalLabel ?? "Original post")}
</ExternalLinkText>
)}
{r.downloads?.map((d) => (
diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts
@@ -217,3 +217,75 @@ test("the articles: on by default, refused alone only when not asked for by name
assert.equal((await run("demo-x", ["111"], { shots: false, media: false, articles: true })).ok, true);
assert.equal(calls[0].articles, true);
});
+
+test("a Wayback pages channel: its records rendered from their captures, no fetcher, nothing in the availability sidecar", async () => {
+ const root = path.join(channelsDir, "demo-pages");
+ await mkdir(root, { recursive: true });
+ await writeFile(
+ path.join(root, "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ name: "Pages",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ wayback: { targets: [{ url: "https://blog.example/", match: "prefix" }] },
+ }),
+ );
+ const page = {
+ originalUrl: "https://blog.example/a.html",
+ captureTs: "20140305120000",
+ waybackUrl: "https://web.archive.org/web/20140305120000/https://blog.example/a.html",
+ rawUrl: "https://web.archive.org/web/20140305120000id_/https://blog.example/a.html",
+ kind: "generic" as const,
+ extractor: "generic",
+ extractorVersion: 1,
+ };
+ await writePosts(root, [
+ {
+ id: "20140305120000-0123456789ab",
+ slug: "demo-pages/20140305120000-0123456789ab",
+ channelSlug: "demo-pages",
+ author: "blog.example",
+ createdAt: "2014-03-05T12:00:00.000Z",
+ uploadDate: "20140305",
+ text: "A page.",
+ url: page.originalUrl,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page,
+ },
+ ]);
+ const loads: string[] = [];
+ const res = await run("demo-pages", ["20140305120000-0123456789ab"], {
+ media: false,
+ pageDeps: {
+ openPage: async () => ({
+ page: {
+ goto: async (url: string) => {
+ loads.push(url);
+ return { status: () => 200 };
+ },
+ waitForSelector: async () => ({}),
+ waitForTimeout: async () => {},
+ evaluate: async (fn: string) => (fn.includes("scrollHeight") ? { width: 1280, height: 900 } : 0),
+ on: () => {},
+ screenshot: async () => new Uint8Array([137, 80, 78, 71]),
+ },
+ close: async () => {},
+ }),
+ paced: (fn: () => Promise<unknown>) => fn(),
+ fetchFile: async () => null,
+ },
+ });
+ assert.equal(res.ok, true, res.error);
+ assert.deepEqual(res.outcomes.map((o) => o.state), ["captured"]);
+ assert.deepEqual(loads, ["https://web.archive.org/web/20140305120000if_/https://blog.example/a.html"]);
+ assert.deepEqual(await readPostAvailability(root), {});
+ assert.equal(
+ (await run("demo-pages", ["nope"])).error,
+ "1 id(s) not in demo-pages's posts archive: nope",
+ );
+});
diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts
@@ -17,7 +17,7 @@
import path from "node:path";
import { readChannelConfig } from "./channels";
import type { Paths } from "../lib/paths";
-import type { PostAvailability } from "../lib/posts";
+import type { Post, PostAvailability } from "../lib/posts";
import { isSocialChannel } from "../lib/channelConfig";
import {
alwaysCookies,
@@ -38,6 +38,12 @@ import {
type SocialFetcher,
} from "../social/fetchers";
import { postsMediaDir } from "../social/postCapture";
+import { isWaybackPagesChannel } from "../lib/waybackPages/config";
+import {
+ captureWaybackPageRecords,
+ liveWaybackPageCaptureDeps,
+ type WaybackPageCaptureDeps,
+} from "../social/waybackPageCapture";
import "../social/blueskyFetcher";
import "../social/xGalleryDlFetcher";
import "../social/xPlaywrightFetcher";
@@ -64,6 +70,9 @@ export type CapturePostsOptions = {
signal?: AbortSignal;
// The job's drain: stop between posts.
drain?: AbortSignal;
+ // A Wayback pages channel's render and archive (tests; default the
+ // process's Wayback client and a headless Chromium).
+ pageDeps?: WaybackPageCaptureDeps;
};
export type CapturePostsResult = {
@@ -126,6 +135,10 @@ export async function capturePosts(
if (!config) return fail(`No such channel: ${slug}`);
if (!isSocialChannel(config)) return fail(`${slug} is not a social channel.`);
+ // A Wayback pages channel (release 37 S4): no fetcher — each record is
+ // rendered from its capture's replay, its images from the archive.
+ if (isWaybackPagesChannel(config)) return captureChannelPageRecords(opts, channelRoot, ids);
+
const accountUrl = config.url ?? "";
const fetcher = resolveSocialFetcher(config.postFetcher, accountUrl);
const problem = capturePostsProblem(fetcher);
@@ -257,3 +270,57 @@ export async function capturePosts(
}
return { ok: true, outcomes: result.outcomes };
}
+
+// capture-posts on a Wayback pages channel: the records' shots from their
+// captures' replays (social/waybackPageCapture.ts). Only ids in the channel's
+// posts archive; nothing is recorded in the availability sidecar (a capture
+// says nothing about the original — release 37 S5 owns that).
+async function captureChannelPageRecords(
+ opts: CapturePostsOptions,
+ channelRoot: string,
+ ids: string[],
+): Promise<CapturePostsResult> {
+ const log = (line: string) => opts.onLog?.(line);
+ const wanted = new Set(ids);
+ const records = new Map<string, Post>();
+ for (const p of await readAllPosts(channelRoot)) if (wanted.has(p.id)) records.set(p.id, p);
+ const stray = ids.filter((id) => !records.has(id));
+ if (stray.length) return { ok: false, outcomes: [], error: strayIdsRefusal(opts.slug, stray) };
+ log(
+ `Capturing ${ids.length} page record(s) of ${opts.slug} from the Wayback Machine:` +
+ [opts.shots === false ? "" : " screenshot", opts.media === false ? "" : " images"].join("") +
+ (opts.force ? ", again where already captured" : "") +
+ ".",
+ );
+ const controller = new AbortController();
+ const signal = opts.signal ?? controller.signal;
+ let result;
+ try {
+ result = await captureWaybackPageRecords(
+ {
+ ids,
+ records,
+ outDir: postsMediaDir(channelRoot),
+ shots: opts.shots,
+ media: opts.media,
+ force: opts.force,
+ signal,
+ drain: opts.drain,
+ onLog: log,
+ },
+ opts.pageDeps ?? liveWaybackPageCaptureDeps(),
+ );
+ } catch (err) {
+ const message = (err as Error).message;
+ log(`[error] ${message}`);
+ return { ok: false, outcomes: [], error: message };
+ }
+ const count = (state: string) => result.outcomes.filter((o) => o.state === state).length;
+ log(
+ `Done: ${count("captured")} captured, ${count("error")} failed; ` +
+ `${ids.length - result.outcomes.length} not attempted or already captured.`,
+ );
+ const stoppedByOperator = signal.aborted || Boolean(opts.drain?.aborted);
+ if (result.stoppedEarly && !stoppedByOperator) return { ok: false, outcomes: result.outcomes, error: result.stoppedEarly };
+ return { ok: true, outcomes: result.outcomes };
+}
diff --git a/common/controller/handEdits.test.ts b/common/controller/handEdits.test.ts
@@ -10,7 +10,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
import { tmpdir } from "node:os";
import path from "node:path";
import { createIteration, currentIteration, makeCurrent, readIteration, readIterations, updateIteration, writeIterationFile } from "../lib/report/iterations";
-import { addClaimByHand, defaultHandBase, HandEditError, parseMoment, startBlankArticle } from "./handEdits";
+import { addClaimByHand, defaultHandBase, HandEditError, parseMoment, replacePageCitationWithRecord, startBlankArticle } from "./handEdits";
const ROOTS: string[] = [];
after(() => {
@@ -186,3 +186,61 @@ test("an article older than iterations: its report.json is the base; the claim's
assert.match(i1.feedback ?? "", /^from the article's report\.json: added c2/);
assert.equal(reportOf(paths, "older", 1).sections[0].claims.length, 2);
});
+
+test("Import this capture: a page citation becomes a post citation of its page record, the page kept as its fallback", async () => {
+ const paths = store();
+ const PAGES = "synth-pages";
+ const put = (file: string, text: string) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, text);
+ };
+ put(
+ path.join(paths.channelsDir, PAGES, "config.json"),
+ JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "webpage", name: "Pages", url: "https://web.archive.org/web/*/blog.example/*" }),
+ );
+ const rid = "20140305120000-0123456789ab";
+ put(
+ path.join(paths.channelsDir, PAGES, "posts", "2014-03.jsonl"),
+ JSON.stringify({
+ id: rid,
+ slug: `${PAGES}/${rid}`,
+ channelSlug: PAGES,
+ author: "blog.example",
+ createdAt: "2014-03-04T18:30:00.000Z",
+ uploadDate: "20140304",
+ text: "The first loaf came out flat, and the second, and the third.",
+ url: "https://blog.example/a.html",
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }) + "\n",
+ );
+ await startBlankArticle("bread", { title: "Bread" }, paths, NOW);
+ const page = { kind: "page", url: "https://blog.example/a.html", title: "A post", archiveUrl: `https://web.archive.org/web/20140305120000/https://blog.example/a.html`, quote: "The first loaf came out flat", speaker: "Pat" };
+ await writeIterationFile(
+ "bread",
+ 1,
+ "report.json",
+ { ...reportOf(paths, "bread", 1), citations: { p1: page, p2: { ...page, quote: "words the page never said" } }, sections: [{ id: "s", title: "S", claims: [{ id: "c1", text: "x", citations: ["p1", "p2"] }] }] },
+ paths,
+ );
+ const r = await replacePageCitationWithRecord("bread", { cite: "p1", channel: PAGES, id: rid }, paths, NOW);
+ assert.equal(r.n, 1);
+ assert.equal(r.amended, true);
+ assert.equal(r.check.status, "ok");
+ const after = reportOf(paths, "bread", 1);
+ assert.deepEqual(after.citations.p1, {
+ kind: "post",
+ channel: PAGES,
+ id: rid,
+ quote: "The first loaf came out flat",
+ speaker: "Pat",
+ fallback: { kind: "page", url: page.url, title: "A post", archiveUrl: page.archiveUrl },
+ });
+ // A quote the record does not hold: refused, nothing written.
+ await assert.rejects(replacePageCitationWithRecord("bread", { cite: "p2", channel: PAGES, id: rid }, paths, NOW), /does not check against the page record/);
+ assert.equal(reportOf(paths, "bread", 1).citations.p2.kind, "page");
+ // Only a page citation.
+ await assert.rejects(replacePageCitationWithRecord("bread", { cite: "p1", channel: PAGES, id: rid }, paths, NOW), /is a post, not a page/);
+});
diff --git a/common/controller/handEdits.ts b/common/controller/handEdits.ts
@@ -29,6 +29,7 @@
//
// SERVER-ONLY.
+import { pageCitationAsPost } from "../lib/citations/pageAsPost";
import type { Paths } from "../lib/paths";
import { getPaths } from "../lib/paths";
import {
@@ -364,6 +365,98 @@ export async function addClaimByHand(id: string, input: HandClaimInput, paths: H
return { n, amended: amend, claim: cidClaim, section: sections[si]!.id, added, warnings };
}
+// ─── a page citation turned into its page record (release 37 S4) ───
+
+export type ImportedCaptureInput = {
+ // The page citation's id in the report.
+ cite: string;
+ // The page record the capture became: its Wayback pages channel and id.
+ channel: string;
+ id: string;
+ // Or the rewritten citation itself, as find-copy's page mode names it per
+ // item (`as`, built by the same pageCitationAsPost): its channel and id are
+ // the record's.
+ as?: Extract<Citation, { kind: "post" }>;
+ base?: number | null;
+};
+
+export type ImportedCaptureResult = {
+ n: number;
+ amended: boolean;
+ citation: Citation;
+ check: QuoteResult;
+};
+
+/**
+ * IMPORT THIS CAPTURE, the report's half: the `page` citation `cite` becomes
+ * a `post` citation of the page record its archived copy was imported as
+ * (`channel`/`id`), its quote and common fields kept and the page facts kept
+ * as its `fallback`. The quote is checked against the record's text first, as
+ * a hand-added post's is; a quote the record does not hold is refused. Written
+ * as a hand edit (the base hand iteration amended, else a new one).
+ */
+export async function replacePageCitationWithRecord(
+ id: string,
+ input: ImportedCaptureInput,
+ paths: HandPaths = getPaths(),
+ now: Date = new Date(),
+): Promise<ImportedCaptureResult> {
+ assertArticleId(id);
+ const base = input.base ?? (await defaultHandBase(id, paths));
+ let baseIt: Iteration | null = null;
+ let report: Report;
+ if (base === null || base === undefined) {
+ if (!(await hasArticleReport(id, paths)) || (await readIterations(id, paths)).iterations.length) fail(`"${id}" has no report to change`);
+ report = await readArticleReport(id, paths);
+ } else {
+ baseIt = await readIteration(id, base, paths);
+ if (!baseIt) fail(`"${id}" has no iteration ${iterationLabel(base)}`);
+ if (baseIt!.status !== "done") fail(`${iterationLabel(base)} is ${baseIt!.status}: change a done iteration`);
+ report = await readReportOf(id, base, paths);
+ }
+ const old = report.citations?.[input.cite];
+ if (!old) fail(`the report has no citation "${input.cite}"`);
+ if (old!.kind !== "page") fail(`citation "${input.cite}" is a ${old!.kind}, not a page`);
+ const page = old as Extract<Citation, { kind: "page" }>;
+ if (input.as && input.as.kind !== "post") fail("`as` is a post citation");
+ const channel = str(input.as?.channel ?? input.channel);
+ const rid = str(input.as?.id ?? input.id);
+ if (!channel || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(channel)) fail("the channel is a channel's slug");
+ if (!rid) fail("name the page record's id");
+ // One builder for both paths: find-copy's `as` is this same citation.
+ const citation = pageCitationAsPost(page, { channel, id: rid }) as Citation;
+ const [check] = await checkAddedCitations([{ kind: "post", channel, id: rid, quote: page.quote }], {
+ respellings: report.respellings,
+ paths,
+ now: now.toISOString(),
+ });
+ if (!passes(check!)) {
+ fail("the quote does not check against the page record", [`${channel}/${rid}: ${check!.status}${check!.message ? ` — ${check!.message}` : ""}`]);
+ }
+ const next: Report = { ...report, citations: { ...report.citations, [input.cite]: citation } };
+ const parsed = parseReport(next, { id });
+ if (!parsed.ok) fail("the report with the citation does not read", parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`));
+ const line = `${input.cite}: the page citation is now the page record ${channel}/${rid} (Import this capture)`;
+ const cur = await currentIteration(id, paths);
+ const amend = !!baseIt && baseIt.kind === "hand" && cur.report !== base && cur.reportFrom !== base && cur.video !== base && !baseIt.projectDir;
+ let n: number;
+ if (amend) {
+ n = base!;
+ await writeIterationFile(id, n, "report.json", next, paths);
+ await updateIteration(id, n, (it) => ({ feedback: it.feedback ? `${it.feedback}\n${line}` : line }), paths, now);
+ } else {
+ const it = await createIteration(
+ id,
+ { kind: "hand", model: HAND_MODEL, parent: baseIt ? base! : null, feedback: baseIt ? line : `from the article's report.json: ${line}`, status: "running" },
+ paths,
+ now,
+ );
+ n = it.n;
+ await finishHand(id, n, next, paths, now);
+ }
+ return { n, amended: amend, citation, check: { ...check!, citation: input.cite } };
+}
+
// ─── reading a moment, for the form ───
export type MomentRead = {
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -355,6 +355,24 @@ export class ArchiveOrgClient {
});
}
+ // A request SOMETHING ELSE makes (release 37 S4: a headless browser's load of
+ // a Wayback replay page for a page record's shot), run in this client's
+ // chain and gap: it waits for every earlier request and the gap, and the
+ // next one waits for it to end and the gap after. No retry here — the caller
+ // reads the answer and stops on a 429/503 rather than asking again.
+ paced<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {
+ return this.serial(async () => {
+ const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now();
+ if (wait > 0) await this.deps.sleep(wait, signal);
+ this.requests++;
+ try {
+ return await fn();
+ } finally {
+ this.lastDoneAt = this.deps.now();
+ }
+ });
+ }
+
getJson(url: string, signal?: AbortSignal): Promise<unknown> {
return this.serial(async () => {
const res = await this.getOnce(url, "application/json", signal);
diff --git a/common/lib/archives/mementos.test.ts b/common/lib/archives/mementos.test.ts
@@ -123,3 +123,21 @@ test("an import's ask across sources: a copy's URL names its source; a page's UR
// The Wayback Machine's own sentences, unchanged.
assert.match(err("https://blog.example/"), /not a Wayback Machine capture/);
});
+
+test("the view's copy link names archive.today for its records (lane D's pageCopyLinks)", async () => {
+ const { pageCopyLinks, pageCaptureView } = await import("../waybackPages/view");
+ const page = {
+ originalUrl: "https://journal.example/a.html",
+ captureTs: "20190512083000",
+ waybackUrl: "https://archive.ph/Ab3dE",
+ rawUrl: "https://archive.ph/Ab3dE",
+ source: "archive.today",
+ archiveUrl: "https://archive.ph/Ab3dE",
+ };
+ assert.deepEqual(pageCopyLinks(page).copy, { label: "archive.today copy, 2019-05-12", url: "https://archive.ph/Ab3dE" });
+ const { source: _s, archiveUrl: _a, ...wb } = page;
+ assert.match(pageCopyLinks({ ...wb, waybackUrl: "https://web.archive.org/web/20190512083000/https://journal.example/a.html" }).copy.label, /^Wayback Machine copy, /);
+ const view = pageCaptureView({ id: "20190512083000-aaaaaaaaaaaa", text: "x", page: { ...page, kind: "generic", extractor: "generic", extractorVersion: 1 } });
+ assert.equal(view?.source, "archive.today");
+ assert.equal(view?.waybackUrl, "https://archive.ph/Ab3dE");
+});
diff --git a/common/lib/citations/docs.ts b/common/lib/citations/docs.ts
@@ -19,6 +19,7 @@ import {
CITATIONS_VERSION,
MAX_CITATION_SPAN_SECONDS,
PAGE_CITATION_FIELD_DOCS,
+ PAGE_FALLBACK_FIELD_DOCS,
POST_CITATION_FIELD_DOCS,
SOURCE_ARCHIVE_FIELD_DOCS,
SOURCE_CITATION_FIELD_DOCS,
@@ -141,6 +142,7 @@ export function renderCitationsMarkdown(): string {
CITATION_PAD_FIELD_DOCS,
);
renderKeyTable(out, '#### `"post"`', postCitationSchema.shape, POST_CITATION_FIELD_DOCS);
+ renderKeyTable(out, "#### `fallback` (post)", postCitationSchema.shape.fallback.unwrap().shape, PAGE_FALLBACK_FIELD_DOCS);
renderKeyTable(out, '#### `"source"`', sourceCitationSchema.shape, SOURCE_CITATION_FIELD_DOCS);
renderKeyTable(out, '#### `"page"`', pageCitationSchema.shape, PAGE_CITATION_FIELD_DOCS);
diff --git a/common/lib/citations/pageAsPost.ts b/common/lib/citations/pageAsPost.ts
@@ -0,0 +1,19 @@
+// A PAGE citation as a POST citation of the page record its capture became
+// (release 37): the ONE builder both paths use — umtool's Import this capture
+// (controller/handEdits.ts replacePageCitationWithRecord) and find-copy's page
+// mode (publish/findCopyPages.ts, its items' `as`) — so they write identical
+// citations. Its words and editorial fields kept; the page's address, title
+// and archived copy kept as its `fallback`. Pure, client-safe.
+
+import type { PageCitation, PostCitation } from "./schema";
+
+export function pageCitationAsPost(c: PageCitation, pointTo: { channel: string; id: string }): PostCitation {
+ const { kind: _kind, url, title, archiveUrl, ...common } = c;
+ return {
+ kind: "post",
+ channel: pointTo.channel,
+ id: pointTo.id,
+ ...common,
+ fallback: { kind: "page", url, ...(title ? { title } : {}), ...(archiveUrl ? { archiveUrl } : {}) },
+ };
+}
diff --git a/common/lib/citations/schema.ts b/common/lib/citations/schema.ts
@@ -98,11 +98,21 @@ const span = {
export const videoCitationSchema = z.strictObject({ kind: z.literal("video"), ...span, ...common });
export const audioCitationSchema = z.strictObject({ kind: z.literal("audio"), ...span, ...common });
+// The page citation a post citation replaced (release 37 S4, "Import this
+// capture"): the page's address, title and archived copy, kept so a reader
+// that cannot resolve the post still has the page.
+export const pageFallbackSchema = z.strictObject({
+ kind: z.literal("page"),
+ url: text,
+ title: text.optional(),
+ archiveUrl: text.optional(),
+});
export const postCitationSchema = z.strictObject({
kind: z.literal("post"),
channel: text,
id: text,
thread: z.boolean().optional(),
+ fallback: pageFallbackSchema.optional(),
...common,
});
export const sourceCitationSchema = z.strictObject({
@@ -135,6 +145,7 @@ export type AudioCitation = z.infer<typeof audioCitationSchema>;
export type PostCitation = z.infer<typeof postCitationSchema>;
export type SourceCitation = z.infer<typeof sourceCitationSchema>;
export type PageCitation = z.infer<typeof pageCitationSchema>;
+export type PageFallback = z.infer<typeof pageFallbackSchema>;
export type Citation = z.infer<typeof citationSchema>;
export type CitationKind = Citation["kind"];
// The kinds that cite a span of a record's media: a clip, a start and an end.
@@ -190,6 +201,15 @@ export const POST_CITATION_FIELD_DOCS: FieldDocs<Own<PostCitation>> = {
"The post's channel slug. A path segment of the moment page. The citing site must name it in `channels` or `citedChannels` (see [SITE.md](SITE.md)), and may carry the post (the post visibility rule).",
id: "The post's id. A path segment of the moment page.",
thread: "True to show the post with the thread it belongs to. Absent = the post alone.",
+ fallback:
+ "The `page` citation this one replaced (`{kind: \"page\", url, title?, archiveUrl?}`): a page citation whose Wayback copy was imported as a page record (umtool's **Import this capture**) becomes a `post` citation of that record, its page facts kept here so the page can still be shown where the post is not resolved. Absent = the citation was always a post.",
+};
+
+export const PAGE_FALLBACK_FIELD_DOCS: FieldDocs<PageFallback> = {
+ kind: '`"page"`.',
+ url: "The page's address, as the page citation named it.",
+ title: "The page's title, as the page citation named it.",
+ archiveUrl: "The archived copy the page citation named (the capture imported).",
};
export const SOURCE_CITATION_FIELD_DOCS: FieldDocs<Own<SourceCitation>> = {
diff --git a/common/lib/corpus.ts b/common/lib/corpus.ts
@@ -98,7 +98,7 @@ const SHARD_SCHEME = {
// timestamp fragment.
const POST_SCHEME = {
description:
- "Social posts (X/Twitter, Bluesky, forum threads) are archived as a PARALLEL corpus to " +
+ "Social posts (X/Twitter, Bluesky, forum threads) and web pages captured by the Wayback Machine are archived as a PARALLEL corpus to " +
"video transcripts and are served as paginated JSON shards under the same " +
"scheme: (1) GET the channel's posts manifest; (2) look up the post id in " +
"its `slugToPage` map to get a page number N; (3) GET page-<NNNN>.json and " +
@@ -113,7 +113,13 @@ const POST_SCHEME = {
"forum }; `forum` (platform \"xenforo\": one channel is one forum thread) " +
"carries { host, threadId, threadTitle, page, position, authorId, editedAt, " +
"quotes: [{ postId, author }] }, and quoted text in a forum post's `text` " +
- "is marked with leading \"> \" lines",
+ "is marked with leading \"> \" lines; `page` (platform \"webpage\") is pageRecords",
+ pageRecords:
+ "a channel whose `kind` is \"wayback-pages\" holds PAGE RECORDS (platform \"webpage\"): one captured " +
+ "state of a web page, or one item (a tweet, a Tumblr post, a forum post) of a capture. `page` carries " +
+ "{ originalUrl, captureTs, waybackUrl, rawUrl, kind, title?, publishedAt?, firstSeenTs?, versionOf?, " +
+ "noContent?, extractor, extractorVersion, extractorFallback? }; cite the original (it may be gone) AND " +
+ "the Wayback copy (`waybackUrl`). Records of the same `originalUrl` are versions of one page",
ordering:
"newest first, by `createdAt` (ISO-8601, ms precision where the source provides it)",
dateFilter:
@@ -170,6 +176,10 @@ export type CorpusChannel = {
};
// Present only for social channels.
postCount?: number;
+ // What kind of posts channel it is, when it is not an account's: a WAYBACK
+ // PAGES channel ("wayback-pages", release 37) holds page records — captures
+ // of web pages, each post carrying `page` (POST_SCHEME.pageRecords).
+ kind?: "wayback-pages";
// Number of this channel's videos that carry a digest. Present only when
// non-zero, and deliberately reported ALONGSIDE videoCount rather than
// instead of it: the ratio is the coverage of the derived layer, which is
@@ -250,6 +260,9 @@ export function buildSiteCorpus(
// slug -> archived post count, for the social channels in this site. Absent
// / empty means the site has no posts corpus and postScheme is omitted.
postCounts?: Record<string, number>;
+ // slug -> the channel's kind, for a posts channel that is not an account's
+ // (release 37: "wayback-pages").
+ channelKinds?: Record<string, "wayback-pages">;
// slug -> digested video count. Absent / empty means the site ships no
// derived layer and digestScheme is omitted.
digestCounts?: Record<string, number>;
@@ -280,6 +293,7 @@ export function buildSiteCorpus(
videoCount: c.count,
...(c.groupId ? { groupId: c.groupId } : {}),
...(postCount ? { postCount } : {}),
+ ...(opts.channelKinds?.[c.slug] ? { kind: opts.channelKinds[c.slug] } : {}),
...(digestCount ? { digestCount } : {}),
// One definition of the manifest URL shape, shared with every reader.
// The conditional spreads stay here: whether a layer is ADVERTISED is a
diff --git a/common/lib/report/views.ts b/common/lib/report/views.ts
@@ -39,6 +39,7 @@
// Pure, no imports but types and pure helpers: the export site's pages and the
// browser can use it.
+import type { PageCaptureView } from "../waybackPages/view";
import { citationAnchor, extractCiteRefs } from "../citations/inline";
import {
formatMomentSeconds,
@@ -447,6 +448,9 @@ export type MomentPostView = {
text: string;
shot?: string;
media?: { src: string; kind: "image" | "video" }[];
+ // A page record's capture (platform "webpage", release 37 S4): its kind and
+ // date, the version list, no content, the extractor-fallback note.
+ page?: PageCaptureView;
};
export type MomentPageView = {
diff --git a/common/lib/wayback.ts b/common/lib/wayback.ts
@@ -85,6 +85,22 @@ export function waybackRawUrl(ref: Pick<WaybackRef, "captureTs" | "originalUrl">
return `https://web.archive.org/web/${ref.captureTs}id_/${ref.originalUrl}`;
}
+// The capture as a page with no toolbar (`if_`, the replay's frame mode): what
+// a page record's shot renders (release 37 S4).
+export function waybackFrameUrl(ref: Pick<WaybackRef, "captureTs" | "originalUrl">): string {
+ return `https://web.archive.org/web/${ref.captureTs}if_/${ref.originalUrl}`;
+}
+
+// A file a capture names (an image), through its own Wayback URL (`im_`): a
+// web.archive.org URL keeps its timestamp and original, anything else is
+// asked for at `captureTs` — the archive answers the nearest capture of it.
+export function waybackFileUrl(captureTs: string, url: string): string {
+ const ref = parseWaybackUrl(url);
+ return ref
+ ? `https://web.archive.org/web/${ref.captureTs}im_/${ref.originalUrl}`
+ : `https://web.archive.org/web/${captureTs}im_/${url}`;
+}
+
// `YYYY-MM-DD` of a capture timestamp, or the year (/month) when that is all
// it names.
export function waybackCaptureDate(captureTs: string): string {
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -164,6 +164,9 @@ export const WAYBACK_PAGE_MAX_BYTES = 2 * 1024 * 1024;
// How many redirects inside the archive a capture fetch follows.
export const WAYBACK_MAX_REDIRECTS = 5;
+// The cap on one archived file a page record's capture downloads (release 37 S4).
+export const WAYBACK_FILE_MAX_BYTES = 10 * 1024 * 1024;
+
const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8,application/json;q=0.8,*/*;q=0.1";
// One capture's bytes (getCapture).
@@ -412,6 +415,56 @@ export class WaybackClient {
throw new WaybackCaptureRefusal("redirect-loop", `the capture of ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`);
}
+ // Run a request something else makes (a headless browser's load of a
+ // replay page, release 37 S4) in this client's chain and gap.
+ paced<T>(fn: () => Promise<T>, o: { signal?: AbortSignal } = {}): Promise<T> {
+ return this.http.paced(fn, o.signal);
+ }
+
+ // A FILE a capture names (release 37 S4: a page record's image), by its own
+ // Wayback URL (`im_`, lib/wayback.ts waybackFileUrl), through the same chain,
+ // gap and back-off: its body read up to `maxBytes` (default 10 MB), redirects
+ // followed by hand inside web.archive.org only (≤ WAYBACK_MAX_REDIRECTS, the
+ // modifier kept). Answers null for a file the archive does not hold (404/410)
+ // or one over the cap; throws WaybackCaptureRefusal for a redirect off the
+ // archive or a loop, ArchiveOrgRequestError as getCapture does.
+ async getArchivedFile(
+ url: string,
+ o: { maxBytes?: number; accept?: string; signal?: AbortSignal } = {},
+ ): Promise<{ body: Buffer; contentType: string | null; url: string } | null> {
+ const maxBytes = o.maxBytes ?? WAYBACK_FILE_MAX_BYTES;
+ let at = url;
+ const seen = new Set<string>();
+ for (let hop = 0; hop <= WAYBACK_MAX_REDIRECTS; hop++) {
+ seen.add(at);
+ let res;
+ try {
+ res = await this.http.getBounded(at, o.accept ?? "image/*,*/*;q=0.5", { maxBytes, signal: o.signal, manualRedirect: true });
+ } catch (e) {
+ if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) return null;
+ throw e;
+ }
+ if (res.location !== null || (res.status >= 300 && res.status < 400)) {
+ const next = res.location;
+ let host = "";
+ try {
+ host = next ? new URL(next).hostname : "";
+ } catch {
+ host = "";
+ }
+ if (!next || !isWaybackHost(host)) {
+ throw new WaybackCaptureRefusal("offsite-redirect", `the archived file ${url} redirects off the Wayback Machine (${next ?? "no URL"})`);
+ }
+ if (seen.has(next)) throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirects in a loop (${next})`);
+ at = next;
+ continue;
+ }
+ if (res.tooLarge || !res.body) return null;
+ return { body: res.body, contentType: res.headers.get("content-type"), url: at };
+ }
+ throw new WaybackCaptureRefusal("redirect-loop", `the archived file ${url} redirected more than ${WAYBACK_MAX_REDIRECTS} times`);
+ }
+
// The captures of `url`, oldest first: every capture, or (`okOnly`) only the
// ones that recorded a 200. Throws ArchiveOrgRequestError when the API kept
// refusing (`rateLimited`) or answered an error.
diff --git a/common/lib/waybackPages/view.test.ts b/common/lib/waybackPages/view.test.ts
@@ -0,0 +1,86 @@
+// How a page record is shown (release 37 S4): the kind, the links, the
+// version list, no content and the fallback note.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/view.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { Post } from "../posts";
+import { pageRecordId } from "./types";
+import { PAGE_ORIGINAL_GONE_LABEL } from "./liveness";
+import { isWholePageId, pageCaptureLine, pageCaptureView, pageKindLabel, pageVersionsLine } from "./view";
+
+const URL_A = "https://blog.example/a.html";
+
+function rec(ts: string, text: string, over: Partial<Post["page"]> = {}): Post {
+ const id = pageRecordId(ts, URL_A);
+ return {
+ id,
+ slug: `pages/${id}`,
+ channelSlug: "pages",
+ author: "blog.example",
+ createdAt: "2014-03-05T12:00:00.000Z",
+ uploadDate: "20140305",
+ text,
+ url: URL_A,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page: {
+ originalUrl: URL_A,
+ captureTs: ts,
+ waybackUrl: `https://web.archive.org/web/${ts}/${URL_A}`,
+ rawUrl: `https://web.archive.org/web/${ts}id_/${URL_A}`,
+ kind: "generic",
+ extractor: "generic",
+ extractorVersion: 1,
+ ...over,
+ },
+ };
+}
+
+test("a whole-page record: links, kind, and the versions of the same page", () => {
+ const a = rec("20140305120000", "First.");
+ const b = rec("20150611090000", "First.");
+ const c = rec("20160102000000", "Second.");
+ const other = { ...rec("20150101000000", "x"), page: { ...rec("20150101000000", "x").page!, originalUrl: "https://blog.example/b.html" } };
+ assert.ok(isWholePageId(a.id));
+ assert.ok(!isWholePageId("tumblr-123"));
+ const v = pageCaptureView(b, [a, c, other])!;
+ assert.equal(v.kindLabel, "Web page");
+ assert.equal(v.captureDate, "2015-06-11");
+ assert.deepEqual(v.links.original, { label: "Original (may be gone)", url: URL_A });
+ assert.deepEqual(v.links.copy, { label: "Wayback Machine copy, 2015-06-11", url: b.page!.waybackUrl });
+ assert.equal(v.versions?.count, 3);
+ assert.deepEqual(v.versions?.changedOn, ["2016-01-02"]);
+ assert.deepEqual(v.versions?.captures.map((x) => x.current), [false, true, false]);
+ assert.equal(pageVersionsLine(v.versions!), "3 captures of this page; text changed on 2016-01-02.");
+ assert.equal(pageVersionsLine({ count: 2, changedOn: [] }), "2 captures of this page; the text is the same in both.");
+ assert.equal(pageVersionsLine({ count: 4, changedOn: ["a", "b", "c"] }), "4 captures of this page; text changed on a, b and c.");
+ assert.equal(pageCaptureView(a)?.versions, undefined, "one capture: no list");
+ assert.equal(pageCaptureView({ id: "p", text: "" }), undefined);
+});
+
+test("no content, the fallback note, an item seen first in an earlier capture", () => {
+ const shell = rec("20220101000000", "", { noContent: true, kind: "x-profile", extractorFallback: { from: "x", fromVersion: 1, error: "boom" } });
+ const v = pageCaptureView(shell)!;
+ assert.equal(v.noContent, true);
+ assert.equal(v.kindLabel, "X/Twitter profile");
+ assert.equal(v.fallbackNote, "The x reader could not read this capture (boom); the text is the generic reader's.");
+ const item = { ...rec("20140305120000", "t", { kind: "tumblr-post", firstSeenTs: "20120601000000" }), id: "tumblr-1" };
+ const iv = pageCaptureView(item)!;
+ assert.equal(iv.firstSeenDate, "2012-06-01");
+ assert.equal(pageCaptureLine(iv), "Tumblr post · captured 2014-03-05 (first seen 2012-06-01)");
+ assert.equal(pageKindLabel("newkind"), "Web page (newkind)");
+
+});
+
+test("an original known gone is named as such; the Wayback copy is the only copy", () => {
+ const r = { ...rec("20140305120000", "x"), isDeleted: true };
+ const v = pageCaptureView(r)!;
+ assert.equal(v.originalGone, true);
+ assert.equal(v.links.original.label, PAGE_ORIGINAL_GONE_LABEL);
+ assert.equal(pageCaptureView(rec("20140305120000", "x"), [], { originalGone: true })!.links.original.label, PAGE_ORIGINAL_GONE_LABEL);
+ assert.equal(pageCaptureView(rec("20140305120000", "x"))!.links.original.label, "Original (may be gone)");
+});
diff --git a/common/lib/waybackPages/view.ts b/common/lib/waybackPages/view.ts
@@ -0,0 +1,184 @@
+// HOW A PAGE RECORD IS SHOWN (release 37 S4): the facts every surface that
+// renders a page record — a report site's moment page and citation card, the
+// editor's Wayback pages panel, umtool's evidence rail, the corpus viewer's
+// post modal — prints about its capture, in the same words everywhere:
+//
+// the kind ("Tumblr post", "Web page", …), the capture's date,
+// "Original (may be gone)" + "Wayback Machine copy, <date>"
+// (lib/wayback.ts waybackCitationLinks),
+// the version list — "4 captures of this page; text changed on …" — from
+// the records of the same original URL,
+// "This capture holds no content." for a shell, and the extractor-fallback
+// note when a site extractor failed and the generic one read the page.
+//
+// Client-safe and pure: types only from ./types (whose urlHash is
+// node:crypto), so the whole-page test is the id's shape, not a hash.
+
+import type { Post } from "../posts";
+import type { PagePostInfo } from "./types";
+import { waybackCaptureDate, waybackCitationLinks, type WaybackLink } from "../wayback";
+import { PAGE_ORIGINAL_GONE_LABEL } from "./liveness";
+import { pageArchiveLink } from "../archives/mementos";
+
+export const PAGE_KIND_LABELS: Record<string, string> = {
+ generic: "Web page",
+ "tumblr-post": "Tumblr post",
+ "tumblr-index": "Tumblr page",
+ tweet: "Tweet",
+ "x-profile": "X/Twitter profile",
+ "forum-post": "Forum post",
+ gdoc: "Google Doc",
+ "yt-about": "YouTube channel page",
+};
+
+export function pageKindLabel(kind: string): string {
+ return PAGE_KIND_LABELS[kind] ?? `Web page (${kind})`;
+}
+
+export const PAGE_NO_CONTENT_LINE = "This capture holds no content.";
+
+// A whole-page record's id is pageRecordId(captureTs, originalUrl):
+// `<ts>-<12 hex>`. An item's id is the source's own (`tumblr-…`, `tweet-…`).
+const WHOLE_PAGE_ID = /^\d{4,14}-[0-9a-f]{12}$/;
+export function isWholePageId(id: string): boolean {
+ return WHOLE_PAGE_ID.test(id);
+}
+
+export type PageVersionsView = {
+ // Captures of the page held (this one included).
+ count: number;
+ // The capture dates on which the text differs from the capture before.
+ changedOn: string[];
+ // Each capture, oldest first.
+ captures: { id: string; date: string; waybackUrl: string; current: boolean }[];
+};
+
+export type PageCaptureView = {
+ kind: string;
+ kindLabel: string;
+ captureTs: string;
+ captureDate: string;
+ originalUrl: string;
+ waybackUrl: string;
+ links: { original: WaybackLink; copy: WaybackLink };
+ // The original is known gone: the Wayback copy is the only copy.
+ originalGone?: boolean;
+ // Release 37 lane F: the archive source when it is not the Wayback Machine
+ // ("archive.today"); `waybackUrl` is then that copy's URL.
+ source?: string;
+ title?: string;
+ noContent?: boolean;
+ // The extractor-fallback sentence.
+ fallbackNote?: string;
+ // An item seen in more than one capture: the first one's date.
+ firstSeenDate?: string;
+ versions?: PageVersionsView;
+};
+
+// THE ONE PLACE a page record's two links are named: "Original (may be gone)"
+// and "<archive> copy, <date>" (lib/wayback.ts waybackCitationLinks). Every
+// surface — compose's record view, this module's view, the MCP — goes through
+// it, so a record from another archive is one change here.
+// `originalGone`: the original is known gone (release 37 S5's check recorded
+// it `deleted`) — the original is then named as such (PAGE_ORIGINAL_GONE_LABEL).
+// Release 37 lane F: a record from another archive source (`page.source`,
+// "archive.today") names that source and links its copy (`page.archiveUrl`):
+// "archive.today copy, <date>".
+export function pageCopyLinks(
+ page: Pick<PagePostInfo, "originalUrl" | "captureTs" | "waybackUrl" | "rawUrl"> & Partial<Pick<PagePostInfo, "source" | "archiveUrl">>,
+ o: { originalGone?: boolean } = {},
+): {
+ original: WaybackLink;
+ copy: WaybackLink;
+} {
+ const base = waybackCitationLinks(page);
+ const other = page.source && page.source !== "wayback" ? pageArchiveLink(page) : null;
+ const links = other ? { ...base, copy: { label: `${other.label} copy, ${waybackCaptureDate(page.captureTs)}`, url: other.url } } : base;
+ return o.originalGone ? { ...links, original: { ...links.original, label: PAGE_ORIGINAL_GONE_LABEL } } : links;
+}
+
+export function pageFallbackNote(page: Pick<PagePostInfo, "extractorFallback">): string | undefined {
+ const f = page.extractorFallback;
+ if (!f) return undefined;
+ return `The ${f.from} reader could not read this capture (${f.error}); the text is the generic reader's.`;
+}
+
+const tsKey = (ts: string) => ts.padEnd(14, "0");
+
+// The versions of a whole-page record: the other whole-page records of the
+// same original URL (`siblings` may hold anything — the channel's records;
+// the ones that are not versions of this page are ignored). Undefined for an
+// item record, or a page held in one capture only.
+export function pageVersions(post: Pick<Post, "id" | "page" | "text">, siblings: ReadonlyArray<Pick<Post, "id" | "page" | "text">>): PageVersionsView | undefined {
+ if (!post.page || !isWholePageId(post.id)) return undefined;
+ const original = post.page.originalUrl;
+ const all = new Map<string, Pick<Post, "id" | "page" | "text">>();
+ for (const s of [post, ...siblings]) {
+ if (s.page && s.page.originalUrl === original && isWholePageId(s.id)) all.set(s.id, s);
+ }
+ if (all.size < 2) return undefined;
+ const list = [...all.values()].sort((a, b) => tsKey(a.page!.captureTs).localeCompare(tsKey(b.page!.captureTs)));
+ const changedOn: string[] = [];
+ for (let i = 1; i < list.length; i++) {
+ if (list[i]!.text.trim() !== list[i - 1]!.text.trim()) changedOn.push(waybackCaptureDate(list[i]!.page!.captureTs));
+ }
+ return {
+ count: list.length,
+ changedOn,
+ captures: list.map((s) => ({
+ id: s.id,
+ date: waybackCaptureDate(s.page!.captureTs),
+ waybackUrl: s.page!.waybackUrl,
+ current: s.id === post.id,
+ })),
+ };
+}
+
+// "4 captures of this page; text changed on 2015-06-11 and 2016-01-02." /
+// "2 captures of this page; the text is the same in both."
+export function pageVersionsLine(v: Pick<PageVersionsView, "count" | "changedOn">): string {
+ const head = `${v.count} captures of this page`;
+ if (v.changedOn.length === 0) return `${head}; the text is the same in ${v.count === 2 ? "both" : "all"}.`;
+ const dates =
+ v.changedOn.length === 1
+ ? v.changedOn[0]
+ : `${v.changedOn.slice(0, -1).join(", ")} and ${v.changedOn[v.changedOn.length - 1]}`;
+ return `${head}; text changed on ${dates}.`;
+}
+
+export function pageCaptureView(
+ post: Pick<Post, "id" | "page" | "text"> & Partial<Pick<Post, "isDeleted" | "availability">>,
+ siblings: ReadonlyArray<Pick<Post, "id" | "page" | "text">> = [],
+ // Whether the original is known gone; default: the record's own flag (the
+ // index merges the availability sidecar onto a served record).
+ o: { originalGone?: boolean } = {},
+): PageCaptureView | undefined {
+ const page = post.page;
+ if (!page) return undefined;
+ const originalGone = o.originalGone ?? (post.isDeleted === true || post.availability === "deleted");
+ const versions = pageVersions(post, siblings);
+ const fallbackNote = pageFallbackNote(page);
+ const firstSeen =
+ page.firstSeenTs && tsKey(page.firstSeenTs) !== tsKey(page.captureTs) ? waybackCaptureDate(page.firstSeenTs) : undefined;
+ return {
+ kind: page.kind,
+ kindLabel: pageKindLabel(page.kind),
+ captureTs: page.captureTs,
+ captureDate: waybackCaptureDate(page.captureTs),
+ originalUrl: page.originalUrl,
+ waybackUrl: page.archiveUrl ?? page.waybackUrl,
+ links: pageCopyLinks(page, { originalGone }),
+ ...(page.source && page.source !== "wayback" ? { source: page.source } : {}),
+ ...(originalGone ? { originalGone: true } : {}),
+ ...(page.title ? { title: page.title } : {}),
+ ...(page.noContent ? { noContent: true } : {}),
+ ...(fallbackNote ? { fallbackNote } : {}),
+ ...(firstSeen ? { firstSeenDate: firstSeen } : {}),
+ ...(versions ? { versions } : {}),
+ };
+}
+
+// One line of what the capture is: "Tumblr post · captured 2012-06-01".
+export function pageCaptureLine(v: Pick<PageCaptureView, "kindLabel" | "captureDate" | "firstSeenDate">): string {
+ return `${v.kindLabel} · captured ${v.captureDate}${v.firstSeenDate ? ` (first seen ${v.firstSeenDate})` : ""}`;
+}
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -69,6 +69,7 @@
// thrown together (ComposeReportsError), so a failed compose leaves no half
// set of reports behind.
+import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view";
import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { publishFileSizeProblem } from "../lib/builtExport";
@@ -761,13 +762,20 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
const config = await configOf(c.channel);
if (c.kind === "post") {
const post = (await postOf(c.channel, c.id))!;
+ // A page record (a Wayback capture, release 37 S4): the original, named
+ // as possibly gone, then the Wayback copy — as an archived video's.
+ const page = post.page
+ ? pageCopyLinks(post.page, { originalGone: (await postGoneState(paths.channelsDir, c.channel, c.id)) === "deleted" })
+ : null;
return defined({
channel: c.channel,
channelTitle: config?.name ?? post.authorName,
id: c.id,
+ ...(post.page?.title ? { title: post.page.title } : {}),
date: post.createdAt.slice(0, 10),
platform: post.platform,
- originalUrl: post.url,
+ originalUrl: page ? page.original.url : post.url,
+ ...(page ? { originalLabel: page.original.label, downloads: [page.copy] } : {}),
corpusUrl: corpusLink(c.channel, `${c.channel}/${c.id}`, { vm: "post" }),
});
}
@@ -888,9 +896,15 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol
} as const;
if (c.kind === "post") {
const post = postsByChannel.get(c.channel)!.get(c.id)!;
+ const pageView = post.page
+ ? pageCaptureView(post, [...postsByChannel.get(c.channel)!.values()], {
+ originalGone: (await postGoneState(paths.channelsDir, c.channel, c.id)) === "deleted",
+ })
+ : undefined;
const postView: MomentPostView = {
author: postAuthor(post),
text: post.text,
+ ...(pageView ? { page: pageView } : {}),
...(entry?.kind === "post"
? {
shot: `/media/${entry.file}`,
diff --git a/common/publish/composeReportsPages.test.ts b/common/publish/composeReportsPages.test.ts
@@ -0,0 +1,164 @@
+// Integration: a cited PAGE RECORD (release 37 S4) through the REAL site
+// compose (bin/compose-site.ts main) over a temp corpus: a Wayback pages
+// channel holding two captures of one page, a report citing the later one as
+// a post, and the prepared shot. The moment page carries the capture — its
+// kind, both links, the version list — and the record's links are the
+// original named as possibly gone and the Wayback copy. Every id is invented.
+//
+// Run with: node_modules/.bin/tsx --test publish/composeReportsPages.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "compose-pages-"));
+const PINNED: Record<string, string> = {
+ TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"),
+ SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"),
+ SITES_DIR: path.join(ROOT, "transcripts", "sites"),
+ SETTINGS_FILE: path.join(ROOT, "settings.json"),
+ EXPORT_PUBLIC_DIR: path.join(ROOT, "public"),
+ EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"),
+ EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"),
+ EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"),
+ EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"),
+ CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"),
+ SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"),
+ CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"),
+ ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"),
+ ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"),
+};
+Object.assign(process.env, PINNED);
+delete process.env.REPORTS_ALLOW_MISSING_MEDIA;
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { buildIndex } = await import("../controller/buildIndex");
+const { writePosts } = await import("../lib/posts-server");
+const { main: composeSite } = await import("../bin/compose-site");
+const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION, reportMediaDir, reportMediaIndexFile } = await import("./reportMedia");
+const { pageRecordId } = await import("../lib/waybackPages/types");
+
+const paths = getPaths();
+const PAGES = "demo-pages";
+const REPORT = "page-report";
+const URL_A = "https://blog.example/2014/03/a-post.html";
+const TS1 = "20140305120000";
+const TS2 = "20150611090000";
+const ID1 = pageRecordId(TS1, URL_A);
+const ID2 = pageRecordId(TS2, URL_A);
+
+const writeJson = (file: string, value: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(value, null, 2));
+};
+const readJson = <T = Record<string, unknown>>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T;
+const pub = (...p: string[]) => path.join(paths.exportPublicDir, ...p);
+
+const record = (id: string, ts: string, text: string) => ({
+ id,
+ slug: `${PAGES}/${id}`,
+ channelSlug: PAGES,
+ author: "Pat Example",
+ createdAt: "2014-03-04T18:30:00.000Z",
+ uploadDate: "20140304",
+ text,
+ url: URL_A,
+ platform: "webpage" as const,
+ isReply: false,
+ isRepost: false,
+ links: [],
+ threadId: "page-0123456789ab",
+ page: {
+ originalUrl: URL_A,
+ captureTs: ts,
+ waybackUrl: `https://web.archive.org/web/${ts}/${URL_A}`,
+ rawUrl: `https://web.archive.org/web/${ts}id_/${URL_A}`,
+ kind: "generic" as const,
+ title: "A Post About Bread",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+});
+
+test("a cited page record: its moment page carries the capture, the versions and both links", async () => {
+ writeJson(paths.settingsFile, {});
+ writeJson(path.join(paths.channelsDir, PAGES, "config.json"), {
+ handling: "transcribe",
+ name: "Demo Pages",
+ url: "https://web.archive.org/web/*/blog.example/*",
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: "blog.example",
+ wayback: { targets: [{ url: "blog.example/", match: "prefix" }] },
+ });
+ await writePosts(path.join(paths.channelsDir, PAGES), [
+ record(ID1, TS1, "The first loaf came out flat."),
+ record(ID2, TS2, "The first loaf came out flat. Update: the fourth loaf rose."),
+ ]);
+ writeJson(path.join(paths.sitesDir, "cited", "site.json"), {
+ siteId: "cited",
+ siteTitle: "Site cited",
+ siteDescription: "fixture",
+ headerTitle: "cited",
+ homeTagline: "",
+ socialLinks: [],
+ groups: [{ id: "default", name: "All channels", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [{ slug: PAGES, groupId: "default" }],
+ siteUrl: "https://cited.example.test",
+ archives: false,
+ search: false,
+ pages: [REPORT],
+ });
+ writeJson(path.join(paths.sitesDir, "cited", "reports", REPORT, "report.json"), {
+ format: "archilyzer-report",
+ version: 1,
+ id: REPORT,
+ kind: "sweep",
+ title: "The bread blog",
+ citations: { p1: { kind: "post", channel: PAGES, id: ID2, quote: "the fourth loaf rose" } },
+ sections: [{ id: "s1", title: "The blog", claims: [{ id: "c1", text: "The blog said the fourth loaf rose.", citations: ["p1"] }] }],
+ });
+ const dir = reportMediaDir(paths, "cited");
+ mkdirSync(path.join(dir, "posts", PAGES, ID2), { recursive: true });
+ writeFileSync(path.join(dir, "posts", PAGES, ID2, "shot.png"), "shot");
+ writeJson(reportMediaIndexFile(paths, "cited"), {
+ format: REPORT_MEDIA_FORMAT,
+ version: REPORT_MEDIA_VERSION,
+ siteId: "cited",
+ preparedAt: "2026-10-20T00:00:00.000Z",
+ moments: {
+ [`${PAGES}/${ID2}`]: { kind: "post", file: `posts/${PAGES}/${ID2}/shot.png`, bytes: 4, sha256: "e".repeat(64), width: null, height: null, durationSec: null, media: [] },
+ },
+ problems: [],
+ });
+ await buildIndex({ paths, onLog: () => {} });
+ const log = console.log;
+ console.log = () => {};
+ try {
+ await composeSite({ siteId: "cited", paths });
+ } finally {
+ console.log = log;
+ }
+
+ const m = readJson<{
+ kind: string;
+ record: { title?: string; originalUrl?: string; originalLabel?: string; downloads?: { label: string; url: string }[] };
+ post: { shot?: string; page?: { kindLabel: string; captureDate: string; versions?: { count: number; changedOn: string[] } } };
+ }>(pub("m", PAGES, ID2, "moment.json"));
+ assert.equal(m.kind, "post");
+ assert.equal(m.record.title, "A Post About Bread");
+ assert.equal(m.record.originalUrl, URL_A);
+ assert.equal(m.record.originalLabel, "Original (may be gone)");
+ assert.deepEqual(m.record.downloads, [{ label: "Wayback Machine copy, 2015-06-11", url: `https://web.archive.org/web/${TS2}/${URL_A}` }]);
+ assert.equal(m.post.shot, `/media/posts/${PAGES}/${ID2}/shot.png`);
+ assert.equal(m.post.page?.kindLabel, "Web page");
+ assert.equal(m.post.page?.captureDate, "2015-06-11");
+ assert.deepEqual(m.post.page?.versions && { count: m.post.page.versions.count, changedOn: m.post.page.versions.changedOn }, {
+ count: 2,
+ changedOn: ["2015-06-11"],
+ });
+});
diff --git a/common/publish/findCopyPages.test.ts b/common/publish/findCopyPages.test.ts
@@ -89,7 +89,15 @@ test("which channel covers a page; the date a citation asks for; the record a qu
assert.equal(recordForQuote([{ id: "a", text: "x" }], "not there"), "a");
assert.deepEqual(
pageCitationAsPost({ kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x", quote: "q", label: "L", note: "n" }, { channel: "blog", id: "r1" }),
- { kind: "post", channel: "blog", id: "r1", quote: "q", label: "L", note: "n" },
+ {
+ kind: "post",
+ channel: "blog",
+ id: "r1",
+ quote: "q",
+ label: "L",
+ note: "n",
+ fallback: { kind: "page", url: PAGE_ARTICLE_URL, title: "T", archiveUrl: "https://web.archive.org/web/1/x" },
+ },
);
});
@@ -145,7 +153,15 @@ test("a gone cited page: dry run names the nearest capture; the run imports it a
const id = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL);
assert.equal(item.outcome, "imported", item.detail);
assert.deepEqual(item.pointTo, { channel: "old-blog", id });
- assert.deepEqual(item.as, { kind: "post", channel: "old-blog", id, date: "2015-06", quote: "Update: the fourth loaf rose.", label: "The post" });
+ assert.deepEqual(item.as, {
+ kind: "post",
+ channel: "old-blog",
+ id,
+ date: "2015-06",
+ quote: "Update: the fourth loaf rose.",
+ label: "The post",
+ fallback: { kind: "page", url: PAGE_ARTICLE_URL },
+ });
assert.deepEqual((await readAllPosts(dir)).map((p) => p.id), [id]);
// Again: the channel holds the page — nothing fetched.
@@ -227,3 +243,8 @@ test("a cited page record whose original is gone: held when its capture is store
await wb.close();
}
});
+
+test("find-copy's `as` and Import this capture write the same citation (one builder, the page as its fallback)", async () => {
+ const { pageCitationAsPost: shared } = await import("../lib/citations/pageAsPost");
+ assert.equal(pageCitationAsPost, shared);
+});
diff --git a/common/publish/findCopyPages.ts b/common/publish/findCopyPages.ts
@@ -38,6 +38,7 @@ import { nearestAcrossSources } from "../lib/archives/index";
import path from "node:path";
import type { Paths } from "../lib/paths";
import type { Citation, PageCitation, PostCitation } from "../lib/citations/schema";
+import { pageCitationAsPost } from "../lib/citations/pageAsPost";
import type { Post } from "../lib/posts";
import { readAllPosts, readPostAvailability } from "../lib/posts-server";
import { listChannelConfigs } from "../controller/channels";
@@ -162,12 +163,10 @@ export function recordForQuote(records: ReadonlyArray<Pick<Post, "id" | "text">>
return records[0]!.id;
}
-// A page citation as a post citation of the record: its words and editorial
-// fields kept; the record carries the URL, the title and the Wayback copy.
-export function pageCitationAsPost(c: PageCitation, pointTo: { channel: string; id: string }): PostCitation {
- const { kind: _kind, url: _url, title: _title, archiveUrl: _archive, ...common } = c;
- return { kind: "post", channel: pointTo.channel, id: pointTo.id, ...common };
-}
+// A page citation as a post citation of the record: the one builder, shared
+// with umtool's Import this capture (lib/citations/pageAsPost.ts) — its words
+// and editorial fields kept, the page kept as its `fallback`.
+export { pageCitationAsPost };
// ─── find-copy, page mode ───
diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts
@@ -140,6 +140,12 @@ export type PostCaptureRecord = {
sensitive?: boolean;
// The screenshot, when one was taken.
shot?: CapturedFile;
+ // A page record's shot (release 37 S4, platform "webpage"): of the item's
+ // own element ("item") or of the whole page ("page" — a whole-page record,
+ // or an item the render could not locate); `trimmed` when the page ran
+ // past the height cap.
+ shotScope?: "item" | "page";
+ trimmed?: boolean;
mediaState: CaptureMediaState;
media: CapturedFile[];
// The X Article the post links to, when one was captured or tried.
diff --git a/common/social/waybackPageCapture.test.ts b/common/social/waybackPageCapture.test.ts
@@ -0,0 +1,287 @@
+// Page records' shots and images (release 37 S4), over the fake Wayback on
+// loopback (common/testing/web/fakeWayback.mjs): the records come from the
+// fake's own captures through the real extractors; the run's logic is driven
+// with a stub page, and the crop with a real headless Chromium (skipped,
+// saying why, on a host with no browser). No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/waybackPageCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ IMAGE_PNG,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ PAGE_SPLIT_POSTS,
+ PAGE_SPLIT_TS,
+ PAGE_SPLIT_URL,
+ startFakeWayback,
+} from "../testing/web/fakeWayback.mjs";
+import type { Post } from "../lib/posts";
+import { recordsOfCapture } from "../controller/importPage";
+import type { StoredCapture } from "../lib/waybackPages/store-server";
+import { WaybackClient } from "../lib/waybackClient";
+import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback";
+import {
+ captureWaybackPageRecords,
+ openWaybackRenderPage,
+ PAGE_MEDIA_MAX,
+ pageItemTarget,
+ pageRecordImages,
+ shootPageRecord,
+ type WaybackPageCaptureDeps,
+} from "./waybackPageCapture";
+import { readPostCapture, SHOT_FILENAME } from "./postCapture";
+import type { PageLike } from "./playwrightRuntime";
+import { pngSize } from "../publish/citedPostCaptures";
+
+async function recordsOf(fetchUrl: string, ts: string, original: string): Promise<Post[]> {
+ const res = await fetch(fetchUrl);
+ const body = Buffer.from(await res.arrayBuffer());
+ const capture = { originalUrl: original, captureTs: ts, mimetype: "text/html", contentType: "text/html; charset=utf-8" } as StoredCapture;
+ return recordsOfCapture("pages", capture, body).posts;
+}
+
+async function fixtureRecords(base: string) {
+ const article = await recordsOf(`${base}/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL);
+ const split = await recordsOf(`${base}/web/${PAGE_SPLIT_TS}id_/${PAGE_SPLIT_URL}`, PAGE_SPLIT_TS, PAGE_SPLIT_URL);
+ return { article: article[0]!, split };
+}
+
+test("what a record is shot as: the whole page, or its item's element", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const { article, split } = await fixtureRecords(wb.base);
+ assert.deepEqual(pageItemTarget(article), { scope: "page" });
+ assert.deepEqual(split.map((p) => p.id).sort(), PAGE_SPLIT_POSTS.map((id) => `tumblr-${id}`).sort());
+ const t = pageItemTarget(split[0]!);
+ assert.equal(t.scope, "item");
+ if (t.scope === "item") {
+ assert.equal(t.kind, "tumblr-post");
+ assert.ok(t.selectors.includes(`#post-${t.nativeId}`));
+ assert.ok(new RegExp(t.permalink!).test(`/post/${t.nativeId}/on-crusts`));
+ assert.ok(!new RegExp(t.permalink!).test(`/post/${t.nativeId}9`));
+ }
+ const tweet = { id: "tweet-123456789012345678", page: { ...article.page!, kind: "tweet" as const } };
+ const tt = pageItemTarget(tweet);
+ assert.equal(tt.scope, "item");
+ if (tt.scope === "item") assert.ok(tt.selectors[0]!.includes("123456789012345678"));
+ assert.deepEqual(pageItemTarget({ id: "yt-about-UCx-2014", page: { ...article.page!, kind: "yt-about" } }), { scope: "page" });
+ assert.deepEqual(pageItemTarget({ id: "x" }), { scope: "page" });
+ } finally {
+ await wb.close();
+ }
+});
+
+test("a record's images go by their own Wayback URLs (im_), deduplicated and capped", () => {
+ const page = { originalUrl: "https://a.example/", captureTs: "20140101000000", waybackUrl: "w", rawUrl: "r", kind: "generic" as const, extractor: "generic", extractorVersion: 1 };
+ const many = Array.from({ length: PAGE_MEDIA_MAX + 5 }, (_, n) => ({ kind: "image" as const, url: `https://a.example/${n}.jpg` }));
+ const imgs = pageRecordImages({
+ page,
+ media: [
+ { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" },
+ { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" },
+ { kind: "link-card", url: "https://a.example/card" },
+ ...many,
+ ],
+ });
+ assert.equal(imgs[0]!.url, "https://web.archive.org/web/20130101000000im_/https://a.example/x.png");
+ assert.equal(imgs[1]!.url, "https://web.archive.org/web/20140101000000im_/https://a.example/0.jpg");
+ assert.equal(imgs.length, PAGE_MEDIA_MAX);
+ assert.equal(waybackFileUrl("2014", "https://web.archive.org/web/2012/https://b.example/i.gif"), "https://web.archive.org/web/2012im_/https://b.example/i.gif");
+ assert.equal(waybackFrameUrl({ captureTs: "2014", originalUrl: "https://b.example/" }), "https://web.archive.org/web/2014if_/https://b.example/");
+});
+
+// A page that answers without a browser: the item is found at a fixed box.
+function stubPage(o: { itemFound?: boolean; status?: number } = {}) {
+ const visited: string[] = [];
+ const clips: unknown[] = [];
+ const page: PageLike = {
+ goto: async (url: string) => {
+ visited.push(url);
+ return { status: () => o.status ?? 200 };
+ },
+ waitForSelector: async () => ({}),
+ waitForTimeout: async () => {},
+ evaluate: async (fn: string) => {
+ if (fn.includes("data-archilyzer-capture")) return o.itemFound === false ? null : { x: 190, y: 160, width: 534, height: 140 };
+ if (fn.includes("scrollHeight")) return { width: 1280, height: 9500 };
+ return 0;
+ },
+ on: () => {},
+ screenshot: async (opts) => {
+ clips.push(opts?.clip);
+ return new Uint8Array(IMAGE_PNG);
+ },
+ };
+ return { page, visited, clips };
+}
+
+async function setup(stub = stubPage()) {
+ const wb = await startFakeWayback();
+ const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 });
+ const outDir = await mkdtemp(path.join(os.tmpdir(), "page-capture-"));
+ let paced = 0;
+ let opened = 0;
+ const deps: WaybackPageCaptureDeps = {
+ openPage: async () => {
+ opened++;
+ return { page: stub.page, close: async () => {} };
+ },
+ paced: (fn, signal) => {
+ paced++;
+ return client.paced(fn, { signal });
+ },
+ fetchFile: (url, signal) => client.getArchivedFile(url, { signal }),
+ now: () => new Date("2026-10-20T12:00:00.000Z"),
+ };
+ const { article, split } = await fixtureRecords(wb.base);
+ const records = new Map([article, ...split].map((p) => [p.id, p]));
+ return {
+ wb,
+ deps,
+ outDir,
+ records,
+ article,
+ split,
+ stub,
+ counts: () => ({ paced, opened }),
+ close: async () => {
+ await wb.close();
+ await rm(outDir, { recursive: true, force: true });
+ },
+ };
+}
+
+test("a run: the whole page shot to the cap, the item clipped to its box, images saved; nothing said about the original", async () => {
+ const s = await setup();
+ try {
+ const crumb = s.split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[1]}`)!;
+ assert.ok(crumb.media?.length, "the second post carries its image");
+ const logs: string[] = [];
+ const res = await captureWaybackPageRecords(
+ { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal, onLog: (l) => logs.push(l) },
+ s.deps,
+ );
+ assert.equal(res.stoppedEarly, undefined);
+ assert.deepEqual(res.outcomes.map((o) => o.state), ["captured", "captured"]);
+ assert.ok(res.outcomes.every((o) => o.availability === undefined), "a capture says nothing about the original");
+ // Each page load inside the client's chain, the frame (`if_`) URL.
+ assert.equal(s.counts().paced, 2);
+ assert.equal(s.counts().opened, 1);
+ assert.deepEqual(s.stub.visited, [waybackFrameUrl(s.article.page!), waybackFrameUrl(crumb.page!)]);
+ // The whole page: cut at 8000 px; the item: its own box.
+ assert.deepEqual(s.stub.clips[0], { x: 0, y: 0, width: 1280, height: 8000 });
+ assert.deepEqual(s.stub.clips[1], { x: 190, y: 160, width: 534, height: 140 });
+ const a = await readPostCapture(path.join(s.outDir, s.article.id));
+ assert.equal(a?.shotScope, "page");
+ assert.equal(a?.trimmed, true);
+ assert.equal(a?.url, waybackFrameUrl(s.article.page!));
+ const c = await readPostCapture(path.join(s.outDir, crumb.id));
+ assert.equal(c?.shotScope, "item");
+ assert.equal(c?.mediaState, "ok");
+ assert.equal(c?.media.length, 1);
+ assert.match(c!.media[0]!.url!, /\/web\/20120601000000im_\/http:\/\/24\.media\.tumblr\.com\//);
+ assert.deepEqual((await readdir(path.join(s.outDir, crumb.id))).sort(), ["capture.json", "media-1.png", SHOT_FILENAME]);
+ // The image went through the archive's own URL.
+ assert.ok(s.wb.requests.some((r) => r.path.includes("im_/http://24.media.tumblr.com/")));
+
+ // A second run skips both; force shoots again.
+ const again = await captureWaybackPageRecords(
+ { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal },
+ s.deps,
+ );
+ assert.equal(again.outcomes.length, 0);
+ assert.equal(s.counts().paced, 2);
+ } finally {
+ await s.close();
+ }
+});
+
+test("an item the render cannot find is shot as the page; a 429 stops the run", async () => {
+ const s = await setup(stubPage({ itemFound: false }));
+ try {
+ const ids = s.split.map((p) => p.id);
+ const logs: string[] = [];
+ const res = await captureWaybackPageRecords(
+ { ids: [ids[0]!], records: s.records, outDir: s.outDir, media: false, signal: new AbortController().signal, onLog: (l) => logs.push(l) },
+ s.deps,
+ );
+ assert.equal(res.outcomes[0]?.state, "captured");
+ assert.equal((await readPostCapture(path.join(s.outDir, ids[0]!)))?.shotScope, "page");
+ assert.ok(logs.some((l) => /was not found on the rendered page; shot the whole page/.test(l)));
+ } finally {
+ await s.close();
+ }
+ const busy = await setup(stubPage({ status: 429 }));
+ try {
+ const ids = busy.split.map((p) => p.id);
+ const res = await captureWaybackPageRecords(
+ { ids, records: busy.records, outDir: busy.outDir, signal: new AbortController().signal },
+ busy.deps,
+ );
+ assert.equal(res.outcomes.length, 1);
+ assert.equal(res.outcomes[0]?.state, "error");
+ assert.match(res.stoppedEarly ?? "", /answered 429; stopping/);
+ } finally {
+ await busy.close();
+ }
+});
+
+// ─── A real browser over the fake's captures ───
+
+test("a real headless Chromium: the whole page, and one post clipped to its box", async (t) => {
+ const wb = await startFakeWayback();
+ let opened;
+ try {
+ opened = await openWaybackRenderPage(wb.base);
+ } catch (e) {
+ await wb.close();
+ t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`);
+ return;
+ }
+ const dir = await mkdtemp(path.join(os.tmpdir(), "page-shot-"));
+ const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 });
+ const paced: WaybackPageCaptureDeps["paced"] = (fn, signal) => client.paced(fn, { signal });
+ const load = (u: string) => u.replace("https://web.archive.org", wb.base);
+ try {
+ const { article, split } = await fixtureRecords(wb.base);
+ const whole = await shootPageRecord(opened.page, {
+ url: load(waybackFrameUrl(article.page!)),
+ canonicalUrl: waybackFrameUrl(article.page!),
+ target: pageItemTarget(article),
+ dir: path.join(dir, "whole"),
+ signal: new AbortController().signal,
+ paced,
+ });
+ assert.equal(whole.state, "captured", whole.error);
+ assert.equal(whole.shotScope, "page");
+ const wsize = await pngSize(path.join(dir, "whole", SHOT_FILENAME));
+ assert.equal(wsize?.width, 1280);
+
+ const post = split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[0]}`)!;
+ const item = await shootPageRecord(opened.page, {
+ url: load(waybackFrameUrl(post.page!)),
+ canonicalUrl: waybackFrameUrl(post.page!),
+ target: pageItemTarget(post),
+ dir: path.join(dir, "item"),
+ signal: new AbortController().signal,
+ paced,
+ });
+ assert.equal(item.state, "captured", item.error);
+ assert.equal(item.shotScope, "item");
+ const isize = await pngSize(path.join(dir, "item", SHOT_FILENAME));
+ // The post box is 500 px + padding + border wide: clipped to it, not the page.
+ assert.ok(isize && isize.width > 500 && isize.width < 560, `width ${isize?.width}`);
+ assert.ok(isize!.height < 400, `height ${isize?.height}`);
+ // Nothing but the archive's origin was asked (the tumblr assets were refused).
+ assert.ok(!wb.requests.some((r) => r.path.includes("tumblr.com/iframe")));
+ } finally {
+ await opened.close();
+ await wb.close();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/waybackPageCapture.ts b/common/social/waybackPageCapture.ts
@@ -0,0 +1,578 @@
+// Capturing PAGE RECORDS (release 37 S4, platform "webpage"): a screenshot of
+// each record as the Wayback Machine replays its capture, and the images it
+// names, into `posts-media/<id>/` (postCapture.ts owns the layout and the
+// record) — what `capture-posts` does for a Wayback pages channel.
+//
+// THE RENDER is the capture's replay with the `if_` modifier (no toolbar:
+// lib/wayback.ts waybackFrameUrl) in a headless Chromium, one fresh context
+// with no profile and no cookies, JavaScript OFF (the archive rewrites a
+// capture's links and styles server-side; the capture's own scripts would only
+// ask the archive for more), and every request that is not to the archive
+// refused — a render never reaches the live web. Fonts, stylesheets and images
+// load from the archive; audio/video are refused.
+// - a WHOLE-PAGE record (lib/waybackPages/toPost.ts isWholePageRecord) is
+// shot full page, cut at PAGE_SHOT_MAX_HEIGHT CSS px (`trimmed`);
+// - a SPLIT record (a tweet, a Tumblr post, a forum post — one item of a
+// capture that holds several) is shot clipped to its own element, found by
+// the id the extractor used (`pageItemTarget`); an item the render cannot
+// find is shot as the whole page, `shotScope: "page"`, and the log says so.
+//
+// THE IMAGES in a record's `media` are saved through their own Wayback URLs
+// (`im_`, waybackFileUrl) — at most PAGE_MEDIA_MAX per record, each capped.
+//
+// POLITE: every contact is the process's Wayback client's — the page load runs
+// inside its chain and gap (`paced`), the images through `getArchivedFile` —
+// and the job runs on the `platform:archive.org` queue. A page load answered
+// 429/503 stops the run there, the rest left for a later run.
+//
+// A capture says nothing about whether the ORIGINAL is still up, so no outcome
+// carries an availability: the posts-availability sidecar of a page record is
+// the original's state (release 37 S5), never this render's.
+
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import type { Post } from "../lib/posts";
+import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback";
+import { WAYBACK_ORIGIN, waybackClient, waybackTestOrigin } from "../lib/waybackClient";
+import { isWholePageRecord } from "../lib/waybackPages/toPost";
+import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import {
+ captureWork,
+ describeCapturedFile,
+ postCaptureDir,
+ readPostCapture,
+ SHOT_FILENAME,
+ writePostCapture,
+ type CapturedFile,
+ type CaptureMediaState,
+ type PostCaptureRecord,
+ type PostCaptureState,
+} from "./postCapture";
+
+// A whole page is shot to this height (CSS px) and no further.
+export const PAGE_SHOT_MAX_HEIGHT = 8000;
+// The window the page renders in.
+export const PAGE_VIEWPORT = { width: 1280, height: 1600 };
+// The images one record's capture saves.
+export const PAGE_MEDIA_MAX = 20;
+// How long a replay may take to load.
+export const PAGE_LOAD_TIMEOUT_MS = 60_000;
+
+// ─── Which element is the record ───
+
+export type PageShotTarget =
+ | { scope: "page" }
+ | {
+ scope: "item";
+ kind: string;
+ // The item's own id as the page carries it (a status id, a Tumblr post
+ // id, a forum post id).
+ nativeId: string;
+ // CSS selectors that name the item directly, most specific first.
+ selectors: string[];
+ // A link whose href matches this (a regexp source, tested on the
+ // href's path) is the item's permalink; a link matching `anyPermalink`
+ // with another id is another item's.
+ permalink?: string;
+ anyPermalink?: string;
+ };
+
+const reEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+const cssString = (s: string) => JSON.stringify(s);
+
+// What to shoot for a record: the whole page, or the item's element. Derived
+// from the record's kind and id (the ids lane C's extractors make —
+// plans/FACTS.md "Release 37 lane C"), so no locator is stored.
+export function pageItemTarget(post: Pick<Post, "id" | "page">): PageShotTarget {
+ if (!post.page || isWholePageRecord(post)) return { scope: "page" };
+ const kind = post.page.kind;
+ if (kind === "tweet") {
+ const id = post.id.replace(/^tweet-/, "");
+ if (!/^\d+$/.test(id)) return { scope: "page" };
+ return {
+ scope: "item",
+ kind,
+ nativeId: id,
+ selectors: [
+ `div.tweet[data-tweet-id=${cssString(id)}]`,
+ `[data-tweet-id=${cssString(id)}]`,
+ `li[data-item-id=${cssString(id)}]`,
+ `[data-item-id=${cssString(id)}]`,
+ ],
+ permalink: `/status(?:es)?/${reEscape(id)}(?:[/?#]|$)`,
+ anyPermalink: `/status(?:es)?/\\d+(?:[/?#]|$)`,
+ };
+ }
+ if (kind === "tumblr-post") {
+ const id = post.id.replace(/^tumblr-/, "");
+ if (!/^\d+$/.test(id)) return { scope: "page" };
+ return {
+ scope: "item",
+ kind,
+ nativeId: id,
+ selectors: [`#post-${id}`, `#post_${id}`, `[data-post-id=${cssString(id)}]`],
+ permalink: `/post/${reEscape(id)}(?:[/?#]|$)`,
+ anyPermalink: `/post/\\d+(?:[/?#]|$)`,
+ };
+ }
+ if (kind === "forum-post") {
+ const id = post.id;
+ if (!/^\d+$/.test(id)) return { scope: "page" };
+ return {
+ scope: "item",
+ kind,
+ nativeId: id,
+ selectors: [`#js-post-${id}`, `article[data-content=${cssString(`post-${id}`)}]`, `#post-${id}`],
+ permalink: `/posts/${reEscape(id)}(?:[/?#]|$)`,
+ anyPermalink: `/posts/\\d+(?:[/?#]|$)`,
+ };
+ }
+ if (kind === "x-profile") {
+ return {
+ scope: "item",
+ kind,
+ nativeId: post.id,
+ selectors: [".ProfileHeaderCard", ".profile-card", ".profile-details", ".ProfileCanopy"],
+ };
+ }
+ // A yt-about record, or a kind this module does not know: the page.
+ return { scope: "page" };
+}
+
+// Marks the item's element (`data-archilyzer-capture`) and answers its box in
+// document coordinates, or null when the page holds no such item:
+// 1. the first selector that matches exactly one element;
+// 2. else the LARGEST element around a link to the item's permalink that
+// holds no link to another item's permalink (lane C's Tumblr rule).
+export const LOCATE_ITEM_SCRIPT = (t: Extract<PageShotTarget, { scope: "item" }>) => `(() => {
+ const selectors = ${JSON.stringify(t.selectors)};
+ const own = ${t.permalink ? `new RegExp(${JSON.stringify(t.permalink)})` : "null"};
+ const any = ${t.anyPermalink ? `new RegExp(${JSON.stringify(t.anyPermalink)})` : "null"};
+ for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture");
+ const pathOf = (a) => { try { return new URL(a.getAttribute("href"), location.href).pathname; } catch { return ""; } };
+ let found = null;
+ for (const sel of selectors) {
+ let hits = [];
+ try { hits = Array.from(document.querySelectorAll(sel)); } catch { hits = []; }
+ if (hits.length === 1) { found = hits[0]; break; }
+ if (hits.length > 1) { found = hits[0].closest(".tweet") || hits[0]; break; }
+ }
+ if (!found && own) {
+ const links = Array.from(document.querySelectorAll("a[href]"));
+ const mine = links.filter((a) => own.test(pathOf(a)));
+ const others = any ? links.filter((a) => any.test(pathOf(a)) && !own.test(pathOf(a))) : [];
+ let best = null;
+ for (const a of mine) {
+ let el = a.parentElement;
+ let top = null;
+ while (el && el !== document.body && el !== document.documentElement) {
+ if (others.some((o) => el.contains(o))) break;
+ top = el;
+ el = el.parentElement;
+ }
+ if (top && (!best || (top.contains(best)))) best = top;
+ }
+ found = best;
+ }
+ if (!found) return null;
+ found.setAttribute("data-archilyzer-capture", "");
+ const r = found.getBoundingClientRect();
+ return { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height };
+})()`;
+
+// The page's own size, for a whole-page shot.
+export const PAGE_SIZE_SCRIPT = `(() => {
+ const d = document.documentElement, b = document.body;
+ return {
+ width: Math.max(d ? d.scrollWidth : 0, b ? b.scrollWidth : 0, window.innerWidth),
+ height: Math.max(d ? d.scrollHeight : 0, b ? b.scrollHeight : 0, 1),
+ };
+})()`;
+
+// Let the images finish loading (each capped at 5 s), so a shot is not of
+// grey boxes.
+const IMAGES_LOADED_SCRIPT = `(() => {
+ const imgs = Array.from(document.images).filter((i) => !i.complete);
+ return Promise.all(imgs.map((i) => new Promise((r) => {
+ i.addEventListener("load", r, { once: true });
+ i.addEventListener("error", r, { once: true });
+ setTimeout(r, 5000);
+ }))).then(() => imgs.length);
+})()`;
+
+type Rect = { x: number; y: number; width: number; height: number };
+
+// ─── Deps ───
+
+export type WaybackPageCaptureDeps = {
+ // A page in a fresh browser context: opened on the first shot, closed at
+ // the end of the run.
+ openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>;
+ // Run a page load inside the Wayback client's chain and gap.
+ paced: <T>(fn: () => Promise<T>, signal: AbortSignal) => Promise<T>;
+ // One archived file (an image) through the Wayback client; null when the
+ // archive does not hold it.
+ fetchFile: (url: string, signal: AbortSignal) => Promise<{ body: Buffer; contentType: string | null } | null>;
+ // The URL to load for a web.archive.org URL (the e2e suite's fake origin).
+ loadUrl?: (url: string) => string;
+ now?: () => Date;
+ pageTimeoutMs?: number;
+};
+
+// A headless Chromium with a fresh context: no profile, no cookies, no
+// JavaScript, and nothing but `allowOrigin` reachable.
+export async function openWaybackRenderPage(
+ allowOrigin: string,
+): Promise<{ page: PageLike; close: () => Promise<void> }> {
+ const { chromium } = await importPlaywright();
+ const browser = await chromium.launch({ headless: true });
+ try {
+ const context = (await browser.newContext({
+ viewport: PAGE_VIEWPORT,
+ deviceScaleFactor: 1,
+ locale: "en-US",
+ colorScheme: "light",
+ javaScriptEnabled: false,
+ })) as unknown as {
+ newPage: () => Promise<PageLike>;
+ close: () => Promise<void>;
+ route: (
+ match: (url: URL) => boolean,
+ handler: (route: {
+ request: () => { url: () => string; resourceType: () => string };
+ abort: () => Promise<void>;
+ continue: () => Promise<void>;
+ }) => unknown,
+ ) => Promise<void>;
+ };
+ const origin = new URL(allowOrigin).origin;
+ await context.route(
+ () => true,
+ (route) => {
+ const req = route.request();
+ let ok = false;
+ try {
+ const u = new URL(req.url());
+ ok = u.origin === origin || u.protocol === "data:";
+ } catch {
+ ok = false;
+ }
+ const type = req.resourceType();
+ if (!ok || type === "media" || type === "websocket" || type === "eventsource") return route.abort();
+ return route.continue();
+ },
+ );
+ const page = await context.newPage();
+ return {
+ page,
+ close: async () => {
+ await context.close().catch(() => {});
+ await browser.close().catch(() => {});
+ },
+ };
+ } catch (err) {
+ await browser.close().catch(() => {});
+ throw err;
+ }
+}
+
+// The process's deps: the process's Wayback client (its chain, gap and
+// back-off), and the e2e suite's fake origin when E2E_WAYBACK_ORIGIN_FILE
+// names one (lib/waybackClient.ts waybackTestOrigin).
+export function liveWaybackPageCaptureDeps(): WaybackPageCaptureDeps {
+ const testOrigin = waybackTestOrigin();
+ const loadUrl = (u: string) => (testOrigin ? u.replace(/^https?:\/\/(?:web|wayback)\.archive\.org/, testOrigin) : u);
+ return {
+ openPage: () => openWaybackRenderPage(testOrigin ?? WAYBACK_ORIGIN),
+ paced: (fn, signal) => waybackClient.paced(fn, { signal }),
+ fetchFile: (url, signal) => waybackClient.getArchivedFile(url, { signal }),
+ loadUrl,
+ };
+}
+
+// ─── One record's shot ───
+
+export type PageShotResult = {
+ state: PostCaptureState;
+ shot?: CapturedFile;
+ shotScope?: "item" | "page";
+ trimmed?: boolean;
+ error?: string;
+ // The page load answered 429/503: the run stops.
+ rateLimited?: boolean;
+ note?: string;
+};
+
+function firstLine(err: unknown): string {
+ return ((err as Error)?.message ?? String(err)).split("\n")[0];
+}
+
+// Shoot one record: load `url` (inside `paced`), find the item (or take the
+// page), write shot.png into `dir`. `canonicalUrl` is what the record names.
+export async function shootPageRecord(
+ page: PageLike,
+ o: {
+ url: string;
+ canonicalUrl: string;
+ target: PageShotTarget;
+ dir: string;
+ signal: AbortSignal;
+ paced: WaybackPageCaptureDeps["paced"];
+ pageTimeoutMs?: number;
+ },
+): Promise<PageShotResult> {
+ let status: number | undefined;
+ try {
+ status = await o.paced(async () => {
+ const response = await page.goto(o.url, { waitUntil: "load", timeout: o.pageTimeoutMs ?? PAGE_LOAD_TIMEOUT_MS });
+ await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => 0);
+ return (response as { status?: () => number } | null)?.status?.();
+ }, o.signal);
+ } catch (err) {
+ if (o.signal.aborted) return { state: "error", error: "cancelled" };
+ return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` };
+ }
+ if (status === 429 || status === 503) {
+ return { state: "error", error: `the Wayback Machine answered ${status}`, rateLimited: true };
+ }
+ if (status !== undefined && status >= 400) {
+ return { state: "error", error: `the Wayback Machine answered HTTP ${status} for ${o.canonicalUrl}` };
+ }
+
+ let rect: Rect | null = null;
+ let scope: "item" | "page" = "page";
+ let note: string | undefined;
+ if (o.target.scope === "item") {
+ rect = (await page.evaluate(LOCATE_ITEM_SCRIPT(o.target)).catch(() => null)) as Rect | null;
+ if (rect && rect.width >= 1 && rect.height >= 1) scope = "item";
+ else {
+ rect = null;
+ note = `the ${o.target.kind} ${o.target.nativeId} was not found on the rendered page; shot the whole page`;
+ }
+ }
+ let trimmed = false;
+ if (!rect) {
+ const size = (await page.evaluate(PAGE_SIZE_SCRIPT).catch(() => null)) as { width: number; height: number } | null;
+ const width = Math.max(1, Math.min(size?.width ?? PAGE_VIEWPORT.width, PAGE_VIEWPORT.width * 2));
+ const height = Math.max(1, size?.height ?? PAGE_VIEWPORT.height);
+ trimmed = height > PAGE_SHOT_MAX_HEIGHT;
+ rect = { x: 0, y: 0, width, height: Math.min(height, PAGE_SHOT_MAX_HEIGHT) };
+ } else if (rect.height > PAGE_SHOT_MAX_HEIGHT) {
+ trimmed = true;
+ rect = { ...rect, height: PAGE_SHOT_MAX_HEIGHT };
+ }
+ let png: Uint8Array;
+ try {
+ png = await page.screenshot({
+ type: "png",
+ fullPage: true,
+ clip: {
+ x: Math.max(0, Math.floor(rect.x)),
+ y: Math.max(0, Math.floor(rect.y)),
+ width: Math.ceil(rect.width),
+ height: Math.ceil(rect.height),
+ },
+ });
+ } catch (err) {
+ return { state: "error", error: `The screenshot failed: ${firstLine(err)}` };
+ }
+ await mkdir(o.dir, { recursive: true });
+ await writeFile(path.join(o.dir, SHOT_FILENAME), png);
+ return {
+ state: "captured",
+ shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl),
+ shotScope: scope,
+ ...(trimmed ? { trimmed } : {}),
+ ...(note ? { note } : {}),
+ };
+}
+
+// ─── The images ───
+
+const EXT_BY_TYPE: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+ "image/svg+xml": "svg",
+};
+
+function imageExt(url: string, contentType: string | null): string {
+ const ct = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct];
+ let pathname = url;
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ /* the raw string */
+ }
+ const m = /\.([a-z0-9]{2,5})$/i.exec(pathname);
+ return m ? m[1].toLowerCase().replace("jpeg", "jpg") : "bin";
+}
+
+// The images a record's capture saves: its `media` of kind image, each by its
+// own Wayback URL at the record's capture time, deduplicated, at most
+// PAGE_MEDIA_MAX.
+export function pageRecordImages(post: Pick<Post, "media" | "page">): { url: string; source: string }[] {
+ const ts = post.page?.captureTs;
+ if (!ts) return [];
+ const out: { url: string; source: string }[] = [];
+ for (const m of post.media ?? []) {
+ if (m.kind !== "image" || !/^https?:\/\//.test(m.url)) continue;
+ const url = waybackFileUrl(ts, m.url);
+ if (out.some((x) => x.url === url)) continue;
+ out.push({ url, source: m.url });
+ if (out.length >= PAGE_MEDIA_MAX) break;
+ }
+ return out;
+}
+
+// ─── The run ───
+
+const STOP_AFTER_ERRORS = 3;
+
+export type PageCaptureInput = Pick<
+ PostCaptureInput,
+ "ids" | "outDir" | "shots" | "media" | "force" | "signal" | "drain" | "onLog"
+> & {
+ // The archived records, by id (capturePosts reads them).
+ records: ReadonlyMap<string, Post>;
+};
+
+export async function captureWaybackPageRecords(
+ input: PageCaptureInput,
+ deps: WaybackPageCaptureDeps,
+): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false };
+ const now = deps.now ?? (() => new Date());
+ const load = deps.loadUrl ?? ((u: string) => u);
+ const outcomes: PostCaptureOutcome[] = [];
+ const stopped = (why: string): PostCaptureResult => {
+ onLog?.(why);
+ return { outcomes, stoppedEarly: why };
+ };
+
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ let errorsInARow = 0;
+ try {
+ for (const [i, id] of input.ids.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.");
+ const post = input.records.get(id);
+ if (!post?.page) {
+ onLog?.(`${id}: not a page record (no capture facts) — skipped.`);
+ outcomes.push({ id, state: "error", files: 0, error: "not a page record" });
+ continue;
+ }
+ const dir = postCaptureDir(input.outDir, id);
+ const existing = await readPostCapture(dir);
+ const work = captureWork(existing, { ...wanted, articles: false });
+ if (!work.shot && !work.media) {
+ onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`);
+ continue;
+ }
+ onLog?.(`[${i + 1}/${input.ids.length}] ${id}`);
+ const frameUrl = waybackFrameUrl(post.page);
+
+ let state: PostCaptureState | undefined = work.shot ? undefined : existing?.state;
+ let shot = work.shot ? undefined : existing?.shot;
+ let shotScope = work.shot ? undefined : existing?.shotScope;
+ let trimmed = work.shot ? undefined : existing?.trimmed;
+ let error: string | undefined;
+ let stop: string | undefined;
+
+ if (work.shot) {
+ browser ??= await deps.openPage();
+ const res = await shootPageRecord(browser.page, {
+ url: load(frameUrl),
+ canonicalUrl: frameUrl,
+ target: pageItemTarget(post),
+ dir,
+ signal,
+ paced: deps.paced,
+ ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}),
+ });
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ state = res.state;
+ shot = res.shot;
+ shotScope = res.shotScope;
+ trimmed = res.trimmed;
+ error = res.error;
+ if (res.note) onLog?.(`${id}: ${res.note}.`);
+ if (res.rateLimited) stop = `${res.error}; stopping.`;
+ }
+
+ let mediaState: CaptureMediaState = work.media ? "skipped" : (existing?.mediaState ?? "skipped");
+ let media: CapturedFile[] = work.media ? [] : (existing?.media ?? []);
+ if (work.media && !stop && (state === undefined || state === "captured")) {
+ const images = pageRecordImages(post);
+ if (images.length === 0) {
+ mediaState = "none";
+ } else {
+ let failed = 0;
+ for (const [n, im] of images.entries()) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ let got;
+ try {
+ got = await deps.fetchFile(im.url, signal);
+ } catch (err) {
+ failed++;
+ onLog?.(`${id}: image ${n + 1} failed: ${firstLine(err)}`);
+ if ((err as { rateLimited?: boolean }).rateLimited) {
+ stop = `${firstLine(err)}; stopping.`;
+ break;
+ }
+ continue;
+ }
+ if (!got) {
+ failed++;
+ onLog?.(`${id}: image ${n + 1} is not in the archive (or over the cap): ${im.source}`);
+ continue;
+ }
+ const name = `media-${n + 1}.${imageExt(im.source, got.contentType)}`;
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, name), got.body);
+ media.push(await describeCapturedFile(dir, name, im.url));
+ }
+ mediaState = failed > 0 ? "error" : "ok";
+ if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`;
+ }
+ state ??= existing?.state ?? "captured";
+ }
+
+ const finalState: PostCaptureState = state ?? "error";
+ const record: PostCaptureRecord = {
+ version: 1,
+ id,
+ url: frameUrl,
+ capturedAt: now().toISOString(),
+ state: finalState,
+ ...(shot ? { shot } : {}),
+ ...(shot && shotScope ? { shotScope } : {}),
+ ...(shot && trimmed ? { trimmed } : {}),
+ mediaState,
+ media,
+ ...(error ? { error } : {}),
+ };
+ await writePostCapture(dir, record);
+ outcomes.push({ id, state: finalState, files: (shot ? 1 : 0) + media.length, ...(error ? { error } : {}) });
+ onLog?.(
+ `${id}: ${finalState}` +
+ (work.shot && shot ? `, shot (${shotScope ?? "page"}${trimmed ? ", trimmed" : ""})` : "") +
+ (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" ? ", no images" : "") +
+ (error ? ` — ${error}` : ""),
+ );
+ if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`);
+ errorsInARow = finalState === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} records in a row failed; stopping rather than going through the rest.`);
+ }
+ }
+ return { outcomes };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -23,7 +23,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. |
| `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. |
| `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. |
-| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane E): Save Page Now — `POST /save` (the fake keys `FAKE_SPN_ACCESS`/`FAKE_SPN_SECRET` in `Authorization: LOW …`, else 401; `spn.busyTimes` 429s; `spn.refuseUrls` answered `error:blocked-url`) and `GET /save/status/<job>` (`spn.pendingPolls` pending, then success at `SPN_CAPTURE_TS`, or `spn.failUrls` → `error:not-found`); a saved page is then served raw like a page capture (`spn.pages[url]` or a synthetic page); `wb.spnForms`, `wb.spnCaptures`. |
+| `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. Release 32 R8: a format's stream at `/web/<ts>id_/<googlevideo url>` (yt-dlp's `2id_` form) serves bytes (206 for a Range) for an id in `streams` (default `videos`), else 404 — `videos` without `streams` is the live "page captured, no video" case; `streamBusyTimes` 429s. Release 37 (lane A): PAGE captures served raw (`PAGE_CAPTURES`, `opts.pageCaptures`) — an article with nav/header/footer around an `<article>` (two captures), a body still carrying the toolbar insert and rewritten hrefs, a 3 MB page, a `text/plain` and an `image/jpeg` capture, and one that redirects off the archive; a timestamp with no capture of a known page answers 302 to the nearest; CDX honours `closest=`. Release 37 (lane E): Save Page Now — `POST /save` (the fake keys `FAKE_SPN_ACCESS`/`FAKE_SPN_SECRET` in `Authorization: LOW …`, else 401; `spn.busyTimes` 429s; `spn.refuseUrls` answered `error:blocked-url`) and `GET /save/status/<job>` (`spn.pendingPolls` pending, then success at `SPN_CAPTURE_TS`, or `spn.failUrls` → `error:not-found`); a saved page is then served raw like a page capture (`spn.pages[url]` or a synthetic page); `wb.spnForms`, `wb.spnCaptures`. Release 37 (lane D): a Tumblr-themed index holding two posts (`PAGE_SPLIT_URL`/`PAGE_SPLIT_TS`, `PAGE_CAPTURES_SPLIT`, served by default) for the split-record shot, and `/web/<ts>im_/<image url>` answering a small PNG (`IMAGE_PNG`). |
| `web/fakeRangedCdn.mjs` | Release 32 R7: a fake media CDN shaped like Odysee's `player.odycdn.com` — ranged GETs with a Referer answer 206 (`Content-Range`), unranged 429, no Referer 403, past the end 416; `refuseAfterBytes` (429/403 once a budget is served), `corruptOnce`, `ignoreRange`, `requireUnlock` + `unlockBytes` (served only after `cdn.unlock()` — a player's page open — lapsing after a budget; `cdn.lock()` takes it back). Release 32 R10: `dropAfterBytes` / `drops` / `dropGapBytes` cut the connection mid-body (undici's body read throws) or before any response (the fetch throws `fetch failed`); a cut request is `dropped: true`. `cdn.fetch` sends `https://player.odycdn.com` to it. |
| `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. |
| `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. |
diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts
@@ -25,6 +25,12 @@ export const PAGE_IMAGE_URL: string;
export const PAGE_IMAGE_TS: string;
export const PAGE_JUMP_URL: string;
export const PAGE_JUMP_TS: string;
+// Release 37 (lane D): a capture of several items, and archived images (`im_`).
+export const PAGE_SPLIT_URL: string;
+export const PAGE_SPLIT_TS: string;
+export const PAGE_SPLIT_POSTS: string[];
+export const PAGE_CAPTURES_SPLIT: FakePageCapture[];
+export const IMAGE_PNG: Buffer;
export const VIDEOS: string[];
// Release 37 (lane E): Save Page Now.
@@ -50,7 +56,7 @@ export function startFakeWayback(opts?: {
busyTimes?: number;
downTimes?: number;
streamBusyTimes?: number;
- // (release 37) the page captures served raw (default PAGE_CAPTURES).
+ // (release 37) the page captures served raw (default PAGE_CAPTURES + PAGE_CAPTURES_SPLIT).
pageCaptures?: FakePageCapture[];
// (release 37 lane F) originals CDX and their captures answer 403 for.
excluded?: string[];
diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs
@@ -152,6 +152,50 @@ export const PAGE_CAPTURES = [
{ original: PAGE_JUMP_URL, timestamp: PAGE_JUMP_TS, statuscode: "302", mimetype: "text/html", offsite: "https://elsewhere.example/landing" },
];
+// ─── Release 37 (lane D): a capture that holds several items, and images ───
+//
+// SPLIT a Tumblr-themed blog index (two posts, each a fixed-width box, the
+// second with an image) — split by the Tumblr extractor into
+// `tumblr-<id>` records, each shot clipped to its own post
+// Served as every page capture is (`id_` / `if_` / framed). `/web/<ts>im_/<url>`
+// of an image URL (.jpg/.jpeg/.png/.gif/.webp) answers a small PNG — the page
+// records' images through their own Wayback URLs; any other `im_` is a 404.
+export const PAGE_SPLIT_URL = "https://crumb-notes.tumblr.com/";
+export const PAGE_SPLIT_TS = "20120601000000";
+export const PAGE_SPLIT_POSTS = ["30000000002", "30000000001"];
+// A 2×2 PNG (opaque grey).
+export const IMAGE_PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAADklEQVR4nGNoAAMGCAUAKg4GARWeQtcAAAAASUVORK5CYII=",
+ "base64",
+);
+
+const splitHtml = `<!DOCTYPE html>
+<html><head><title>Crumb Notes</title>
+<style>body{margin:0;font:16px sans-serif;background:#eee}#content{width:900px;margin:0 auto;padding:20px}
+.post{width:500px;background:#fff;border:1px solid #999;margin:0 0 40px 0;padding:16px}#header{height:120px;background:#ccd}</style>
+</head><body>
+<iframe id="tumblr_controls" src="http://assets.tumblr.com/iframe.html?lang=en_US&name=crumb-notes" width="1" height="1"></iframe>
+<div id="header"><h1><a href="/">Crumb Notes</a></h1></div>
+<div id="content">
+ <div class="post">
+ <h3><a href="http://crumb-notes.tumblr.com/post/30000000002/on-crusts">On crusts</a></h3>
+ <p>A crust should crackle when it cools on the rack.</p>
+ <div class="date"><a href="http://crumb-notes.tumblr.com/post/30000000002/on-crusts">June 1st, 2012</a></div>
+ </div>
+ <div class="post">
+ <h3><a href="http://crumb-notes.tumblr.com/post/30000000001/on-crumbs">On crumbs</a></h3>
+ <p>An open crumb comes from a wet dough and a long, slow rise.</p>
+ <img src="http://24.media.tumblr.com/tumblr_crumb_500.jpg" alt="a sliced loaf" width="300" height="200" />
+ <div class="date"><a href="http://crumb-notes.tumblr.com/post/30000000001/on-crumbs">May 20th, 2012</a></div>
+ </div>
+ <div id="navigation"><a href="/page/2">Older →</a></div>
+</div>
+</body></html>`;
+
+export const PAGE_CAPTURES_SPLIT = [
+ { original: PAGE_SPLIT_URL, timestamp: PAGE_SPLIT_TS, statuscode: "200", mimetype: "text/html", body: () => splitHtml },
+];
+
// The answer to `/web/<ts>[mod]/<original>` for a page capture, or null when
// the original is not one of PAGE_CAPTURES.
function pageCaptureAnswer(pageCaptures, ts, mod, original, send, res) {
@@ -264,7 +308,7 @@ export const VIDEOS = ["gone-video-05"];
export async function startFakeWayback(opts = {}) {
// Release 37: the page captures are served beside whatever `captures` says,
// and listed by CDX unless a test names its own `captures`.
- const pageCaptures = opts.pageCaptures ?? PAGE_CAPTURES;
+ const pageCaptures = opts.pageCaptures ?? [...PAGE_CAPTURES, ...PAGE_CAPTURES_SPLIT];
const captures = opts.captures ?? [...CAPTURES, ...pageCaptures];
const videos = opts.videos ?? VIDEOS;
const streams = opts.streams ?? videos;
@@ -361,6 +405,12 @@ export async function startFakeWayback(opts = {}) {
const to = Math.min(body.length - 1, range[2] ? Number(range[2]) : body.length - 1);
return send(206, "video/mp4", body.subarray(from, to + 1), { "content-range": `bytes ${from}-${to}/${body.length}` });
}
+ // Release 37 (lane D): an archived image by its own Wayback URL.
+ const im = /^\/web\/(\d{1,14})im_\/(.+)$/.exec(u.pathname + u.search);
+ if (im) {
+ if (/\.(?:jpe?g|png|gif|webp)$/i.test(im[2])) return send(200, "image/png", IMAGE_PNG);
+ return send(404, "text/html", "<p>Wayback Machine has not archived that URL.</p>");
+ }
// Release 37: a page capture (PAGE_CAPTURES), raw.
const pc = /^\/web\/(\d{1,14})(id_|if_)?\/(.+)$/.exec(u.pathname + u.search);
if (pc && pageCaptureAnswer(pageCaptures, pc[1], pc[2] ?? "", pc[3], send, res)) return;
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -8,6 +8,8 @@
- **find-copy finds a copy of a gone page a report cites.** `pnpm ops find-copy` with `"pages": true` checks each page a report cites at its own site; for one that is gone it imports the Wayback capture nearest the citation's date into the Wayback pages channel you name (`"channel"`) or the one whose targets cover it, and its result names the record the citation should now cite. A page still up is left (save it now instead), and a cited page record whose original is gone keeps its stored capture. `"dryRun": true` asks the same questions and imports nothing. The report is not rewritten.
- **Ask for a small change to a report video in words, on the local model, and apply it with one click.** The Build tab's Look panel and the clip editor's side column have an **Ask** box: "make the joins 0.15 s with less smear", "louder", "no QR", "keep 2 s after the last word", "cut the first 3 seconds of r014". The assistant answers with proposed edits shown as a list of changes ("join 0.22 s → 0.15 s", "smear 0.5 → 0.3"), each with **Apply**, plus **Apply all** and **Dismiss**; nothing changes until you apply, and each edit is checked again and written by the same code the Look panel and the clip editor use. A change it cannot make, or a value out of range, is listed with the reason instead. It runs on the local model by default (in every preset but `api`), so it works without Claude Code; it waits while a transcription has the GPU, and the box says so. A note on the whole project can be asked too: the reply comes back on the note with an **Apply all**. **Preview join** renders the first few joins in the saved look and plays them in place. It can change the look, the blur slide, the room at the clips' edges, a clip's edges or room, and a set of declared deck and effect settings (`pnpm ops report-draft` task `video-assist`; the MCP's `generate`).
- **The Look panel has the blur slide's and the room's numbers.** With the join set to blur slide, **Travel**, **Smear** and **Grain** are fields; with room at the clips' edges on, **Tail up to, s** (how far the sound may run past a cut) and **Silence gap, s**. Video revisions of an article can now change the look, the slide and the room too.
+- **Wayback page records can be shot, and every surface says what the capture is.** On a Wayback pages channel's page, **Capture** shoots each record as the Wayback Machine replays it (no toolbar, in a headless browser that reaches nothing but the archive): a whole page down to 8000 px, a tweet, Tumblr post or forum post clipped to itself, and the images it shows saved from the archive — one job at archive.org's pace (`pnpm ops capture-posts` does the same). Each record's row opens to its shot and to what the capture is: its kind, **Original (may be gone)** and **Wayback Machine copy, <date>**, "3 captures of this page; text changed on …" with each capture linked, a capture that holds no content, and a note when a site's reader failed and the generic one read the page. The same lines are on a report site's moment page and citation card for a cited page record, in the archive's post viewer, in umtool's evidence rail and in the MCP's `get_post`. `search_transcripts` takes `platforms: ["webpage"]`, and `corpus.json` marks a Wayback pages channel (`kind: "wayback-pages"`). Needs a restart of the editor and umtool.
+- **Import this capture: a cited page's Wayback copy becomes the evidence.** In umtool's evidence rail, a page citation whose archived copy is a Wayback capture has **Import this capture**: pick a Wayback pages channel or name a new one, Import (the editor's import-page), then **Cite this** on the record it made. A store article's citation becomes a citation of that record — its quote checked against the record's text first — with the page kept as its fallback, written as a hand iteration; a site report shows the replacement citation to put in its draft. Preparing the report's media then copies the record's shot like any post's. Needs a restart of umtool.
- **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor.
- **Scan a Wayback pages channel, then choose what to import.** A channel whose config names `wayback.targets` (a page, a prefix, a host or a domain, with optional dates) has a **Captures** tab: **Scan now** lists what the Wayback Machine holds of them — one row per distinct version of each page, with when it was first and last seen — without fetching a single page, at archive.org's pace, at most 50,000 rows a run; **Continue scan** picks up where a run stopped, and a later scan marks what is **new**. Filter by year, path and text, then **Import selected** or **Import all in range** (asked to confirm above 50): one import job per capture, one at a time. Rows already imported are marked and skipped. The same over HTTP: `pnpm ops wayback-scan --json '{"slug":"<slug>"}'` and `pnpm ops wayback-import --json '{"slug":"<slug>","year":"2014"}'` (both take `dryRun`); offline, `pnpm archilyzer wayback scan <slug>`. With `wayback.auto: true` the download lane imports the captures later scans add, at the same pace; it is off unless a channel turns it on.
- **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model.
diff --git a/editor/app/api/channels/[slug]/posts-media/[id]/[name]/route.ts b/editor/app/api/channels/[slug]/posts-media/[id]/[name]/route.ts
@@ -0,0 +1,42 @@
+import path from "node:path";
+import { readFile, stat } from "node:fs/promises";
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { POSTS_MEDIA_DIRNAME } from "yt-dlp-transcript-common/social/postCapture";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/channels/<slug>/posts-media/<id>/<name> — one file of a post's
+// capture (release 37 S4: a page record's shot.png and images, shown on the
+// Wayback pages panel). `channels/<slug>/posts-media/<id>/` is on the corpus
+// disk (the media tier never moves it); images only, read-only.
+
+const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
+const IMAGE_TYPES: Record<string, string> = {
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ gif: "image/gif",
+ webp: "image/webp",
+ avif: "image/avif",
+};
+
+export async function GET(_request: Request, { params }: { params: Promise<{ slug: string; id: string; name: string }> }) {
+ const { slug, id, name } = await params;
+ if (![slug, id, name].every((s) => SAFE_SEGMENT.test(s)) || name.startsWith(".")) {
+ return NextResponse.json({ error: "Invalid path" }, { status: 400 });
+ }
+ const type = IMAGE_TYPES[name.split(".").pop()!.toLowerCase()];
+ if (!type) return NextResponse.json({ error: "Not an image" }, { status: 404 });
+ const dir = path.resolve(getPaths().channelsDir, slug, POSTS_MEDIA_DIRNAME, id);
+ const file = path.resolve(dir, name);
+ if (!file.startsWith(dir + path.sep)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ try {
+ if (!(await stat(file)).isFile()) throw new Error("not a file");
+ return new NextResponse(new Uint8Array(await readFile(file)), {
+ headers: { "content-type": type, "cache-control": "no-store" },
+ });
+ } catch {
+ return NextResponse.json({ error: "Not found" }, { status: 404 });
+ }
+}
diff --git a/editor/app/channels/[slug]/components/WaybackPageRecords.tsx b/editor/app/channels/[slug]/components/WaybackPageRecords.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+// A Wayback pages channel's records (release 37 S4): each with what its
+// capture is (PageCaptureFacts — the kind, "Original (may be gone)", "Wayback
+// Machine copy, <date>", the version list, no content, the fallback note), its
+// shot when one is captured, and Capture: the screenshot of the record as the
+// archive replays it, and its images (`capture-posts`, on archive.org's pace).
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import { PageCaptureFacts } from "yt-dlp-transcript-common/components/PageCaptureFacts";
+import type { PageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view";
+import { cancelJobAction } from "../../../jobs/actions";
+import { capturePostsAction } from "../socialActions";
+
+export type WaybackPageRecordRow = {
+ id: string;
+ title: string;
+ view: PageCaptureView;
+ // The captured shot, when there is one (the editor's posts-media route).
+ shot?: string;
+ // How many images the capture saved.
+ images?: number;
+};
+
+export function WaybackPageRecords({ slug, rows }: { slug: string; rows: WaybackPageRecordRow[] }) {
+ const [picked, setPicked] = useState<string[]>([]);
+ const [force, setForce] = useState(false);
+ const toggle = (id: string) => setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));
+ const ids = picked.length > 0 ? picked : rows.filter((r) => !r.shot).map((r) => r.id);
+ return (
+ <div className="mt-3 flex flex-col gap-3">
+ <table aria-label="page records" className="w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-muted-foreground">
+ <th className="w-6 py-1 pr-2 font-medium">
+ <span className="sr-only">Pick</span>
+ </th>
+ <th className="py-1 pr-2 font-medium">Page</th>
+ <th className="py-1 pr-2 font-medium">Kind</th>
+ <th className="py-1 font-medium">Captured</th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((r) => (
+ <tr key={r.id} data-page-record={r.id} className="border-t border-border align-top">
+ <td className="py-1 pr-2">
+ <input
+ type="checkbox"
+ aria-label={`pick ${r.id}`}
+ checked={picked.includes(r.id)}
+ onChange={() => toggle(r.id)}
+ />
+ </td>
+ <td className="py-1 pr-2">
+ <a href={r.view.originalUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2">
+ {r.title}
+ </a>
+ {r.view.noContent && <span className="ml-2 text-xs text-muted-foreground">(no content)</span>}
+ <details>
+ <summary className="cursor-pointer text-xs text-muted-foreground">
+ {r.view.versions ? `${r.view.versions.count} captures` : "The capture"}
+ {r.shot ? " · shot" : ""}
+ </summary>
+ <div className="mt-2 flex flex-col gap-2">
+ <PageCaptureFacts view={r.view} />
+ {r.shot && (
+ // eslint-disable-next-line @next/next/no-img-element -- a capture of unknown size, served from the corpus
+ <img
+ data-page-shot={r.id}
+ src={r.shot}
+ alt={`Screenshot of the ${r.view.links.copy.label}`}
+ className="max-h-[32rem] max-w-full self-start rounded border border-border object-contain object-top"
+ />
+ )}
+ {r.images ? <span className="text-xs text-muted-foreground">{r.images} image(s) saved</span> : null}
+ </div>
+ </details>
+ </td>
+ <td className="py-1 pr-2 font-mono text-xs">{r.view.kind}</td>
+ <td className="py-1">
+ <a href={r.view.waybackUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2">
+ {r.view.captureDate}
+ </a>
+ {r.view.source && <span className="ml-2 text-xs text-muted-foreground">{r.view.links.copy.label.replace(/ copy, .*$/, "")}</span>}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ <div aria-label="capture page records" className="flex flex-col gap-2">
+ <label className="flex items-center gap-2 text-xs">
+ <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} />
+ Capture again where already captured
+ </label>
+ <StreamActionLog
+ trigger={() => capturePostsAction(slug, force && picked.length === 0 ? rows.map((r) => r.id) : ids, undefined, true, true, force)}
+ cancelAction={cancelJobAction}
+ buttonLabel={
+ picked.length > 0
+ ? `Capture ${picked.length} picked`
+ : `Capture ${ids.length} without a shot`
+ }
+ runningLabel="Capturing…"
+ label={`Capture page records of ${slug}`}
+ disabled={ids.length === 0 && !(force && rows.length > 0)}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx b/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx
@@ -10,23 +10,14 @@ import Link from "next/link";
import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
import { cancelJobAction } from "../../../jobs/actions";
import { archiveLookupAction, importPageAction, reextractPagesAction } from "../waybackPagesActions";
+import { WaybackPageRecords, type WaybackPageRecordRow } from "./WaybackPageRecords";
import { ConnectArchiveSession } from "../../../settings/components/ArchiveSessionSection";
import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
import type { ArchiveLookup } from "yt-dlp-transcript-common/lib/archives/index";
import { archiveSourceLabel, isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos";
-export type WaybackPagesRecordRow = {
- id: string;
- title: string;
- kind: string;
- captureTs: string;
- captureDate: string;
- originalUrl: string;
- waybackUrl: string;
- // Release 37 lane F: the archive source, when it is not the Wayback Machine.
- source?: string;
- noContent?: boolean;
-};
+// A record's row: its capture's view and its shot (WaybackPageRecords.tsx).
+export type WaybackPagesRecordRow = WaybackPageRecordRow;
export type WaybackPagesState = {
recordCount: number;
@@ -87,36 +78,7 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac
))}
</ul>
)}
- {state.recent.length > 0 && (
- <table aria-label="page records" className="mt-3 w-full text-sm">
- <thead>
- <tr className="text-left text-xs text-muted-foreground">
- <th className="py-1 pr-2 font-medium">Page</th>
- <th className="py-1 pr-2 font-medium">Kind</th>
- <th className="py-1 font-medium">Captured</th>
- </tr>
- </thead>
- <tbody>
- {state.recent.map((r) => (
- <tr key={r.id} data-page-record={r.id} className="border-t border-border align-top">
- <td className="py-1 pr-2">
- <a href={r.originalUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2">
- {r.title}
- </a>
- {r.noContent && <span className="ml-2 text-xs text-muted-foreground">(no content)</span>}
- </td>
- <td className="py-1 pr-2 font-mono text-xs">{r.kind}</td>
- <td className="py-1">
- <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2">
- {r.captureDate}
- </a>
- {r.source && <span className="ml-2 text-xs text-muted-foreground">{archiveSourceLabel(r.source)}</span>}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- )}
+ {state.recent.length > 0 && <WaybackPageRecords slug={slug} rows={state.recent} />}
</section>
<section aria-label="import a capture" className="flex flex-col gap-2 rounded-lg border border-border p-3">
<h4 className="text-sm font-semibold">Import a capture</h4>
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -10,7 +10,7 @@ import {
readPostAvailability,
readPostFetchState,
} from "yt-dlp-transcript-common/lib/posts-server";
-import { isPostGone } from "yt-dlp-transcript-common/lib/posts";
+import { isPostGone, type Post, type PostAvailabilityMap } from "yt-dlp-transcript-common/lib/posts";
import { resolveSocialFetcher } from "yt-dlp-transcript-common/social/fetchers";
import { describeOlderBackfill } from "yt-dlp-transcript-common/social/olderBackfill";
import "yt-dlp-transcript-common/social/blueskyFetcher";
@@ -35,7 +35,8 @@ import { savePageNowAvailability } from "yt-dlp-transcript-common/controller/sav
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server";
import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession";
-import { waybackCaptureDate } from "yt-dlp-transcript-common/lib/wayback";
+import { pageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view";
+import { postsMediaDir, readPostCapture } from "yt-dlp-transcript-common/social/postCapture";
import { listPostFetchersFor } from "./socialActions";
import { NoReportYet } from "./components/NoReportYet";
import type { ChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
@@ -216,21 +217,7 @@ export default async function ChannelDetailPage({
const pageRecords = isWaybackPagesChannel(config) ? (await readAllPosts(channelRoot)).filter((p) => p.page) : [];
const wayback = isWaybackPagesChannel(config)
? {
- captureCount: await countStoredCaptures(channelRoot),
- recent: pageRecords
- .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))
- .slice(0, 20)
- .map((p) => ({
- id: p.id,
- title: p.page!.title || p.text.split("\n")[0].slice(0, 120) || p.url,
- kind: p.page!.kind,
- captureTs: p.page!.captureTs,
- captureDate: waybackCaptureDate(p.page!.captureTs),
- originalUrl: p.page!.originalUrl,
- waybackUrl: p.page!.archiveUrl ?? p.page!.waybackUrl,
- ...(p.page!.source ? { source: p.page!.source } : {}),
- ...(p.page!.noContent ? { noContent: true } : {}),
- })),
+ ...(await waybackPagesRows(channelRoot, slug, pageRecords, postAvailability)),
// Release 37 lane F: archive.today's check, passed once in Connect.
archiveSession: await readArchiveSessionStatus(paths),
}
@@ -979,3 +966,34 @@ export default async function ChannelDetailPage({
</div>
);
}
+
+// A Wayback pages channel's newest records (release 37 S1/S4): each with its
+// capture's view (the version list read off every record of the channel) and
+// its shot when captured.
+async function waybackPagesRows(
+ channelRoot: string,
+ slug: string,
+ all: Post[],
+ availability: PostAvailabilityMap,
+) {
+ const recent = [...all]
+ .sort((a, b) => b.page!.captureTs.padEnd(14, "0").localeCompare(a.page!.captureTs.padEnd(14, "0")))
+ .slice(0, 20);
+ const mediaDir = postsMediaDir(channelRoot);
+ return {
+ captureCount: await countStoredCaptures(channelRoot),
+ recent: await Promise.all(
+ recent.map(async (p) => {
+ const capture = await readPostCapture(path.join(mediaDir, p.id)).catch(() => null);
+ const base = `/api/channels/${encodeURIComponent(slug)}/posts-media/${encodeURIComponent(p.id)}`;
+ return {
+ id: p.id,
+ title: p.page!.title || p.text.split("\n")[0].slice(0, 120) || p.url,
+ view: pageCaptureView(p, all, { originalGone: isPostGone(availability[p.id]?.availability) })!,
+ ...(capture?.shot ? { shot: `${base}/${capture.shot.name}?v=${capture.shot.sha256.slice(0, 8)}` } : {}),
+ ...(capture?.media.length ? { images: capture.media.length } : {}),
+ };
+ }),
+ ),
+ };
+}
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -22,6 +22,7 @@ import {
import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config";
import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts";
+import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
import {
emptyAccountOlderProblem,
fetchPosts,
@@ -306,18 +307,23 @@ export async function capturePostsAction(
if (!isSocialChannel(config)) {
return { ok: false, error: `${slug} is not a social channel.` };
}
- await registerBuiltinSocialFetchers();
- const problem = capturePostsProblem(
- resolveSocialFetcher(config.postFetcher, config.url),
- );
- if (problem) return { ok: false, error: problem };
+ // A Wayback pages channel has no fetcher: its records are rendered from
+ // their captures, on archive.org's queue (release 37 S4).
+ const pages = isWaybackPagesChannel(config);
+ if (!pages) {
+ await registerBuiltinSocialFetchers();
+ const problem = capturePostsProblem(
+ resolveSocialFetcher(config.postFetcher, config.url),
+ );
+ if (problem) return { ok: false, error: problem };
+ }
const stray = strayCaptureIds(
wanted,
await readSeenPostIds(path.join(paths.channelsDir, slug)),
);
if (stray) return { ok: false, error: strayIdsRefusal(slug, stray) };
- const key = resolveQueueKey(downloadQueueKey(config), queueKey);
+ const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey);
return runManagedFunction({
kind: "capture-posts",
queueKey: key,
diff --git a/editor/e2e/wayback-pages-capture.spec.ts b/editor/e2e/wayback-pages-capture.spec.ts
@@ -0,0 +1,123 @@
+// Page records' shots (release 37 S4), end to end over the fake Wayback
+// Machine (common/testing/web/fakeWayback.mjs), named to the test server
+// through E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). The real web.archive.org is
+// never contacted.
+//
+// A Wayback pages channel holds an article captured twice and a Tumblr-themed
+// index split into two post records. The channel page shows each record's
+// capture — "Original (may be gone)", "Wayback Machine copy, <date>", the
+// version list — and Capture shoots every record without a shot in a headless
+// Chromium (the whole page; each post clipped to its own box) and saves the
+// post's image through its `im_` URL; the shots show on the page.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { readFile, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ startFakeWayback,
+ PAGE_ARTICLE_LATER_TS,
+ PAGE_ARTICLE_TS,
+ PAGE_ARTICLE_URL,
+ PAGE_SPLIT_POSTS,
+ PAGE_SPLIT_TS,
+ PAGE_SPLIT_URL,
+} from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs";
+import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types";
+import { baseUrl } from "./baseUrl";
+import { generateReport, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { waybackOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "capture-pages";
+
+async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> {
+ let last = { status: "", tail: [] as string[] };
+ await expect
+ .poll(
+ async () => {
+ const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=60`, { headers: AUTH });
+ const body = (await res.json()) as { job: { status: string }; tail?: string[] };
+ last = { status: body.job.status, tail: body.tail ?? [] };
+ return last.status;
+ },
+ { timeout: 90_000, intervals: [1_000] },
+ )
+ .toMatch(/^(done|failed|cancelled)$/);
+ return last;
+}
+
+async function ops(request: APIRequestContext, action: string, data: Record<string, unknown>) {
+ const res = await request.post(`${baseUrl}/api/ops/${action}`, { headers: AUTH, data });
+ const body = (await res.json()) as { ok?: boolean; jobId?: string; error?: string; slug?: string };
+ expect(res.status(), body.error).toBe(200);
+ return body;
+}
+
+test("a Wayback pages channel's records: their captures shown, then shot from the archive's replay", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+ await generateReport(page, "new");
+
+ const wb = await startFakeWayback();
+ const originFile = waybackOriginFile(resolvePath(testPaths().transcriptsDir));
+ await writeFile(originFile, wb.base);
+ try {
+ await ops(request, "create-channel", {
+ slug: SLUG,
+ fields: { name: "Capture pages", handling: "transcribe", url: "https://web.archive.org/web/*/blog.example/*" },
+ });
+ for (const url of [
+ `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`,
+ `https://web.archive.org/web/${PAGE_ARTICLE_LATER_TS}/${PAGE_ARTICLE_URL}`,
+ `https://web.archive.org/web/${PAGE_SPLIT_TS}/${PAGE_SPLIT_URL}`,
+ ]) {
+ const job = await waitForJob(request, (await ops(request, "import-page", { slug: SLUG, url })).jobId!);
+ expect(job.status, job.tail.join("\n")).toBe("done");
+ }
+
+ await page.goto(`/channels/${SLUG}`);
+ const pages = page.getByRole("region", { name: "Wayback pages" });
+ await expect(pages.getByLabel("pages held")).toHaveText("4 records from 3 captures");
+ const later = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL);
+ const row = page.locator(`[data-page-record="${later}"]`);
+ await row.locator("summary").click();
+ await expect(row.getByRole("link", { name: "Original (may be gone)" })).toHaveAttribute("href", PAGE_ARTICLE_URL);
+ await expect(row.getByRole("link", { name: "Wayback Machine copy, 2015-06-11" })).toHaveAttribute(
+ "href",
+ `https://web.archive.org/web/${PAGE_ARTICLE_LATER_TS}/${PAGE_ARTICLE_URL}`,
+ );
+ await expect(row.locator("[data-page-versions]")).toContainText("2 captures of this page; text changed on 2015-06-11.");
+
+ // Capture every record without a shot: one job on archive.org's queue.
+ await page.getByRole("button", { name: "Capture 4 without a shot" }).click();
+ await expect(page.getByRole("log", { name: `Capture page records of ${SLUG} output` })).toContainText("Done: 4 captured, 0 failed", {
+ timeout: 120_000,
+ });
+ const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+ const capture = async (id: string) =>
+ JSON.parse(await readFile(path.join(channelRoot, "posts-media", id, "capture.json"), "utf8")) as {
+ state: string;
+ shotScope?: string;
+ mediaState: string;
+ media: unknown[];
+ };
+ expect(await capture(later)).toMatchObject({ state: "captured", shotScope: "page" });
+ const crumbs = await capture(`tumblr-${PAGE_SPLIT_POSTS[1]}`);
+ expect(crumbs).toMatchObject({ state: "captured", shotScope: "item", mediaState: "ok" });
+ expect(crumbs.media).toHaveLength(1);
+ expect(wb.requests.some((r) => r.path.startsWith(`/web/${PAGE_SPLIT_TS}if_/`))).toBe(true);
+ expect(wb.requests.some((r) => r.path.includes("im_/http://24.media.tumblr.com/"))).toBe(true);
+
+ await page.reload();
+ const shotRow = page.locator(`[data-page-record="tumblr-${PAGE_SPLIT_POSTS[1]}"]`);
+ await shotRow.locator("summary").click();
+ const img = shotRow.locator(`[data-page-shot]`);
+ await expect(img).toBeVisible();
+ await expect.poll(() => img.evaluate((i: HTMLImageElement) => i.naturalWidth)).toBeGreaterThan(400);
+ await expect(page.getByRole("button", { name: "Capture 0 without a shot" })).toBeDisabled();
+ } finally {
+ await rm(originFile, { force: true });
+ await wb.close();
+ }
+});
diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts
@@ -12,6 +12,12 @@ import {
type PromptRequest,
} from "./promptRequest";
+// A page record (platform "webpage": a Wayback Machine capture, release 37
+// S4) is cited by BOTH its links, as get_post prints them.
+export const PAGE_RECORD_CITE_RULE =
+ "A web-page post (platform `webpage`, a Wayback Machine capture) is cited with both of its links: " +
+ "`[page by <author>, <capture date>](<original url>) ([Wayback Machine copy](<wayback url>))` — the original may be gone; the copy is the evidence.";
+
// ─── The orchestration text a sweep / ask runs on ───
//
// The server stays the single source of truth for the sweep discipline —
@@ -151,7 +157,7 @@ function batchStep(req: PromptRequest, ctx: PlanContext, reportPath: string): st
`to that video's moment_base (full link = \`<moment_base><seconds>\`; no ` +
`moment_base → link the \`source:\` URL instead). A POST finding has no ` +
`timestamp — cite it as **\`[post by <author>, <date>](<source url>)\`**, ` +
- `never with \`@ mm:ss\`. ${CLAIM_QUOTES_RULE} ${VERBATIM_QUOTES_RULE} ${WHOLE_SENTENCE_QUOTE_RULE} ` +
+ `never with \`@ mm:ss\`. ${PAGE_RECORD_CITE_RULE} ${CLAIM_QUOTES_RULE} ${VERBATIM_QUOTES_RULE} ${WHOLE_SENTENCE_QUOTE_RULE} ` +
`Then discard the fragment. Batches are ` +
`independent, so you may dispatch several subagents in parallel.\n` +
` - **Fallback:** with no Task tool, do the batch inline — call ` +
@@ -587,7 +593,7 @@ export function buildSweepInstructions(
`url>)\` link** (append the cited integer seconds to that video's ` +
`\`moment_base\` from the tool output); **cite every post finding as ` +
`\`[post by <author>, <date>](<source url>)\`** — posts have no timeline, ` +
- `so they never take a \`@ mm:ss\`.`;
+ `so they never take a \`@ mm:ss\`. ${PAGE_RECORD_CITE_RULE}`;
const notes =
ctx.notes && ctx.notes.length > 0
diff --git a/mcp/src/search.test.ts b/mcp/src/search.test.ts
@@ -1800,3 +1800,67 @@ test("server: a salvage transcript is marked partial by get_transcript and get_v
assert.match(windowed, /PARTIAL TRANSCRIPT — made from a damaged recording/);
await client.close();
});
+
+// ─── Release 37 S4: page records ───
+
+const PAGE_POST: Post = {
+ id: "20140305120000-0123456789ab",
+ slug: "chan-b/20140305120000-0123456789ab",
+ channelSlug: "chan-b",
+ author: "blog.example",
+ createdAt: "2014-03-04T18:30:00.000Z",
+ uploadDate: "20140304",
+ text: "A zephyrpost of a page, captured.",
+ url: "https://blog.example/a.html",
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ page: {
+ originalUrl: "https://blog.example/a.html",
+ captureTs: "20140305120000",
+ waybackUrl: "https://web.archive.org/web/20140305120000/https://blog.example/a.html",
+ rawUrl: "https://web.archive.org/web/20140305120000id_/https://blog.example/a.html",
+ kind: "generic",
+ title: "A Page About Zephyrs",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+};
+
+class PageSource extends StubSource {
+ async postsManifest(ch: ChannelRef): Promise<ChannelPostsManifest | null> {
+ const m = await super.postsManifest(ch);
+ return m ? { ...m, slugToPage: { ...m.slugToPage, [PAGE_POST.id]: 0 } } : null;
+ }
+ async postsPage(ch: ChannelRef, page: number): Promise<Post[]> {
+ const posts = await super.postsPage(ch, page);
+ return posts.length ? [...posts, PAGE_POST] : posts;
+ }
+}
+
+test("server: get_post prints a page record's capture — the original and the Wayback copy", async () => {
+ const client = await connectClient(new PageSource());
+ const out = firstText(await client.callTool({ name: "get_post", arguments: { post_id: PAGE_POST.id } }));
+ assert.match(out, /- page: Web page \(kind generic\), captured 2014-03-05 \(timestamp 20140305120000\)/);
+ assert.match(out, /- page title: A Page About Zephyrs/);
+ assert.match(out, /- original: https:\/\/blog\.example\/a\.html — Original \(may be gone\)/);
+ assert.match(out, /- wayback: https:\/\/web\.archive\.org\/web\/20140305120000\/https:\/\/blog\.example\/a\.html — Wayback Machine copy, 2014-03-05/);
+ await client.close();
+});
+
+test("search: platforms keeps only post hits on those platforms; a page record's hit has its page's title", async () => {
+ const src = new PageSource();
+ const all = await searchTranscripts(src, { query: "zephyrpost", contentTypes: ["post"] });
+ assert.ok(all.hits.length >= 2, "the stub's post and the page record");
+ const pages = await searchTranscripts(src, { query: "zephyrpost", contentTypes: ["post"], postPlatforms: ["webpage"] });
+ assert.deepEqual(pages.hits.map((h) => h.videoId), [PAGE_POST.id]);
+ assert.equal(pages.hits[0]!.title, "A Page About Zephyrs");
+ const client = await connectClient(src);
+ const out = firstText(
+ await client.callTool({ name: "search_transcripts", arguments: { query: "zephyrpost", content_types: ["post"], platforms: ["webpage"] } }),
+ );
+ assert.match(out, /A Page About Zephyrs/);
+ assert.doesNotMatch(out, /a zephyrpost mentioning something/);
+ await client.close();
+});
diff --git a/mcp/src/search.ts b/mcp/src/search.ts
@@ -488,6 +488,9 @@ export async function searchTranscripts(
aliases?: SearchAlias[];
// Which corpora to search. Defaults to both video transcripts and posts.
contentTypes?: ContentType[];
+ // The post platforms a POST hit may be on (release 37 S4: "webpage" for
+ // Wayback page records). Absent = every platform. Videos are not narrowed.
+ postPlatforms?: string[];
// The share-link filter set (availability state / upload-date range /
// media type / audience). When selective, it also drives filter-first page
// planning, so a narrow question reads a fraction of the corpus.
@@ -781,6 +784,7 @@ export async function searchTranscripts(
postPagesScanned++;
for (const post of posts) {
if (onlyIds && !onlyIds.has(post.id)) continue;
+ if (opts.postPlatforms && !opts.postPlatforms.includes(post.platform)) continue;
if (!match(post.text)) continue;
if (isExcluded("", [{ text: post.text }])) continue;
all.push({
@@ -793,7 +797,8 @@ export async function searchTranscripts(
platform: post.platform,
// A post has no title; its body stands in so a worklist row is
// still readable without pulling snippets.
- title: truncate(post.text, 120),
+ // A page record has its page's title.
+ title: post.page?.title ? truncate(post.page.title, 120) : truncate(post.text, 120),
uploadDate: post.uploadDate,
webpageUrl: post.url,
matches: 1,
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -1,3 +1,4 @@
+import { pageCaptureView, PAGE_NO_CONTENT_LINE } from "yt-dlp-transcript-common/lib/waybackPages/view";
import {
Server,
type Prompt,
@@ -420,9 +421,11 @@ export const TOOLS: Tool[] = [
name: "search_transcripts",
description:
"Search the archive for a term or phrase. The corpus holds video " +
- "transcripts AND social posts (X/Twitter, Bluesky, forum threads) from the same " +
+ "transcripts AND social posts (X/Twitter, Bluesky, forum threads, and web pages " +
+ "captured by the Wayback Machine — platform 'webpage') from the same " +
"commentators; by default BOTH are searched and returned in one result " +
- "set — use content_types to narrow. A post hit carries no timestamps " +
+ "set — use content_types to narrow, and platforms to keep only posts on " +
+ "some platforms (platforms:['webpage'] + content_types:['post'] = page captures only). A post hit carries no timestamps " +
"(cite it as a bare source, never with @ mm:ss). Returns matching " +
"videos with timestamped snippets. Substring match by default; set regex " +
"to true for a case-insensitive regular expression. Scope is optional and " +
@@ -503,6 +506,15 @@ export const TOOLS: Tool[] = [
"(archived social posts). Defaults to BOTH. Posts have no " +
"timeline, so their hits carry no timestamps.",
},
+ platforms: {
+ type: "array",
+ items: { type: "string", enum: ["twitter", "bluesky", "xenforo", "webpage"] },
+ description:
+ "Keep only POST hits on these platforms: 'twitter', 'bluesky', " +
+ "'xenforo' (forum threads), 'webpage' (Wayback Machine page " +
+ "captures). Absent = every platform. Video hits are not narrowed — " +
+ "add content_types:['post'] for posts only.",
+ },
link_style: {
type: "string",
enum: ["inline", "base"],
@@ -640,7 +652,9 @@ export const TOOLS: Tool[] = [
description:
"Fetch one archived social post by id: its full text, author, timestamp, " +
"outbound links and permalink. Posts have no timeline — cite them as a " +
- "bare source with no @ mm:ss.",
+ "bare source with no @ mm:ss. A web page captured by the Wayback Machine " +
+ "(platform 'webpage') also answers its capture: kind, date, the original " +
+ "URL and the Wayback copy.",
inputSchema: {
type: "object",
properties: {
@@ -1635,6 +1649,7 @@ async function handleSearch(
useAliases: args.use_aliases !== false,
maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined,
contentTypes: parseContentTypes(args.content_types),
+ ...(postPlatformsArg(args.platforms) ? { postPlatforms: postPlatformsArg(args.platforms) } : {}),
});
const aliasNote = describeFiredAliases(result.firedAliases);
@@ -1684,6 +1699,8 @@ async function handleSearch(
`- post_id: ${h.videoId} | channel: ${h.channelName}` +
(h.siteTitle ? ` | site: ${h.siteTitle}` : "") +
` | posted: ${formatDate(h.uploadDate)} | platform: ${h.platform ?? "post"}` +
+ // A page record (a Wayback capture): its page's title.
+ (h.platform === "webpage" && h.title ? `\n- page: ${h.title}` : "") +
(includeSnippets && h.webpageUrl ? `\n- source: ${h.webpageUrl}` : "");
const body = h.snippets.map((sn) => ` - ${sn.text}`).join("\n");
return body ? `${head}\n${body}` : head;
@@ -2207,6 +2224,14 @@ async function handleGetTranscripts(
return text(`${blocks.join("\n\n---\n\n")}${footer}`);
}
+// search_transcripts' `platforms`: the post platforms named, or undefined.
+const POST_PLATFORM_ARGS = new Set(["twitter", "bluesky", "xenforo", "webpage"]);
+function postPlatformsArg(raw: unknown): string[] | undefined {
+ if (!Array.isArray(raw)) return undefined;
+ const out = raw.filter((p): p is string => typeof p === "string" && POST_PLATFORM_ARGS.has(p));
+ return out.length ? out : undefined;
+}
+
// Render one post as markdown. No timestamps anywhere — a post has no timeline,
// and emitting a 0:00 would invite a bogus `@ mm:ss` citation.
function postToMarkdown(post: Post, heading = true, archive: string | null = null): string {
@@ -2247,6 +2272,18 @@ function postToMarkdown(post: Post, heading = true, archive: string | null = nul
);
}
}
+ // A page record (a Wayback Machine capture, release 37 S4): what the
+ // capture is and its two links — cite the original AND the Wayback copy.
+ if (post.page) {
+ const v = pageCaptureView(post)!;
+ lines.push(`- page: ${v.kindLabel} (kind ${v.kind}), captured ${v.captureDate} (timestamp ${v.captureTs})`);
+ if (v.title) lines.push(`- page title: ${v.title}`);
+ lines.push(`- original: ${v.links.original.url} — ${v.links.original.label}`);
+ lines.push(`- wayback: ${v.links.copy.url} — ${v.links.copy.label}`);
+ if (v.firstSeenDate) lines.push(`- first seen: in a capture of ${v.firstSeenDate}`);
+ if (v.noContent) lines.push(`- ${PAGE_NO_CONTENT_LINE}`);
+ if (v.fallbackNote) lines.push(`- note: ${v.fallbackNote}`);
+ }
if (post.media?.length) {
lines.push(`- media: ${post.media.length} item(s), linked not archived:`);
for (const m of post.media.slice(0, 20)) {
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -11379,3 +11379,44 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
`joinPreviewTimeline`: 4 consecutive clips, each the last 3 s of its cut (the last clip its first 3 s), cards out,
windows untouched; refused for a deck, a montage, hard cuts. umtool `/api/report/join-preview` (a `join preview
<project>` job on lib/jobs.ts).
+
+## Release 37 lane D: page records shot, shown and cited (verified 2026-10-20, branch `r37/cite`)
+
+- **The shot** (`social/waybackPageCapture.ts`): `capture-posts` on a Wayback pages channel never resolves a
+ fetcher — `capturePosts` branches on `isWaybackPagesChannel` (and `capturePostsAction` skips the fetcher check and
+ queues on `WAYBACK_PAGES_QUEUE` = `platform:archive.org`). Each record's replay `waybackFrameUrl` (`/web/<ts>if_/…`,
+ lib/wayback.ts) loads in a fresh headless Chromium context: JavaScript OFF, every request not to the archive's
+ origin (or the e2e fake's, `waybackTestOrigin`) aborted, media/websocket refused. The load runs INSIDE the Wayback
+ client's chain and gap (`WaybackClient.paced` → `ArchiveOrgClient.paced`, new); a 429/503 page stops the run.
+ Whole-page record (`isWholePageRecord`) → full page clipped at `PAGE_SHOT_MAX_HEIGHT` 8000 CSS px (`trimmed`);
+ split record → `pageItemTarget` from kind + id (tweet `[data-tweet-id]`/`[data-item-id]`, tumblr `#post-<id>`/
+ `[data-post-id]`, forum `#js-post-<id>`, x-profile the header card), else the largest element around the item's
+ permalink holding no other item's; not found → the page, `shotScope: "page"`. `PostCaptureRecord` gained
+ `shotScope?` and `trimmed?`. Images: `media` of kind image, at most 20, each by `waybackFileUrl` (`im_`) through
+ `WaybackClient.getArchivedFile` (new: bounded 10 MB, in-archive redirects only, null for 404/410/over cap).
+ No outcome carries an availability (a capture says nothing about the original — S5's).
+- **How a capture is shown** (`lib/waybackPages/view.ts`, client-safe): `pageCaptureView(post, siblings)` →
+ `{kind, kindLabel, captureDate, links: {original, copy}, noContent?, fallbackNote?, firstSeenDate?, versions?}`.
+ `pageCopyLinks` is THE one place the two link labels are made (today `waybackCitationLinks`); with
+ `originalGone` (the record `isDeleted`/`availability: "deleted"`, or the sidecar's verdict where a surface reads
+ raw records: compose via `postGoneState`, the editor's rows and umtool's rail via `readPostAvailability`) the
+ original's label is lane E's `PAGE_ORIGINAL_GONE_LABEL`. Whole-page = id shape
+ `^\d{4,14}-[0-9a-f]{12}$` (`isWholePageId`; no hash in the client). Versions = whole-page records of the same
+ `originalUrl`; `changedOn` = capture dates whose text differs from the one before. `PageCaptureFacts`
+ (common/components) renders it on the moment page (`MomentPostView.page`), the post modal and the editor's
+ records table; compose's post `RecordView` for a page record carries `originalLabel` + `downloads: [copy]`, and
+ `CitationCard`'s post links now print them.
+- **The post citation's `fallback`** (`citations/schema.ts`, `pageFallbackSchema`, CITATIONS.md): `{kind: "page",
+ url, title?, archiveUrl?}` — the page citation a post citation replaced. ONE builder,
+ `lib/citations/pageAsPost.ts` `pageCitationAsPost(c, {channel, id})`, used by find-copy's page mode (its items'
+ `as`, re-exported from publish/findCopyPages.ts) and by `replacePageCitationWithRecord` (controller/handEdits.ts,
+ which also takes find-copy's `as` directly): page → post of the record, common fields kept, quote
+ checked like a hand-added post's (refused when it does not check), a hand iteration (amend-or-new, as
+ `addClaimByHand`). umtool `/api/articles/import-capture` (GET channels | GET ?job&slug | POST start | POST use) →
+ `lib/articles/importCapture.ts`; a site report (not `ARTICLES_KEY`) gets the replacement back, never written.
+- **MCP / corpus:** `get_post` prints a `page` block (kind, capture date + ts, title, original, wayback, first seen,
+ no content, fallback note); `search_transcripts` `platforms` (post platforms; videos not narrowed);
+ `corpus.json` channel `kind: "wayback-pages"` (`buildSiteCorpus` `channelKinds`, from compose-site); POST_SCHEME
+ `pageRecords`. Editor route `GET /api/channels/<slug>/posts-media/<id>/<name>` serves a capture's images.
+- **The fake:** `PAGE_SPLIT_URL`/`PAGE_SPLIT_TS` (a Tumblr-themed index, two fixed-width posts, one image) served by
+ default, and `/web/<ts>im_/<image url>` → a 2×2 PNG (`IMAGE_PNG`).
diff --git a/plans/release-37/archive-sources.md b/plans/release-37/archive-sources.md
@@ -87,8 +87,33 @@ One module and one registry entry; nothing else names a source.
## Gates
-(filled below with numbers)
+All through the session's locks, from the worktree root. Baseline (main b8458892 + this branch's first edits in
+flight): common 4764 tests (the 4 fails were this lane's own half-written env/settings docs, so 4762 pass / 2 skipped
+clean), editor 356/356, mcp 379/379, test:scripts 1317 (1313 pass / 4 skipped).
+
+GATES_PLACEHOLDER
## Rulings followed / decisions
-(filled below)
+- **The stored body is the copy AS SERVED** (archive.today's rewritten snapshot, bar and all); it is unwrapped each time
+ it is read, so a better unwrap is a `reextract-pages`, never a refetch. `getCapture` answers both (`body`, `page`).
+- **Records keep the id scheme** (`pageRecordId(captureTs, originalUrl)`): a Wayback capture and an archive.today copy
+ of one page at the same second would share a record; judged negligible, and the second is not stored again.
+- **`waybackUrl`/`rawUrl` hold the archive.today copy's URL** for such a record (the fields are required; an older
+ reader still links the copy) and `archiveUrl` + `source` say whose; `pageArchiveLink` is the one reader to use.
+- **A 429 from archive.today is never retried**: the run stops with a sentence and the process client rests 30 min
+ (settable). 502/503/504 are retried three times. A check page at any status is a check, not a rate limit.
+- **The browser fallback is one headless read on the archive profile** (the forum browser's profile code), only when
+ `archives.archiveTodayBrowser` is on and no e2e fake is active; it waits a check out and never clicks. A window opens
+ only on Connect.
+- **Nearest by time**, not by digits, for archive.today (the Wayback client's CDX re-sort by digit distance is A's and
+ untouched).
+- **archive.today's layout is as known**, unverified live (synthetic fixtures only): `#HEADER`/`#CONTENT`,
+ `/o/<id>/<url>` links, `old-src` images, Memento headers. If a live copy drops class names, site extractors will
+ not claim it and the generic one reads it; the raw copy is kept for a later re-extract.
+- **The panel's region label stays "Wayback pages"** (an e2e contract of lanes A and B); only the New channel form's
+ kind is renamed "Archived pages".
+- **find-copy's page mode (lane E)** asks `nearestAcrossSources` (Wayback, then archive.today; an exclusion passes
+ on) and imports the row's own copy URL; given an explicit Wayback client (its tests) it stays Wayback-only.
+- **`cdxPage` (lane B)** maps a 403 to `WaybackExcludedError` (still an `ArchiveOrgRequestError` 403).
+- **`archilyzer archive lookup`** was added beside the ops action so the orchestrator can look without an editor.
diff --git a/plans/release-37/cite.md b/plans/release-37/cite.md
@@ -0,0 +1,136 @@
+# Release 37 lane D — `r37/cite`: renders, citations, the moment page, the MCP (as shipped)
+
+The plan of record is [`wayback-pages.md`](wayback-pages.md) ("S4"). Lane A put page records in the posts store
+([`core.md`](core.md)), lane C read the sites ([`extractors.md`](extractors.md)), lane B chose captures. This lane makes
+a page record something a person can SEE and CITE: its capture shot from the archive's replay, the same lines about
+the capture on every surface that shows it, a report's bare `page` citation turned into a citation of the record
+with one button, and the MCP and `/corpus.json` naming it. Rulings followed: no model anywhere (shots, views, the
+import and the rewrite are deterministic code, each a button); every archive.org request through the Wayback
+client's chain and gap on the `platform:archive.org` queue; a render reaches nothing but the archive; synthetic
+fixtures only; commits end with the one Co-Authored-By trailer.
+
+## What
+
+1. **Shots** (`common/social/waybackPageCapture.ts`). `capture-posts` on a Wayback pages channel branches before any
+ fetcher (`capturePosts` → `captureChannelPageRecords`; `capturePostsAction` skips the fetcher check and queues on
+ `WAYBACK_PAGES_QUEUE`). Each record's replay with the `if_` modifier (`waybackFrameUrl`, no toolbar) loads in a
+ fresh headless Chromium context — JavaScript off, every request to anything but the archive's origin aborted
+ (media/websocket too) — INSIDE the Wayback client's chain and gap (`WaybackClient.paced` → new
+ `ArchiveOrgClient.paced`). A whole-page record is shot full page to 8000 CSS px (`trimmed` past it); a split record
+ (tweet, Tumblr post, forum post, X profile header) is clipped to its own element, located from its kind and id
+ (`pageItemTarget`: the extractor's own markup ids, else the largest element around its permalink holding no other
+ item's) — not found, the page (`shotScope: "page"`, logged). Its `media` images (≤ 20) are saved through their own
+ `im_` URLs (`waybackFileUrl`, new `WaybackClient.getArchivedFile`: 10 MB cap, in-archive redirects only). A 429/503
+ page stops the run; three failures in a row stop it. No outcome carries an availability (S5 owns the original's
+ state). `PostCaptureRecord` gained `shotScope?`, `trimmed?`.
+2. **How a capture is shown** (`common/lib/waybackPages/view.ts`, client-safe; `common/components/PageCaptureFacts.tsx`).
+ `pageCaptureView(post, siblings)`: kind label, capture date, `links` (`pageCopyLinks` — the ONE place "Original (may
+ be gone)" / "Wayback Machine copy, <date>" are made, so lane F's other archives are one line), the version list
+ (whole-page records of the same original; "N captures of this page; text changed on …"), "This capture holds no
+ content.", the extractor-fallback sentence, an item's first-seen date. On: the report site's moment page
+ (`MomentPostView.page`; compose's post `RecordView` for a page record carries the page title, `originalLabel` and
+ `downloads: [copy]`) and citation card (`PostLinks` prints `originalLabel`/`downloads`), the corpus viewer's post
+ modal, the editor's Wayback pages panel, umtool's evidence rail, `get_post`.
+3. **The editor's records** (`WaybackPageRecords.tsx` in `WaybackPagesPanel`): each row opens to its capture and its
+ shot (new `GET /api/channels/<slug>/posts-media/<id>/<name>`, images only); **Capture** shoots the picked records,
+ or every record without a shot (`capturePostsAction`), with "capture again" for force.
+4. **Import this capture** (umtool). A `page` citation whose `archiveUrl` is a Wayback capture gets the button in the
+ evidence rail (`ImportCapture.tsx`): pick a Wayback pages channel or name a new one (scoped
+ `web.archive.org/web/*/<host>/*` through the editor's `create-channel`), Import (`import-page`, the job followed),
+ **Cite this** on a record it made. A store article: `replacePageCitationWithRecord` (common
+ `controller/handEdits.ts`) — the citation becomes `{kind: "post", channel, id, …common, fallback: {kind: "page", url,
+ title?, archiveUrl?}}`, its quote checked against the record first (refused when it does not check), written as a
+ hand iteration (amend-or-new, as `addClaimByHand`). A site report is built from its draft, which umtool never
+ writes: the replacement citation is shown for the draft. Route `/api/articles/import-capture` (GET channels, GET
+ `?job&slug`, POST `start`, POST `use`), lib `umtool/lib/articles/importCapture.ts`. `reports-prepare` copies the
+ record's shot like any post capture (`copyCitedPostCaptures`, unchanged — `posts-media/<id>/shot.png`).
+5. **The citation schema:** `postCitationSchema.fallback` (`pageFallbackSchema`, additive, optional);
+ `PAGE_FALLBACK_FIELD_DOCS`; CITATIONS.md regenerated.
+6. **MCP:** `get_post` prints a page record's capture (kind, capture date and timestamp, title, original, wayback,
+ first seen, no content, fallback note); `search_transcripts` takes `platforms` (post platforms; video hits not
+ narrowed), and a page record's hit is titled by its page; `PAGE_RECORD_CITE_RULE` in `instructions.ts` (cite the
+ original AND the Wayback copy). **`/corpus.json`:** a Wayback pages channel carries `kind: "wayback-pages"`
+ (`buildSiteCorpus` `channelKinds`, from compose-site); `POST_SCHEME.pageRecords` documents `page`.
+7. **The fake** (`fakeWayback.mjs`, a separate block): a Tumblr-themed index capture of two fixed-width posts
+ (`PAGE_SPLIT_*`, served by default) and `/web/<ts>im_/<image>` answering a PNG (`IMAGE_PNG`).
+
+## Interfaces
+
+- `social/waybackPageCapture.ts`: `captureWaybackPageRecords(input, deps)`, `shootPageRecord`, `pageItemTarget`,
+ `pageRecordImages`, `openWaybackRenderPage(allowOrigin)`, `liveWaybackPageCaptureDeps()`, `PAGE_SHOT_MAX_HEIGHT`,
+ `PAGE_MEDIA_MAX`; `CapturePostsOptions.pageDeps?` (tests).
+- `lib/wayback.ts`: `waybackFrameUrl`, `waybackFileUrl`. `WaybackClient.paced`, `WaybackClient.getArchivedFile`,
+ `WAYBACK_FILE_MAX_BYTES`; `ArchiveOrgClient.paced`.
+- `lib/waybackPages/view.ts`: `pageCaptureView`, `pageCopyLinks`, `pageVersions`, `pageVersionsLine`,
+ `pageCaptureLine`, `pageKindLabel`, `pageFallbackNote`, `isWholePageId`, `PAGE_NO_CONTENT_LINE`; component
+ `PageCaptureFacts`.
+- `citations/schema.ts`: `pageFallbackSchema`, `PageFallback`, `PAGE_FALLBACK_FIELD_DOCS`.
+- `controller/handEdits.ts`: `replacePageCitationWithRecord(id, {cite, channel, id, base?})`.
+- `lib/corpus.ts`: `CorpusChannel.kind?`, `buildSiteCorpus(…, {channelKinds})`. MCP `searchTranscripts({postPlatforms})`.
+
+## Commits
+
+| sha | what |
+|---|---|
+| `9acf73ec` | page records' shots and images (capture-posts on a pages channel), lib/waybackPages/view.ts + PageCaptureFacts on the moment page, card and post modal |
+| `3955bfd6` | the editor's records + Capture + posts-media route; the citation `fallback`, replacePageCitationWithRecord; umtool Import this capture (route, lib, rail, stub); MCP get_post/platforms/instructions; corpus.json kind; e2e specs; OPERATING/FACTS/CHANGELOG |
+| `aace18a1` | merge main (lane B) |
+| `2ec5cecc` | tests: compose of a cited page record, the moment page, the card, PageCaptureFacts, MCP; CITATIONS.md regenerated; a page hit's title in search output |
+| `41575aff` | merge main (lane E) |
+| `55a3ed30` | one page→post builder shared with find-copy (`lib/citations/pageAsPost.ts`); a gone original named with lane E's label; the archiveOrgClient merge repaired |
+| `1f069fe3` | the e2e spec's wait, this record |
+| `41cc0658`, `de2fd52b` | merge main (lane G; r38/video-assist) |
+
+## Gates
+
+All through the session's locks, from the worktree root.
+
+- tsc (`pnpm -r … exec tsc --noEmit`): clean at `3955bfd6` and on the final code (after `55a3ed30`'s edits). The
+ merge commit `41575aff` itself did not compile (archiveOrgClient keep-both cut `send()`'s closing lines); fixed
+ in `55a3ed30`.
+- common: lane A's record at main d261ab33: 4765 tests. This branch, full run after the lane B merge: **4799 tests,
+ 4795 pass, 2 fail, 2 skipped** — both mine (an architecture back-edge from a lib test into components; a card
+ assertion on an icon-wrapped link), fixed; each touched file re-run green after the lane E merge:
+ composeReportsPages 1/1, findCopyPages 4/4 (lane E's `as` expectation now carries the fallback), handEdits 8/8,
+ capturePosts 6/6, waybackPageCapture 5/5 (the real-Chromium crop test ran, not skipped), view 3/3,
+ architecture 4/4, liveness 7/7, PageCaptureFacts 1/1, citations 12/12, MomentArticle.page 1/1.
+- editor unit: **357 / 357**. mcp: **381 / 381** (379 at main + 2). umtool unit: **45 / 45**. test:scripts:
+ **1316: 1312 pass, 0 fail, 4 skipped**. export unit: **117 / 117**.
+- After merging main (lane G, r38/video-assist; `de2fd52b`): tsc clean; common **4856 / 4854 / 0 fail / 2
+ skipped**; editor **362/362**; mcp **382/382**; umtool **45/45**; test:scripts **1327: 1323 / 0 / 4 skipped**;
+ the four docs checks 0.
+- Docs: `docs env --check`, `docs files --check` (CITATIONS.md regenerated), `docs cli --check`, `settings example
+ --check`: all 0.
+- e2e (editor, start mode): `wayback-pages-capture.spec.ts` + `wayback-pages.spec.ts`: 1 passed (lane A's), 1
+ failed — the capture itself ran clean ("Done: 4 captured, 0 failed", item and page shots, the image), the spec
+ waited for the wrong line; fixed. Re-run (stamp at 55a3ed30): `wayback-pages-capture.spec.ts` +
+ `capture-posts.spec.ts` **2 / 2 passed** (53 s) — the four records shot (two whole pages, two Tumblr posts clipped
+ to their boxes), the post's image saved through `im_`, the shot shown on the page.
+- e2e (umtool, start mode, stamp e5ddfa0e607c): `import-capture.spec.ts` + `article-evidence.spec.ts` **4 / 4
+ passed** (22.6 s).
+
+## Decisions
+
+- The shot path is NOT a registered `SocialFetcher`: a "webpage" fetcher would be listed by the channel form and
+ resolved by every fetcher-shaped path (availability, fetch); `capturePosts` branches on the channel kind instead.
+- JavaScript off in the render: the archive rewrites a capture's links and styles server-side, and the capture's
+ own scripts would only ask the archive for more. Pages that draw themselves with script shoot as their HTML.
+- Every request off the archive's origin is aborted: a render never touches the live web (or a tracker in a
+ capture). Audio/video sub-resources are refused.
+- The page load holds the Wayback client's chain for its whole duration (sub-resources included); the gap follows
+ it — one stream at a time from this process.
+- No locator hint was added to the draft (no shared-shape change): the extractors' ids carry enough.
+- An item the render cannot find is shot as the whole page (marked `shotScope: "page"`), not refused: the capture
+ is still the evidence.
+- Image cap 20 per record, 10 MB each.
+- Import this capture refuses a quote the record does not hold (the hand-edit rule), never writes a site report
+ (built from its draft — the replacement is shown), and keeps the page as `fallback`.
+- `search_transcripts` filter is `platforms` (post platforms), not a new content type: `content_types` stays
+ video|post, and a page record is a post.
+- `corpus.json` gains an optional channel `kind` with no spec bump (additive; absent = an account's channel).
+
+## Found and left
+
+- The editor has no single-post page; the records table on the channel page is the editor's post view for page
+ records.
+- A site report's draft is not rewritten by umtool (it never writes a draft); its replacement citation is shown.
diff --git a/umtool/app/api/articles/import-capture/route.ts b/umtool/app/api/articles/import-capture/route.ts
@@ -0,0 +1,80 @@
+import { errorResponse, EditorError } from "@/lib/articles/generation";
+import {
+ captureImportStatus,
+ ImportCaptureError,
+ startCaptureImport,
+ useImportedRecord,
+ webpageChannels,
+} from "@/lib/articles/importCapture";
+import { isReportHost, readReportFile } from "@/lib/articles/sites";
+import { clearPiecesCache } from "@/lib/pieces";
+import { clearRailCounts } from "@/lib/rail";
+
+export const dynamic = "force-dynamic";
+
+// IMPORT THIS CAPTURE (release 37 S4; lib/articles/importCapture.ts): a page
+// citation's Wayback copy imported as a page record, then cited as one.
+//
+// GET the Wayback pages channels a capture can go into
+// GET ?job=<id>&slug=<slug> the import job's state, and its records once done
+// POST {action: "start", site, report, cite, slug | newChannel: {name}}
+// create-channel (when asked) + import-page → {slug, jobId}
+// POST {action: "use", site, report, cite, slug, id}
+// the citation rewritten (a store article, a hand
+// edit) or, for a site report, the replacement for its draft
+
+const NO_STORE = { "cache-control": "no-store" };
+
+function fail(err: unknown): Response {
+ if (err instanceof ImportCaptureError) {
+ return Response.json({ error: err.message, problems: err.problems }, { status: err.status, headers: NO_STORE });
+ }
+ if (err instanceof EditorError) return errorResponse(err);
+ return Response.json({ error: (err as Error).message }, { status: 500, headers: NO_STORE });
+}
+
+export async function GET(request: Request) {
+ const q = new URL(request.url).searchParams;
+ try {
+ const job = q.get("job");
+ if (job) return Response.json(await captureImportStatus(job, q.get("slug") ?? ""), { headers: NO_STORE });
+ return Response.json({ channels: await webpageChannels() }, { headers: NO_STORE });
+ } catch (err) {
+ return fail(err);
+ }
+}
+
+export async function POST(request: Request) {
+ let body: Record<string, unknown>;
+ try {
+ body = (await request.json()) as Record<string, unknown>;
+ } catch {
+ return Response.json({ error: "the body is JSON" }, { status: 400, headers: NO_STORE });
+ }
+ const s = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : "");
+ const site = s("site");
+ const reportId = s("report");
+ const cite = s("cite");
+ try {
+ if (!isReportHost(site)) throw new ImportCaptureError(`no site ${site}`, 404);
+ const read = await readReportFile(site, reportId);
+ if (!read.report) throw new ImportCaptureError(read.problems[0]?.message ?? "no report", 404);
+ if (body.action === "start") {
+ const nc = body.newChannel as { name?: unknown } | undefined;
+ const into = nc && typeof nc === "object" ? { create: { name: String(nc.name ?? "") } } : { slug: s("slug") };
+ if ("slug" in into && !into.slug) throw new ImportCaptureError("pick a Wayback pages channel, or name a new one");
+ return Response.json(await startCaptureImport(read.report, cite, into), { headers: NO_STORE });
+ }
+ if (body.action === "use") {
+ const out = await useImportedRecord(site, read.report, cite, s("slug"), s("id"));
+ if (out.written) {
+ clearPiecesCache();
+ clearRailCounts();
+ }
+ return Response.json(out, { headers: NO_STORE });
+ }
+ throw new ImportCaptureError('action is "start" or "use"');
+ } catch (err) {
+ return fail(err);
+ }
+}
diff --git a/umtool/components/articles/EvidencePanel.tsx b/umtool/components/articles/EvidencePanel.tsx
@@ -4,6 +4,8 @@ import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "re
import CitedClip, { type CitedClipHandle } from "@/components/clips/CitedClip";
import type { Evidence } from "@/lib/articles/evidence";
import AddToVideo, { type VideoProjectLink } from "./AddToVideo";
+import ImportCapture from "./ImportCapture";
+import { pageCaptureLine, pageVersionsLine, PAGE_NO_CONTENT_LINE } from "yt-dlp-transcript-common/lib/waybackPages/view";
// One citation's evidence: what it quotes, who and when, the transcript around
// it with the cited cues marked, and the media that plays it -- the prepared
@@ -71,10 +73,51 @@ const EvidencePanel = forwardRef<
)}
</div>
{ev.record?.title && <div className="text-[var(--color-dim)]">{ev.record.title}</div>}
- {ev.originalUrl && (
- <a href={ev.originalUrl} target="_blank" rel="noopener noreferrer" className="ink-link">
- original ↗
- </a>
+ {(ev.originalUrl || ev.copy) && (
+ <div className="flex flex-wrap gap-x-3">
+ {ev.originalUrl && (
+ <a href={ev.originalUrl} target="_blank" rel="noopener noreferrer" className="ink-link">
+ {ev.originalLabel ?? "original"} ↗
+ </a>
+ )}
+ {ev.copy && (
+ <a href={ev.copy.url} target="_blank" rel="noopener noreferrer" className="ink-link">
+ {ev.copy.label} ↗
+ </a>
+ )}
+ </div>
+ )}
+ {ev.page && (
+ <div data-page-capture={ev.page.kind} className="space-y-0.5 text-[var(--color-dim)]">
+ <div className="font-mono text-[11px]">{pageCaptureLine(ev.page)}</div>
+ {ev.page.noContent && <div data-page-no-content="">{PAGE_NO_CONTENT_LINE}</div>}
+ {ev.page.fallbackNote && <div data-page-fallback="">{ev.page.fallbackNote}</div>}
+ {ev.page.versions && (
+ <div data-page-versions={ev.page.versions.count}>
+ {pageVersionsLine(ev.page.versions)}{" "}
+ {ev.page.versions.captures.map((c) =>
+ c.current ? (
+ <span key={c.id} className="mr-2 font-mono font-semibold">
+ {c.date}
+ </span>
+ ) : (
+ <a key={c.id} href={c.waybackUrl} target="_blank" rel="noopener noreferrer" className="ink-link mr-2 font-mono">
+ {c.date}
+ </a>
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ {ev.importCapture && (
+ <ImportCapture
+ site={ev.importCapture.site}
+ report={ev.importCapture.report}
+ cite={ev.cite}
+ writable={ev.importCapture.writable}
+ host={ev.importCapture.host}
+ />
)}
{ev.record && ev.start !== undefined && ev.end !== undefined && (ev.kind === "video" || ev.kind === "audio") && (
@@ -96,7 +139,11 @@ const EvidencePanel = forwardRef<
{ev.post.text && <p className="whitespace-pre-wrap font-serif text-[15px] leading-snug">{ev.post.text}</p>}
{ev.post.shot && (
// eslint-disable-next-line @next/next/no-img-element
- <img src={ev.post.shot} alt="capture of the post" className="w-full rounded-[2px] border border-reader-seam" />
+ <img
+ src={ev.post.shot}
+ alt={ev.page ? `capture of the Wayback Machine copy, ${ev.page.captureDate}` : "capture of the post"}
+ className="w-full rounded-[2px] border border-reader-seam"
+ />
)}
</div>
)}
diff --git a/umtool/components/articles/ImportCapture.tsx b/umtool/components/articles/ImportCapture.tsx
@@ -0,0 +1,186 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Input, Select } from "@/components/ui/field";
+
+// IMPORT THIS CAPTURE (release 37 S4): a page citation's Wayback copy imported
+// into a Wayback pages channel (picked, or created for the page's host) as a
+// page record — the editor's import-page, one job at archive.org's pace — and
+// then the citation rewritten as a post citation of that record, the page kept
+// as its fallback (/api/articles/import-capture). A site report is built from
+// its draft: the replacement citation is shown for the draft instead.
+
+type Channel = { slug: string; name: string };
+type Rec = { id: string; title?: string; text: string };
+type Status = { status: string; done: boolean; ok?: boolean; error?: string; records: Rec[] };
+
+const NEW = "__new__";
+
+async function call<T>(init?: RequestInit, query = ""): Promise<T> {
+ const r = await fetch(`/api/articles/import-capture${query}`, { cache: "no-store", ...init });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error([j.error ?? r.statusText, ...((j.problems as string[] | undefined) ?? [])].join(" — "));
+ return j as T;
+}
+
+export default function ImportCapture({
+ site,
+ report,
+ cite,
+ writable,
+ host,
+}: {
+ site: string;
+ report: string;
+ cite: string;
+ writable: boolean;
+ host: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const [channels, setChannels] = useState<Channel[] | null>(null);
+ const [pick, setPick] = useState("");
+ const [name, setName] = useState(host ? `${host} pages` : "");
+ const [job, setJob] = useState<{ slug: string; jobId: string } | null>(null);
+ const [status, setStatus] = useState<Status | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [used, setUsed] = useState<{ written: boolean; n?: number; citation: unknown } | null>(null);
+
+ useEffect(() => {
+ if (!open || channels) return;
+ call<{ channels: Channel[] }>()
+ .then((j) => {
+ setChannels(j.channels);
+ setPick(j.channels[0]?.slug ?? NEW);
+ })
+ .catch((e) => setError((e as Error).message));
+ }, [open, channels]);
+
+ // Follow the import job until it ends.
+ useEffect(() => {
+ if (!job || status?.done) return;
+ const t = setInterval(() => {
+ call<Status>(undefined, `?${new URLSearchParams({ job: job.jobId, slug: job.slug })}`)
+ .then(setStatus)
+ .catch((e) => setError((e as Error).message));
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job, status?.done]);
+
+ const start = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const body = pick === NEW ? { newChannel: { name } } : { slug: pick };
+ const j = await call<{ slug: string; jobId: string }>({
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "start", site, report, cite, ...body }),
+ });
+ setStatus(null);
+ setJob(j);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const use = async (id: string) => {
+ if (!job) return;
+ setBusy(true);
+ setError(null);
+ try {
+ setUsed(
+ await call({
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "use", site, report, cite, slug: job.slug, id }),
+ }),
+ );
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (!open) {
+ return (
+ <Button size="sm" onClick={() => setOpen(true)}>
+ Import this capture
+ </Button>
+ );
+ }
+ return (
+ <div data-import-capture={cite} className="space-y-2 rounded-[3px] border border-seam-2 p-2.5">
+ <div className="micro">Import this capture</div>
+ {!job && (
+ <>
+ <label className="flex items-center gap-2">
+ <span className="text-[var(--color-dim)]">into</span>
+ <Select aria-label="Wayback pages channel" value={pick} onChange={(e) => setPick(e.target.value)} disabled={!channels}>
+ {(channels ?? []).map((c) => (
+ <option key={c.slug} value={c.slug}>
+ {c.name} ({c.slug})
+ </option>
+ ))}
+ <option value={NEW}>a new Wayback pages channel…</option>
+ </Select>
+ </label>
+ {pick === NEW && (
+ <Input aria-label="new channel name" value={name} onChange={(e) => setName(e.target.value)} placeholder="name" />
+ )}
+ <Button size="sm" variant="go" onClick={start} disabled={busy || !channels || (pick === NEW && !name.trim())}>
+ Import
+ </Button>
+ </>
+ )}
+ {job && !status?.done && (
+ <div role="status" className="text-[var(--color-dim)]">
+ importing into {job.slug}… {status?.status ?? "queued"}
+ </div>
+ )}
+ {status?.done && !status.ok && <div className="text-[var(--color-bad)]">{status.error ?? `the import ${status.status}`}</div>}
+ {status?.done && status.ok && !used && (
+ <div className="space-y-1.5">
+ <div role="status" className="text-[var(--color-dim)]">
+ {status.records.length} record{status.records.length === 1 ? "" : "s"} in {job?.slug}: cite one
+ </div>
+ <ul className="space-y-1.5">
+ {status.records.map((r) => (
+ <li key={r.id} data-imported-record={r.id} className="flex items-start gap-2">
+ <Button size="sm" onClick={() => use(r.id)} disabled={busy}>
+ Cite this
+ </Button>
+ <span>
+ <span className="font-mono text-[11px]">{r.id}</span>
+ {r.title && <span> — {r.title}</span>}
+ {r.text && <span className="block text-[var(--color-dim)]">{r.text}</span>}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {used?.written && (
+ <div role="status" className="text-[var(--color-dim)]">
+ {cite} now cites the page record; written to i{used.n} (the page is kept as its fallback).
+ </div>
+ )}
+ {used && !used.written && (
+ <div className="space-y-1">
+ <div role="status" className="text-[var(--color-dim)]">
+ {writable ? "" : "This report is built from its draft: put this citation in the draft as "}
+ {cite}:
+ </div>
+ <pre data-replacement-citation="" className="overflow-x-auto whitespace-pre-wrap rounded-[2px] bg-panel-2 p-2 font-mono text-[11px]">
+ {JSON.stringify(used.citation, null, 2)}
+ </pre>
+ </div>
+ )}
+ {error && <div className="text-[var(--color-bad)]">{error}</div>}
+ </div>
+ );
+}
diff --git a/umtool/e2e/fixtures/editor-stub-import-page.mjs b/umtool/e2e/fixtures/editor-stub-import-page.mjs
@@ -0,0 +1,118 @@
+// The editor's side of Import this capture (release 37 S4), stubbed:
+//
+// POST /api/ops/create-channel {fields: {name, handling, url}}
+// a Wayback pages channel's config.json written into the fixture corpus
+// (slug from the name, as the form derives it) → {ok, slug, jobIds: []}
+// POST /api/ops/import-page {slug, url}
+// a job "ip-<n>": running after 0.5 s, done after 1.5 s, when it writes
+// ONE page record into <CHANNELS_DIR>/<slug>/posts/ — its text the
+// fixture's synthetic page (it holds the cited quote) — and ends its log
+// with the editor's `@@import-page {…}` result line
+// GET /api/ops/job/ip-<n>?tail=N
+// that job's state and log
+//
+// Never the Wayback Machine, never a real editor. Every request is recorded by
+// the main stub's `record`.
+
+import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const IMPORT_PAGE_TEXT =
+ "The first loaf came out flat, and the second, and the third, which is how it goes when the starter is young.";
+
+const jobs = new Map();
+let next = 1;
+
+function slugOf(name) {
+ return String(name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "pages";
+}
+
+function parseCapture(url) {
+ const m = /^https?:\/\/web\.archive\.org\/web\/(\d{4,14})[a-z]{0,2}_?\/(.+)$/.exec(String(url));
+ return m ? { ts: m[1], original: m[2] } : null;
+}
+
+/**
+ * Handles the three routes; answers true when it did. `ctx`: {channels, json,
+ * readBody, push(record)}.
+ */
+export function importPageRoute(req, res, url, ctx) {
+ const { json, readBody } = ctx;
+ if (req.method === "POST" && url.pathname === "/api/ops/create-channel") {
+ readBody(req, (body) => {
+ const fields = body?.fields ?? {};
+ const slug = body?.slug ?? slugOf(fields.name);
+ ctx.push({ path: url.pathname, body });
+ const dir = path.join(ctx.channels, slug);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ path.join(dir, "config.json"),
+ JSON.stringify({ name: fields.name, handling: fields.handling ?? "transcribe", sourceKind: "social", platform: "webpage", url: fields.url }, null, 2),
+ );
+ json(res, 200, { ok: true, slug, jobIds: [] });
+ });
+ return true;
+ }
+ if (req.method === "POST" && url.pathname === "/api/ops/import-page") {
+ readBody(req, (body) => {
+ ctx.push({ path: url.pathname, body });
+ const cap = parseCapture(body?.url);
+ if (!body?.slug || !cap) return json(res, 400, { ok: false, error: "not one capture" });
+ const id = `ip-${next++}`;
+ const job = { id, status: "queued", log: [`Import ${body.url} into ${body.slug}`] };
+ jobs.set(id, job);
+ setTimeout(() => (job.status = "running"), 500);
+ setTimeout(() => {
+ const recordId = `${cap.ts}-0123456789ab`;
+ const post = {
+ id: recordId,
+ slug: `${body.slug}/${recordId}`,
+ channelSlug: body.slug,
+ author: new URL(cap.original).hostname,
+ createdAt: "2014-03-04T18:30:00.000Z",
+ uploadDate: "20140304",
+ text: IMPORT_PAGE_TEXT,
+ url: cap.original,
+ platform: "webpage",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ threadId: "page-0123456789ab",
+ page: {
+ originalUrl: cap.original,
+ captureTs: cap.ts,
+ waybackUrl: `https://web.archive.org/web/${cap.ts}/${cap.original}`,
+ rawUrl: `https://web.archive.org/web/${cap.ts}id_/${cap.original}`,
+ kind: "generic",
+ title: "A Post About Bread",
+ extractor: "generic",
+ extractorVersion: 1,
+ },
+ };
+ try {
+ const dir = path.join(ctx.channels, body.slug, "posts");
+ mkdirSync(dir, { recursive: true });
+ appendFileSync(path.join(dir, "2014-03.jsonl"), JSON.stringify(post) + "\n");
+ appendFileSync(path.join(ctx.channels, body.slug, "posts-archive"), `webpage ${recordId}\n`);
+ } catch {
+ /* the fixture was rebuilt under the job */
+ }
+ job.log.push(`@@import-page ${JSON.stringify({ ok: true, slug: body.slug, url: body.url, captureTs: cap.ts, records: [recordId], written: 1, updated: 0, unchanged: 0 })}`);
+ job.status = "done";
+ }, 1500);
+ json(res, 200, { ok: true, jobId: id });
+ });
+ return true;
+ }
+ const m = /^\/api\/ops\/job\/(ip-\d+)$/.exec(url.pathname);
+ if (req.method === "GET" && m) {
+ const job = jobs.get(m[1]);
+ if (!job) {
+ json(res, 404, { ok: false, error: "no such job" });
+ return true;
+ }
+ json(res, 200, { ok: true, job: { id: job.id, kind: "import-page", status: job.status }, tail: job.log });
+ return true;
+ }
+ return false;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -23,6 +23,7 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { fileURLToPath } from "node:url";
import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs";
+import { importPageRoute } from "./editor-stub-import-page.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs";
import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs";
@@ -1173,6 +1174,8 @@ const server = http.createServer((req, res) => {
return json(res, 401, { error: "missing bearer token" });
}
+ // Release 37 S4: Import this capture (editor-stub-import-page.mjs).
+ if (importPageRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return;
if ((url.pathname === "/api/ops/fetch-windows" || url.pathname.startsWith("/api/ops/job/")) && fetchWindowsRoute(req, res, url, fwCtx)) return;
if (url.pathname.startsWith("/api/ops/") && generationRoute(req, res, url, auth) !== null) return;
diff --git a/umtool/e2e/import-capture.spec.ts b/umtool/e2e/import-capture.spec.ts
@@ -0,0 +1,94 @@
+import { test, expect } from "@playwright/test";
+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Import this capture (release 37 S4): a store article's `page` citation whose
+// archived copy is a Wayback Machine capture. Its evidence offers Import this
+// capture; into a new Wayback pages channel (the stub editor's create-channel
+// writes its config, its import-page writes ONE synthetic page record —
+// e2e/fixtures/editor-stub-import-page.mjs); the record is cited, and the
+// article's citation is a post citation of it — written as a hand iteration by
+// the REAL replacePageCitationWithRecord, its quote checked against the
+// record — with the page kept as its fallback. Then its evidence shows the
+// page record: "Original (may be gone)", the Wayback copy, the kind.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const ARTICLES = path.join(FIXTURE, "articles");
+const CHANNELS = path.join(FIXTURE, "channels");
+const ID = "capture-import";
+const DIR = path.join(ARTICLES, ID);
+const SLUG = "blog-example-pages";
+const ORIGINAL = "https://blog.example/2014/03/a-post.html";
+const ARCHIVE = `https://web.archive.org/web/20140305120000/${ORIGINAL}`;
+
+const report = {
+ format: "archilyzer-report",
+ version: 1,
+ id: ID,
+ kind: "sweep",
+ title: "The Bread Blog",
+ citations: {
+ p1: { kind: "page", url: ORIGINAL, title: "A Post About Bread", archiveUrl: ARCHIVE, quote: "The first loaf came out flat" },
+ },
+ sections: [{ id: "s1", title: "The blog", claims: [{ id: "c1", text: "The blog said the first loaf was flat.", citations: ["p1"] }] }],
+};
+
+function clean() {
+ rmSync(DIR, { recursive: true, force: true });
+ rmSync(path.join(CHANNELS, SLUG), { recursive: true, force: true });
+}
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ clean();
+ mkdirSync(DIR, { recursive: true });
+ writeFileSync(path.join(DIR, "report.json"), JSON.stringify(report, null, 2));
+ await warm(playwright, [`/articles/${ID}`, `/api/sites/evidence?site=articles&report=${ID}&cite=p1`, "/api/articles/import-capture"]);
+});
+
+test.afterAll(clean);
+
+test("a page citation's capture imported as a page record, then cited as one, the page kept as its fallback", async ({ page }) => {
+ test.setTimeout(90_000);
+ await page.goto(`/articles/${ID}?tab=article`);
+ await page.locator("button[data-cite='p1']").first().click();
+ const ev = page.locator("[data-evidence='p1']");
+ await expect(ev.getByRole("link", { name: /Wayback Machine copy, 2014-03-05/ })).toHaveAttribute("href", ARCHIVE);
+
+ await ev.getByRole("button", { name: "Import this capture" }).click();
+ const box = ev.locator("[data-import-capture='p1']");
+ await box.getByLabel("Wayback pages channel").selectOption({ label: "a new Wayback pages channel…" });
+ await box.getByLabel("new channel name").fill("Blog example pages");
+ await box.getByRole("button", { name: "Import" }).click();
+ await expect(box.getByRole("status")).toContainText("1 record in blog-example-pages", { timeout: 30_000 });
+ expect(existsSync(path.join(CHANNELS, SLUG, "config.json"))).toBe(true);
+
+ const rec = box.locator("[data-imported-record]");
+ await expect(rec).toHaveCount(1);
+ await expect(rec).toContainText("A Post About Bread");
+ await rec.getByRole("button", { name: "Cite this" }).click();
+ await expect(box.getByRole("status")).toContainText("p1 now cites the page record; written to i1");
+
+ // The hand iteration: a post citation of the record, the page its fallback.
+ const its = readdirSync(path.join(DIR, "iterations")).filter((n) => /^\d+$/.test(n));
+ expect(its).toEqual(["1"]);
+ const written = JSON.parse(readFileSync(path.join(DIR, "iterations", "1", "report.json"), "utf8"));
+ expect(written.citations.p1).toEqual({
+ kind: "post",
+ channel: SLUG,
+ id: "20140305120000-0123456789ab",
+ quote: "The first loaf came out flat",
+ fallback: { kind: "page", url: ORIGINAL, title: "A Post About Bread", archiveUrl: ARCHIVE },
+ });
+
+ // What crossed the wire: the channel scoped on the page's host, the capture.
+ const asked = JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { path: string; body?: Record<string, unknown> }[];
+ const create = asked.find((r) => r.path === "/api/ops/create-channel");
+ expect(create?.body).toMatchObject({ fields: { name: "Blog example pages", url: "https://web.archive.org/web/*/blog.example/*" } });
+ expect(asked.find((r) => r.path === "/api/ops/import-page")?.body).toEqual({ slug: SLUG, url: ARCHIVE });
+});
diff --git a/umtool/lib/articles/article.ts b/umtool/lib/articles/article.ts
@@ -77,9 +77,9 @@ export async function recordMeta(channel: string, id: string): Promise<RecordMet
// A channel's posts, by id. A big X archive is thousands of posts, so one read
// per channel per minute.
const postsMemo = new Map<string, { at: number; value: Promise<Map<string, Post>> }>();
-export function channelPosts(channel: string): Promise<Map<string, Post>> {
+export function channelPosts(channel: string, o: { fresh?: boolean } = {}): Promise<Map<string, Post>> {
const hit = postsMemo.get(channel);
- if (hit && Date.now() - hit.at < 60_000) return hit.value;
+ if (hit && !o.fresh && Date.now() - hit.at < 60_000) return hit.value;
const value = readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, channel))
.then((list) => new Map(list.map((p) => [p.id, p])))
.catch(() => new Map<string, Post>());
diff --git a/umtool/lib/articles/evidence.ts b/umtool/lib/articles/evidence.ts
@@ -9,6 +9,12 @@ import { corpusPlay } from "@/lib/clips/cited";
import type { CitedPlay } from "@/lib/clips/types";
import { channelPosts, corpusMediaUrl, postShotFile, recordDir, recordMeta } from "./article";
import { storeFor } from "./sites";
+import { pageCaptureView, pageCopyLinks } from "yt-dlp-transcript-common/lib/waybackPages/view";
+import { mementoSourceOf } from "yt-dlp-transcript-common/lib/archives/mementos";
+import type { PageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view";
+import { parseWaybackUrl } from "yt-dlp-transcript-common/lib/wayback";
+import { ARTICLES_KEY, CHANNELS_DIR } from "@/lib/paths";
+import { readPostAvailability } from "yt-dlp-transcript-common/lib/posts-server";
// What a citation's EVIDENCE panel shows: the cited seconds with the transcript
// around them, and something to play -- found, never fetched.
@@ -46,6 +52,15 @@ export type Evidence = {
play: EvidencePlay | null;
fetchLine?: string;
post?: { author?: string; text?: string; url?: string; shot?: string };
+ // What `originalUrl` is, when "original" would not say ("Original (may be
+ // gone)" for a page record), and the archived copy beside it (release 37 S4).
+ originalLabel?: string;
+ copy?: { label: string; url: string };
+ // A page record's capture: kind, date, versions, no content, fallback note.
+ page?: PageCaptureView;
+ // A page citation whose archived copy is a Wayback capture: Import this
+ // capture turns it into a page record (lib/articles/importCapture.ts).
+ importCapture?: { site: string; report: string; writable: boolean; host: string };
};
type Cite = NonNullable<Report["citations"]>[string];
@@ -144,19 +159,52 @@ export async function citationEvidence(siteId: string, report: Report, citeId: s
};
}
if (c.kind === "post") {
- const post = (await channelPosts(c.channel)).get(c.id);
+ const posts = await channelPosts(c.channel);
+ const post = posts.get(c.id);
const shot = await postShotFile(c.channel, c.id);
+ const avail = post?.page
+ ? await readPostAvailability(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, c.channel)).catch(() => ({}) as Record<string, { availability?: string }>)
+ : {};
+ const page = post?.page
+ ? pageCaptureView(post, [...posts.values()], { originalGone: (avail as Record<string, { availability?: string }>)[c.id]?.availability === "deleted" })
+ : undefined;
return {
...base,
- record: { channel: c.channel, id: c.id },
- ...(post?.url ? { originalUrl: post.url } : {}),
+ record: { channel: c.channel, id: c.id, ...(page?.title ? { title: page.title } : {}) },
+ ...(page
+ ? { originalUrl: page.links.original.url, originalLabel: page.links.original.label, copy: page.links.copy, page }
+ : post?.url
+ ? { originalUrl: post.url }
+ : {}),
post: {
...(post ? { author: post.authorName ?? post.author, text: post.text, url: post.url } : {}),
...(shot ? { shot: corpusMediaUrl(shot) } : {}),
},
};
}
- if (c.kind === "page") return { ...base, originalUrl: c.url };
+ if (c.kind === "page") {
+ const ref = parseWaybackUrl(c.archiveUrl);
+ let host = "";
+ try {
+ host = ref ? new URL(ref.originalUrl).hostname : "";
+ } catch {
+ host = "";
+ }
+ return {
+ ...base,
+ originalUrl: c.url,
+ ...(c.title ? { label: c.label ?? c.title } : {}),
+ ...(c.archiveUrl
+ ? {
+ copy: ref
+ ? pageCopyLinks({ originalUrl: c.url, captureTs: ref.captureTs, waybackUrl: c.archiveUrl, rawUrl: c.archiveUrl }).copy
+ : // Release 37 lane F: an archive.today copy says so.
+ { label: mementoSourceOf(c.archiveUrl) === "archive.today" ? "archive.today copy" : "archived copy", url: c.archiveUrl },
+ }
+ : {}),
+ ...(ref ? { importCapture: { site: siteId, report: report.id, writable: siteId === ARTICLES_KEY, host } } : {}),
+ };
+ }
if (c.kind === "source") {
const s = report.sources?.[c.source];
return { ...base, ...(s?.url ? { originalUrl: s.url } : {}), ...(s?.title ? { label: c.label ?? s.title } : {}) };
diff --git a/umtool/lib/articles/importCapture.ts b/umtool/lib/articles/importCapture.ts
@@ -0,0 +1,171 @@
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import type { Report } from "yt-dlp-transcript-common/lib/report/schema";
+import { parseWaybackUrl } from "yt-dlp-transcript-common/lib/wayback";
+import { HandEditError, replacePageCitationWithRecord } from "yt-dlp-transcript-common/controller/handEdits";
+import type { Citation } from "yt-dlp-transcript-common/lib/citations/schema";
+import { pageCitationAsPost } from "yt-dlp-transcript-common/lib/citations/pageAsPost";
+import { ARTICLES_KEY, CHANNELS_DIR } from "@/lib/paths";
+import { askEditor } from "./generation";
+import { channelPosts } from "./article";
+import { sitesPaths } from "./sites";
+
+// IMPORT THIS CAPTURE (release 37 S4): a report's `page` citation whose
+// archived copy is a Wayback Machine capture becomes a page record — the
+// editor's `import-page` into a Wayback pages channel picked (or created) here
+// — and then a `post` citation of that record, the page kept as its
+// `fallback`. No model: three buttons over the editor's ops door.
+//
+// start create-channel (when asked) → import-page {slug, url: archiveUrl}
+// status the job's state, and when done the records it made (the
+// `@@import-page` line of its log)
+// use a store article: the citation rewritten as a hand edit (common
+// controller/handEdits.ts replacePageCitationWithRecord). A site
+// report is built from its draft, which umtool never writes: the
+// replacement citation comes back for the draft.
+
+export const IMPORT_PAGE_MARKER = "@@import-page ";
+
+export type PagesChannel = { slug: string; name: string };
+
+/** The Wayback pages channels (platform "webpage") a capture can go into. */
+export async function webpageChannels(): Promise<PagesChannel[]> {
+ let names: string[] = [];
+ try {
+ names = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR);
+ } catch {
+ return [];
+ }
+ const out: PagesChannel[] = [];
+ for (const slug of names.sort()) {
+ if (slug.startsWith(".")) continue;
+ try {
+ const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8"));
+ if (c?.sourceKind === "social" && c?.platform === "webpage") out.push({ slug, name: typeof c.name === "string" ? c.name : slug });
+ } catch {
+ // not a channel
+ }
+ }
+ return out;
+}
+
+export class ImportCaptureError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ readonly problems: string[] = [],
+ ) {
+ super(message);
+ }
+}
+
+/** The page citation `cite` and its capture, or the refusal. */
+export function importablePage(report: Report, cite: string): { url: string; title?: string; archiveUrl: string; host: string } {
+ const c = report.citations?.[cite];
+ if (!c) throw new ImportCaptureError(`no citation ${cite}`, 404);
+ if (c.kind !== "page") throw new ImportCaptureError(`citation ${cite} is a ${c.kind}, not a page`);
+ const ref = parseWaybackUrl(c.archiveUrl);
+ if (!c.archiveUrl || !ref) throw new ImportCaptureError(`citation ${cite} has no Wayback Machine copy (archiveUrl) to import`);
+ let host = "";
+ try {
+ host = new URL(ref.originalUrl).hostname;
+ } catch {
+ host = "";
+ }
+ return { url: c.url, ...(c.title ? { title: c.title } : {}), archiveUrl: c.archiveUrl, host };
+}
+
+/** A capture page citation's import, started: into `slug`, or a channel created for its host. */
+export async function startCaptureImport(
+ report: Report,
+ cite: string,
+ into: { slug: string } | { create: { name: string } },
+): Promise<{ slug: string; jobId: string; created: boolean }> {
+ const page = importablePage(report, cite);
+ let slug: string;
+ let created = false;
+ if ("create" in into) {
+ const name = into.create.name.trim();
+ if (!name) throw new ImportCaptureError("give the new channel a name");
+ if (!page.host) throw new ImportCaptureError("the capture names no host to scope a channel by");
+ const made = await askEditor<{ slug: string }>("/api/ops/create-channel", {
+ method: "POST",
+ body: { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${page.host}/*` } },
+ });
+ slug = made.slug;
+ created = true;
+ } else {
+ slug = into.slug;
+ if (!(await webpageChannels()).some((c) => c.slug === slug)) throw new ImportCaptureError(`${slug} is not a Wayback pages channel`);
+ }
+ const job = await askEditor<{ jobId: string }>("/api/ops/import-page", { method: "POST", body: { slug, url: page.archiveUrl } });
+ return { slug, jobId: job.jobId, created };
+}
+
+export type ImportedRecord = { id: string; title?: string; text: string };
+
+export type ImportStatus = {
+ status: string;
+ done: boolean;
+ ok?: boolean;
+ error?: string;
+ records: ImportedRecord[];
+};
+
+/** Where an import job is, and the records it made once it is done. */
+export async function captureImportStatus(jobId: string, slug: string): Promise<ImportStatus> {
+ if (!/^[A-Za-z0-9_-]+$/.test(jobId)) throw new ImportCaptureError(`"${jobId}" is not a job id`);
+ const got = await askEditor<{ job: { status: string }; tail?: string[] }>(`/api/ops/job/${jobId}?tail=80`, { fresh: true });
+ const status = got.job.status;
+ const done = status === "done" || status === "failed" || status === "cancelled";
+ const line = [...(got.tail ?? [])].reverse().find((l) => l.includes(IMPORT_PAGE_MARKER));
+ let result: { ok?: boolean; error?: string; records?: string[] } | null = null;
+ if (line) {
+ try {
+ result = JSON.parse(line.slice(line.indexOf(IMPORT_PAGE_MARKER) + IMPORT_PAGE_MARKER.length));
+ } catch {
+ result = null;
+ }
+ }
+ const ids = result?.records ?? [];
+ const posts = ids.length ? await channelPosts(slug, { fresh: true }) : new Map();
+ return {
+ status,
+ done,
+ ...(result ? { ok: result.ok === true } : {}),
+ ...(result?.error ? { error: result.error } : done && status !== "done" ? { error: `the import job ${status}` } : {}),
+ records: ids.map((id) => {
+ const p = posts.get(id);
+ return { id, ...(p?.page?.title ? { title: p.page.title } : {}), text: (p?.text ?? "").slice(0, 280) };
+ }),
+ };
+}
+
+/** The citation that replaces the page citation: a post of the record, the page as its fallback. */
+export function replacementCitation(report: Report, cite: string, slug: string, id: string): Citation {
+ const c = report.citations?.[cite];
+ if (!c || c.kind !== "page") throw new ImportCaptureError(`citation ${cite} is not a page citation`);
+ return pageCitationAsPost(c, { channel: slug, id });
+}
+
+/**
+ * Use the imported record: a store article's citation rewritten (a hand
+ * edit, its quote checked against the record); a site report's replacement
+ * handed back for its draft.
+ */
+export async function useImportedRecord(
+ site: string,
+ report: Report,
+ cite: string,
+ slug: string,
+ id: string,
+): Promise<{ written: boolean; n?: number; citation: Citation }> {
+ if (site !== ARTICLES_KEY) return { written: false, citation: replacementCitation(report, cite, slug, id) };
+ try {
+ const r = await replacePageCitationWithRecord(report.id, { cite, channel: slug, id }, sitesPaths());
+ return { written: true, n: r.n, citation: r.citation };
+ } catch (e) {
+ if (e instanceof HandEditError) throw new ImportCaptureError(e.message, 400, e.problems);
+ throw e;
+ }
+}