Archilyzer · Source

archilyzer

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

commit 17198a610426c57c8c1109d37fdac2848288baaf
parent 9ede6e8fc8ac6381089e7478e328d288af1770e0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:40:22 -0400

wayback pages: the channel page's records and Capture, Import this capture, the MCP and corpus.json

- editor: each page record's row opens to its capture (PageCaptureFacts) and
  its shot (GET /api/channels/<slug>/posts-media/<id>/<name>); Capture shoots
  the picked records, or every record without a shot (capture-posts).
- citations: a post citation's optional `fallback` (the page citation it
  replaced); handEdits.replacePageCitationWithRecord writes it as a hand
  iteration, the quote checked against the record first.
- umtool: the evidence rail shows a page record's capture and both links, a
  page citation's Wayback copy, and Import this capture (pick or create a
  Wayback pages channel, import-page through the editor, Cite this);
  /api/articles/import-capture; the editor stub answers create-channel,
  import-page and its job.
- mcp: get_post prints a page record's capture; search_transcripts
  `platforms`; the instructions' page-record citation rule.
- corpus.json: a Wayback pages channel is `kind: "wayback-pages"`.
- e2e specs: editor wayback-pages-capture, umtool import-capture.
- docs: OPERATING "Shoot and cite a capture", FACTS, CHANGELOG.

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

Diffstat:
MOPERATING.md | 26++++++++++++++++++++++++++
Mcommon/bin/compose-site.ts | 10++++++++++
Mcommon/controller/handEdits.test.ts | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/handEdits.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/citations/docs.ts | 2++
Mcommon/lib/citations/schema.ts | 20++++++++++++++++++++
Mcommon/lib/corpus.ts | 18++++++++++++++++--
Mcommon/lib/waybackPages/view.ts | 13++++++++++++-
Mcommon/publish/composeReports.ts | 4++--
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/channels/[slug]/posts-media/[id]/[name]/route.ts | 42++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/WaybackPageRecords.tsx | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/WaybackPagesPanel.tsx | 43++++---------------------------------------
Meditor/app/channels/[slug]/page.tsx | 50++++++++++++++++++++++++++++++--------------------
Aeditor/e2e/wayback-pages-capture.spec.ts | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.ts | 10++++++++--
Mmcp/src/search.ts | 7++++++-
Mmcp/src/server.ts | 41++++++++++++++++++++++++++++++++++++++---
Mplans/FACTS.md | 36++++++++++++++++++++++++++++++++++++
Aumtool/app/api/articles/import-capture/route.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/EvidencePanel.tsx | 57++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Aumtool/components/articles/ImportCapture.tsx | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/editor-stub-import-page.mjs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 3+++
Aumtool/e2e/import-capture.spec.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/article.ts | 4++--
Mumtool/lib/articles/evidence.ts | 48++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/articles/importCapture.ts | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
28 files changed, 1395 insertions(+), 82 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -112,6 +112,32 @@ pnpm ops reextract-pages --json '{"slug":"old-blog","dryRun":true}' --wait - An x.com / twitter.com capture is private exactly as X posts are (`social.x.visibility`): while X is private, only a Wayback pages channel whose target is on X takes one, and a public site leaves that channel out. +### 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. +- 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/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 @@ -364,6 +364,99 @@ 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; + 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" }>; + const channel = str(input.channel); + const rid = str(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"); + const { kind: _k, url, title, archiveUrl, ...commonFields } = page; + const citation = { + kind: "post", + channel, + id: rid, + ...commonFields, + fallback: { kind: "page", url, ...(title ? { title } : {}), ...(archiveUrl ? { archiveUrl } : {}) }, + } 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/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/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/waybackPages/view.ts b/common/lib/waybackPages/view.ts @@ -68,6 +68,17 @@ export type PageCaptureView = { 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. +export function pageCopyLinks(page: Pick<PagePostInfo, "originalUrl" | "captureTs" | "waybackUrl" | "rawUrl">): { + original: WaybackLink; + copy: WaybackLink; +} { + return waybackCitationLinks(page); +} + export function pageFallbackNote(page: Pick<PagePostInfo, "extractorFallback">): string | undefined { const f = page.extractorFallback; if (!f) return undefined; @@ -134,7 +145,7 @@ export function pageCaptureView( captureDate: waybackCaptureDate(page.captureTs), originalUrl: page.originalUrl, waybackUrl: page.waybackUrl, - links: waybackCitationLinks(page), + links: pageCopyLinks(page), ...(page.title ? { title: page.title } : {}), ...(page.noContent ? { noContent: true } : {}), ...(fallbackNote ? { fallbackNote } : {}), diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -69,7 +69,7 @@ // thrown together (ComposeReportsError), so a failed compose leaves no half // set of reports behind. -import { pageCaptureView } from "../lib/waybackPages/view"; +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"; @@ -764,7 +764,7 @@ export async function resolveReports(opts: ResolveReportsOptions): Promise<Resol 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 ? waybackCitationLinks(post.page) : null; + const page = post.page ? pageCopyLinks(post.page) : null; return defined({ channel: c.channel, channelTitle: config?.name ?? post.authorName, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **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. - **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. - **Focus the queues on a site, or on some channels, from a terminal.** `pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"<id>"}}'` does what the /channels focus bar's **Focus site** does: that site's channels lead every lane, and the focus follows the site's membership. `{"kind":"channels","slugs":[…]}` focuses a list and `{"kind":"none"}` ends the focus. `focus` goes alone in the body. Needs a restart of the editor. 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,110 @@ +"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 Wayback Machine copy, ${r.view.captureDate}`} + 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> + </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,17 +10,10 @@ import Link from "next/link"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { cancelJobAction } from "../../../jobs/actions"; import { importPageAction, reextractPagesAction } from "../waybackPagesActions"; +import { WaybackPageRecords, type WaybackPageRecordRow } from "./WaybackPageRecords"; -export type WaybackPagesRecordRow = { - id: string; - title: string; - kind: string; - captureTs: string; - captureDate: string; - originalUrl: string; - waybackUrl: 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; @@ -70,35 +63,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> - </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 @@ -24,7 +24,8 @@ import { SocialChannelPanel } from "./components/SocialChannelPanel"; import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; -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"; @@ -186,25 +187,7 @@ export default async function ChannelDetailPage({ : undefined; // A WAYBACK PAGES channel (release 37): its captures, its scope, Import a // capture — no fetcher, nothing to fetch. - const wayback = isWaybackPagesChannel(config) - ? { - captureCount: await countStoredCaptures(channelRoot), - recent: (await readAllPosts(channelRoot)) - .filter((p) => p.page) - .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!.waybackUrl, - ...(p.page!.noContent ? { noContent: true } : {}), - })), - } - : null; + const wayback = isWaybackPagesChannel(config) ? await waybackPagesRows(channelRoot, slug) : null; return ( <div className="flex flex-col gap-6"> <RunningJobsList jobs={socialRunningJobs} hideChannelSlug /> @@ -931,3 +914,30 @@ 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) { + const all = (await readAllPosts(channelRoot)).filter((p) => p.page); + 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)!, + ...(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/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('"ok":true', { + 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.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); @@ -2207,6 +2222,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 +2270,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 @@ -11138,3 +11138,39 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri brace-matched string-aware and `JSON.parse`d, or — when assigned as a JS string — unescaped (`\xNN`, `\uNNNN`) then parsed; renderers found by key anywhere (`channelAboutFullMetadataRenderer` | `aboutChannelViewModel`, `c4TabbedHeaderRenderer` | `pageHeaderViewModel`, `channelMetadataRenderer`). + +## 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`). 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. Written only by + `replacePageCitationWithRecord` (controller/handEdits.ts): 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/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"; @@ -1115,6 +1116,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,10 @@ 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 type { PageCaptureView } from "yt-dlp-transcript-common/lib/waybackPages/view"; +import { parseWaybackUrl } from "yt-dlp-transcript-common/lib/wayback"; +import { ARTICLES_KEY } from "@/lib/paths"; // What a citation's EVIDENCE panel shows: the cited seconds with the transcript // around them, and something to play -- found, never fetched. @@ -46,6 +50,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 +157,46 @@ 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 page = post?.page ? pageCaptureView(post, [...posts.values()]) : 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 + : { label: "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,177 @@ +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 { 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`); + const { kind: _kind, url, title, archiveUrl, ...common } = c; + return { + kind: "post", + channel: slug, + id, + ...common, + fallback: { kind: "page", url, ...(title ? { title } : {}), ...(archiveUrl ? { archiveUrl } : {}) }, + } as Citation; +} + +/** + * 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; + } +}