Archilyzer · Source

archilyzer

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

commit 2ad96a50e005328c20b235b31255ed2eba16b65b
parent 45d240f314237c42e6a205e49239f60275c951b7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 07:23:42 -0500

Merge r38/case-verify-leads: a research case's verify, leads and evidence stages (release 38 lane C) -- each finding's captions side by side with the quote marked and an audio check through the editor's transcribe and a word diff, five statuses including quarantined, a hand correction keeping the reader's original; the links a posts or forum channel makes most, each lead archive, watch or never-archive (a never-archive name kept only as its hash); Wayback captures and forum attachments as evidence, marked unverified, in the export's Evidence section; wayback-scan marks an excluded target; a Newgrounds page extractor

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

Diffstat:
MOPERATING.md | 6+++++-
Mcommon/controller/casePipelineRun.ts | 24+++++++++++++++++++++++-
Acommon/controller/reextractPages.newgrounds.test.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/waybackScan.test.ts | 34++++++++++++++++++++++++++++++++++
Mcommon/controller/waybackScan.ts | 30++++++++++++++++++++++++++++--
Acommon/lib/research/caseEvidence.ts | 34++++++++++++++++++++++++++++++++++
Mcommon/lib/research/casePipeline.test.ts | 22+++++++++++++++++++++-
Mcommon/lib/research/casePipeline.ts | 9++++++++-
Mcommon/lib/research/caseTypes.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/research/caseTypes.ts | 92++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/research/privateNames-server.ts | 1+
Acommon/lib/research/wordDiff.test.ts | 32++++++++++++++++++++++++++++++++
Acommon/lib/research/wordDiff.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/ng-art-2014.html | 33+++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/ng-movie-2014.html | 28++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/ng-user-2010.html | 19+++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/ng-user-2014.html | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/extractors/generic.ts | 2+-
Mcommon/lib/waybackPages/extractors/index.test.ts | 8++++++--
Mcommon/lib/waybackPages/extractors/index.ts | 8+++++---
Acommon/lib/waybackPages/extractors/newgrounds.test.ts | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/newgrounds.ts | 315+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/scanFile.ts | 5++++-
Mcommon/lib/waybackPages/types.ts | 6+++++-
Mcommon/lib/waybackPages/view.ts | 3+++
Meditor/CHANGELOG.md | 3+++
Meditor/app/api/ops/wayback-scan/route.ts | 5++++-
Meditor/app/channels/[slug]/captures/components/CapturesPanel.tsx | 4++--
Meditor/app/channels/[slug]/captures/page.tsx | 2+-
Meditor/e2e/wayback-captures.spec.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mplans/FACTS.md | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/release-38/research-cases-and-assist.md | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/evidence/route.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/leads/context/route.ts | 17+++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/leads/older/route.ts | 16++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/leads/route.ts | 41+++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/verify/audio/route.ts | 27+++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/verify/captions/route.ts | 16++++++++++++++++
Aumtool/app/api/research/cases/[id]/stages/verify/route.ts | 32++++++++++++++++++++++++++++++++
Mumtool/app/research/[case]/pipeline/page.tsx | 21++++++++++++++++++---
Mumtool/components/research/BoardView.tsx | 2+-
Mumtool/components/research/CasePipeline.tsx | 30+++++++++++++++++++++++++++++-
Aumtool/components/research/stages/EvidencePanel.tsx | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/LeadsPanel.tsx | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/VerifyPanel.tsx | 386+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/types.ts | 10++++++++++
Mumtool/docs/README.md | 2+-
Mumtool/docs/research.md | 34+++++++++++++++++++++++++++++++++-
Aumtool/e2e/case-stages.spec.ts | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/case-stages-fixture.mjs | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/editor-stub-case-stages.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub-import-page.mjs | 19+++++++++++++++----
Mumtool/e2e/fixtures/editor-stub-intake.mjs | 32++++++++++++++++++++++++++++++--
Mumtool/e2e/fixtures/editor-stub.mjs | 3+++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Mumtool/e2e/import-capture.spec.ts | 5+++--
Aumtool/lib/research/case-editor.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-evidence.ts | 316+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-findings-store.ts | 48++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-leads.ts | 376+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-stage-files.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-stage-hrefs.ts | 9+++++++++
Aumtool/lib/research/case-stages.test.ts | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-verify.ts | 370+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/playwright.config.ts | 3+++
65 files changed, 4507 insertions(+), 34 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -245,11 +245,15 @@ pnpm ops reextract-pages --json '{"slug":"old-blog","dryRun":true}' --wait - `reextract-pages` (the channel page's **Re-extract**) re-reads every stored body with the extractor it goes to now — no request — and replaces the records when anything changed. Offline with the editor stopped: `pnpm archilyzer wayback pages reextract <slug> --dry-run`. +- Site extractors read Google Docs, YouTube channel pages, X, Newgrounds (a user page, an art page, a movie page: + `ng-user`, `ng-art`, `ng-movie`), XenForo threads and Tumblr; every other page is the generic extractor's. A + channel imported before an extractor existed is put right by a re-extract. - 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. - A URL the Wayback Machine answers 403 for (while it answers others) is **excluded** — "excluded from the Wayback Machine (cause unknown)": `wayback-lookup` answers 403 with `refusal: "excluded"`, `import-page` and - `archive-lookup` carry the same code and sentence. + `archive-lookup` carry the same code and sentence, and `wayback-scan` marks that target excluded (its report's + `refusal`, the Captures tab's line) and goes on to the next one. ### Archived pages: the Wayback Machine and archive.today diff --git a/common/controller/casePipelineRun.ts b/common/controller/casePipelineRun.ts @@ -13,7 +13,11 @@ // // Stage 4 (the read) is lane B's: it writes findings.jsonl through appendFindings, as a person's rows do. +import { readFile } from "node:fs/promises"; +import path from "node:path"; import type { Paths } from "../lib/paths"; +import { CASE_FILES } from "../lib/research/caseTypes"; +import { evidenceRows } from "../lib/research/caseEvidence"; import type { CaseBatch, CaseDefinition, CaseStageRun, CoverageRow, DateCheck, FindingRow } from "../lib/research/caseTypes"; import { CasePipelineError, @@ -141,6 +145,22 @@ async function coverageLine(dir: string, def: CaseDefinition, paths: Paths | nul ].join(" "); } +/** evidence.json's rows (lane C's evidence stage); none when there is no file, and a file that does not parse is said. */ +async function readEvidenceRows(dir: string, log: (line: string) => void) { + let text: string; + try { + text = await readFile(/* turbopackIgnore: true */ path.join(dir, CASE_FILES.evidence), "utf8"); + } catch { + return []; + } + try { + return evidenceRows(JSON.parse(text)); + } catch (e) { + log(`${CASE_FILES.evidence} is not JSON (${(e as Error).message}): the Evidence section is left out`); + return []; + } +} + /** REPORT.md and REPORT.html from the merge and the summary, behind the privacy gate. */ export async function runExport(dir: string, caseId: string, title: string, by: By, o: { minRelevance?: number; paths?: Paths } = {}) { const def = await definitionOf(dir, caseId); @@ -158,7 +178,9 @@ export async function runExport(dir: string, caseId: string, title: string, by: ], def.privateNames.sha256, ); - const markdown = reportMarkdown({ title, summary, merged, coverage: await coverageLine(dir, def, o.paths ?? null) }); + // Lane C: the captures and forum attachments the case took (evidence.json), in an Evidence section. + const evidence = await readEvidenceRows(dir, log); + const markdown = reportMarkdown({ title, summary, merged, coverage: await coverageLine(dir, def, o.paths ?? null), evidence }); await writeReport(dir, markdown, reportHtml(markdown), def.privateNames.sha256); const shown = merged.sections.reduce((n, s) => n + s.rows.length, 0); log(`REPORT.md and REPORT.html: ${shown} findings in ${merged.sections.length} sections, ${merged.quarantined.length} quarantined`); diff --git a/common/controller/reextractPages.newgrounds.test.ts b/common/controller/reextractPages.newgrounds.test.ts @@ -0,0 +1,90 @@ +// Release 38 lane C: the raw captures a Wayback pages channel keeps are what +// make a new extractor worth having. A Newgrounds user page imported while +// only the generic extractor read it is STALE now, and `reextract-pages` +// turns its record into the Newgrounds extractor's, asking nobody anything. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/reextractPages.newgrounds.test.ts + +import test, { after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import type { Paths } from "../lib/paths"; +import { reextractPages } from "./reextractPages"; +import { readAllPosts, upsertPosts } from "../lib/posts-server"; +import { genericExtractor } from "../lib/waybackPages/extractors/generic"; +import { pageRecordId } from "../lib/waybackPages/types"; +import { draftToPost } from "../lib/waybackPages/toPost"; +import { listStoredCaptures, writeStoredCapture } from "../lib/waybackPages/store-server"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "reextract-ng-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); +const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths; + +const USER = "http://pocketfox.newgrounds.com/"; +const TS = "20140304120000"; +const HTML = readFileSync(new URL("../lib/waybackPages/extractors/__fixtures__/ng-user-2014.html", import.meta.url), "utf8"); + +test("a Newgrounds capture the generic extractor read is stale, and a re-extract reads it as a user page", async () => { + const root = path.join(paths.channelsDir, "ng-pages"); + await mkdir(root, { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ + handling: "transcribe", + name: "Newgrounds pages", + sourceKind: "social", + platform: "webpage", + socialHandle: "pocketfox.newgrounds.com", + url: "https://web.archive.org/web/*/pocketfox.newgrounds.com*", + wayback: { targets: [{ url: "pocketfox.newgrounds.com/", match: "prefix" }] }, + }), + ); + // As an import before this extractor existed stored it: the body, and the generic extractor's record. + const body = Buffer.from(HTML, "utf8"); + const capture = { originalUrl: USER, captureTs: TS }; + const old = genericExtractor.extract({ html: HTML, capture: { ...capture, waybackUrl: "", rawUrl: "" } }); + const oldPost = draftToPost(old[0], { channelSlug: "ng-pages", capture, extractor: { name: "generic", version: 1 } }); + await writeStoredCapture( + root, + { + ...capture, + mimetype: "text/html", + bytes: body.length, + sha256: createHash("sha256").update(body).digest("hex"), + fetchedAt: "2026-10-20T00:00:00.000Z", + extractor: "generic", + extractorVersion: 1, + records: [oldPost.id], + }, + body, + ); + await upsertPosts(root, [oldPost]); + + const dry = await reextractPages({ paths, slug: "ng-pages", dryRun: true }); + assert.equal(dry.ok, true, dry.error); + assert.equal(dry.stale, 1, "made by the generic extractor, now claimed by newgrounds"); + assert.equal(dry.written, false); + + const done = await reextractPages({ paths, slug: "ng-pages" }); + assert.equal(done.ok, true, done.error); + assert.equal(done.written, true); + const posts = await readAllPosts(root); + assert.equal(posts.length, 1); + const p = posts[0]; + assert.equal(p.id, pageRecordId(TS, USER), "a user page's record is the capture's, as before"); + assert.equal(p.page?.kind, "ng-user"); + assert.equal(p.page?.extractor, "newgrounds"); + assert.equal(p.author, "pocketfox"); + assert.match(p.text, /Location: Lake Erie/); + assert.match(p.text, /The lighthouse loop finally went up/); + const [entry] = await listStoredCaptures(root); + assert.equal(entry.capture.extractor, "newgrounds"); + + const again = await reextractPages({ paths, slug: "ng-pages" }); + assert.equal(again.stale, 0); + assert.equal(again.written, false); +}); diff --git a/common/controller/waybackScan.test.ts b/common/controller/waybackScan.test.ts @@ -205,3 +205,37 @@ test("the body and the job: refused before any job for a channel that is not a W assert.equal(result.pass, 3, "a full pass is a new pass"); assert.equal(result.complete, true); }); + +test("release 38 lane C: an excluded target is answered, not failed -- marked, and the next target goes on", async () => { + const paths = getPaths(); + const targets = [ + { url: "gone.example", match: "host" as const }, + { url: "blog.example", match: "host" as const }, + ]; + const wayback = { targets, collapse: "digest" as const, auto: false }; + await channel("blog-excluded", { targets }); + const fake = await startFakeWayback({ captures: SCAN_CAPTURES, excluded: ["gone.example"] }); + try { + const c = new WaybackClient({ fetch: fake.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }); + const lines: string[] = []; + const run = await runWaybackScan({ paths, slug: "blog-excluded", wayback, client: c, onLog: (l) => lines.push(l) }); + assert.equal(run.ok, true, run.error); + assert.equal(run.stopped, undefined); + assert.deepEqual(run.excluded, ["gone.example"]); + const [gone, blog] = run.targets; + assert.equal(gone.refusal, "excluded"); + assert.match(gone.error ?? "", /excluded from the Wayback Machine \(cause unknown\)/); + assert.equal(gone.complete, true); + assert.equal(gone.rows, 0); + assert.equal(blog.refusal, undefined); + assert.ok(blog.rows > 0, "the next target was listed"); + assert.ok(lines.some((l) => /excluded from the Wayback Machine \(cause unknown\)/.test(l)), "the log says so"); + const file = (await readWaybackScan(paths.channelsDir, "blog-excluded"))!; + assert.equal(file.targets[0].excluded, "excluded from the Wayback Machine (cause unknown)"); + // A new pass asks again: the mark is cleared when the pass starts. + const full = await runWaybackScan({ paths, slug: "blog-excluded", wayback, client: c, full: true }); + assert.deepEqual(full.excluded, ["gone.example"]); + } finally { + await fake.close(); + } +}); diff --git a/common/controller/waybackScan.ts b/common/controller/waybackScan.ts @@ -25,7 +25,7 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import { isSafeChannelSegment } from "../lib/citations/moments"; import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; -import { WAYBACK_ORIGIN, waybackClient } from "../lib/waybackClient"; +import { WAYBACK_EXCLUDED_PHRASE, WAYBACK_ORIGIN, isWaybackExcluded, waybackClient } from "../lib/waybackClient"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { keepCaptureUrl, @@ -118,6 +118,12 @@ export type WaybackScanTargetReport = { resumeKey?: string; // A dry run: what the next request for this target would be. next?: string; + // Release 38 lane C: the Wayback Machine answered 403 for this target's + // listing — "excluded from the Wayback Machine (cause unknown)". A fact about + // the URL, not an outage: the target is done for this pass and the run goes + // on to the next one. + refusal?: "excluded"; + error?: string; }; export type WaybackScanResult = { @@ -135,6 +141,8 @@ export type WaybackScanResult = { // Why the run stopped before every target's end: "row cap", "drained", // "cancelled", "request cap", or the refusal. stopped?: string; + // Release 38 lane C: the targets the Wayback Machine excludes (their URLs). + excluded?: string[]; error?: string; path?: string; }; @@ -188,7 +196,7 @@ export function startPass(file: WaybackScanFile, nowIso: string, incremental: bo file.passStartedAt = nowIso; const passFrom = incremental && !fresh ? cdxTsBefore(previous, PASS_OVERLAP_DAYS) : undefined; file.targets = file.targets.map((t): WaybackScanTarget => { - const { resumeKey: _r, completedAt: _c, passFrom: _p, ...rest } = t; + const { resumeKey: _r, completedAt: _c, passFrom: _p, excluded: _x, ...rest } = t; return { ...rest, complete: false, rows: 0, ...(passFrom ? { passFrom } : {}) }; }); } @@ -220,6 +228,7 @@ export async function runWaybackScan(opts: RunWaybackScanOpts): Promise<WaybackS { url: t.url, match: t.match, requests: 0, rows: 0, added: 0, complete: t.complete, ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}) }, ]), ); + const excluded: string[] = []; const result = (extra: Partial<WaybackScanResult> = {}): WaybackScanResult => ({ ok: true, slug: opts.slug, @@ -232,6 +241,7 @@ export async function runWaybackScan(opts: RunWaybackScanOpts): Promise<WaybackS added: [...reports.values()].reduce((n, r) => n + r.added, 0), totalRows: file.rows.length, complete: file.targets.every((t) => t.complete), + ...(excluded.length ? { excluded: [...excluded] } : {}), ...extra, }); @@ -280,6 +290,22 @@ export async function runWaybackScan(opts: RunWaybackScanOpts): Promise<WaybackS body = await client.cdxPage(url, opts.signal ? { signal: opts.signal } : {}); } catch (e) { if (opts.signal?.aborted) { stopped = "cancelled"; break outer; } + if (isWaybackExcluded(e)) { + // Release 38 lane C: an excluded target is answered, not failed — + // done for this pass (a new pass asks again), the next target goes on. + t.complete = true; + t.completedAt = now().toISOString(); + t.excluded = WAYBACK_EXCLUDED_PHRASE; + delete t.resumeKey; + r.complete = true; + r.refusal = "excluded"; + r.error = (e as Error).message; + delete r.resumeKey; + excluded.push(t.url); + log(` ${WAYBACK_EXCLUDED_PHRASE}: the listing answered HTTP 403; the next target goes on`); + await flush(); + break; + } error = e instanceof ArchiveOrgRequestError ? e.message : `the CDX request failed: ${(e as Error).message}`; stopped = error; break outer; diff --git a/common/lib/research/caseEvidence.ts b/common/lib/research/caseEvidence.ts @@ -0,0 +1,34 @@ +// A CASE'S EVIDENCE, as the export prints it (release 38 lane C, stage 10). `evidence.json` (CaseEvidence[]) is +// written by umtool's evidence stage (umtool/lib/research/case-evidence.ts); the export (casePipelineRun.ts +// runExport → casePipeline.ts reportMarkdown) lists it in an Evidence section with this. Pure, client-safe; the +// lines are the house markdown reportHtml reads (links only, no emphasis). +import { evidenceLabel, forumAttachmentLabel, isEvidenceKind, isEvidenceState, type CaseEvidence } from "./caseTypes"; + +const clean = (s: string) => String(s ?? "").replace(/\s+/g, " ").trim(); +const iso = (ts?: string) => (ts && /^\d{8}/.test(ts) ? `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : ""); + +/** The rows of an evidence.json value that are rows (anything else dropped). */ +export function evidenceRows(raw: unknown): CaseEvidence[] { + return (Array.isArray(raw) ? raw : []).filter( + (r): r is CaseEvidence => !!r && typeof r === "object" && typeof r.id === "string" && isEvidenceKind(r.kind) && isEvidenceState(r.state) && typeof r.url === "string", + ); +} + +/** One row as a report line: its label, its link, what it backs. */ +export function evidenceLine(r: CaseEvidence): string { + const backs = r.findings?.length ? ` (for ${r.findings.join(", ")})` : ""; + if (r.kind === "forum-attachment") { + const files = r.files?.length ? `, ${r.files.length} ${r.files.length === 1 ? "file" : "files"} captured` : r.state === "captured" ? "" : `, ${r.state}`; + return `- ${forumAttachmentLabel(r.position, r.post)} — [the post](${r.url})${files}${backs}`; + } + if (r.state === "excluded") return `- ${evidenceLabel(r)} — ${r.url}${r.at ? `, asked for ${iso(r.at)}` : ""}${backs}`; + if (r.state === "captured" && r.captureTs) return `- ${evidenceLabel(r)} — [${r.url}](https://web.archive.org/web/${r.captureTs}/${r.url})${backs}`; + const what = r.state === "failed" ? "Wayback capture failed" : "Wayback capture not taken yet"; + return `- ${what} — ${r.url}${r.at ? `, for ${iso(r.at)}` : ""}${r.message ? `: ${clean(r.message)}` : ""}${backs}`; +} + +/** The Evidence section (none when there is no evidence). */ +export function evidenceSection(rows: readonly CaseEvidence[]): string[] { + if (!rows.length) return []; + return ["## Evidence", "", "Captures and forum attachments the case took. A forum attachment is unverified: looked at, not vouched for.", "", ...rows.map(evidenceLine), ""]; +} diff --git a/common/lib/research/casePipeline.test.ts b/common/lib/research/casePipeline.test.ts @@ -7,7 +7,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { BATCH_LINE_MAX, NAME_WITHHELD, type CaseDefinition, type FindingRow } from "./caseTypes"; +import { BATCH_LINE_MAX, NAME_WITHHELD, type CaseDefinition, type CaseEvidence, type FindingRow } from "./caseTypes"; import { CasePipelineError, NAMING_RULE, @@ -285,6 +285,26 @@ test("mergeFindings: within 20 s on one recording is one finding (higher relevan assert.doesNotMatch(html, /<script/); }); +test("lane C: the export's Evidence section -- an excluded target, a capture, a forum attachment marked unverified; a finding's label", () => { + const d = def(); + const at = "2026-11-02T00:00:00.000Z"; + const quarantined = row({ row: "f6", slug: "forum", id: "p1", t: 0, relevance: 3, verify: { status: "quarantined", at: "x" }, evidence: [{ kind: "forum-attachment", url: "https://forum.example/p1", post: "70003", position: 3, evidence: "e3" }] }); + const m = mergeFindings(d, [quarantined], (r) => r.batch.replace(/-\d+-\d+$/, "")); + const evidence = [ + { id: "e1", kind: "wayback", url: "http://gone.example/", at: "20140304", state: "excluded", createdAt: at, updatedAt: at }, + { id: "e2", kind: "wayback", url: "http://page.example/a", at: "20140304", state: "captured", captureTs: "20140304120000", findings: ["f6"], createdAt: at, updatedAt: at }, + { id: "e3", kind: "forum-attachment", url: "https://forum.example/p1", slug: "forum", post: "70003", position: 3, state: "captured", files: ["minutes.png", "shot.png"], findings: ["f6"], createdAt: at, updatedAt: at }, + ] as const; + const md = reportMarkdown({ title: "Wren", summary: null, merged: m, coverage: "Scope.", evidence: evidence as unknown as CaseEvidence[] }); + assert.match(md, /## Evidence\n\n.+\n\n- excluded from the Wayback Machine \(cause unknown\) — http:\/\/gone\.example\/, asked for 2014-03-04\n/); + assert.match(md, /- Wayback capture, 2014-03-04 — \[http:\/\/page\.example\/a\]\(https:\/\/web\.archive\.org\/web\/20140304120000\/http:\/\/page\.example\/a\) \(for f6\)/); + assert.match(md, /- forum attachment, post #3, unverified — \[the post\]\(https:\/\/forum\.example\/p1\), 2 files captured \(for f6\)/); + assert.match(md, /## Evidence[\s\S]*## Coverage/); + assert.match(md, /## Quarantined[\s\S]*row f6\. quarantined\. forum attachment, post #3, unverified\./, "the finding's own line names its post by its #N"); + assert.doesNotMatch(reportMarkdown({ title: "Wren", summary: null, merged: m, coverage: "Scope." }), /## Evidence/); + assert.match(reportHtml(md), /forum attachment, post #3, unverified/); +}); + test("dateChecks: uploads around and after each key date, and the sentence", () => { const d = def({ keyDates: [{ date: "2021-03-01", label: "the shop closes" }] }); const uploads = [ diff --git a/common/lib/research/casePipeline.ts b/common/lib/research/casePipeline.ts @@ -22,6 +22,7 @@ import { QUOTE_WORDS_MAX, VERIFY_STATUSES, WINDOW_TRACKS, + forumAttachmentLabel, isCaseStatus, isFindingBy, isRelevance, @@ -33,12 +34,14 @@ import { type CaseBatch, type CaseDefinition, type CaseEra, + type CaseEvidence, type CaseSummaryText, type DateCheck, type FindingRow, type ReaderGroup, type WindowTrack, } from "./caseTypes"; +import { evidenceSection } from "./caseEvidence"; /** A refusal a caller can fix, with the HTTP status a route answers it with. */ export class CasePipelineError extends Error { @@ -829,7 +832,8 @@ export function findingLine(r: FindingRow): string { asides.push(`row ${r.row}`); if (r.quoteCheck === "not-found") asides.push("quote not found in the window's captions: check it"); if (r.verify && r.verify.status !== "unverified") asides.push(r.verify.status); - for (const e of r.evidence ?? []) if (e.kind === "forum-attachment") asides.push(`forum attachment${e.post ? `, post #${e.post}` : ""}, unverified`); + // One label everywhere (caseTypes.ts forumAttachmentLabel): the post's "#N" in its thread when known. + for (const e of r.evidence ?? []) if (e.kind === "forum-attachment") asides.push(forumAttachmentLabel(e.position, e.post)); lines.push(` Note: ${asides.join(". ")}.`); return lines.join("\n"); } @@ -840,6 +844,8 @@ export type ReportContext = { merged: MergeResult; /** One line on what was read: the scope, the candidates, the batches. */ coverage: string; + /** Lane C: evidence.json's rows, listed in an Evidence section (caseEvidence.ts). */ + evidence?: readonly CaseEvidence[]; }; /** The merged report as cited markdown. */ @@ -866,6 +872,7 @@ export function reportMarkdown(c: ReportContext): string { for (const r of c.merged.quarantined) out.push(findingLine(r)); out.push(""); } + out.push(...evidenceSection(c.evidence ?? [])); out.push("## Coverage", "", clean(c.coverage), ""); return out.join("\n"); } diff --git a/common/lib/research/caseTypes.test.ts b/common/lib/research/caseTypes.test.ts @@ -130,3 +130,33 @@ test("private names: stored as hashes, matched on words and 2–3-word phrases, assert.equal(privateNameHits("then Jane posted it", definition.privateNames.sha256), 0); assert.equal(privateNameHits("anything", []), 0); }); + +test("lane C: the evidence labels, the excluded sentence the editor says, and a redaction that never names", async () => { + const { EXCLUDED_SENTENCE, evidenceLabel, forumAttachmentLabel, isEvidenceKind, isEvidenceState } = await import("./caseTypes"); + const { WAYBACK_EXCLUDED_PHRASE } = await import("../waybackClient"); + const { withholdPrivateNames } = await import("./casePrivacy-server"); + const redactPrivateNames = (t: string, h: string[]) => { + const r = withholdPrivateNames(t, h); + return { text: r.text, hits: r.replaced }; + }; + assert.equal(EXCLUDED_SENTENCE, WAYBACK_EXCLUDED_PHRASE, "one sentence in every surface"); + assert.equal(forumAttachmentLabel(14, "880011"), "forum attachment, post #14, unverified"); + assert.equal(forumAttachmentLabel(undefined, "880011"), "forum attachment, post #880011, unverified"); + assert.equal(evidenceLabel({ kind: "forum-attachment", position: 3 }), "forum attachment, post #3, unverified"); + assert.equal(evidenceLabel({ kind: "wayback", state: "excluded" }), EXCLUDED_SENTENCE); + assert.equal(evidenceLabel({ kind: "wayback", captureTs: "20140304120000" }), "Wayback capture, 2014-03-04"); + assert.ok(isEvidenceKind("wayback") && isEvidenceState("excluded")); + assert.equal(isEvidenceState("done"), false); + + const hashes = definition.privateNames.sha256; + const r = redactPrivateNames("then Jane Q Private posted it, and @jane posted too", hashes); + assert.equal(r.text, "then [name withheld] posted it, and @jane posted too"); + assert.equal(r.hits, 1); + const handle = redactPrivateNames("see x.com/QuietHandle for more", [privateNameHash("quiethandle")]); + assert.equal(handle.text, "see x.com/[name withheld] for more"); + assert.deepEqual(redactPrivateNames("nothing here", []), { text: "nothing here", hits: 0 }); + // A possessive does not slip a name past the gate, nor past a redaction. + assert.equal(privateNameHits("ask QuietHandle’s friend", [privateNameHash("quiethandle")]), 1); + assert.equal(privateNameHits("Jane Q Private's post", hashes), 1); + assert.equal(redactPrivateNames("found QuietHandle's account", [privateNameHash("quiethandle")]).text, "found [name withheld]'s account"); +}); diff --git a/common/lib/research/caseTypes.ts b/common/lib/research/caseTypes.ts @@ -17,6 +17,7 @@ // <case>/findings.jsonl FindingRow, one per line, appended (stage 4; verify and merge rewrite whole) // <case>/leads.json CaseLead[] (stage 8) // <case>/date-checks.json DateCheck[] (stage 9) +// <case>/evidence.json CaseEvidence[] (stage 10; lane C's extension) // <case>/summary.json CaseSummaryText: the report's summary, by hand or a model's draft (stage 5) // <case>/REPORT.md, REPORT.html the merged report as exported (stage 5, behind the privacy gate) // <case>/stages.json CaseStageRuns: each stage's last run (state, counts, log), CLI or page @@ -38,6 +39,7 @@ export const CASE_FILES = Object.freeze({ findings: "findings.jsonl", leads: "leads.json", dateChecks: "date-checks.json", + evidence: "evidence.json", summary: "summary.json", report: "REPORT.md", reportHtml: "REPORT.html", @@ -235,10 +237,34 @@ export type FindingVerify = { note?: string; /** "Corrected by hand" keeps what the reader wrote. */ original?: { quote: string; speaker?: string }; + /** Lane C: the last audio check -- the window transcribed through the editor and its words diffed with the quote. */ + audio?: AudioCheck; +}; + +/** An audio check's outcome: what the worker heard, and how much of the quote it holds. */ +export type AudioCheck = { + at: string; + /** The editor's transcribe-file job. */ + job: string; + /** The window's transcript (private names already NAME_WITHHELD). */ + text: string; + /** The quote's words found in order in the transcript, of all its words. */ + matched: number; + words: number; + /** The worker that heard it, as the editor names it. */ + worker?: string; }; /** A forum post's attachment or screenshot, shown everywhere as "forum attachment, post #N, unverified". */ -export type FindingEvidence = { kind: "forum-attachment" | "wayback"; post?: string; url: string; capturedAt?: string }; +export type FindingEvidence = { + kind: "forum-attachment" | "wayback"; + post?: string; + url: string; + capturedAt?: string; + /** Lane C: the CaseEvidence row it came from, and a forum post's position in its thread (the "#N"). */ + evidence?: string; + position?: number; +}; export type FindingRow = { /** `f<n>`: unique in the case, never reused. */ @@ -312,6 +338,68 @@ export type CaseLead = { channel?: string; }; +// --------------------------------------------------------------------------------------------------------------- +// Stage 10: evidence capture (lane C's extension: the contract named FindingEvidence but no file for the captures) + +/** Wayback captures at chosen dates; a forum post's attachments or screenshot. */ +export const EVIDENCE_KINDS = ["wayback", "forum-attachment"] as const; +export type EvidenceKind = (typeof EVIDENCE_KINDS)[number]; + +/** + * planned: not asked yet. queued: the editor's job is running. captured: held. excluded: the Wayback Machine answered + * 403 for the URL (EXCLUDED_SENTENCE). failed: the job or the editor said no (its words in `message`). + */ +export const EVIDENCE_STATES = ["planned", "queued", "captured", "excluded", "failed"] as const; +export type EvidenceState = (typeof EVIDENCE_STATES)[number]; + +export type CaseEvidence = { + /** `e<n>`: unique in the case, never reused. */ + id: string; + kind: EvidenceKind; + /** wayback: the page's own URL. forum-attachment: the post's permalink. */ + url: string; + /** wayback: the date chosen, YYYYMMDD (the capture nearest it). */ + at?: string; + /** The channel it went into (a Wayback pages channel), or the forum channel the post is in. */ + slug?: string; + /** forum-attachment: the post's id, and its "#N" in the thread when the forum gives one. */ + post?: string; + position?: number; + state: EvidenceState; + /** The editor's job (import-page, capture-posts). */ + job?: string; + /** wayback: the capture landed on, and the records it made. */ + captureTs?: string; + records?: string[]; + /** forum-attachment: the files captured, relative to the channel's posts-media/<post>/. */ + files?: string[]; + /** The refusal's code ("excluded", …) and the sentence shown for it. */ + refusal?: string; + message?: string; + /** The finding rows it is evidence for. */ + findings?: string[]; + note?: string; + createdAt: string; + updatedAt: string; +}; + +/** What a Wayback 403 means, in every surface (the editor's WAYBACK_EXCLUDED_PHRASE; a test keeps them equal). */ +export const EXCLUDED_SENTENCE = "excluded from the Wayback Machine (cause unknown)"; + +/** A forum attachment's label, in every surface: never shown as anything but unverified. */ +export function forumAttachmentLabel(position?: number | null, post?: string | null): string { + const n = typeof position === "number" && position > 0 ? String(position) : post ? post : "?"; + return `forum attachment, post #${n}, unverified`; +} + +/** The label a finding's evidence or an evidence row carries. */ +export function evidenceLabel(e: { kind: EvidenceKind; position?: number; post?: string; capturedAt?: string; captureTs?: string; state?: EvidenceState }): string { + if (e.kind === "forum-attachment") return forumAttachmentLabel(e.position, e.post); + if (e.state === "excluded") return EXCLUDED_SENTENCE; + const ts = e.captureTs ?? e.capturedAt; + return ts && /^\d{8}/.test(ts) ? `Wayback capture, ${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : "Wayback capture"; +} + export type DateCheck = { /** The key date checked, YYYY-MM-DD. */ date: string; @@ -331,6 +419,8 @@ const isOneOf = typeof value === "string" && (list as readonly string[]).includes(value); export const isVerifyStatus = isOneOf(VERIFY_STATUSES); +export const isEvidenceKind = isOneOf(EVIDENCE_KINDS); +export const isEvidenceState = isOneOf(EVIDENCE_STATES); export const isLeadDisposition = isOneOf(LEAD_DISPOSITIONS); export const isFindingBy = isOneOf(FINDING_BY); export const isCaseStatus = isOneOf(CASE_STATUSES); diff --git a/common/lib/research/privateNames-server.ts b/common/lib/research/privateNames-server.ts @@ -14,3 +14,4 @@ export function privateNameHits(text: string, hashes: readonly string[]): number const set = new Set(hashes); return privateNameCandidates(text).filter((c) => set.has(privateNameHash(c))).length; } + diff --git a/common/lib/research/wordDiff.test.ts b/common/lib/research/wordDiff.test.ts @@ -0,0 +1,32 @@ +// Release 38 lane C: the audio check's word diff -- the quote's words aligned with what the worker heard. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/research/wordDiff.test.ts +import test from "node:test"; +import assert from "node:assert/strict"; +import { heardShare, quoteWordDiff } from "./wordDiff"; + +test("a quote heard whole: every word the same, the window's other words left out", () => { + const d = quoteWordDiff("the lighthouse keeper called in", "okay so the lighthouse keeper called in last night"); + assert.equal(d.matched, 5); + assert.equal(d.words, 5); + assert.deepEqual(d.ops.map((o) => o.op), ["same", "same", "same", "same", "same"]); + assert.equal(heardShare(d), 1); +}); + +test("a quote the captions rewrote: the missing and the extra words, in place", () => { + const d = quoteWordDiff("the lighthouse keeper rang in", "and then the lighthouse keeper called in again"); + assert.equal(d.matched, 4); + assert.deepEqual( + d.ops.map((o) => `${o.op[0]}:${o.word}`), + ["s:the", "s:lighthouse", "s:keeper", "m:rang", "e:called", "s:in"], + ); +}); + +test("punctuation and case do not count; nothing heard is all missing", () => { + assert.equal(quoteWordDiff("How much was it? You cut it all,", "how much was it you cut it all").matched, 8); + const none = quoteWordDiff("not said at all", ""); + assert.equal(none.matched, 0); + assert.deepEqual(none.ops.map((o) => o.op), ["missing", "missing", "missing", "missing"]); + assert.equal(quoteWordDiff("", "words").words, 0); + assert.equal(quoteWordDiff("alpha beta", "gamma delta").matched, 0); +}); diff --git a/common/lib/research/wordDiff.ts b/common/lib/research/wordDiff.ts @@ -0,0 +1,63 @@ +// A finding's quote against what was heard (release 38 lane C, stage 7's audio check): the quote's words aligned with +// a transcript's (a window transcribed through the editor, or another caption track) by longest common subsequence. +// Pure and client-safe: the case page draws the diff, the MCP's case_verify can say the same numbers. +import { wordsOf } from "../report/quoteWords"; + +export type WordOp = { op: "same" | "missing" | "extra"; word: string }; + +export type WordDiff = { + /** The quote's words found in order in the transcript. */ + matched: number; + /** The quote's words. */ + words: number; + /** + * The alignment over the stretch of the transcript the quote matched: `missing` is a quote word the transcript does + * not have there, `extra` a transcript word the quote does not have. Transcript words before the first match and + * after the last are left out (the window is wider than the quote). + */ + ops: WordOp[]; +}; + +const split = (s: string) => wordsOf(s).split(" ").filter(Boolean); + +/** How much of `quote` the `heard` text holds, in order, and where they differ. */ +export function quoteWordDiff(quote: string, heard: string): WordDiff { + const q = split(quote); + const h = split(heard); + const n = q.length; + const m = h.length; + if (n === 0) return { matched: 0, words: 0, ops: [] }; + if (m === 0) return { matched: 0, words: n, ops: q.map((word) => ({ op: "missing", word })) }; + // lcs[i][j]: the LCS of q[i..] and h[j..]. + const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0)); + for (let i = n - 1; i >= 0; i--) { + for (let j = m - 1; j >= 0; j--) { + lcs[i][j] = q[i] === h[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const ops: WordOp[] = []; + let i = 0; + let j = 0; + while (i < n && j < m) { + if (q[i] === h[j]) { + ops.push({ op: "same", word: q[i] }); + i++; + j++; + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + ops.push({ op: "missing", word: q[i++] }); + } else { + ops.push({ op: "extra", word: h[j++] }); + } + } + while (i < n) ops.push({ op: "missing", word: q[i++] }); + // Trim the transcript's words outside the matched stretch. + const firstSame = ops.findIndex((o) => o.op === "same"); + if (firstSame < 0) return { matched: 0, words: n, ops: q.map((word) => ({ op: "missing", word })) }; + let lastSame = ops.length - 1; + while (lastSame > 0 && ops[lastSame].op !== "same") lastSame--; + const trimmed = ops.filter((o, k) => o.op !== "extra" || (k > firstSame && k < lastSame)); + return { matched: lcs[0][0], words: n, ops: trimmed }; +} + +/** The share of the quote heard, 0–1. */ +export const heardShare = (d: Pick<WordDiff, "matched" | "words">): number => (d.words ? d.matched / d.words : 0); diff --git a/common/lib/waybackPages/extractors/__fixtures__/ng-art-2014.html b/common/lib/waybackPages/extractors/__fixtures__/ng-art-2014.html @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Newgrounds art page (/art/view/<user>/<slug>), 2014 layout. Invented, every word. --> +<html lang="en"> +<head> +<title>Lighthouse at Dusk by pocketfox on Newgrounds</title> +<meta property="og:title" content="Lighthouse at Dusk"> +<meta property="og:description" content="Painted over three nights."> +<meta itemprop="datePublished" content="2014-03-03T15:22:00-05:00"> +</head> +<body> +<div id="header"><a href="http://www.newgrounds.com/">Newgrounds</a></div> +<div class="column wide"> + <div class="pod"> + <div class="pod-head"><h2 itemprop="name">Lighthouse at Dusk</h2></div> + <div class="pod-body"><div class="image"><img src="https://web.archive.org/web/20140310000000im_/http://art.ngfiles.com/images/123/pocketfox_lighthouse-at-dusk.png" alt="Lighthouse at Dusk"></div></div> + </div> + <div class="pod"> + <div class="pod-head"><h2>Author Comments</h2></div> + <div class="pod-body"><div id="author_comments"><p>Painted over three nights. The keeper's window is the only warm thing in it.</p><p>Prints: <a href="http://pocketfox.tumblr.com/prints">pocketfox.tumblr.com/prints</a></p></div></div> + </div> +</div> +<div class="column thin"> + <div class="pod"> + <div class="pod-body"> + <div class="item-user"><div class="item-details-main"><h4><a href="http://pocketfox.newgrounds.com/">pocketfox</a></h4></div></div> + <dl class="sidestats"><dt>Score</dt><dd>4.21 / 5.00</dd><dt>Uploaded</dt><dd>Mar 3, 2014</dd><dd>| 3:22 PM EST</dd><dt>Views</dt><dd>1,024</dd></dl> + <dl class="sidestats"><dt>Tags</dt><dd><ul class="tags"><li><a href="/search/conduct/art?match=tags&amp;tags=lighthouse">lighthouse</a></li><li><a href="/search/conduct/art?match=tags&amp;tags=harbor">harbor</a></li></ul></dd></dl> + </div> + </div> +</div> +<div id="footer">© Newgrounds</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/ng-movie-2014.html b/common/lib/waybackPages/extractors/__fixtures__/ng-movie-2014.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Newgrounds movie page (/portal/view/<id>), 2014 layout. Invented, every word. --> +<html lang="en"> +<head> +<title>Lighthouse Loop</title> +<meta property="og:title" content="Lighthouse Loop"> +<meta name="description" content="A short loop of a lighthouse."> +</head> +<body> +<div id="header"><a href="http://www.newgrounds.com/">Newgrounds</a></div> +<div class="column wide"> + <div class="pod"> + <div class="pod-head"><h2 itemprop="name">Lighthouse Loop</h2></div> + <div class="pod-body"><div id="embed_wrapper"><object data="http://uploads.ungrounded.net/634000/634512_lighthouse.swf"><embed src="http://uploads.ungrounded.net/634000/634512_lighthouse.swf"></object></div></div> + </div> + <div class="pod"> + <div class="pod-head"><h2>Author Comments</h2></div> + <div class="pod-body"><div id="author_comments">Forty seconds of a lighthouse. Sound by <a href="http://tidewater.newgrounds.com/">tidewater</a>.</div></div> + </div> +</div> +<div class="column thin"> + <div class="pod"><div class="pod-body"> + <div class="authorlinks"><div class="item-user"><h4><a href="http://pocketfox.newgrounds.com/">pocketfox</a></h4></div><div class="item-user"><h4><a href="http://tidewater.newgrounds.com/">tidewater</a></h4></div></div> + <dl class="sidestats"><dt>Uploaded</dt><dd>Feb 27, 2014</dd><dd>| 9:05 PM EST</dd><dt>Views</dt><dd>8,812</dd></dl> + </div></div> +</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/ng-user-2010.html b/common/lib/waybackPages/extractors/__fixtures__/ng-user-2010.html @@ -0,0 +1,19 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Newgrounds user page in the older layout (a podtop heading and a podcontent body side by side). Invented user, every word. --> +<html> +<head><title>Newgrounds.com — pocketfox's Profile</title></head> +<body> +<div id="topnav"><a href="http://www.newgrounds.com/">Home</a></div> +<div class="two3"> + <div class="podtop"><h2 class="profile">pocketfox's Profile</h2></div> + <div class="podcontent"> + <p>Harbors, boats, and the odd lighthouse.</p> + <dl><dt>Location:</dt><dd>Lake Erie</dd><dt>Joined:</dt><dd>3/4/09</dd></dl> + </div> + <div class="podtop"><h2>Recent Submissions</h2></div> + <div class="podcontent"> + <ul><li><a href="http://www.newgrounds.com/portal/view/634512">Lighthouse Loop</a></li></ul> + </div> +</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/ng-user-2014.html b/common/lib/waybackPages/extractors/__fixtures__/ng-user-2014.html @@ -0,0 +1,69 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Newgrounds user page in the 2012–2017 layout (pods with a pod-head and a pod-body). Invented user, every word. --> +<html lang="en"> +<head> +<title>pocketfox on Newgrounds</title> +<meta property="og:title" content="pocketfox"> +<meta property="og:description" content="pocketfox's profile on Newgrounds."> +<link rel="stylesheet" href="//css.ngfiles.com/ng_publish.css"> +</head> +<body> +<!-- BEGIN WAYBACK TOOLBAR INSERT --><div id="wm-ipp-base">toolbar</div><!-- END WAYBACK TOOLBAR INSERT --> +<div id="header"><div class="navigation"><a href="https://web.archive.org/web/20140304120000/http://www.newgrounds.com/">Newgrounds</a> <a href="/portal">Movies</a> <a href="/games">Games</a> <a href="/art">Art</a></div></div> +<div id="main"> + <div class="user-header"> + <div class="user-header-icon"><img src="https://web.archive.org/web/20140304120000im_/http://aicon.ngfiles.com/123/1234567.png" alt="pocketfox"></div> + <div class="user-header-name"><h1><a href="http://pocketfox.newgrounds.com/">pocketfox</a></h1></div> + <div class="user-header-links"><a href="http://pocketfox.newgrounds.com/news/">News</a> <a href="http://pocketfox.newgrounds.com/movies/">Movies</a> <a href="http://pocketfox.newgrounds.com/art/">Art</a> <a href="http://pocketfox.newgrounds.com/fans/">Fans</a></div> + </div> + <div class="column thin"> + <div class="pod"> + <div class="pod-head"><h2 class="user">Profile</h2></div> + <div class="pod-body"> + <div class="ql-body">I draw harbors and the boats in them. Short loops, mostly.</div> + <dl class="stats-general"> + <dt>Age, Gender</dt><dd>24, Male</dd> + <dt>Location</dt><dd>Lake Erie</dd> + <dt>Joined on</dt><dd>3/4/09</dd> + <dt>Job</dt><dd>Sign painter</dd> + </dl> + </div> + </div> + <div class="pod"> + <div class="pod-head"><h2>Contact Info / Websites</h2></div> + <div class="pod-body"> + <ul class="links"> + <li><a href="https://web.archive.org/web/20140304120000/http://twitter.com/pocketfoxdraws">twitter.com/pocketfoxdraws</a></li> + <li><a href="http://pocketfox.tumblr.com/">pocketfox.tumblr.com</a></li> + </ul> + </div> + </div> + <div class="pod"> + <div class="pod-head"><h2>Stats</h2></div> + <div class="pod-body"> + <dl class="stats-general"><dt>Level</dt><dd>21</dd><dt>Exp Points</dt><dd>1,234 / 1,600</dd><dt>Fans</dt><dd>312</dd></dl> + </div> + </div> + </div> + <div class="column wide"> + <div class="pod"> + <div class="pod-head"><h2>Latest News</h2></div> + <div class="pod-body"> + <div class="blog-post"> + <h3><a href="http://pocketfox.newgrounds.com/news/post/880011">Harbor loop is up</a></h3> + <span class="date">Mar 1, 2014</span> + <div class="blog-body">The lighthouse loop finally went up. Thanks for the votes.</div> + </div> + </div> + </div> + <div class="pod"> + <div class="pod-head"><h2>Art</h2></div> + <div class="pod-body"> + <a href="http://www.newgrounds.com/art/view/pocketfox/lighthouse-at-dusk" title="Lighthouse at Dusk"><img src="https://web.archive.org/web/20140304120000im_/http://art.ngfiles.com/thumbnails/123/pocketfox_lighthouse.png" alt="Lighthouse at Dusk"></a> + </div> + </div> + </div> +</div> +<div id="footer"><p>© Copyright 1995-2014 Newgrounds, Inc.</p></div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/generic.ts b/common/lib/waybackPages/extractors/generic.ts @@ -1,6 +1,6 @@ // THE GENERIC EXTRACTOR (release 37 S1): any captured page as ONE record — its // readable text, title, author, date, links and images — for every capture no -// site extractor claims (articles, personal sites, Newgrounds pages, a group's +// site extractor claims (articles, personal sites, a group's // old site). Pure: no network, no disk, no clock (a PageExtractor). // // What it does, in order: diff --git a/common/lib/waybackPages/extractors/index.test.ts b/common/lib/waybackPages/extractors/index.test.ts @@ -34,6 +34,10 @@ const CASES: [html: string, url: string, expected: string | null][] = [ [fixture("yt-about-2019-polymer.html"), "https://www.youtube.com/channel/UCteapot0000000000000001/about", "yt-about"], [fixture("yt-channel-2021.html"), "https://www.youtube.com/c/TeapotChannel", "yt-about"], [fixture("yt-about-2024-handle.html"), "https://www.youtube.com/@TeapotChannel/about", "yt-about"], + [fixture("ng-user-2014.html"), "http://pocketfox.newgrounds.com/", "newgrounds"], + [fixture("ng-user-2010.html"), "http://pocketfox.newgrounds.com/", "newgrounds"], + [fixture("ng-art-2014.html"), "http://www.newgrounds.com/art/view/pocketfox/lighthouse-at-dusk", "newgrounds"], + [fixture("ng-movie-2014.html"), "http://www.newgrounds.com/portal/view/634512", "newgrounds"], // Pages no site extractor claims: an article, a personal site, a video page. [`<!DOCTYPE html><html><head><title>A story</title></head><body><article><h1>A story</h1><p>Words.</p></article></body></html>`, "https://news.example/2014/05/a-story", null], [`<html><body><h1>My homepage</h1><a href="/post/12">a post</a></body></html>`, "http://home.example/", null], @@ -46,8 +50,8 @@ test("the registry sends each capture to its extractor, and an unknown page to n for (const [html, url, expected] of CASES) assert.equal(pick(html, url), expected, url); }); -test("the registry: five extractors, unique names, version 1, most specific first", () => { - assert.deepEqual(SITE_EXTRACTORS.map((e) => e.name), ["gdoc", "yt-about", "x", "xenforo", "tumblr"]); +test("the registry: six extractors, unique names, version 1, most specific first", () => { + assert.deepEqual(SITE_EXTRACTORS.map((e) => e.name), ["gdoc", "yt-about", "x", "newgrounds", "xenforo", "tumblr"]); for (const e of SITE_EXTRACTORS) assert.equal(e.version, 1); }); diff --git a/common/lib/waybackPages/extractors/index.ts b/common/lib/waybackPages/extractors/index.ts @@ -4,18 +4,20 @@ import type { PageExtractor } from "../types"; import { gdocExtractor } from "./gdoc"; +import { newgroundsExtractor } from "./newgrounds"; import { tumblrExtractor } from "./tumblr"; import { xExtractor } from "./x"; import { xenforoExtractor } from "./xenforo"; import { ytAboutExtractor } from "./ytAbout"; -// Most specific first: the three that match by host (Google Docs, YouTube, -// X), then XenForo by its markup on any host, then Tumblr (its own host, or -// a custom domain whose markup is a Tumblr theme). +// Most specific first: the four that match by host (Google Docs, YouTube, +// X, Newgrounds), then XenForo by its markup on any host, then Tumblr (its +// own host, or a custom domain whose markup is a Tumblr theme). export const SITE_EXTRACTORS: readonly PageExtractor[] = [ gdocExtractor, ytAboutExtractor, xExtractor, + newgroundsExtractor, xenforoExtractor, tumblrExtractor, ]; diff --git a/common/lib/waybackPages/extractors/newgrounds.test.ts b/common/lib/waybackPages/extractors/newgrounds.test.ts @@ -0,0 +1,124 @@ +// Release 38 lane C: the Newgrounds extractor over synthetic captures in +// Newgrounds' two layouts — a user page's pods read whole (where the generic +// extractor keeps one block), an art page and a movie page as items with +// stable ids, a page with nothing readable as a whole-page shell — and which +// Newgrounds URLs it claims. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/newgrounds.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractNewgrounds, newgroundsExtractor, newgroundsPageOf } from "./newgrounds"; +import { genericExtractor } from "./generic"; +import { chooseExtractor } from "../extract"; +import { captureOf, fixture } from "./__fixtures__/capture"; + +const USER = "http://pocketfox.newgrounds.com/"; +const ART = "http://www.newgrounds.com/art/view/pocketfox/lighthouse-at-dusk"; +const MOVIE = "http://www.newgrounds.com/portal/view/634512"; + +test("which URLs are Newgrounds pages: a user's root, an art view, a portal view — nothing else", () => { + const of = (u: string) => newgroundsPageOf(new URL(u)); + assert.deepEqual(of(USER), { kind: "ng-user", user: "pocketfox" }); + assert.deepEqual(of("https://PocketFox.newgrounds.com"), { kind: "ng-user", user: "pocketfox" }); + assert.deepEqual(of(ART), { kind: "ng-art", user: "pocketfox", slug: "lighthouse-at-dusk" }); + assert.deepEqual(of(`${MOVIE}/`), { kind: "ng-movie", id: "634512" }); + for (const u of [ + "http://www.newgrounds.com/", + "http://www.newgrounds.com/portal", + "http://pocketfox.newgrounds.com/news/post/880011", + "http://uploads.ungrounded.net/634000/634512_lighthouse.swf", + "http://art.newgrounds.com/", + "http://newgrounds.com.example/", + "https://www.youtube.com/user/pocketfox", + ]) { + assert.equal(of(u), null, u); + } + assert.equal(newgroundsExtractor.matches(new URL(USER), ""), true); + assert.equal(newgroundsExtractor.matches(new URL("http://www.newgrounds.com/"), ""), false); +}); + +test("a 2014 user page: every pod read, its stats as pairs, its links, and no Wayback chrome", () => { + const [d, ...rest] = extractNewgrounds({ html: fixture("ng-user-2014.html"), capture: captureOf(USER, "20140304120000") }); + assert.equal(rest.length, 0); + assert.equal(d.kind, "ng-user"); + assert.equal(d.itemId, undefined, "each capture of a user page is a version of it"); + assert.equal(d.author, "pocketfox"); + assert.equal(d.authorName, "pocketfox"); + assert.equal(d.noContent, undefined); + for (const line of [ + "Profile", + "I draw harbors and the boats in them. Short loops, mostly.", + "Age, Gender: 24, Male", + "Location: Lake Erie", + "Joined on: 3/4/09", + "Contact Info / Websites", + "Exp Points: 1,234 / 1,600", + "Latest News", + "The lighthouse loop finally went up. Thanks for the votes.", + ]) { + assert.ok(d.text.includes(line), `has "${line}"`); + } + assert.ok(!/toolbar|Copyright|Movies Games/.test(d.text), "no toolbar, footer or navigation"); + assert.ok(d.links.includes("http://twitter.com/pocketfoxdraws"), "a Wayback-rewritten link, unwrapped"); + assert.ok(d.links.includes("http://pocketfox.tumblr.com/")); + assert.ok(d.links.includes("http://pocketfox.newgrounds.com/news/post/880011")); + assert.ok(d.links.includes(ART)); + + // The generic extractor on the same capture reads much less of it. + const g = genericExtractor.extract({ html: fixture("ng-user-2014.html"), capture: captureOf(USER, "20140304120000") })[0]; + assert.ok(g.text.length < d.text.length / 2, `generic ${g.text.length} chars vs ${d.text.length}`); +}); + +test("the older layout: a podtop heading and its podcontent sibling", () => { + const [d] = extractNewgrounds({ html: fixture("ng-user-2010.html"), capture: captureOf(USER, "20100601000000") }); + assert.equal(d.kind, "ng-user"); + assert.match(d.text, /pocketfox's Profile\nHarbors, boats, and the odd lighthouse\./); + assert.match(d.text, /Location: Lake Erie/); + assert.match(d.text, /Recent Submissions/); + assert.equal(d.title, "pocketfox's Profile"); + assert.ok(d.links.includes(MOVIE)); +}); + +test("an art page: one item by user and slug, its comments, image, tags and date", () => { + const [d, ...rest] = extractNewgrounds({ html: fixture("ng-art-2014.html"), capture: captureOf(ART, "20140310000000") }); + assert.equal(rest.length, 0); + assert.equal(d.kind, "ng-art"); + assert.equal(d.itemId, "ng-art-pocketfox-lighthouse-at-dusk"); + assert.equal(d.url, "https://www.newgrounds.com/art/view/pocketfox/lighthouse-at-dusk"); + assert.equal(d.title, "Lighthouse at Dusk"); + assert.equal(d.author, "pocketfox"); + assert.equal(d.publishedAt, "2014-03-03T20:22:00.000Z", "datePublished, its zone kept"); + assert.match(d.text, /^Lighthouse at Dusk\nPainted over three nights\. The keeper's window is the only warm thing in it\./); + assert.deepEqual(d.tags, ["lighthouse", "harbor"]); + assert.deepEqual(d.media, [{ kind: "image", url: "http://art.ngfiles.com/images/123/pocketfox_lighthouse-at-dusk.png", name: "Lighthouse at Dusk" }]); + assert.ok(d.links.includes("http://pocketfox.tumblr.com/prints")); +}); + +test("a movie page: one item by id, credited to the first author box, its file linked, the printed date read", () => { + const [d] = extractNewgrounds({ html: fixture("ng-movie-2014.html"), capture: captureOf(MOVIE, "20140301000000") }); + assert.equal(d.kind, "ng-movie"); + assert.equal(d.itemId, "ng-movie-634512"); + assert.equal(d.url, "https://www.newgrounds.com/portal/view/634512"); + assert.equal(d.author, "pocketfox"); + assert.equal(d.title, "Lighthouse Loop"); + assert.match(d.text, /Forty seconds of a lighthouse\. Sound by http:\/\/tidewater\.newgrounds\.com\//); + assert.match(d.text, /Credits: pocketfox, tidewater/); + assert.equal(d.publishedAt, "2014-02-27T21:05:00.000Z", "a printed date is read as UTC"); + assert.ok(d.links.includes("http://uploads.ungrounded.net/634000/634512_lighthouse.swf")); +}); + +test("a page with nothing readable is one whole-page shell, never an item", () => { + for (const url of [USER, ART, MOVIE]) { + const drafts = extractNewgrounds({ html: "<html><body><div id='header'>Newgrounds</div></body></html>", capture: captureOf(url, "20150101000000") }); + assert.equal(drafts.length, 1); + assert.equal(drafts[0].noContent, true, url); + assert.equal(drafts[0].itemId, undefined, url); + } +}); + +test("the dispatcher sends a Newgrounds capture here, and every other page where it went before", () => { + const html = fixture("ng-user-2014.html"); + assert.equal(chooseExtractor({ html, capture: captureOf(USER, "20140304120000") }).name, "newgrounds"); + assert.equal(chooseExtractor({ html, capture: captureOf("http://www.newgrounds.com/", "20140304120000") }).name, "generic"); +}); diff --git a/common/lib/waybackPages/extractors/newgrounds.ts b/common/lib/waybackPages/extractors/newgrounds.ts @@ -0,0 +1,315 @@ +// Newgrounds captures (release 38 lane C, "Found during the case"): a user +// page (`<user>.newgrounds.com/`), an art page +// (`www.newgrounds.com/art/view/<user>/<slug>`) and a movie page +// (`www.newgrounds.com/portal/view/<id>`). The generic extractor reads almost +// nothing of a 2014 user page: its content sits in many small "pods" (a +// heading box and a body box, stats as <dl> pairs, a sidebar column) and the +// densest-block pick keeps one of them. Here every pod is read, in page order, +// as "Heading" then its lines. +// +// kind itemId url author +// ng-user none (each capture a version) — the subdomain +// ng-art ng-art-<user>-<slug> https://www.newgrounds.com/art/view/… the URL's user +// ng-movie ng-movie-<id> https://www.newgrounds.com/portal/view/<id> the first author link +// +// Two layouts are read: the 2012–2017 pods (`.pod` holding `.pod-head` and +// `.pod-body`) and the older side-by-side boxes (`.podtop` then +// `.podcontent`). A page with nothing readable is ONE whole-page draft, +// `noContent`, with no item id (a later shell must not overwrite a good +// capture's record). Shapes are synthetic as of 2026-11-02 (no live page was +// read): the raw capture is kept, so a better reading is a `reextract-pages`. + +import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; +import type { PostMedia } from "../../posts"; +import { + absoluteUrl, + findAll, + findFirst, + hasClass, + isEl, + isoFromIso, + metaContent, + pageTitle, + parseEnglishDate, + parseHtml, + pushUnique, + renderBlock, + squash, + textOf, + unwrapWaybackHtml, + type HtmlElement, +} from "./util"; + +export const NEWGROUNDS_EXTRACTOR_NAME = "newgrounds"; +export const NEWGROUNDS_EXTRACTOR_VERSION = 1; + +// Subdomains that are Newgrounds' own services, not a user's page. +const NOT_USERS = new Set(["www", "art", "uploads", "css", "img", "js", "aicon", "uimg", "picon", "chat", "store", "wiki", "m", "api", "audio", "games", "portal"]); + +export type NewgroundsPage = + | { kind: "ng-user"; user: string } + | { kind: "ng-art"; user: string; slug: string } + | { kind: "ng-movie"; id: string }; + +const isNgHost = (host: string) => host === "newgrounds.com" || host.endsWith(".newgrounds.com"); + +// What a Newgrounds URL is a page of, or null (a page this extractor leaves to the generic one). +export function newgroundsPageOf(url: URL): NewgroundsPage | null { + const host = url.hostname.toLowerCase(); + if (!isNgHost(host)) return null; + const path = url.pathname.replace(/\/+$/, "") || "/"; + if (host === "www.newgrounds.com" || host === "newgrounds.com") { + const art = /^\/art\/view\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)$/.exec(path); + if (art) return { kind: "ng-art", user: art[1].toLowerCase(), slug: art[2].toLowerCase() }; + const movie = /^\/portal\/view\/(\d+)$/.exec(path); + if (movie) return { kind: "ng-movie", id: movie[1] }; + return null; + } + const sub = host.slice(0, -".newgrounds.com".length); + if (!sub || sub.includes(".") || NOT_USERS.has(sub)) return null; + // The user page itself (its root, or the old /profile path). + if (path === "/" || path === "/profile") return { kind: "ng-user", user: sub }; + return null; +} + +// --- the pods ------------------------------------------------------------------------------------ + +type Pod = { heading: string; body: HtmlElement }; + +const isHeading = (e: HtmlElement) => /^h[1-6]$/.test(e.tag); + +// Every pod of the page, in order: a `.pod` with its head and body, or a +// `.podtop` heading followed (as a sibling) by its `.podcontent`. +function podsOf(root: HtmlElement): Pod[] { + const out: Pod[] = []; + const seen = new Set<HtmlElement>(); + const walk = (el: HtmlElement) => { + const kids = el.children.filter(isEl); + for (let i = 0; i < kids.length; i++) { + const c = kids[i]; + if (hasClass(c, "pod")) { + const head = findFirst(c, (e) => hasClass(e, "pod-head") || hasClass(e, "podtop")); + const body = findFirst(c, (e) => hasClass(e, "pod-body") || hasClass(e, "podcontent")); + if (body && !seen.has(body)) { + seen.add(body); + out.push({ heading: head ? textOf(findFirst(head, isHeading) ?? head) : "", body }); + continue; + } + } + if (hasClass(c, "podtop")) { + const next = kids[i + 1]; + if (next && hasClass(next, "podcontent") && !seen.has(next)) { + seen.add(next); + out.push({ heading: textOf(findFirst(c, isHeading) ?? c), body: next }); + i++; + continue; + } + } + if (hasClass(c, "pod-body") || hasClass(c, "podcontent")) { + if (!seen.has(c)) { + seen.add(c); + out.push({ heading: "", body: c }); + } + continue; + } + walk(c); + } + }; + walk(root); + return out; +} + +// A <dl>'s pairs as "Term: value" lines (a term with several values joins them). +function dlLines(dl: HtmlElement): string[] { + const lines: string[] = []; + let term = ""; + let values: string[] = []; + const flush = () => { + if (term || values.length) lines.push(term ? `${term.replace(/:$/, "")}: ${values.join(" ")}`.trim() : values.join(" ")); + term = ""; + values = []; + }; + for (const c of dl.children) { + if (!isEl(c)) continue; + if (c.tag === "dt") { + flush(); + term = textOf(c); + } else if (c.tag === "dd") { + const lis = findAll(c, (e) => e.tag === "li"); + const v = lis.length ? lis.map((li) => textOf(li)).filter(Boolean).join(", ") : textOf(c).replace(/^\|\s*/, ""); + if (v) values.push(v); + } + } + flush(); + return lines; +} + +type Read = { text: string; links: string[]; media: PostMedia[] }; + +// A pod body's lines: its <dl>s as pairs, the rest as the shared renderer writes it. +function readBody(body: HtmlElement, base: string): Read { + const dls = findAll(body, (e) => e.tag === "dl"); + const rest = renderBlock(body, base, (e) => e.tag === "dl"); + const lines = rest.text ? [rest.text] : []; + for (const dl of dls) lines.push(...dlLines(dl)); + return { text: lines.join("\n").trim(), links: rest.links, media: rest.media }; +} + +function addRead(into: Read, r: Read) { + for (const l of r.links) pushUnique(into.links, l); + for (const m of r.media) if (!into.media.some((x) => x.url === m.url && x.kind === m.kind)) into.media.push(m); +} + +// The value of a sidestats term ("Uploaded" → "Mar 3, 2014 3:22 PM EST"). +function sideStat(root: HtmlElement, term: RegExp): string | undefined { + for (const dl of findAll(root, (e) => e.tag === "dl")) { + const kids = dl.children.filter(isEl); + for (let i = 0; i < kids.length; i++) { + if (kids[i].tag !== "dt" || !term.test(textOf(kids[i]))) continue; + const vals: string[] = []; + for (let j = i + 1; j < kids.length && kids[j].tag === "dd"; j++) vals.push(textOf(kids[j]).replace(/^\|\s*/, "")); + const v = squash(vals.join(" ")); + if (v) return v; + } + } + return undefined; +} + +// The users an item credits: links to <user>.newgrounds.com in its author boxes. +function creditedUsers(root: HtmlElement, base: string): string[] { + const boxes = findAll(root, (e) => hasClass(e, "item-user") || hasClass(e, "authorlinks") || hasClass(e, "item-details-main")); + const out: string[] = []; + for (const box of boxes) { + for (const a of findAll(box, (e) => e.tag === "a")) { + const href = absoluteUrl(a.attrs.href, base); + if (!href) continue; + try { + const p = newgroundsPageOf(new URL(href)); + if (p?.kind === "ng-user") pushUnique(out, p.user); + } catch { + // not a URL + } + } + } + return out; +} + +const stripSiteTitle = (t: string | undefined) => + t + ?.replace(/\s*(?:[|—–-]\s*)?Newgrounds\.com\s*(?:[|—–-]\s*)?/i, " ") + .replace(/\s+on Newgrounds$/i, "") + .trim() || undefined; + +// --- the drafts ------------------------------------------------------------------------------------ + +function noContent(page: NewgroundsPage | null, author: string | undefined): PageRecordDraft[] { + return [{ + kind: page?.kind ?? "ng-user", + ...(author ? { author } : {}), + text: "This capture holds no readable Newgrounds content.", + links: [], + noContent: true, + }]; +} + +function extractUser(root: HtmlElement, base: string, user: string): PageRecordDraft[] { + const pods = podsOf(root); + const name = textOf(findFirst(root, (e) => hasClass(e, "user-header-name"))) || undefined; + const all: Read = { text: "", links: [], media: [] }; + const blocks: string[] = []; + for (const p of pods) { + const r = readBody(p.body, base); + addRead(all, r); + if (!r.text) continue; + blocks.push(p.heading ? `${p.heading}\n${r.text}` : r.text); + } + // The header's own links (News, Movies, Art, Fans) are furniture: only the pods are read. + if (blocks.length === 0) return noContent({ kind: "ng-user", user }, user); + const draft: PageRecordDraft = { + kind: "ng-user", + author: user, + title: stripSiteTitle(pageTitle(root)) ?? metaContent(root, "og:title") ?? user, + text: [name && name.toLowerCase() !== user ? name : "", ...blocks].filter(Boolean).join("\n\n"), + links: all.links, + }; + if (name) draft.authorName = name; + if (all.media.length) draft.media = all.media; + return [draft]; +} + +function extractItem(root: HtmlElement, base: string, page: Extract<NewgroundsPage, { kind: "ng-art" | "ng-movie" }>): PageRecordDraft[] { + const title = + textOf(findFirst(root, (e) => e.attrs.itemprop === "name" && isHeading(e))) || + metaContent(root, "og:title") || + stripSiteTitle(pageTitle(root)) || + undefined; + const comments = findFirst(root, (e) => e.attrs.id === "author_comments"); + const credited = creditedUsers(root, base); + const author = page.kind === "ng-art" ? page.user : credited[0]; + const read: Read = { text: "", links: [], media: [] }; + const lines: string[] = []; + if (title) lines.push(title); + if (comments) { + const r = readBody(comments, base); + addRead(read, r); + if (r.text) lines.push(r.text); + } else { + const d = metaContent(root, "og:description") ?? metaContent(root, "description"); + if (d) lines.push(d); + } + if (credited.length > 1) lines.push(`Credits: ${credited.join(", ")}`); + // The work itself: an art page's image, a movie's embedded file. + for (const img of findAll(root, (e) => e.tag === "img" && !!e.attrs.src)) { + const inImage = findFirst(root, (e) => (hasClass(e, "image") || e.attrs.itemprop === "image") && findFirst(e, (x) => x === img) !== null); + if (!inImage) continue; + const src = absoluteUrl(img.attrs.src, base); + if (src && !read.media.some((m) => m.url === src)) read.media.push({ kind: "image", url: src, ...(img.attrs.alt ? { name: img.attrs.alt } : {}) }); + } + for (const e of findAll(root, (x) => (x.tag === "embed" || x.tag === "object") && !!(x.attrs.src ?? x.attrs.data))) { + const src = absoluteUrl(e.attrs.src ?? e.attrs.data, base); + if (src) pushUnique(read.links, src); + } + const tagsDl = findAll(root, (e) => e.tag === "ul" && hasClass(e, "tags")); + const tags: string[] = []; + for (const ul of tagsDl) for (const li of findAll(ul, (e) => e.tag === "li")) pushUnique(tags, textOf(li).toLowerCase()); + const uploaded = sideStat(root, /^(uploaded|date added)/i); + const publishedAt = + isoFromIso(metaContent(root, "datePublished")) ?? (uploaded ? parseEnglishDate(uploaded) : undefined); + if (!title && !comments) return noContent(page, author); + const draft: PageRecordDraft = { + kind: page.kind, + itemId: page.kind === "ng-art" ? `ng-art-${page.user}-${page.slug}` : `ng-movie-${page.id}`, + url: page.kind === "ng-art" ? `https://www.newgrounds.com/art/view/${page.user}/${page.slug}` : `https://www.newgrounds.com/portal/view/${page.id}`, + text: lines.join("\n"), + links: read.links, + }; + if (title) draft.title = title; + if (author) draft.author = author; + if (publishedAt) draft.publishedAt = publishedAt; + if (read.media.length) draft.media = read.media; + if (tags.length) draft.tags = tags; + return [draft]; +} + +export function extractNewgrounds(input: PageExtractInput): PageRecordDraft[] { + const html = unwrapWaybackHtml(input.html); + const base = input.capture.originalUrl; + let page: NewgroundsPage | null = null; + try { + page = newgroundsPageOf(new URL(base)); + } catch { + page = null; + } + const root = parseHtml(html); + if (!page) return noContent(null, undefined); + return page.kind === "ng-user" ? extractUser(root, base, page.user) : extractItem(root, base, page); +} + +export const newgroundsExtractor: PageExtractor = { + name: NEWGROUNDS_EXTRACTOR_NAME, + version: NEWGROUNDS_EXTRACTOR_VERSION, + matches(originalUrl) { + return newgroundsPageOf(originalUrl) !== null; + }, + extract: extractNewgrounds, +}; diff --git a/common/lib/waybackPages/scanFile.ts b/common/lib/waybackPages/scanFile.ts @@ -9,7 +9,7 @@ // summary}`. // targets[] per target: {key, url, match, from?, to?, resumeKey?, complete, // rows (CDX rows read this pass), lastScanAt?, completedAt?, -// passFrom?} +// passFrom?, excluded?} // rows[] {originalUrl, digest, firstTs, lastTs, count, mimetype, status, // pass (the pass that first listed it)} // summary {pages, versions, byYear (first seen), byPrefix (first one and @@ -49,6 +49,9 @@ export type WaybackScanTarget = { completedAt?: string; // The lower bound this pass asks from (a later pass only). passFrom?: string; + // Release 38 lane C: this pass's listing was refused as excluded — + // WAYBACK_EXCLUDED_PHRASE. Cleared when a new pass starts. + excluded?: string; }; export type WaybackScanRow = { diff --git a/common/lib/waybackPages/types.ts b/common/lib/waybackPages/types.ts @@ -9,7 +9,7 @@ import type { WaybackProvenance } from "../wayback"; import type { ForumPostInfo, PostMedia, PostRef } from "../posts"; // What an extractor recognised the capture as. "generic" is the fallback for -// every page no site extractor claims (articles, personal sites, Newgrounds). +// every page no site extractor claims (articles, personal sites). export const PAGE_KINDS = [ "generic", "tumblr-post", @@ -19,6 +19,10 @@ export const PAGE_KINDS = [ "forum-post", "gdoc", "yt-about", + // Release 38 lane C: Newgrounds (extractors/newgrounds.ts). + "ng-user", + "ng-art", + "ng-movie", ] as const; export type PageKind = (typeof PAGE_KINDS)[number]; diff --git a/common/lib/waybackPages/view.ts b/common/lib/waybackPages/view.ts @@ -29,6 +29,9 @@ export const PAGE_KIND_LABELS: Record<string, string> = { "forum-post": "Forum post", gdoc: "Google Doc", "yt-about": "YouTube channel page", + "ng-user": "Newgrounds user page", + "ng-art": "Newgrounds art", + "ng-movie": "Newgrounds movie", }; export function pageKindLabel(kind: string): string { diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **A research case can be verified, its leads decided and its evidence captured, all in umtool.** The case pipeline page gains **7 Verify**, **8 Leads** and **10 Evidence**. **Verify** shows each finding's moment in every caption track side by side — the original audio's captions beside the uploaded `en` ones, the quote's words lit where they land and "holds the quote" or "4 of 5 words" on each — and an **Audio check** that has the editor transcribe the window on a local worker (its held media, or a clip fetched through it; **Run even while transcription is paused** for a pause-all) and diffs what was heard with the quote ("Heard 9 of 9 words"). A finding is marked Verified, Corrected, Disputed, Unverified or Quarantined (one first seen on a forum says so); **Correct by hand** keeps the reader's words ("The reader wrote: …"). **Leads** lists the accounts and pages a forum or posts channel links most, counted by post, with the posts around each on demand; **Never archive** makes the lead's name one of the case's private names — stored as its hash, never as text, and withheld from then on — and **Archive** creates its channel through the editor on no site and starts its first fetch (**Older walk** after). **Evidence** takes Wayback captures of a list of pages at chosen dates (a page the Wayback Machine will not show is the row "excluded from the Wayback Machine (cause unknown)") and a forum post's attachments and screenshot, shown everywhere as "forum attachment, post #N, unverified", attached to the findings they back and listed in the exported report's Evidence section. Any quote, note or role typed by hand that holds one of the case's private names is refused by the privacy gate, with the row and a count, never the name. Needs a restart of umtool. +- **Newgrounds pages are read whole.** A Wayback capture of a 2014 Newgrounds user page used to come out as one small block of it: the page keeps its profile, stats, links and news in many small boxes the generic extractor dropped. A user page (`<user>.newgrounds.com/`) is now read box by box — "Profile", "Location: …", "Joined on: …", its links — and an art page or a movie page is one record per work (its title, author, comments, image or file, tags, credits and date) that later captures update. A channel imported before this is put right by **Re-extract** (`reextract-pages`), from the captures it already keeps; nothing is fetched. Needs a restart of the editor. +- **A Wayback scan goes on past a page the archive excludes.** A target the Wayback Machine answers 403 for stopped the whole `wayback-scan` as an error. Now that target is marked "excluded from the Wayback Machine (cause unknown)" on the Captures tab (and `refusal: "excluded"` in the scan's result), it is done for this pass, and the next target is scanned. A new pass asks again. Needs a restart of the editor. - **Sync on an X, Bluesky or forum channel fetches its posts.** The Sync button on a social channel ran yt-dlp's video listing against the profile and failed. Every Sync — the channel rows', the dashboard's, a group's, Sync all, `pnpm ops sync`, a sync job's Retry — now runs the channel's post fetch (the same job as the channel page's Fetch posts: on the platform's queue, paced, and for X only on a fresh cookie jar), and a refusal is its own sentence beside the button. A full sweep is the video listing's, so a Sync never starts a social channel's whole re-walk; that is still Fetch posts → Re-fetch full history. - **A report video's project page names the sites its links depend on, and says when one is behind.** Each site a clip's QR opens is listed with its deploy's date (its `corpus.json`, read by Check links) and the cited videos newer than it — uploaded or transcribed after it, and not found on it — and the check's new `site-deploy-behind` row offers **Publish <site>**, which asks the editor to build and deploy it. - **A per-project link policy: cite via one site, these channels direct.** The Ember cut's citeUrls were rewritten by hand twice to send two channels to anilyzer and one to YouTube. A project's **Link policy** (Overview, or `umtool link-policy <p> --via <site> --direct a,b`) now says it once: new clips are written by it, and every clip that breaks it is a check row with a one-press fix (`umtool link-policy <p> --fix` for all). diff --git a/editor/app/api/ops/wayback-scan/route.ts b/editor/app/api/ops/wayback-scan/route.ts @@ -21,7 +21,10 @@ export const dynamic = "force-dynamic"; // channel with no `wayback.targets`. The log ends `@@wayback-scan {slug, // dryRun, pass, newPass, targets: [{url, match, requests, rows, added, // complete, resumeKey?, next?}], requests, rowsRead, added, totalRows, -// complete, stopped?, error?}`. +// complete, stopped?, error?, excluded?}`. A target the Wayback Machine +// answers 403 for is EXCLUDED (release 38 lane C): its report carries +// `refusal: "excluded"` and "excluded from the Wayback Machine (cause +// unknown)", it is done for this pass, and the run goes on to the next target. // // AN ADAPTER: the refusals are the controller's (controller/waybackScan.ts). export async function POST(request: Request) { diff --git a/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx b/editor/app/channels/[slug]/captures/components/CapturesPanel.tsx @@ -30,7 +30,7 @@ export type CapturesStatus = { lastScanJobId?: string; pass: number; complete: boolean; - targets: { url: string; match: string; complete: boolean; rows: number; resumable: boolean }[]; + targets: { url: string; match: string; complete: boolean; rows: number; resumable: boolean; excluded?: string }[]; auto: boolean; liveScanJobId?: string; }; @@ -122,7 +122,7 @@ export function CapturesPanel({ slug, status, rows, matching, matchingToImport, <ul className="text-xs text-muted-foreground flex flex-col gap-0.5" aria-label="scan targets"> {status.targets.map((t) => ( <li key={`${t.match} ${t.url}`}> - <span className="font-mono">{t.url}</span> ({t.match}) — {t.complete ? "complete" : t.resumable ? `${n(t.rows)} rows read, continues` : "not scanned this pass"} + <span className="font-mono">{t.url}</span> ({t.match}) — {t.excluded ? <span data-scan-target-excluded="">{t.excluded}</span> : t.complete ? "complete" : t.resumable ? `${n(t.rows)} rows read, continues` : "not scanned this pass"} </li> ))} </ul> diff --git a/editor/app/channels/[slug]/captures/page.tsx b/editor/app/channels/[slug]/captures/page.tsx @@ -65,7 +65,7 @@ export default async function CapturesPage({ complete: scan ? wayback.targets.every((t) => scan.targets.some((s) => s.key === waybackTargetKey(t) && s.complete)) : false, targets: wayback.targets.map((t) => { const st = scan?.targets.find((s) => s.key === waybackTargetKey(t)); - return { url: t.url, match: t.match, complete: st?.complete ?? false, rows: st?.rows ?? 0, resumable: !!st?.resumeKey }; + return { url: t.url, match: t.match, complete: st?.complete ?? false, rows: st?.rows ?? 0, resumable: !!st?.resumeKey, ...(st?.excluded ? { excluded: st.excluded } : {}) }; }), auto: wayback.auto, ...(liveScan ? { liveScanJobId: liveScan.id } : {}), diff --git a/editor/e2e/wayback-captures.spec.ts b/editor/e2e/wayback-captures.spec.ts @@ -156,3 +156,48 @@ test("Captures: scan on the fake → the table → filter by year → Import sel await wb.close(); } }); + +// Release 38 lane C: a target the Wayback Machine excludes (a CDX 403) is a +// line of its own on the tab, and the scan goes on to the next target. +test("Captures: an excluded target is marked, and the next target is scanned", async ({ page }) => { + test.setTimeout(120_000); + await resetData("empty"); + const transcripts = resolvePath(testPaths().transcriptsDir); + const slug = "synth-pages-excluded"; + const channelRoot = path.join(transcripts, "channels", slug); + await mkdir(channelRoot, { recursive: true }); + const targets = [ + { url: "gone.example", match: "host" }, + { url: "blog.example", match: "host" }, + ]; + await writeFile( + path.join(channelRoot, "config.json"), + JSON.stringify({ + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + socialHandle: "blog.example", + name: "Synth Blog, one target excluded", + url: "https://web.archive.org/web/*/blog.example*", + wayback: { targets }, + }), + ); + const wb = await startFakeWayback({ captures: SCAN_CAPTURES, excluded: ["gone.example"] }); + const originFile = waybackOriginFile(transcripts); + await writeFile(originFile, wb.base); + try { + await page.goto(`/channels/${slug}/captures`); + await page.getByRole("button", { name: "Scan now" }).click(); + const status = page.getByLabel("captures status line"); + await expect(status).toContainText("7 versions of 5 pages", { timeout: 30_000 }); + await expect(status).toContainText("complete"); + const list = page.getByRole("list", { name: "scan targets" }); + await expect(list.locator("li").filter({ hasText: "gone.example" }).locator("[data-scan-target-excluded]")).toHaveText( + "excluded from the Wayback Machine (cause unknown)", + ); + await expect(list.locator("li").filter({ hasText: "blog.example" })).toContainText("complete"); + } finally { + await rm(originFile, { force: true }); + await wb.close(); + } +}); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11570,3 +11570,68 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri the job makes later finds the store in its render phase and threw — the job's work was done and it ended `failed`. Counted as a skip like the missing store. The cookie actions do not revalidate at all (the banner refetches its view). + +## Release 38 lane C: a case's verify, leads and evidence; Newgrounds; an excluded scan target (verified 2026-11-02, branch `r38/case-verify-leads`) + +- **Where:** umtool `lib/research/case-{stage-files,findings-store,editor,verify,leads,evidence,stage-hrefs}.ts`, + routes `app/api/research/cases/[id]/stages/{verify[/captions|/audio],leads[/context|/older],evidence}`, panels + `components/research/stages/{Verify,Leads,Evidence}Panel.tsx` drawn by lane A's `CasePipeline.tsx` as + `#stage-verify` (7), `#stage-leads` (8), `#stage-evidence` (10), in its STAGE_NAV; the pipeline page reads their + first frames (`components/research/stages/types.ts` `CaseStagePanels`, each a view or `{error}`). +- **On lane A's store** (`common/lib/research/caseStore-server.ts`): leads.json and evidence.json are written with + its `withFileLock(<file>.lock)` (O_EXCL, cross-process) and `writeAtomic`; findings with `mutateFindings` + (`case-findings-store.ts`): A's `readFindings`, a 409 when any line does not check, the change, A's gate + (`assertNoPrivateNames` over `rowGateText`, PrivacyBlocked 409 naming the row ids), `writeAtomic` — all inside + `findings.jsonl.lock`, the lock A's appendFindings/writeFindings hold. +- **A never-archive lead's hash goes through lane A's `changePrivateNames`** (umtool `lib/research/pipeline.ts`: + `mutateDefinition` + `withholdStored`, so stored candidates and batches are withheld too). +- **Contract additions** (`common/lib/research/caseTypes.ts`): `CASE_FILES.evidence` (`evidence.json`, + `CaseEvidence[]`, `e<n>` ids, states planned/queued/captured/excluded/failed), `FindingVerify.audio` + (`AudioCheck {at, job, text, matched, words, worker?}`), `FindingEvidence.evidence`/`position`, + `EXCLUDED_SENTENCE` (= the editor's `WAYBACK_EXCLUDED_PHRASE`, a test keeps them equal), + `forumAttachmentLabel(position, post)` → "forum attachment, post #N, unverified", `evidenceLabel(e)`, + (the possessive rule is lane A's `stripPossessive`; shown text is withheld with A's `withholdPrivateNames`). + `caseEvidence.ts`: `evidenceRows`, `evidenceLine`, `evidenceSection` — A's `reportMarkdown` takes + `ReportContext.evidence` and prints the section before Coverage; `runExport` reads `evidence.json` (a bad file is + logged and left out); `findingLine` names a forum attachment with `forumAttachmentLabel` (the post's #N). `wordDiff.ts` + `quoteWordDiff(quote, heard)` → `{matched, words, ops}` (LCS over `wordsOf` words; transcript words outside the + matched stretch dropped). +- **Verify:** tracks = the record's primary + `altTracks`, ordered original (`en-orig`) → uploaded (`en`) → + transcription, at most 3; the window is cues starting in [t − 15, t + 35]; the lit words are the + quote-length stretch (max(n + 4, 1.5n) words) with the longest LCS, nearest t on a tie. A finding on a social + channel (xenforo, twitter, bluesky, webpage) shows the post's text as its one track. Shown text is redacted with + the case's hashes. `setVerify`: a quote/speaker change must be status `corrected` (400 otherwise), `original` + is set once and never overwritten; quote ≤ 45 words; quote+speaker+note with a private-name hit → 422 with a + count (now lane A's gate: 409, the row id). `how` = hand (words changed) | audio (asked, and an audio check is kept) | captions. +- **The audio check** (`audioStep`): window [t − 5, t + 30]; media = the first `data/<id>/` file with a media + extension (`audio.*` first), else the tightest `clips/<from>-<to>.*` covering the window, else a fetch through + `fetchForReader` (fetch_clip's path); then `POST /api/ops/transcribe {path, start, end, whilePaused?}` on that + file's clock; the result is the `@@transcribe-result ` line of `GET /api/ops/job/<id>?tail=80`. Kept on + `verify.audio`; the status is never changed by it. +- **Leads:** `leadOf(url)` → `x:@handle` (x.com/twitter.com, not /i /intent /search…), `youtube:@h|c/…|user/…| + channel/…`, `bluesky:<handle>`, `tumblr:|newgrounds:|deviantart:<sub>`, `reddit:u/<n>`, `instagram:`, `tiktok:@`, + else `<host without www>/<path>` lowercased. Counted by POST (one per post per key), the forum's own host (posts' + `forum.host`, and the channel URL for xenforo; ± www) left out. The NAME hashed is the handle/user/last path + segment without "@". never-archive → `leads.json` keeps `{key: "hash:<sha>", url: "", platform, count, + disposition, role?}` and `pipeline.json` gets the sha; a lead whose name hashes into the case's private names is + counted in `withheld`, never listed. archive → `POST /api/ops/create-channel {fields: {name, handling, url}, + fetchPostsNow|fetchPlaylist}` with NO `sites` key (X: `https://x.com/<h>`; YouTube: `<url>/videos` + fetchPlaylist; + anything else a Wayback pages channel `https://web.archive.org/web/*/<host+path>*`); Older walk = `fetch-posts + {slug, older: true}`. +- **Evidence:** lookup = `wayback-lookup {url, okOnly: true, limit: 500}` (403 `refusal: "excluded"` → row + `excluded`); capture = `import-page {slug, url, at: YYYYMMDD}` (a picked Wayback pages channel, or + `create-channel` for the host on no site); forum = `capture-posts {slug, ids: [post], shots: true, media: true}`, + captured when the job is done and `posts-media/<post>/` holds a non-json file. The UI re-asks a queued row every + 1.5 s (`refresh`). +- **Newgrounds** (`common/lib/waybackPages/extractors/newgrounds.ts`, registered after `x`, before `xenforo`): + claims `<user>.newgrounds.com/` (and `/profile`; not www/art/uploads/… subdomains), `www.newgrounds.com/art/view/ + <user>/<slug>`, `/portal/view/<id>`. Kinds `ng-user` (no item id: each capture a version), `ng-art` + (`ng-art-<user>-<slug>`), `ng-movie` (`ng-movie-<id>`). Pods: `.pod` → `.pod-head|.podtop` heading + `.pod-body| + .podcontent`, or a `.podtop` followed by a sibling `.podcontent`; a `<dl>` as "Term: value" lines. Date: + `meta[itemprop=datePublished]`, else the sidestats "Uploaded"/"Date added" value (read as UTC). The fixtures are + synthetic (no live Newgrounds page read). +- **wayback-scan, an excluded target:** `cdxPage`'s `WaybackExcludedError` no longer stops the run: the target's + report gets `refusal: "excluded"` + `error`, the scan file's target `excluded: WAYBACK_EXCLUDED_PHRASE` and + `complete: true` (cleared by `startPass`), the result `excluded: [urls]`, and the loop goes on to the next target. +- **Stage 11 (`fetch-posts {retryOnBlock}`) was already on main** (release 37 lane G, `fetchPosts.ts` "RETRY ON A + BLOCK", tested in `fetchForumPosts.test.ts`: "Waiting N min after a challenge page, try k/M." per wait). diff --git a/plans/release-38/research-cases-and-assist.md b/plans/release-38/research-cases-and-assist.md @@ -138,3 +138,55 @@ Nik Drop: "make the joins 0.15 s with less smear" from the Ask box on local Qwen being described. (Lanes B/C.) - **An X search channel** (a saved query across accounts, leads ranked by author, Archive / Never archive) — lane S `r38/x-search`, launched 2026-10-20. + +## Lane C, as shipped (`r38/case-verify-leads`, 2026-11-02) + +Stages 7, 8 and 10, and the case's found items for lane C. Built beside lane A at first, then merged A +(`r38/case-pipeline` e182dd00) and moved onto its seams: the three stages are panels **7 Verify**, **8 Leads** and +**10 Evidence** of A's `/research/<case>/pipeline` (in its Stages list), on A's store, lock files, privacy gate and +export. FACTS.md, "Release 38 lane C", has the verified details. + +- **7 Verify** — a finding's window in every caption track side by side (en-orig, en, a transcription; a post's + text), the quote's words lit; the **audio check** (held media or a clip fetched through the editor → + `transcribe {path, start, end, whilePaused?}` → `@@transcribe-result` → a word diff, kept as `verify.audio`); the + five statuses (`quarantined` with a forum hint); **correct by hand** keeps the reader's words once in + `verify.original`. Findings are rewritten whole inside A's `findings.jsonl.lock` under A's gate. +- **8 Leads** — the accounts and pages a posts/forum channel links most, counted by post, context on demand + (private names withheld); role + disposition. never-archive → the name's hash through A's `changePrivateNames`, + the lead kept only as `hash:<sha>`; archive → `create-channel` with no `sites` (X never on a site) and its first + fetch; Older walk → `fetch-posts {older}`. +- **10 Evidence** — `evidence.json` (a contract addition): Wayback targets × dates (`wayback-lookup`: a 403 is the + `excluded` row; `import-page {slug, url, at}`), a forum post through `capture-posts` labelled "forum attachment, + post #N, unverified" everywhere (`forumAttachmentLabel`), attached to findings; A's export prints them in an + **Evidence** section (`common/lib/research/caseEvidence.ts`). +- **11 Polite retries** — already on main (release 37 lane G: `fetch-posts {retryOnBlock}`, its log says each wait, + `fetchForumPosts.test.ts`). Nothing added. +- **Found during the case:** a CDX 403 — `wayback-lookup` and `import-page` already answered `refusal: "excluded"` + (release 37 lane F); `wayback-scan` now marks an excluded target and goes on to the next (Captures tab line). + **Newgrounds extractor** (`ng-user`, `ng-art`, `ng-movie`; synthetic fixtures; a reextract of a generic-read + capture tested). **Forum attachments as marked evidence**, **`quarantined`** (as above). + +| commit | what | +|---|---| +| 93b60ec4 | wayback pages: a Newgrounds extractor | +| 72734218 | wayback scan: an excluded target is answered, not failed | +| b1883d14 | research cases: lane C's contract additions (evidence.json, the audio check, the labels, the word diff) | +| ed0c3e61 | research cases: a possessive never slips a private name past the gate (A shipped the same rule) | +| 876b46c0 | umtool research: verify, leads and evidence stages | +| d3a50503 | docs + e2e: research.md, case-stages.spec, CHANGELOG, FACTS | +| 064de1ca | leads: a role note alone keeps the disposition; editor e2e: an excluded scan target | +| 6332a730 | merge lane A; lane C's stages onto its seams (panels, store, gate, changePrivateNames, the export's Evidence) | +| 229ee2ca | the verify panel's status follows a save; the spec waits out a cold read | + +**Gates (after the merge):** root `pnpm typecheck` clean; common 5324 tests, 5322 pass, 0 fail, 2 skipped; umtool +unit 51/51; mcp 385/385; `test:scripts` 2174, 2169 pass, 1 fail (`renderMode.test.mjs` "take --priority killed by a +signal", a timing test that passes alone — 13/13 — and failed the same way before the merge; untouched here), +4 skipped; `archilyzer docs cli --check` and `docs env --check` clean (no ops or CLI changed). umtool e2e +(`case-stages`, `case-pipeline`, `board`, `import-capture`, `research`, `article-research`): 26 passed and the one +case-stages failure fixed, then `case-stages` 4/4 (34 s); editor e2e `wayback-captures` 2/2 (47.6 s, before the merge; the merge touches none of its code). Editor unit 399/400: +`_researchRuns.test.ts` "the research editor is this editor's own ops routes" fails the same on main 3cb071fe. + +**Left:** lane B's appends should use A's `appendFindings` (verify already shares its lock); the MCP's +`case_verify`/`case_leads` (lane D) can call `findingCaptions`/`leadsView` or the stage routes; a live Newgrounds +capture has not been read (the extractor is from synthetic fixtures — a `reextract-pages` fixes held records once +a real page shows a different shape). diff --git a/umtool/app/api/research/cases/[id]/stages/evidence/route.ts b/umtool/app/api/research/cases/[id]/stages/evidence/route.ts @@ -0,0 +1,68 @@ +import { + addForumAttachment, + addTargets, + attachEvidence, + captureTarget, + evidenceView, + lookupTarget, + refreshEvidence, +} from "@/lib/research/case-evidence"; +import { CaseError } from "@/lib/research/case-stage-files"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// STAGE 10, EVIDENCE CAPTURE (release 38 lane C; lib/research/case-evidence.ts). +// GET -> EvidenceView {rows (each with its label), pagesChannels, forumChannels, findings} +// POST {action, …} -> {row?, rows?, view} +// add {urls: [url], dates: [YYYY-MM-DD]} a Wayback target per URL × date +// lookup {id} wayback-lookup: excluded, or how many captures +// capture {id, slug} | {id, create: {name}} import-page, the capture nearest the date +// forum {slug, post} capture-posts: the post's attachments and screenshot +// refresh {id} where a queued row's job is +// attach {id, finding} the row as a finding's evidence +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await evidenceView(id)); + } catch (e) { + return fail(e); + } +} + +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const b = ((await request.json().catch(() => null)) ?? {}) as Record<string, unknown>; + const s = (k: string) => (typeof b[k] === "string" ? (b[k] as string) : ""); + const list = (k: string) => (Array.isArray(b[k]) ? (b[k] as unknown[]).map(String) : typeof b[k] === "string" ? (b[k] as string).split(/[\s,]+/) : []); + let out: Record<string, unknown>; + switch (b.action) { + case "add": + out = { rows: await addTargets(id, list("urls"), list("dates")) }; + break; + case "lookup": + out = { row: await lookupTarget(id, s("id")) }; + break; + case "capture": { + const create = b.create as { name?: unknown } | undefined; + out = { row: await captureTarget(id, s("id"), create && typeof create.name === "string" ? { create: { name: create.name } } : { slug: s("slug") }) }; + break; + } + case "forum": + out = { row: await addForumAttachment(id, s("slug"), s("post")) }; + break; + case "refresh": + out = { row: await refreshEvidence(id, s("id")) }; + break; + case "attach": + out = await attachEvidence(id, s("id"), s("finding")); + break; + default: + throw new CaseError(`not an evidence action: ${JSON.stringify(b.action)} (add, lookup, capture, forum, refresh, attach)`, 400); + } + return ok({ ...out, view: await evidenceView(id) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/leads/context/route.ts b/umtool/app/api/research/cases/[id]/stages/leads/context/route.ts @@ -0,0 +1,17 @@ +import { leadContext } from "@/lib/research/case-leads"; +import { fail, ok } from "../../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// GET ?channel=<slug>&key=<lead> -> {key, snippets: [{post, date, author, text, url, position?}]} +// The posts that link the lead, each a snippet around the link; the case's +// private names withheld. +export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const q = new URL(request.url).searchParams; + return ok(await leadContext(id, q.get("channel") ?? "", q.get("key") ?? "")); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/leads/older/route.ts b/umtool/app/api/research/cases/[id]/stages/leads/older/route.ts @@ -0,0 +1,16 @@ +import { startOlderWalk } from "@/lib/research/case-leads"; +import { fail, ok } from "../../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// POST {key} -> {jobId, slug}: the older walk of an archived lead's channel +// (the editor's fetch-posts {older: true}), once its first fetch has posts. +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const b = ((await request.json().catch(() => null)) ?? {}) as Record<string, unknown>; + return ok(await startOlderWalk(id, String(b.key ?? ""))); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/leads/route.ts b/umtool/app/api/research/cases/[id]/stages/leads/route.ts @@ -0,0 +1,41 @@ +import { decideLead, leadsView } from "@/lib/research/case-leads"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// STAGE 8, LEADS (release 38 lane C; lib/research/case-leads.ts). +// GET ?channel=<slug> -> LeadsView: the accounts and URLs the channel's +// posts link most, merged with the case's decisions +// POST {key, disposition?, role?, name?, url?, count?, channel?} +// -> {lead, created?, view} +// never-archive feeds the lead's name to the case's private names as a hash +// and keeps the lead only as that hash; archive creates the channel through +// the editor's create-channel, on no site, and starts its first fetch. +export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await leadsView(id, new URL(request.url).searchParams.get("channel"))); + } catch (e) { + return fail(e); + } +} + +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const b = ((await request.json().catch(() => null)) ?? {}) as Record<string, unknown>; + const str = (k: string) => (typeof b[k] === "string" ? (b[k] as string) : undefined); + const r = await decideLead(id, { + key: String(b.key ?? ""), + // Absent: the disposition stays as it is; null or "": undecided again. + ...("disposition" in b ? { disposition: b.disposition === null ? null : str("disposition") ?? null } : {}), + role: str("role"), + name: str("name"), + url: str("url"), + ...(typeof b.count === "number" ? { count: b.count } : {}), + }); + return ok({ ...r, view: await leadsView(id, str("channel") ?? null) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/verify/audio/route.ts b/umtool/app/api/research/cases/[id]/stages/verify/audio/route.ts @@ -0,0 +1,27 @@ +import { audioStep } from "@/lib/research/case-verify"; +import { fail, ok } from "../../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// THE AUDIO CHECK, one step per call (the page polls): +// POST {row, whilePaused?} -> fetching {fetchJob} | transcribing {job} | failed +// POST {row, fetchJob, whilePaused?} -> fetching | transcribing {job} | failed +// POST {row, job} -> transcribing | done {audio, ops} | failed +// The window is the held media's, or a clip fetched through the editor's +// fetch-window; it is transcribed by the editor's `transcribe` (a local +// worker; `whilePaused` runs it during a pause-all, the operator's button). +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const b = ((await request.json().catch(() => null)) ?? {}) as Record<string, unknown>; + return ok( + await audioStep(id, String(b.row ?? ""), { + whilePaused: b.whilePaused === true, + ...(typeof b.fetchJob === "string" ? { fetchJob: b.fetchJob } : {}), + ...(typeof b.job === "string" ? { job: b.job } : {}), + }), + ); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/verify/captions/route.ts b/umtool/app/api/research/cases/[id]/stages/verify/captions/route.ts @@ -0,0 +1,16 @@ +import { findingCaptions } from "@/lib/research/case-verify"; +import { fail, ok } from "../../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// GET ?row=f1 -> CaptionsView: the finding's window in every caption track it +// has (en-orig first, then en, then a transcription), side by side, the +// quote's words lit; a post's text for a post. +export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await findingCaptions(id, new URL(request.url).searchParams.get("row") ?? "")); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/stages/verify/route.ts b/umtool/app/api/research/cases/[id]/stages/verify/route.ts @@ -0,0 +1,32 @@ +import { setVerify, verifyView } from "@/lib/research/case-verify"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// STAGE 7, VERIFY (release 38 lane C; lib/research/case-verify.ts). +// GET -> VerifyView {rows, counts, bad, statuses} +// POST {row, status, note?, quote?, speaker?, how?} +// -> {row: VerifyRow, view} +// A quote or speaker changed by hand is status "corrected", and the reader's +// words are kept in verify.original. A hand-written quote, speaker or note +// that matches the case's private names is refused (422), with a count. +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await verifyView(id)); + } catch (e) { + return fail(e); + } +} + +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const b = ((await request.json().catch(() => null)) ?? {}) as Record<string, unknown>; + const str = (k: string) => (typeof b[k] === "string" ? (b[k] as string) : undefined); + const row = await setVerify(id, String(b.row ?? ""), { status: String(b.status ?? ""), note: str("note"), quote: str("quote"), speaker: str("speaker"), how: str("how") }); + return ok({ row, view: await verifyView(id) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/research/[case]/pipeline/page.tsx b/umtool/app/research/[case]/pipeline/page.tsx @@ -6,20 +6,35 @@ import { EmptyState } from "@/components/ui/empty-state"; import { pipelineView } from "@/lib/research/pipeline"; import { researchCaseHref, researchHref } from "@/lib/research/hrefs"; import type { PipelineView } from "@/lib/research/pipeline-types"; +import { verifyView } from "@/lib/research/case-verify"; +import { leadsView } from "@/lib/research/case-leads"; +import { evidenceView } from "@/lib/research/case-evidence"; +import type { CaseStagePanels } from "@/components/research/stages/types"; export const dynamic = "force-dynamic"; // A CASE'S PIPELINE (plans/release-38/research-cases-and-assist.md, lane A), beside its board at // /research/<case>: the stages -- define, coverage, candidates, batches, the read, merge, the privacy gate, -// export and hand-off, date checks -- each with its manual path and its buttons. The page is the client's +// export and hand-off, date checks, and lane C's verify, leads and evidence -- each with its manual path and its buttons. The page is the client's // (components/research/CasePipeline.tsx); this reads the first frame. -export default async function CasePipelinePage({ params }: { params: Promise<{ case: string }> }) { +export default async function CasePipelinePage({ params, searchParams }: { params: Promise<{ case: string }>; searchParams: Promise<{ leads?: string }> }) { const { case: raw } = await params; + const { leads: leadsChannel } = await searchParams; const id = decodeURIComponent(raw); let view: PipelineView | null = null; let error: { status: number; message: string } | null = null; + let panels: CaseStagePanels | null = null; try { view = await pipelineView(id); + // Lane C's stages (verify, leads, evidence): each read on its own, so one that cannot be read says so in its + // panel and the rest of the page stands. + const said = (e: unknown) => ({ error: (e as Error).message }); + const [verify, leads, evidence] = await Promise.all([ + verifyView(id).catch(said), + leadsView(id, leadsChannel ?? null).catch(said), + evidenceView(id).catch(said), + ]); + panels = { verify, leads, evidence }; } catch (e) { error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; } @@ -27,7 +42,7 @@ export default async function CasePipelinePage({ params }: { params: Promise<{ c <div className="flex h-full flex-col"> <AppRail active="research" /> {view ? ( - <CasePipeline initial={view} /> + <CasePipeline initial={view} panels={panels} /> ) : ( <> <AppHeader crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: id }, { label: "Pipeline" }]} /> diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -631,7 +631,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { <div> <span className="micro">Pipeline</span> <p className="mb-0 mt-1.5 text-[12px] text-muted"> - Coverage, candidate windows, batches, findings, the merge and its privacy gate, date checks.{" "} + Coverage, candidate windows, batches, findings, the merge and its privacy gate, verify, leads, date checks, evidence.{" "} <Link prefetch={false} href={researchCasePipelineHref(doc.id)} className="ink-link" data-case-pipeline=""> Open the case pipeline </Link> diff --git a/umtool/components/research/CasePipeline.tsx b/umtool/components/research/CasePipeline.tsx @@ -15,6 +15,10 @@ import type { CaseStage, CaseStageRun } from "yt-dlp-transcript-common/lib/resea import { researchCaseHref, researchCasePipelineApi, researchHref } from "@/lib/research/hrefs"; import type { PipelineView } from "@/lib/research/pipeline-types"; import { cn } from "@/lib/utils"; +import EvidencePanel from "./stages/EvidencePanel"; +import LeadsPanel from "./stages/LeadsPanel"; +import VerifyPanel from "./stages/VerifyPanel"; +import type { CaseStagePanels } from "./stages/types"; // --------------------------------------------------------------------------- // THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A): one panel per stage, in order, each @@ -41,8 +45,11 @@ const STAGE_NAV: { id: string; label: string }[] = [ { id: "read", label: "4 Read" }, { id: "merge", label: "5 Merge" }, { id: "privacy", label: "6 Privacy" }, + { id: "verify", label: "7 Verify" }, + { id: "leads", label: "8 Leads" }, { id: "export", label: "Export" }, { id: "date-checks", label: "9 Date checks" }, + { id: "evidence", label: "10 Evidence" }, ]; async function call<T>(url: string, method: string, body?: unknown): Promise<T> { @@ -121,7 +128,7 @@ function editable(def: PipelineView["definition"]) { }; } -export default function CasePipeline({ initial }: { initial: PipelineView }) { +export default function CasePipeline({ initial, panels }: { initial: PipelineView; panels?: CaseStagePanels | null }) { const hydrated = useHydrated(); const [view, setView] = useState(initial); const [busy, setBusy] = useState<string | null>(null); @@ -661,6 +668,20 @@ export default function CasePipeline({ initial }: { initial: PipelineView }) { </div> </Panel> + {/* ── 7 Verify, 8 Leads (lane C: components/research/stages/) ── */} + {panels && ( + <Panel id="stage-verify" title="7 · Verify" aside={"error" in panels.verify ? undefined : <span className="font-mono text-[11px] text-muted">{panels.verify.counts.verified + panels.verify.counts.corrected} of {panels.verify.rows.length} verified or corrected</span>}> + <Manual>each finding against its captions in both tracks, by ear (the editor transcribes the window), and marked; a correction by hand keeps the reader&apos;s words.</Manual> + {"error" in panels.verify ? <p role="alert" className="m-0 text-[12.5px] text-reject-text">{panels.verify.error}</p> : <VerifyPanel caseId={id} initial={panels.verify} />} + </Panel> + )} + {panels && ( + <Panel id="stage-leads" title="8 · Leads"> + <Manual>the accounts and pages a posts or forum channel links most; a role and a disposition each. Never archive keeps only a hash; Archive creates the channel on no site.</Manual> + {"error" in panels.leads ? <p role="alert" className="m-0 text-[12.5px] text-reject-text">{panels.leads.error}</p> : <LeadsPanel caseId={id} initial={panels.leads} />} + </Panel> + )} + {/* ── Export and hand-off ── */} <Panel id="stage-export" title="Export and hand-off" aside={<RunState run={s.export} />}> <Manual> @@ -734,6 +755,13 @@ export default function CasePipeline({ initial }: { initial: PipelineView }) { ))} </div> </Panel> + {/* ── 10 Evidence (lane C) ── */} + {panels && ( + <Panel id="stage-evidence" title="10 · Evidence capture"> + <Manual>Wayback captures of pages at chosen dates, and a forum post&apos;s attachments and screenshot, through the editor; the export lists them.</Manual> + {"error" in panels.evidence ? <p role="alert" className="m-0 text-[12.5px] text-reject-text">{panels.evidence.error}</p> : <EvidencePanel caseId={id} initial={panels.evidence} />} + </Panel> + )} </div> </div> diff --git a/umtool/components/research/stages/EvidencePanel.tsx b/umtool/components/research/stages/EvidencePanel.tsx @@ -0,0 +1,246 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Table, TD, TH } from "@/components/ui/table"; +import { caseStageApi } from "@/lib/research/case-stage-hrefs"; +import type { EvidenceRow, EvidenceView } from "@/lib/research/case-evidence"; + +// STAGE 10, EVIDENCE CAPTURE (release 38 lane C): Wayback captures of a target +// list at chosen dates (a 403 is a row of its own: "excluded from the Wayback +// Machine (cause unknown)"), and a forum post's attachments and screenshot, +// marked "forum attachment, post #N, unverified" wherever they show. Every +// capture is the editor's job, paced by it. + +const STATE_BADGE: Record<EvidenceRow["state"], "info" | "neutral" | "open" | "blocking" | "state"> = { + planned: "info", + queued: "state", + captured: "neutral", + excluded: "open", + failed: "blocking", +}; + +const iso = (d?: string) => (d && /^\d{8}/.test(d) ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : ""); + +async function call<T>(url: string, init?: { method?: string; body?: unknown }): Promise<T> { + const res = await fetch(url, { + method: init?.method ?? "GET", + headers: init?.body !== undefined ? { "content-type": "application/json" } : undefined, + body: init?.body !== undefined ? JSON.stringify(init.body) : undefined, + cache: "no-store", + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body?.error ?? `HTTP ${res.status}`); + return body as T; +} + +export default function EvidencePanel({ caseId, initial }: { caseId: string; initial: EvidenceView }) { + const [view, setView] = useState(initial); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState<string | null>(null); + const [urls, setUrls] = useState(""); + const [dates, setDates] = useState(""); + const [forum, setForum] = useState(initial.forumChannels[0]?.slug ?? ""); + const [post, setPost] = useState(""); + const [into, setInto] = useState<Record<string, string>>({}); + + const act = async (key: string, body: Record<string, unknown>) => { + setBusy(key); + setError(null); + try { + const r = await call<{ view: EvidenceView }>(caseStageApi(caseId, "evidence"), { method: "POST", body }); + setView(r.view); + return true; + } catch (e) { + setError((e as Error).message); + return false; + } finally { + setBusy(null); + } + }; + + // A queued row is asked again every 1.5 s until its job ends. + const queued = view.rows.filter((r) => r.state === "queued").map((r) => r.id).join(","); + useEffect(() => { + if (!queued) return; + const t = setTimeout(async () => { + for (const id of queued.split(",")) { + try { + const r = await call<{ view: EvidenceView }>(caseStageApi(caseId, "evidence"), { method: "POST", body: { action: "refresh", id } }); + setView(r.view); + } catch (e) { + setError((e as Error).message); + } + } + }, 1500); + return () => clearTimeout(t); + }, [caseId, queued, view]); + + const pagesChannel = (r: EvidenceRow) => into[r.id] ?? r.slug ?? view.pagesChannels[0]?.slug ?? "__new"; + + return ( + <div> + <div className="grid gap-4 md:grid-cols-2"> + <form + aria-label="Wayback targets" + className="rounded-[3px] border border-seam px-3 py-2" + onSubmit={async (e) => { + e.preventDefault(); + if (await act("add", { action: "add", urls: urls.split(/\s+/).filter(Boolean), dates: dates.split(/[\s,]+/).filter(Boolean) })) { + setUrls(""); + } + }} + > + <h2 className="micro mb-1">Wayback captures at chosen dates</h2> + <label className="block text-[12px] text-muted"> + Pages, one per line + <textarea value={urls} onChange={(e) => setUrls(e.target.value)} rows={3} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 font-mono text-[12px] text-text" /> + </label> + <label className="mt-1 block text-[12px] text-muted"> + Dates (YYYY-MM-DD, comma-separated; the capture nearest each) + <input value={dates} onChange={(e) => setDates(e.target.value)} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 font-mono text-[12px] text-text" /> + </label> + <Button type="submit" size="sm" className="mt-2" disabled={busy === "add" || !urls.trim()}> + Add targets + </Button> + </form> + <form + aria-label="Forum attachment" + className="rounded-[3px] border border-seam px-3 py-2" + onSubmit={async (e) => { + e.preventDefault(); + if (await act("forum", { action: "forum", slug: forum, post: post.trim() })) setPost(""); + }} + > + <h2 className="micro mb-1">A forum post&apos;s attachments and screenshot</h2> + <label className="block text-[12px] text-muted"> + Forum channel + <select aria-label="Forum channel" value={forum} onChange={(e) => setForum(e.target.value)} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 text-[13px] text-text"> + {view.forumChannels.map((c) => ( + <option key={c.slug} value={c.slug}> + {c.name} + </option> + ))} + </select> + </label> + <label className="mt-1 block text-[12px] text-muted"> + Post id + <input aria-label="Post id" value={post} onChange={(e) => setPost(e.target.value)} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 font-mono text-[12px] text-text" /> + </label> + <p className="mt-1 text-[11.5px] text-muted">Shown everywhere as a forum attachment, unverified: look at it before describing it.</p> + <Button type="submit" size="sm" className="mt-2" disabled={busy === "forum" || !forum || !post.trim()}> + Capture the post + </Button> + </form> + </div> + {error && <p role="alert" className="mt-2 text-[12.5px] text-reject-text">{error}</p>} + + <Table className="mt-4" aria-label="Captures"> + <thead> + <tr> + <TH>Evidence</TH> + <TH>Page or post</TH> + <TH>Date</TH> + <TH>State</TH> + <TH>Do</TH> + <TH>For</TH> + </tr> + </thead> + <tbody> + {view.rows.length === 0 && ( + <tr> + <TD colSpan={6} className="text-muted"> + Nothing captured yet. + </TD> + </tr> + )} + {view.rows.map((r) => ( + <tr key={r.id} data-evidence={r.id} data-kind={r.kind} data-state={r.state}> + <TD> + <span data-evidence-label="" className={r.kind === "forum-attachment" ? "text-doubt-text" : r.state === "excluded" ? "text-doubt-text" : "text-text"}> + {r.label} + </span> + {r.fileUrls && ( + <span className="mt-1 flex flex-wrap gap-1.5"> + {r.fileUrls.map((f) => ( + <a key={f.name} href={f.url} target="_blank" rel="noreferrer" title={`${f.name}: ${r.label}`} className="block"> + {/* eslint-disable-next-line @next/next/no-img-element */} + <img src={f.url} alt={`${f.name}, ${r.label}`} className="h-12 w-12 rounded-[2px] border border-seam object-cover" /> + </a> + ))} + </span> + )} + </TD> + <TD> + <a href={r.state === "captured" && r.captureTs ? `https://web.archive.org/web/${r.captureTs}/${r.url}` : r.url} target="_blank" rel="noreferrer" className="ink-link font-mono text-[12px] break-all"> + {r.url} + </a> + {r.slug && <span className="block text-[11px] text-muted">into {r.slug}</span>} + </TD> + <TD className="whitespace-nowrap font-mono text-[12px]">{iso(r.captureTs) || iso(r.at) || "—"}</TD> + <TD> + <span className={badgeVariants({ variant: STATE_BADGE[r.state], size: "sm" })}>{r.state}</span> + {r.message && r.state !== "excluded" && <span className="block text-[11.5px] text-muted">{r.message}</span>} + </TD> + <TD> + {r.kind === "wayback" && (r.state === "planned" || r.state === "failed") && ( + <span className="flex flex-wrap items-center gap-1.5"> + <Button type="button" size="sm" variant="quiet" disabled={busy === r.id} onClick={() => act(r.id, { action: "lookup", id: r.id })}> + Look up + </Button> + <select + aria-label={`Capture ${r.id} into`} + value={pagesChannel(r)} + onChange={(e) => setInto({ ...into, [r.id]: e.target.value })} + className="rounded-[3px] border border-seam bg-ground px-1.5 py-0.5 text-[12px] text-text" + > + {view.pagesChannels.map((c) => ( + <option key={c.slug} value={c.slug}> + {c.name} + </option> + ))} + <option value="__new">a new Wayback pages channel</option> + </select> + <Button + type="button" + size="sm" + disabled={busy === r.id} + onClick={() => + act(r.id, pagesChannel(r) === "__new" ? { action: "capture", id: r.id, create: { name: `${new URL(r.url).hostname} pages` } } : { action: "capture", id: r.id, slug: pagesChannel(r) }) + } + > + Capture + </Button> + </span> + )} + {r.state === "queued" && <span className="text-[12px] text-muted">the editor&apos;s job {r.job} is running</span>} + </TD> + <TD> + {r.state === "captured" ? ( + <select + aria-label={`Attach ${r.id} to a finding`} + value="" + onChange={(e) => e.target.value && act(r.id, { action: "attach", id: r.id, finding: e.target.value })} + className="rounded-[3px] border border-seam bg-ground px-1.5 py-0.5 text-[12px] text-text" + > + <option value="">{r.findings?.length ? r.findings.join(", ") : "attach to…"}</option> + {view.findings + .filter((f) => !r.findings?.includes(f.row)) + .map((f) => ( + <option key={f.row} value={f.row}> + {f.row}: {f.quote} + </option> + ))} + </select> + ) : ( + <span className="text-[12px] text-muted">{r.findings?.join(", ") || "—"}</span> + )} + </TD> + </tr> + ))} + </tbody> + </Table> + </div> + ); +} diff --git a/umtool/components/research/stages/LeadsPanel.tsx b/umtool/components/research/stages/LeadsPanel.tsx @@ -0,0 +1,257 @@ +"use client"; + +import { Fragment, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Table, TD, TH } from "@/components/ui/table"; +import { cn } from "@/lib/utils"; +import { caseStageApi } from "@/lib/research/case-stage-hrefs"; +import type { LeadContext, LeadRow, LeadsView } from "@/lib/research/case-leads"; +import type { LeadDisposition } from "yt-dlp-transcript-common/lib/research/caseTypes"; + +// STAGE 8, LEADS (release 38 lane C): the accounts and URLs a posts or forum +// channel links most, with context on demand, a role note and a disposition +// each. never-archive withholds the lead for good (its name becomes one of +// the case's private names, as a hash); archive creates its channel through +// the editor, on no site, and starts its first fetch. + +const DISPOSITION_LABEL: Record<LeadDisposition, string> = { + archive: "Archive", + watch: "Watch", + "never-archive": "Never archive", +}; + +async function call<T>(url: string, init?: { method?: string; body?: unknown }): Promise<T> { + const res = await fetch(url, { + method: init?.method ?? "GET", + headers: init?.body !== undefined ? { "content-type": "application/json" } : undefined, + body: init?.body !== undefined ? JSON.stringify(init.body) : undefined, + cache: "no-store", + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body?.error ?? `HTTP ${res.status}`); + return body as T; +} + +export default function LeadsPanel({ caseId, initial }: { caseId: string; initial: LeadsView }) { + const [view, setView] = useState(initial); + const [error, setError] = useState<string | null>(null); + const [note, setNote] = useState<string | null>(null); + const [busy, setBusy] = useState<string | null>(null); + const [roles, setRoles] = useState<Record<string, string>>({}); + const [context, setContext] = useState<Record<string, LeadContext | "loading">>({}); + + const load = async (channel: string) => { + setBusy("scan"); + setError(null); + try { + setView(await call<LeadsView>(`${caseStageApi(caseId, "leads")}?channel=${encodeURIComponent(channel)}`)); + setContext({}); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + }; + + // `disposition` undefined: the role alone changes; "" makes the lead undecided again. + const decide = async (lead: LeadRow, disposition: LeadDisposition | "" | undefined, role?: string) => { + setBusy(lead.key); + setError(null); + setNote(null); + try { + const r = await call<{ view: LeadsView; created?: { slug: string; jobIds: string[] } }>(caseStageApi(caseId, "leads"), { + method: "POST", + body: { + key: lead.key, + ...(disposition !== undefined ? { disposition: disposition || null } : {}), + ...(role !== undefined ? { role } : {}), + url: lead.url, + count: lead.count, + channel: view.channel, + }, + }); + setView(r.view); + if (r.created) setNote(`Created ${r.created.slug} on no site${r.created.jobIds.length ? "; its first fetch is queued" : ""}.`); + else if (disposition === "never-archive") setNote("Withheld: the name is one of the case's private names now, kept as a hash."); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + }; + + const older = async (lead: LeadRow) => { + setBusy(lead.key); + setError(null); + try { + const r = await call<{ jobId: string; slug: string }>(caseStageApi(caseId, "leads/older"), { method: "POST", body: { key: lead.key } }); + setNote(`The older walk of ${r.slug} is queued.`); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + }; + + const toggleContext = async (lead: LeadRow) => { + if (context[lead.key]) { + const { [lead.key]: _gone, ...rest } = context; + setContext(rest); + return; + } + setContext({ ...context, [lead.key]: "loading" }); + try { + const c = await call<LeadContext>( + `${caseStageApi(caseId, "leads/context")}?channel=${encodeURIComponent(view.channel ?? "")}&key=${encodeURIComponent(lead.key)}`, + ); + setContext((m) => ({ ...m, [lead.key]: c })); + } catch (e) { + setError((e as Error).message); + } + }; + + const listed = view.leads.filter((l) => !l.withheld); + const withheld = view.leads.filter((l) => l.withheld); + + return ( + <div> + <div className="flex flex-wrap items-end gap-3"> + <label className="text-[12px] text-muted"> + Posts or forum channel + <select + aria-label="Posts or forum channel" + value={view.channel ?? ""} + onChange={(e) => e.target.value && load(e.target.value)} + className="mt-0.5 block rounded-[3px] border border-seam bg-ground px-2 py-1 text-[13px] text-text" + > + {!view.channel && <option value="">—</option>} + {view.channels.map((c) => ( + <option key={c.slug} value={c.slug}> + {c.name} ({c.platform}){c.inScope ? " · in scope" : ""} + </option> + ))} + </select> + </label> + <p data-leads-summary="" className="text-[12.5px] text-muted"> + {view.posts} posts read · {listed.length} leads + {view.withheld > 0 && <> · <span data-withheld-count="">{view.withheld} withheld (the case&apos;s private names)</span></>} + </p> + </div> + {note && <p role="status" className="mt-2 text-[12.5px] text-text-2">{note}</p>} + {error && <p role="alert" className="mt-2 text-[12.5px] text-reject-text">{error}</p>} + {!view.channel && <p className="mt-3 text-[13px] text-muted">No posts or forum channel is in the case&apos;s scope: pick one.</p>} + + {view.channel && ( + <Table className="mt-3" aria-label="Leads"> + <thead> + <tr> + <TH>Lead</TH> + <TH>Platform</TH> + <TH className="text-right">Posts</TH> + <TH>Role</TH> + <TH>Disposition</TH> + <TH>Channel</TH> + <TH /> + </tr> + </thead> + <tbody> + {listed.map((l) => ( + <Fragment key={l.key}> + <tr data-lead={l.key} data-disposition={l.disposition ?? ""}> + <TD> + <a href={l.url} target="_blank" rel="noreferrer" className="ink-link font-mono text-[12px]"> + {l.key} + </a> + </TD> + <TD>{l.platform}</TD> + <TD numeric>{l.count}</TD> + <TD> + <input + aria-label={`Role of ${l.key}`} + value={roles[l.key] ?? l.role ?? ""} + placeholder="who this is to the case" + onChange={(e) => setRoles({ ...roles, [l.key]: e.target.value })} + onBlur={() => roles[l.key] !== undefined && roles[l.key] !== (l.role ?? "") && decide(l, undefined, roles[l.key])} + className="w-56 rounded-[3px] border border-seam bg-ground px-1.5 py-0.5 text-[12.5px] text-text" + /> + </TD> + <TD> + <select + aria-label={`Disposition of ${l.key}`} + value={l.disposition ?? ""} + disabled={busy === l.key} + onChange={(e) => decide(l, e.target.value as LeadDisposition | "", roles[l.key])} + className="rounded-[3px] border border-seam bg-ground px-1.5 py-0.5 text-[12.5px] text-text" + > + <option value="">undecided</option> + {view.dispositions.map((d) => ( + <option key={d} value={d}> + {DISPOSITION_LABEL[d]} + </option> + ))} + </select> + </TD> + <TD> + {l.channel ? ( + <span className="flex items-center gap-2"> + <span data-lead-channel="" className="font-mono text-[12px]"> + {l.channel} + </span> + <Button type="button" size="sm" variant="quiet" disabled={busy === l.key} onClick={() => older(l)}> + Older walk + </Button> + </span> + ) : ( + <span className="text-muted">—</span> + )} + </TD> + <TD> + <Button type="button" size="sm" variant="quiet" aria-expanded={!!context[l.key]} onClick={() => toggleContext(l)}> + Context + </Button> + </TD> + </tr> + {context[l.key] && ( + <tr data-lead-context={l.key}> + <TD colSpan={7} className="bg-panel"> + {context[l.key] === "loading" ? ( + <span className="text-muted">Reading the posts…</span> + ) : ( + <ul className="flex flex-col gap-1"> + {(context[l.key] as LeadContext).snippets.map((s) => ( + <li key={s.post} className="text-[12.5px]"> + <a href={s.url} target="_blank" rel="noreferrer" className="ink-link font-mono text-[11px]"> + {s.position ? `#${s.position}` : s.post} + </a>{" "} + <span className="text-muted"> + {s.author} · {s.date} + </span>{" "} + <span className="text-text-2">{s.text}</span> + </li> + ))} + </ul> + )} + </TD> + </tr> + )} + </Fragment> + ))} + {withheld.map((l, i) => ( + <tr key={l.key} data-lead-withheld="" data-disposition="never-archive"> + <TD className="text-muted">[name withheld]</TD> + <TD>{l.platform}</TD> + <TD numeric>{l.count}</TD> + <TD className={cn("text-muted", !l.role && "italic")}>{l.role || "kept as a hash"}</TD> + <TD>{DISPOSITION_LABEL["never-archive"]}</TD> + <TD className="text-muted">never</TD> + <TD> + <span className="sr-only">withheld lead {i + 1}</span> + </TD> + </tr> + ))} + </tbody> + </Table> + )} + </div> + ); +} diff --git a/umtool/components/research/stages/VerifyPanel.tsx b/umtool/components/research/stages/VerifyPanel.tsx @@ -0,0 +1,386 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { caseStageApi } from "@/lib/research/case-stage-hrefs"; +import type { AudioAnswer, CaptionsView, VerifyRow, VerifyView } from "@/lib/research/case-verify"; +import type { VerifyStatus } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import type { WordOp } from "yt-dlp-transcript-common/lib/research/wordDiff"; + +// STAGE 7, VERIFY (release 38 lane C): the findings on the left; on the right +// one finding's window in every caption track side by side with the quote's +// words lit, the audio check (the window transcribed through the editor and +// diffed with the quote), its status, and a correction by hand that keeps the +// reader's words. Nothing here needs a model. + +const STATUS_LABEL: Record<VerifyStatus, string> = { + unverified: "Unverified", + verified: "Verified", + corrected: "Corrected", + disputed: "Disputed", + quarantined: "Quarantined", +}; +const STATUS_BADGE: Record<VerifyStatus, "info" | "neutral" | "open" | "blocking" | "state"> = { + unverified: "info", + verified: "neutral", + corrected: "neutral", + disputed: "blocking", + quarantined: "open", +}; + +const clock = (t: number) => { + const s = Math.max(0, Math.floor(t)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const ss = String(s % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; + +async function call<T>(url: string, init?: { method?: string; body?: unknown }): Promise<T> { + const res = await fetch(url, { + method: init?.method ?? "GET", + headers: init?.body !== undefined ? { "content-type": "application/json" } : undefined, + body: init?.body !== undefined ? JSON.stringify(init.body) : undefined, + cache: "no-store", + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body?.error ?? `HTTP ${res.status}`); + return body as T; +} + +function Diff({ ops }: { ops: WordOp[] }) { + return ( + <p data-audio-diff="" className="font-reader text-[14px] leading-relaxed"> + {ops.map((o, i) => ( + <span key={i}> + {i > 0 && " "} + {o.op === "same" ? ( + <span data-diff="same">{o.word}</span> + ) : o.op === "missing" ? ( + <del data-diff="missing" title="in the quote, not heard" className="text-reject-text"> + {o.word} + </del> + ) : ( + <ins data-diff="extra" title="heard, not in the quote" className="text-doubt-text no-underline"> + [{o.word}] + </ins> + )} + </span> + ))} + </p> + ); +} + +export default function VerifyPanel({ caseId, initial }: { caseId: string; initial: VerifyView }) { + const [view, setView] = useState(initial); + const [sel, setSel] = useState<string | null>(initial.rows[0]?.row ?? null); + const [filter, setFilter] = useState<VerifyStatus | "all">("all"); + const [caps, setCaps] = useState<CaptionsView | null>(null); + const [capsError, setCapsError] = useState<string | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<VerifyStatus>("unverified"); + const [note, setNote] = useState(""); + const [quote, setQuote] = useState(""); + const [speaker, setSpeaker] = useState(""); + const [whilePaused, setWhilePaused] = useState(false); + const [audio, setAudio] = useState<{ state: string; message?: string; ops?: WordOp[] } | null>(null); + const poll = useRef<ReturnType<typeof setTimeout> | null>(null); + + const row: VerifyRow | null = view.rows.find((r) => r.row === sel) ?? null; + + useEffect(() => { + if (!row) return; + setStatus(row.status); + setNote(row.verify?.note ?? ""); + setQuote(row.quote); + setSpeaker(row.speaker); + setAudio(null); + setError(null); + if (poll.current) clearTimeout(poll.current); + // Only when the selection moves: a save keeps what is on screen. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sel]); + + useEffect(() => { + if (!sel) return; + let live = true; + setCaps(null); + setCapsError(null); + call<CaptionsView>(`${caseStageApi(caseId, "verify/captions")}?row=${encodeURIComponent(sel)}`) + .then((c) => live && setCaps(c)) + .catch((e) => live && setCapsError((e as Error).message)); + return () => { + live = false; + }; + }, [caseId, sel, view.rows.find((r) => r.row === sel)?.quote]); + + useEffect(() => () => { + if (poll.current) clearTimeout(poll.current); + }, []); + + const save = useCallback( + async (patch: { status: VerifyStatus; quote?: string; speaker?: string; how?: string }) => { + if (!row) return; + setBusy(true); + setError(null); + try { + const r = await call<{ view: VerifyView }>(caseStageApi(caseId, "verify"), { method: "POST", body: { row: row.row, note, ...patch } }); + setView(r.view); + // The status buttons show what was saved (a correction by hand is "corrected"). + setStatus(patch.status); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(false); + } + }, + [caseId, note, row], + ); + + const step = useCallback( + async (body: Record<string, unknown>) => { + if (!row) return; + try { + const a = await call<AudioAnswer>(caseStageApi(caseId, "verify/audio"), { method: "POST", body: { row: row.row, whilePaused, ...body } }); + if (a.state === "done") { + setAudio({ state: "done", ops: a.ops }); + setView(await call<VerifyView>(caseStageApi(caseId, "verify"))); + return; + } + if (a.state === "failed") { + setAudio({ state: "failed", message: a.message }); + return; + } + setAudio({ state: a.state, message: a.message }); + poll.current = setTimeout(() => step(a.state === "fetching" ? { fetchJob: a.fetchJob } : { job: a.job }), 1000); + } catch (e) { + setAudio({ state: "failed", message: (e as Error).message }); + } + }, + [caseId, row, whilePaused], + ); + + const shown = view.rows.filter((r) => filter === "all" || r.status === filter); + const changed = row ? quote.trim() !== row.quote || speaker.trim() !== row.speaker : false; + const lastAudio = row?.verify?.audio; + + return ( + <div className="grid min-h-0 grid-cols-1 gap-0 border-t border-seam md:grid-cols-[minmax(240px,320px)_1fr]"> + <aside aria-label="Findings" className="min-h-0 overflow-y-auto border-seam py-3 pr-3 md:max-h-[760px] md:border-r"> + <div role="group" aria-label="Filter by status" className="mb-2 flex flex-wrap gap-1"> + {(["all", ...view.statuses] as const).map((s) => ( + <button + key={s} + type="button" + aria-pressed={filter === s} + onClick={() => setFilter(s)} + className={badgeVariants({ variant: filter === s ? "on" : "neutral", size: "md" })} + > + {s === "all" ? `All ${view.rows.length}` : `${STATUS_LABEL[s]} ${view.counts[s]}`} + </button> + ))} + </div> + {view.bad.length > 0 && ( + <p role="alert" className="mb-2 text-[12px] text-reject-text"> + findings.jsonl line {view.bad[0].line} does not parse: {view.bad[0].error}. Nothing is rewritten until it is fixed. + </p> + )} + {view.rows.length === 0 && <p className="text-[12.5px] text-muted">No findings yet: the read stage writes them.</p>} + <ul className="flex flex-col gap-1"> + {shown.map((r) => ( + <li key={r.row}> + <button + type="button" + data-finding={r.row} + data-status={r.status} + aria-current={r.row === sel ? "true" : undefined} + onClick={() => setSel(r.row)} + className={cn( + "w-full rounded-[3px] border px-2 py-1.5 text-left text-[12.5px]", + r.row === sel ? "border-muted bg-panel-2" : "border-transparent hover:bg-panel-2", + )} + > + <span className="flex items-center gap-1.5"> + <span className="font-mono text-[11px] text-muted">{r.row}</span> + <span className={badgeVariants({ variant: STATUS_BADGE[r.status], size: "sm" })}>{STATUS_LABEL[r.status]}</span> + {r.forum && <span className={badgeVariants({ variant: "state", size: "sm" })}>forum</span>} + </span> + <span className="mt-0.5 line-clamp-2 block text-text-2">“{r.quote}”</span> + <span className="block text-[11px] text-muted"> + {r.title} · {clock(r.t)} + </span> + {r.evidenceLabels.map((l, i) => ( + <span key={i} data-evidence-label="" className="block text-[11px] text-doubt-text"> + {l} + </span> + ))} + </button> + </li> + ))} + </ul> + </aside> + + {row ? ( + <section aria-label={`Finding ${row.row}`} data-verify-detail={row.row} className="min-h-0 overflow-y-auto py-3 md:max-h-[760px] md:pl-5"> + <div className="mb-3"> + <div className="micro"> + {row.row} · {row.category} · relevance {row.relevance} · by {row.by} + </div> + <blockquote data-quote="" className="font-reader my-1 text-[17px] leading-snug text-text"> + “{row.quote}” + </blockquote> + <div className="text-[12.5px] text-muted"> + {row.speaker} ·{" "} + <a href={row.url} target="_blank" rel="noreferrer" className="ink-link"> + {row.title} at {clock(row.t)} + </a> + </div> + {row.verify?.original && ( + <p data-original="" className="mt-1 text-[12.5px] text-muted"> + The reader wrote: “{row.verify.original.quote}”{row.verify.original.speaker ? ` (${row.verify.original.speaker})` : ""} + </p> + )} + {row.forum && row.status !== "quarantined" && ( + <p data-forum-hint="" className="mt-1 text-[12.5px] text-doubt-text"> + First seen on a forum: quarantine it until an independent source agrees, and look at any attachment before describing it. + </p> + )} + {row.evidenceLabels.length > 0 && ( + <ul aria-label="Evidence" className="mt-1 text-[12px] text-doubt-text"> + {row.evidenceLabels.map((l, i) => ( + <li key={i} data-evidence-label=""> + {l} + </li> + ))} + </ul> + )} + </div> + + <h2 className="micro mb-1">Captions, side by side</h2> + {capsError && <p role="alert" className="text-[12.5px] text-reject-text">{capsError}</p>} + {caps?.note && <p className="text-[12.5px] text-muted">{caps.note}</p>} + {!caps && !capsError && <p className="text-[12.5px] text-muted">Reading the window…</p>} + {caps && caps.tracks.length > 0 && ( + <div data-tracks="" className={cn("grid gap-3", caps.tracks.length > 1 ? "md:grid-cols-2" : "")}> + {caps.tracks.map((tr) => ( + <div key={tr.track} data-track={tr.track} className="rounded-[3px] border border-seam bg-panel px-3 py-2"> + <div className="mb-1 flex items-center gap-2 text-[12px]"> + <span className="font-medium text-text">{tr.label}</span> + <span className="font-mono text-[11px] text-muted">{tr.track}</span> + <span data-track-holds={tr.holds ? "yes" : "no"} className={cn("ml-auto text-[11px]", tr.holds ? "text-kept-text" : "text-doubt-text")}> + {tr.holds ? "holds the quote" : `${tr.matched} of ${tr.words} words`} + </span> + </div> + <ol className="flex flex-col gap-0.5 text-[13px] leading-snug"> + {tr.cues.map((c, i) => ( + <li key={i} className="flex gap-2"> + {tr.kind !== "post" && <span className="w-12 shrink-0 font-mono text-[11px] text-muted">{clock(c.start)}</span>} + <span className="text-text-2"> + {c.parts.map((p, j) => + p.hit ? ( + <mark key={j} data-lit="" className="rounded-[2px] bg-[color-mix(in_srgb,var(--signal)_24%,transparent)] text-text"> + {p.text} + </mark> + ) : ( + <span key={j}>{p.text}</span> + ), + )} + </span> + </li> + ))} + </ol> + </div> + ))} + </div> + )} + + <h2 className="micro mb-1 mt-4">Audio check</h2> + <div className="flex flex-wrap items-center gap-3 text-[12.5px]"> + <Button type="button" size="sm" disabled={busy || audio?.state === "transcribing" || audio?.state === "fetching"} onClick={() => step({})}> + Audio check + </Button> + <label className="flex items-center gap-1.5 text-muted"> + <input type="checkbox" checked={whilePaused} onChange={(e) => setWhilePaused(e.target.checked)} /> + Run even while transcription is paused + </label> + {audio && audio.state !== "done" && ( + <span data-audio-state={audio.state} className={audio.state === "failed" ? "text-reject-text" : "text-muted"} role={audio.state === "failed" ? "alert" : undefined}> + {audio.message} + </span> + )} + </div> + {lastAudio && ( + <div data-audio-result="" className="mt-2 rounded-[3px] border border-seam px-3 py-2"> + <div className="text-[12.5px]"> + <span data-audio-heard="" className={lastAudio.matched === lastAudio.words ? "text-kept-text" : "text-doubt-text"}> + Heard {lastAudio.matched} of {lastAudio.words} words + </span> + <span className="text-muted"> + {" "} + · {lastAudio.worker ?? "a local worker"} · {new Date(lastAudio.at).toLocaleString()} + </span> + </div> + {audio?.ops && <Diff ops={audio.ops} />} + <p className="mt-1 text-[12px] text-muted">What the worker heard: {lastAudio.text}</p> + </div> + )} + + <h2 className="micro mb-1 mt-4">Status</h2> + <div role="group" aria-label="Verify status" className="flex flex-wrap gap-1"> + {view.statuses.map((s) => ( + <button + key={s} + type="button" + aria-pressed={status === s} + onClick={() => setStatus(s)} + className={badgeVariants({ variant: status === s ? "on" : "neutral", size: "md" })} + > + {STATUS_LABEL[s]} + </button> + ))} + </div> + <label className="mt-2 block text-[12px] text-muted"> + Note + <input value={note} onChange={(e) => setNote(e.target.value)} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 text-[13px] text-text" /> + </label> + <div className="mt-2 flex gap-2"> + <Button type="button" variant="go" size="sm" disabled={busy || changed} onClick={() => save({ status, how: lastAudio ? "audio" : undefined })}> + Save status + </Button> + </div> + + <h2 className="micro mb-1 mt-4">Correct by hand</h2> + <label className="block text-[12px] text-muted"> + Quote (verbatim) + <textarea + value={quote} + onChange={(e) => setQuote(e.target.value)} + rows={3} + className="font-reader mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 text-[14px] text-text" + /> + </label> + <label className="mt-1 block text-[12px] text-muted"> + Speaker + <input value={speaker} onChange={(e) => setSpeaker(e.target.value)} className="mt-0.5 block w-full rounded-[3px] border border-seam bg-ground px-2 py-1 text-[13px] text-text" /> + </label> + <div className="mt-2 flex items-center gap-2"> + <Button type="button" size="sm" disabled={busy || !changed} onClick={() => save({ status: "corrected", quote: quote.trim(), speaker: speaker.trim() })}> + Save as corrected + </Button> + <span className="text-[12px] text-muted">The reader&apos;s words are kept.</span> + </div> + {error && ( + <p role="alert" className="mt-2 text-[12.5px] text-reject-text"> + {error} + </p> + )} + </section> + ) : ( + <section className="px-5 py-4 text-[13px] text-muted">Pick a finding.</section> + )} + </div> + ); +} diff --git a/umtool/components/research/stages/types.ts b/umtool/components/research/stages/types.ts @@ -0,0 +1,10 @@ +import type { EvidenceView } from "@/lib/research/case-evidence"; +import type { LeadsView } from "@/lib/research/case-leads"; +import type { VerifyView } from "@/lib/research/case-verify"; + +/** Lane C's stages' first frames on the case pipeline page, each its view or why it could not be read. */ +export type CaseStagePanels = { + verify: VerifyView | { error: string }; + leads: LeadsView | { error: string }; + evidence: EvidenceView | { error: string }; +}; diff --git a/umtool/docs/README.md b/umtool/docs/README.md @@ -8,7 +8,7 @@ anywhere), Pinned, the **Running** list with today's API spend, and the theme (* | Place | Addresses | Sheet | |---|---|---| | Inbox | `/` (`?hidden=1`, `?muted=1`) | [inbox.md](inbox.md) | -| Research | `/research`, `/research/<case>`, `/research/runs`, `/research/runs/<article>/<n>`, `/research/archive` | [research.md](research.md) | +| Research | `/research`, `/research/<case>`, `/research/<case>/{verify,leads,evidence}`, `/research/runs`, `/research/runs/<article>/<n>`, `/research/archive` | [research.md](research.md) | | Work | `/work`, `/projects` (the projects grid) | [work.md](work.md) | | A site | `/sites/<site>` (`?ws=&rel=`) | [work.md](work.md) | | A piece | `/articles/<id>`, `/sites/<site>/<report>`, `/projects/<path>` (`?tab=`); an article's `/evidence` and `/compare` | [piece.md](piece.md) | diff --git a/umtool/docs/research.md b/umtool/docs/research.md @@ -110,6 +110,38 @@ the other. The files sit beside `case.json`, never in it (`common/lib/research/c findings to the board, one section per reader group, and the board's hand-offs take it from there. - **9 Date checks** — the subject's uploads around each key date and the latest after it, captioned or not, and the sentence ("no response found in captioned uploads through <date>", or the findings that are one). +### 7 Verify, 8 Leads, 10 Evidence (release 38 lane C) + +Three more panels of the pipeline page (`#stage-verify`, `#stage-leads`, `#stage-evidence`, in its **Stages** list). +They write `findings.jsonl` (through the store's lock and the privacy gate), `leads.json` and `evidence.json`; no model +is needed for any of them; every fetch, capture, transcription and channel is the editor's (its ops door), paced by it. + +- **7 Verify**: the findings (`findings.jsonl`) with their status and a **forum** tag for one + first seen on a forum. A finding's window in every caption track it has **side by side** (`en-orig` first, then `en`, + then a transcription; a post's text for a post), the quote's words lit where they land and "holds the quote" or + "N of M words" per track. **Audio check**: the held media (or a clip fetched through the editor) transcribed by the + editor's `transcribe` on a local worker — **Run even while transcription is paused** sends `whilePaused` — then + "Heard N of M words" and the word diff (missing struck through, extra in brackets), kept on the finding + (`verify.audio`). **Status**: Unverified, Verified, Corrected, Disputed, Quarantined (**Save status**, with a note). + **Correct by hand** (quote, speaker) saves as Corrected and keeps the reader's words once in `verify.original` + ("The reader wrote: …"). A hand-written quote, speaker or note that holds one of the case's private names is refused + by the privacy gate (the row id and a count, never the name). +- **8 Leads** (`?leads=<slug>` picks the channel on the first frame): over a posts or forum channel (the scope's first by default), + the accounts and pages its posts link most, **counted by post** (the forum's own links left out); a lead whose name + is a private name is counted as withheld, never listed. **Context** shows the posts that link it (private names + withheld). Each lead: a **Role** note and a **Disposition** — **Never archive** adds the lead's name to the case's + private names as its sha256 (the Private names box's writer, so it is withheld from the stored candidates and + batches too) and keeps the lead only as that hash (`[name withheld]`, no URL, in `leads.json`); + **Archive** creates the channel through `create-channel` **on no site** (X never on a site; a site is the + operator's) and starts its first fetch, then **Older walk** is `fetch-posts {older}`; **Watch** starts nothing. +- **10 Evidence** (`evidence.json`): **Wayback captures at chosen dates** for a list of + pages — **Look up** is `wayback-lookup` (a 403 is the row **excluded from the Wayback Machine (cause unknown)**), + **Capture** is `import-page {slug, url, at}` into a Wayback pages channel (picked, or a new one on no site); **A forum + post's attachments and screenshot** through `capture-posts`, labelled **forum attachment, post #N, unverified** on + the row, its thumbnails, the finding it is attached to and the export. A queued row is asked again every 1.5 s. + **Attach to a finding** records it on both sides (`FindingRow.evidence`). +- **The export** (`REPORT.md`, `REPORT.html`) lists `evidence.json` in an **Evidence** section before Coverage + (`common/lib/research/caseEvidence.ts`), and a finding's own line names its forum attachment the same way. ## Agent runs, `/research/runs` and `/research/runs/<article>/<n>` @@ -142,5 +174,5 @@ Held counts are kept 5 minutes per channel ("Held counts from 3 min ago (kept 5 ## Routes `/api/research/{sources,scope,search,window,coverage,log,media,fetch}`, `/api/research/cases[/<id>[/quotes[/<qid>] -|/verify|/export.md|/handoff|/pipeline[/<op>]]]` (the pipeline's ops are listed in its route), `/api/research/runs/<article>/<n>[/board]` — JSON, `no-store`, errors in words (400 bad +|/verify|/export.md|/handoff|/pipeline[/<op>]|/stages/{verify[/captions|/audio],leads[/context|/older],evidence}]]` (the pipeline's ops are listed in its route), `/api/research/runs/<article>/<n>[/board]` — JSON, `no-store`, errors in words (400 bad input, 404 nothing there, 409 an unreadable file, 502 a source that cannot be read). diff --git a/umtool/e2e/case-stages.spec.ts b/umtool/e2e/case-stages.spec.ts @@ -0,0 +1,227 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { EXCLUDED_URL, FORUM, PAGES, PRIVATE_NAME, STAGES_CASE, TARGET_URL, nameHash } from "./fixtures/case-stages-fixture.mjs"; +import { EN_REWRITE } from "./fixtures/research-fixture.mjs"; +import { researchCaseHref, researchCasePipelineHref } from "../lib/research/hrefs"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// A research case's lane C stages (release 38) on the fixture case +// `fixture-pipeline` (e2e/fixtures/case-stages-fixture.mjs) and the stub +// editor (editor-stub-case-stages.mjs): verify (both tracks side by side, a +// correction that keeps the reader's words, the audio check while paused, a +// forum finding quarantined), leads (counts, never-archive as a hash, archive +// on no site) and evidence (an excluded target, a capture, a forum attachment +// marked unverified everywhere, and in the export's Evidence section). The +// stages are panels of the case's pipeline page (lane A's), #stage-verify, +// #stage-leads, #stage-evidence. In order: each test builds on the last. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const CASE_DIR = path.join(FIXTURE, ".umtool", "research", STAGES_CASE); +const read = (name: string) => readFileSync(path.join(CASE_DIR, name), "utf8"); +const findings = () => + read("findings.jsonl") + .trim() + .split("\n") + .map((l) => JSON.parse(l)); +const asked = (): { path: string; body: Record<string, unknown> }[] => { + try { + return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); + } catch { + return []; + } +}; + +// Screenshots for the review, when asked for (E2E_CASE_STAGES_SHOTS=<dir>). +const SHOTS = process.env.E2E_CASE_STAGES_SHOTS ?? ""; +async function shot(page: Page, name: string, stageId: string) { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + await page.locator(`#stage-${stageId}`).screenshot({ path: path.join(SHOTS, `${name}.png`) }); +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [researchCasePipelineHref(STAGES_CASE), researchCaseHref(STAGES_CASE)]); +}); + +const stage = (page: Page, id: "verify" | "leads" | "evidence") => page.locator(`#stage-${id}`); + +test("the pipeline lists the stages; verify shows both tracks side by side, and a correction keeps the reader's words", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.goto(researchCaseHref(STAGES_CASE)); + await page.locator("[data-case-pipeline]").click(); + await expect(page).toHaveURL(new RegExp(`${researchCasePipelineHref(STAGES_CASE)}$`)); + const nav = page.getByRole("navigation", { name: "Stages" }); + for (const n of ["7 Verify", "8 Leads", "10 Evidence"]) await expect(nav.getByRole("link", { name: n })).toBeVisible(); + await nav.getByRole("link", { name: "7 Verify" }).click(); + + const list = stage(page, "verify").getByRole("complementary", { name: "Findings" }); + await expect(list.locator("[data-finding]")).toHaveCount(3); + await expect(list.locator('[data-finding="f3"]')).toContainText("forum"); + const detail = page.locator('[data-verify-detail="f1"]'); + await expect(detail.locator("[data-quote]")).toContainText(EN_REWRITE.en); + const orig = detail.locator('[data-track="en-orig"]'); + const en = detail.locator('[data-track="en"]'); + // The window is read from the corpus on first view: give it the time a cold shard read takes on a busy machine. + await expect(orig).toContainText("original audio captions", { timeout: 20_000 }); + await expect(orig).toContainText(EN_REWRITE.orig); + await expect(en).toContainText(EN_REWRITE.en); + await expect(en.locator("[data-lit]")).toHaveText([EN_REWRITE.en]); + await expect(en.locator("[data-track-holds]")).toHaveText("holds the quote"); + await expect(orig.locator("[data-track-holds]")).toHaveText("4 of 5 words"); + + await detail.getByLabel("Quote (verbatim)").fill(EN_REWRITE.orig); + await detail.getByLabel("Note").fill("en-orig says called in; the en track rewrote it"); + await detail.getByRole("button", { name: "Save as corrected" }).click(); + await expect(list.locator('[data-finding="f1"]')).toHaveAttribute("data-status", "corrected"); + await expect(detail.locator("[data-original]")).toHaveText(`The reader wrote: “${EN_REWRITE.en}” (host)`); + await expect(detail.getByRole("group", { name: "Verify status" }).getByRole("button", { name: "Corrected", exact: true })).toHaveAttribute("aria-pressed", "true"); + await expect(detail.locator("[data-quote]")).toContainText(EN_REWRITE.orig); + await expect(orig.locator("[data-track-holds]")).toHaveText("holds the quote"); + const f1 = findings().find((r) => r.row === "f1"); + expect(f1.quote).toBe(EN_REWRITE.orig); + expect(f1.verify).toMatchObject({ status: "corrected", how: "hand", original: { quote: EN_REWRITE.en, speaker: "host" } }); + await shot(page, "verify-corrected", "verify"); + + // A private name in a hand-written note is refused, and the refusal never names it. + await detail.getByLabel("Note").fill(`checked with ${PRIVATE_NAME}`); + await detail.getByRole("button", { name: "Save status" }).click(); + await expect(detail.getByRole("alert")).toContainText("the privacy gate blocked the findings"); + await expect(detail.getByRole("alert")).toContainText("(f1)"); + await expect(detail.getByRole("alert")).not.toContainText(PRIVATE_NAME); +}); + +test("the audio check transcribes the window through the editor, while paused, and the finding is verified by ear", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.goto(researchCasePipelineHref(STAGES_CASE, "verify")); + const list = stage(page, "verify").getByRole("complementary", { name: "Findings" }); + await list.locator('[data-finding="f2"]').click(); + const detail = page.locator('[data-verify-detail="f2"]'); + await detail.getByLabel("Run even while transcription is paused").check(); + const before = asked().length; + await detail.getByRole("button", { name: "Audio check" }).click(); + await expect(detail.locator("[data-audio-heard]")).toHaveText("Heard 9 of 9 words", { timeout: 15_000 }); + await expect(detail.locator("[data-audio-diff] [data-diff=same]")).toHaveCount(9); + const req = asked().slice(before).find((r) => r.path === "/api/ops/transcribe"); + expect(req?.body).toMatchObject({ start: 2039, end: 2074, whilePaused: true }); + expect(String(req?.body.path)).toMatch(/harbor-radio\/data\/hr-2022a\/audio\.m4a$/); + await detail.getByRole("group", { name: "Verify status" }).getByRole("button", { name: "Verified", exact: true }).click(); + await detail.getByRole("button", { name: "Save status" }).click(); + await expect(list.locator('[data-finding="f2"]')).toHaveAttribute("data-status", "verified"); + expect(findings().find((r) => r.row === "f2").verify).toMatchObject({ status: "verified", how: "audio", audio: { matched: 9, words: 9 } }); + + // The forum finding: the hint, then quarantined. + await list.locator('[data-finding="f3"]').click(); + const f3 = page.locator('[data-verify-detail="f3"]'); + await expect(f3.locator("[data-forum-hint]")).toContainText("First seen on a forum"); + await expect(f3.locator('[data-track="post"]')).toContainText("forum post #3 by deckhand", { timeout: 20_000 }); + await f3.getByRole("group", { name: "Verify status" }).getByRole("button", { name: "Quarantined", exact: true }).click(); + await f3.getByRole("button", { name: "Save status" }).click(); + await expect(list.locator('[data-finding="f3"]')).toHaveAttribute("data-status", "quarantined"); + await expect(f3.locator("[data-forum-hint]")).toHaveCount(0); +}); + +test("leads: counted by post, a private name withheld; never-archive feeds a hash; archive creates on no site", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.goto(researchCasePipelineHref(STAGES_CASE, "leads")); + const leads = stage(page, "leads"); + await expect(leads.getByLabel("Posts or forum channel")).toHaveValue(FORUM); + await expect(page.locator("[data-leads-summary]")).toContainText("7 posts read · 5 leads"); + await expect(page.locator("[data-withheld-count]")).toHaveText("1 withheld (the case's private names)"); + const table = page.getByRole("table", { name: "Leads" }); + await expect(table.locator("[data-lead]")).toHaveCount(5); + await expect(table.locator('[data-lead="x:@harborwatch"] td').nth(2)).toHaveText("3"); + await expect(table.locator('[data-lead="x:@tidewatcher"] td').nth(2)).toHaveText("2"); + await expect(leads).not.toContainText(PRIVATE_NAME); + + // Context on demand. + await table.locator('[data-lead="x:@harborwatch"]').getByRole("button", { name: "Context" }).click(); + await expect(table.locator('[data-lead-context="x:@harborwatch"] li')).toHaveCount(3); + + // A role, then never-archive: withheld, its name a hash in the case's private names. + await table.getByLabel("Role of x:@tidewatcher").fill("the account the forum blames"); + await table.getByLabel("Role of x:@tidewatcher").blur(); + await expect.poll(() => (existsSync(path.join(CASE_DIR, "leads.json")) ? read("leads.json") : "")).toContain("the account the forum blames"); + await table.getByLabel("Disposition of x:@tidewatcher").selectOption("never-archive"); + await expect(leads.locator('p[role="status"]')).toContainText("kept as a hash"); + await expect(table.locator('[data-lead="x:@tidewatcher"]')).toHaveCount(0); + await expect(table.locator("[data-lead-withheld]")).toHaveCount(1); + await expect(table.locator("[data-lead-withheld]")).toContainText("[name withheld]"); + await expect(table.locator("[data-lead-withheld]")).toContainText("the account the forum blames"); + const pipeline = JSON.parse(read("pipeline.json")); + expect(pipeline.privateNames.sha256).toContain(nameHash("TideWatcher")); + expect(read("leads.json").toLowerCase()).not.toContain("tidewatcher"); + await expect(page.locator("[data-withheld-count]")).toHaveText("2 withheld (the case's private names)"); + + // Archive: the channel created through the editor, on no site, its first fetch started. + await table.getByLabel("Disposition of x:@harborwatch").selectOption("archive"); + await expect(table.locator('[data-lead="x:@harborwatch"] [data-lead-channel]')).toBeVisible(); + const create = asked().filter((r) => r.path === "/api/ops/create-channel").at(-1); + expect(create?.body).toMatchObject({ fields: { url: "https://x.com/HarborWatch" }, fetchPostsNow: true }); + expect(create && "sites" in create.body).toBe(false); + await table.getByLabel("Disposition of youtube:@harborradio").selectOption("watch"); + await expect(table.locator('[data-lead="youtube:@harborradio"]')).toHaveAttribute("data-disposition", "watch"); + await shot(page, "leads-dispositions", "leads"); +}); + +test("evidence: an excluded target, a capture at a date, a forum attachment marked unverified, attached to a finding", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.goto(researchCasePipelineHref(STAGES_CASE, "evidence")); + const ev = stage(page, "evidence"); + const targets = ev.getByRole("form", { name: "Wayback targets" }); + await targets.getByLabel("Pages, one per line").fill(`${EXCLUDED_URL}\n${TARGET_URL}`); + await targets.getByLabel(/^Dates/).fill("2014-03-04"); + await targets.getByRole("button", { name: "Add targets" }).click(); + const table = ev.getByRole("table", { name: "Captures" }); + await expect(table.locator("[data-evidence]")).toHaveCount(2); + + const gone = table.locator('[data-evidence="e1"]'); + await gone.getByRole("button", { name: "Look up" }).click(); + await expect(gone).toHaveAttribute("data-state", "excluded"); + await expect(gone.locator("[data-evidence-label]")).toHaveText("excluded from the Wayback Machine (cause unknown)"); + + const page2 = table.locator('[data-evidence="e2"]'); + await page2.getByLabel("Capture e2 into").selectOption(PAGES); + await page2.getByRole("button", { name: "Capture" }).click(); + await expect(page2).toHaveAttribute("data-state", "captured", { timeout: 15_000 }); + await expect(page2.locator("[data-evidence-label]")).toHaveText("Wayback capture, 2014-03-04"); + const imp = asked().filter((r) => r.path === "/api/ops/import-page").at(-1); + expect(imp?.body).toEqual({ slug: PAGES, url: TARGET_URL, at: "20140304" }); + + const forum = ev.getByRole("form", { name: "Forum attachment" }); + await forum.getByLabel("Forum channel").selectOption(FORUM); + await forum.getByLabel("Post id").fill("70003"); + await forum.getByRole("button", { name: "Capture the post" }).click(); + const att = table.locator('[data-kind="forum-attachment"]'); + await expect(att).toHaveAttribute("data-state", "captured", { timeout: 15_000 }); + await expect(att.locator("[data-evidence-label]")).toHaveText("forum attachment, post #3, unverified"); + await expect(att.locator("img")).toHaveCount(2); + await expect(att.locator("img").first()).toHaveAttribute("alt", /forum attachment, post #3, unverified/); + await att.getByLabel(/^Attach e3 to a finding/).selectOption("f3"); + await expect(att.locator("td").last()).toContainText("f3"); + expect(findings().find((r) => r.row === "f3").evidence).toEqual([ + { kind: "forum-attachment", url: expect.stringContaining("post-70003"), evidence: "e3", post: "70003", position: 3 }, + ]); + await shot(page, "evidence-captures", "evidence"); + + // The finding says it everywhere it shows: its verify row, and the export (lane A's) with its Evidence section. + // A new frame of the page (going to another #stage on the same page would only scroll). + await page.reload(); + await expect(stage(page, "verify").locator('[data-finding="f3"] [data-evidence-label]')).toHaveText("forum attachment, post #3, unverified"); + await page.getByRole("button", { name: "Export the report" }).click(); + await expect(page.locator("#stage-export [data-stage-state]")).toHaveAttribute("data-stage-state", "done", { timeout: 30_000 }); + const md = read("REPORT.md"); + expect(md).toContain("## Evidence"); + expect(md).toContain(`- excluded from the Wayback Machine (cause unknown) — ${EXCLUDED_URL}, asked for 2014-03-04`); + expect(md).toContain(`- Wayback capture, 2014-03-04 — [${TARGET_URL}](https://web.archive.org/web/20140304120000/${TARGET_URL})`); + expect(md).toMatch(/- forum attachment, post #3, unverified — \[the post\]\(.+post-70003\), 2 files captured \(for f3\)/); + expect(md).toMatch(/## Quarantined[\s\S]*row f3\. quarantined\. forum attachment, post #3, unverified\./); + expect(md.toLowerCase()).not.toContain(PRIVATE_NAME.toLowerCase()); +}); diff --git a/umtool/e2e/fixtures/case-stages-fixture.mjs b/umtool/e2e/fixtures/case-stages-fixture.mjs @@ -0,0 +1,166 @@ +// RELEASE 38 LANE C's fixture: a research case with a pipeline beside its +// board -- findings to verify, a forum channel whose posts link accounts (the +// leads), a Wayback pages channel for the captures -- over the research +// fixture's corpus (research-fixture.mjs; its hr-2022b carries an `en-orig` +// primary and an `en` alternate that rewrites the line at 900 s). +// +// INVENTED, every word: no channel, account, post or line here is real. The +// case's one private name is PRIVATE_NAME, stored as its hash only (as the +// pipeline stores every private name); a post links an account of that name, +// and the leads table withholds it. +// +// <reports>/.umtool/research/fixture-pipeline/ +// case.json the board (scope.source: the fixture's local corpus) +// pipeline.json scope channels (harbor-radio, night-desk, harbor-forum), +// privateNames.sha256 = [hash(PRIVATE_NAME)] +// findings.jsonl f1 hr-2022b@900 quoted from the `en` track ("rang in"); +// f2 hr-2022a@2044 (held audio: the audio check's); +// f3 a forum post's claim (quarantine's) +// <channels>/harbor-forum a XenForo thread, 7 posts (platform xenforo) +// <channels>/harbor-pages a Wayback pages channel (platform webpage) +// <channels>/harbor-radio/data/hr-2022a/audio.m4a the held media (bytes the stub never reads) +import { createHash } from "node:crypto"; +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { ARCHIVE, EN_REWRITE, RESEARCH_PHRASE } from "./research-fixture.mjs"; + +export const STAGES_CASE = "fixture-pipeline"; +export const PRIVATE_NAME = "QuietKeeper"; +export const FORUM = "harbor-forum"; +export const PAGES = "harbor-pages"; +export const EXCLUDED_URL = "http://gone.harbor-radio.example/"; +export const TARGET_URL = "http://harbor-radio.example/archive"; +/** What the stub's worker "hears" in f2's window. */ +export const HEARD = `okay so they voted the ${RESEARCH_PHRASE} down eight to one and that was that`; + +// common/lib/research/privateNames-server.ts privateNameHash: sha256 of the NFKC, lowercased, single-spaced term. +export const nameHash = (term) => + createHash("sha256").update(term.normalize("NFKC").toLowerCase().trim().split(/\s+/u).join(" ")).digest("hex"); + +const write = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`); +}; + +const THREAD = "https://forum.harbor.example/threads/the-lighthouse-budget.4401/"; +const post = (n, author, text, links, extra = {}) => ({ + id: String(70000 + n), + slug: `${FORUM}/${70000 + n}`, + channelSlug: FORUM, + author, + createdAt: `2014-03-0${Math.min(n, 9)}T18:00:00.000Z`, + uploadDate: `2014030${Math.min(n, 9)}`, + text, + url: `${THREAD}post-${70000 + n}`, + platform: "xenforo", + isReply: false, + isRepost: false, + links, + forum: { host: "forum.harbor.example", threadId: "4401", threadTitle: "The lighthouse budget", threadUrl: THREAD, page: 1, position: n }, + ...extra, +}); + +export const FORUM_POSTS = [ + post(1, "deckhand", "Harbor Watch posted the council minutes https://x.com/HarborWatch/status/111", ["https://x.com/HarborWatch/status/111"]), + post(2, "ferryfan", "Again from https://twitter.com/HarborWatch and the radio's archive https://harbor-radio.example/archive", ["https://twitter.com/HarborWatch", "https://harbor-radio.example/archive"]), + post(3, "deckhand", "Screenshot attached. Tide Watcher says it was a joke https://x.com/TideWatcher/status/222", ["https://x.com/TideWatcher/status/222"], { + media: [{ kind: "attachment", url: "https://forum.harbor.example/attachments/minutes-png.991/", name: "minutes.png" }], + }), + post(4, "ferryfan", "HarborWatch again https://x.com/HarborWatch/status/333 and the old page https://harbor-radio.example/archive", ["https://x.com/HarborWatch/status/333", "https://harbor-radio.example/archive"]), + post(5, "gull", `someone found ${PRIVATE_NAME}'s account https://x.com/${PRIVATE_NAME}`, [`https://x.com/${PRIVATE_NAME}`]), + post(6, "gull", "TideWatcher deleted it https://x.com/TideWatcher", ["https://x.com/TideWatcher"]), + post(7, "deckhand", "the radio's channel https://www.youtube.com/@HarborRadio and an artist https://pocketfox.newgrounds.com/ plus our own thread https://forum.harbor.example/threads/x.1/", [ + "https://www.youtube.com/@HarborRadio", + "https://pocketfox.newgrounds.com/", + "https://forum.harbor.example/threads/x.1/", + ]), +]; + +/** Write the case, its pipeline files and the two channels. */ +export function makeCaseStagesFixture({ reportsRoot, channels, pub }) { + const at = "2026-11-01T12:00:00.000Z"; + const dir = path.join(reportsRoot, ".umtool", "research", STAGES_CASE); + write(path.join(dir, "case.json"), { + format: "umtool-research-case", + version: 1, + id: STAGES_CASE, + title: "Fixture pipeline", + scope: { source: `local:${pub}`, query: RESEARCH_PHRASE }, + search: null, + sessions: [], + sections: [], + quotes: [], + notes: "", + handoffs: [], + counters: { quote: 0, section: 0 }, + createdAt: at, + updatedAt: at, + }); + write(path.join(dir, "pipeline.json"), { + format: "archilyzer-case-pipeline", + version: 1, + case: STAGES_CASE, + subjects: [{ name: "Harbor Radio", aliases: [] }], + scope: { channels: ["harbor-radio", "night-desk", FORUM], groups: [], sites: [] }, + eras: [], + groups: [], + privateNames: { sha256: [nameHash(PRIVATE_NAME)], note: "a private person named in the forum thread" }, + readerPrompts: { common: "Quote verbatim." }, + status: "verifying", + createdAt: at, + updatedAt: at, + }); + const finding = (row, slug, id, title, date, t, quote, extra = {}) => ({ + row, + batch: "own-1-001", + slug, + id, + date, + title, + t, + url: `${ARCHIVE}/?v=${slug}%2F${id}&t=${t}`, + category: "vote", + relevance: 3, + quote, + summary: "", + speaker: "host", + confidence: "medium", + round: 1, + by: "api", + quoteCheck: "found", + ...extra, + }); + write( + path.join(dir, "findings.jsonl"), + [ + finding("f1", "harbor-radio", "hr-2022b", "Harbor Radio 91: call-in night", "20221103", EN_REWRITE.at, EN_REWRITE.en), + finding("f2", "harbor-radio", "hr-2022a", "Harbor Radio 80: the council vote", "20220211", 2044, `they voted the ${RESEARCH_PHRASE} down eight to one`), + finding("f3", FORUM, "70003", "The lighthouse budget (forum)", "20140303", 0, "Tide Watcher says it was a joke", { speaker: "deckhand", by: "hand", url: FORUM_POSTS[2].url }), + ] + .map((r) => JSON.stringify(r)) + .join("\n") + "\n", + ); + + write(path.join(channels, FORUM, "config.json"), { + name: "Harbor forum: the lighthouse budget", + handling: "transcribe", + sourceKind: "social", + platform: "xenforo", + url: THREAD, + socialHandle: "forum.harbor.example", + }); + write(path.join(channels, FORUM, "posts", "2014-03.jsonl"), FORUM_POSTS.map((p) => JSON.stringify(p)).join("\n") + "\n"); + write(path.join(channels, FORUM, "posts-archive"), FORUM_POSTS.map((p) => `xenforo ${p.id}`).join("\n") + "\n"); + + write(path.join(channels, PAGES, "config.json"), { + name: "Harbor radio pages", + handling: "transcribe", + sourceKind: "social", + platform: "webpage", + socialHandle: "harbor-radio.example", + url: "https://web.archive.org/web/*/harbor-radio.example*", + wayback: { targets: [{ url: "harbor-radio.example/", match: "prefix" }] }, + }); + write(path.join(channels, "harbor-radio", "data", "hr-2022a", "audio.m4a"), "not audio: the stub never reads it\n"); + return { id: STAGES_CASE, dir }; +} diff --git a/umtool/e2e/fixtures/editor-stub-case-stages.mjs b/umtool/e2e/fixtures/editor-stub-case-stages.mjs @@ -0,0 +1,97 @@ +// The editor's side of a research case's verify, leads and evidence stages +// (release 38 lane C), stubbed: +// +// POST /api/ops/transcribe {path, start, end, whilePaused?} +// job "cs-<n>", done after 0.6 s, its log ending with the editor's +// `@@transcribe-result {…}` -- the text the fixture's HEARD +// POST /api/ops/wayback-lookup {url} +// 403 {refusal: "excluded"} for the fixture's EXCLUDED_URL, else two captures +// POST /api/ops/fetch-posts {slug, …} +// job, done after 0.6 s +// GET /api/ops/job/cs-<n>?tail=N +// +// (create-channel and import-page are editor-stub-import-page.mjs's; +// capture-posts is editor-stub-intake.mjs's, shared with U4's Add post.) Never a +// worker, the Wayback Machine or a forum. Every request is recorded by the +// main stub's `record`. + +import path from "node:path"; +import { EXCLUDED_URL, HEARD } from "./case-stages-fixture.mjs"; + +const jobs = new Map(); +let next = 1; + +function job(kind, log, onDone, ms = 600) { + const id = `cs-${next++}`; + const j = { id, kind, status: "queued", log: [...log] }; + jobs.set(id, j); + setTimeout(() => (j.status = "running"), 150); + setTimeout(() => { + try { + onDone?.(j); + } catch { + /* the fixture was rebuilt under the job */ + } + if (j.status !== "failed") j.status = "done"; + }, ms); + return id; +} + +/** Handles the routes above; answers true when it did. `ctx`: {channels, json, readBody, push(record)}. */ +export function caseStagesRoute(req, res, url, ctx) { + const { json, readBody } = ctx; + const post = (p, fn) => { + if (req.method !== "POST" || url.pathname !== p) return false; + readBody(req, (body) => { + ctx.push({ path: url.pathname, body }); + fn(body ?? {}); + }); + return true; + }; + if ( + post("/api/ops/transcribe", (body) => { + if (typeof body.path !== "string" || !path.isAbsolute(body.path)) return json(res, 400, { ok: false, error: '"path" must be an absolute file path' }); + const result = { + version: 1, + path: body.path, + window: { start: body.start, end: body.end }, + worker: { id: "w1", name: "stub parakeet", appId: "parakeet", model: "stub", device: "cpu" }, + transcriptFormat: "parakeet-json", + durationMs: 420, + waitedMs: 0, + cues: [{ start: body.start ?? 0, end: body.end ?? 0, text: HEARD }], + text: HEARD, + }; + const id = job("transcribe-file", [`Transcribe ${path.basename(body.path)} [${body.start}, ${body.end})${body.whilePaused ? " while paused" : ""}`], (j) => { + j.log.push(`@@transcribe-result ${JSON.stringify(result)}`); + }); + json(res, 200, { ok: true, jobId: id }); + }) + ) + return true; + if ( + post("/api/ops/wayback-lookup", (body) => { + if (body.url === EXCLUDED_URL) { + return json(res, 403, { ok: false, error: `${body.url} is excluded from the Wayback Machine (cause unknown): the Wayback Machine answered HTTP 403 for it`, refusal: "excluded" }); + } + const captures = ["20140220093000", "20140304120000"].map((timestamp) => ({ timestamp, status: "200", replayUrl: `https://web.archive.org/web/${timestamp}/${body.url}` })); + json(res, 200, { ok: true, url: body.url, found: captures.length, captures }); + }) + ) + return true; + if ( + post("/api/ops/fetch-posts", (body) => { + if (!body.slug) return json(res, 400, { ok: false, error: "name a channel" }); + json(res, 200, { ok: true, jobId: job("fetch-posts", [`Fetch ${body.older ? "older " : ""}posts of ${body.slug}`]) }); + }) + ) + return true; + const m = /^\/api\/ops\/job\/(cs-\d+)$/.exec(url.pathname); + if (req.method === "GET" && m) { + const j = jobs.get(m[1]); + if (!j) json(res, 404, { ok: false, error: "no such job" }); + else json(res, 200, { ok: true, job: { id: j.id, kind: j.kind, status: j.status }, tail: j.log }); + return true; + } + return false; +} diff --git a/umtool/e2e/fixtures/editor-stub-import-page.mjs b/umtool/e2e/fixtures/editor-stub-import-page.mjs @@ -3,7 +3,7 @@ // 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} +// POST /api/ops/import-page {slug, url} | {slug, url: <the page>, at: YYYYMMDD} // 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 @@ -45,18 +45,29 @@ export function importPageRoute(req, res, url, ctx) { ctx.push({ path: url.pathname, body }); const dir = path.join(ctx.channels, slug); mkdirSync(dir, { recursive: true }); + // Release 38 lane C: an archived lead's channel is X, YouTube or a page, by its URL. + const u = String(fields.url ?? ""); + const platform = /^https?:\/\/(?:www\.)?(?:x|twitter)\.com\//.test(u) ? "twitter" : /youtube\.com\//.test(u) ? "youtube" : "webpage"; 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.stringify( + platform === "youtube" + ? { name: fields.name, handling: fields.handling ?? "youtube", url: u } + : { name: fields.name, handling: fields.handling ?? "transcribe", sourceKind: "social", platform, url: u }, + null, + 2, + ), ); - json(res, 200, { ok: true, slug, jobIds: [] }); + const jobIds = body?.fetchPostsNow || body?.fetchPlaylist ? [`ip-start-${slug}`] : []; + json(res, 200, { ok: true, slug, jobIds, ...(jobIds.length === 1 ? { jobId: jobIds[0] } : {}) }); }); 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); + // Release 38 lane C: the page's own URL and `at` -- the capture nearest that date (here, noon on it). + const cap = parseCapture(body?.url) ?? (body?.at && /^https?:\/\//.test(String(body?.url)) ? { ts: `${String(body.at).slice(0, 8)}120000`, original: String(body.url) } : null); 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}`] }; diff --git a/umtool/e2e/fixtures/editor-stub-intake.mjs b/umtool/e2e/fixtures/editor-stub-intake.mjs @@ -7,11 +7,13 @@ // GET /api/ops/settings?key=channelPriority { value: { focus, channels } } // POST /api/ops/channel-priority {focus} the focus replaced, recorded // POST /api/ops/capture-posts {slug, ids} job cp-<n>: running at once, done after ~1 s, when it -// has written posts-media/<id>/shot.png + capture.json +// has written posts-media/<id>/shot.png + capture.json, and +// each attachment the post names (media[].name) -- shared by +// Add post and a research case's forum evidence (lane C) // GET /api/ops/job/cp-<n> that job // POST /__stub/channel-counts {slug, totals?, undownloaded?, untranscribed?} (no token) a spec's // counts for a channel; {} resets -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import path from "node:path"; import { postShotPng } from "./intake-fixture.mjs"; @@ -22,6 +24,29 @@ const DEFAULT_COUNTS = () => ({ let counts = DEFAULT_COUNTS(); const priority = { focus: { kind: "none" }, channels: {} }; const jobs = new Map(); + +/** The file names of a post's named attachments, read from the channel's posts/*.jsonl (none when unreadable). */ +function attachmentNames(channels, slug, id) { + const dir = path.join(channels, slug, "posts"); + let files = []; + try { + files = readdirSync(dir).filter((f) => f.endsWith(".jsonl")); + } catch { + return []; + } + for (const f of files) { + for (const line of readFileSync(path.join(dir, f), "utf8").split("\n")) { + if (!line.includes(`"id":"${id}"`)) continue; + try { + const p = JSON.parse(line); + if (p.id === id) return (p.media ?? []).map((m) => m?.name).filter((n) => typeof n === "string" && /^[A-Za-z0-9._-]+$/.test(n)); + } catch { + /* not a post */ + } + } + } + return []; +} let nextJob = 1; /** The control door (before the token check). Answers true when it handled the request. */ @@ -89,6 +114,9 @@ export function intakeRoute(req, res, url, { json, readBody, push, channels }) { const d = path.join(channels, slug, "posts-media", pid); mkdirSync(d, { recursive: true }); writeFileSync(path.join(d, "shot.png"), postShotPng()); + // The post's named attachments (release 38 lane C's forum post, case-stages.spec), as the real + // capture saves its media beside the shot. + for (const name of attachmentNames(channels, slug, pid)) writeFileSync(path.join(d, name), postShotPng()); writeFileSync(path.join(d, "capture.json"), JSON.stringify({ version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: new Date().toISOString(), state: "captured", mediaState: "skipped", media: [] }) + "\n"); } job.status = "done"; diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -25,6 +25,7 @@ import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt- import { fileURLToPath } from "node:url"; import { fetchWindowsRoute } from "./editor-stub-fetch-windows.mjs"; import { importPageRoute } from "./editor-stub-import-page.mjs"; +import { caseStagesRoute } from "./editor-stub-case-stages.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { readSuggestions, suggestionsDocOf, writeSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; @@ -1254,6 +1255,8 @@ const server = http.createServer((req, res) => { // UI notes items 13 and 16: a channel's counts, the focus, capture-posts (editor-stub-intake.mjs). if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return; + // Release 38 lane C: a research case's verify, leads and evidence stages (editor-stub-case-stages.mjs). + if (caseStagesRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return; // 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; diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -39,6 +39,7 @@ import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; import { makeUiOpsFixture } from "./ui-ops-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; +import { makeCaseStagesFixture } from "./case-stages-fixture.mjs"; import { makeCaseFixture } from "./case-fixture.mjs"; import { makeDigestContextFixture } from "./digest-context-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; @@ -2353,6 +2354,8 @@ const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS makeDigestContextFixture({ dest, channels: CHANNELS }); // R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest). makeBoardFixture({ reportsRoot: dest, pub: RESEARCH_PUBLIC }); +// Release 38 lane C: a case's pipeline -- findings to verify, a forum's leads, captures (case-stages.spec.ts). +makeCaseStagesFixture({ reportsRoot: dest, channels: CHANNELS, pub: RESEARCH_PUBLIC }); // Release 38 lane A: a case pipeline over two channels with words on disk, beside an empty board. makeCaseFixture({ channels: CHANNELS, reportsRoot: dest }); // R3: transparent runs -- a traced sweep, an imported turns-only one with two diff --git a/umtool/e2e/import-capture.spec.ts b/umtool/e2e/import-capture.spec.ts @@ -88,7 +88,8 @@ test("a page citation's capture imported as a page record, then cited as one, th // 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"); + // The LAST ask of each: the stub's log is the whole run's, and an earlier spec (case-stages) asks both too. + const create = asked.findLast((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 }); + expect(asked.findLast((r) => r.path === "/api/ops/import-page")?.body).toEqual({ slug: SLUG, url: ARCHIVE }); }); diff --git a/umtool/lib/research/case-editor.ts b/umtool/lib/research/case-editor.ts @@ -0,0 +1,75 @@ +import { agentToken } from "@/lib/annotations/agentAuth.mjs"; +import { editorUrl, EDITOR_GET_TIMEOUT_MS, EDITOR_POST_TIMEOUT_MS } from "@/lib/articles/generation"; +import { CaseError } from "./case-stage-files"; + +// --------------------------------------------------------------------------- +// THE EDITOR, AS THE CASE STAGES ASK IT (release 38 lane C). Every fetch, +// capture, transcription and channel goes through the editor's ops door -- +// never yt-dlp, a worker or the Wayback Machine by hand: the editor paces each +// site, holds the cookies and the queues, and records who asked. +// +// Unlike askEditor (lib/articles/generation.ts) a refusal comes back as an +// ANSWER with the editor's body, because the body is the point: a Wayback 403 +// is `{refusal: "excluded"}`, and the capture table says so rather than +// failing. Only "the editor could not be asked" throws. +// --------------------------------------------------------------------------- + +export type EditorAnswer = { ok: boolean; status: number; body: Record<string, unknown> }; + +export async function editorCall(route: string, init: { method?: "GET" | "POST"; body?: unknown } = {}): Promise<EditorAnswer> { + const token = agentToken(); + if (!token) throw new CaseError("WORKER_TOKEN is not set for umtool, so the editor cannot be asked", 503); + const method = init.method ?? "GET"; + let res: Response; + try { + res = await fetch(`${editorUrl()}${route}`, { + method, + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), + cache: "no-store", + signal: AbortSignal.timeout(method === "GET" ? EDITOR_GET_TIMEOUT_MS : EDITOR_POST_TIMEOUT_MS), + }); + } catch (e) { + throw new CaseError(`the editor at ${editorUrl()} did not answer: ${(e as Error).message}`, 502); + } + const body = ((await res.json().catch(() => null)) ?? {}) as Record<string, unknown>; + if (res.status === 503) throw new CaseError("the editor's ops surface is off (it has no WORKER_TOKEN)", 503); + if (res.status === 401) throw new CaseError("the editor refused umtool's WORKER_TOKEN", 502); + return { ok: res.ok && body.ok !== false, status: res.status, body }; +} + +/** The editor's words for a refusal. */ +export const refusalText = (a: EditorAnswer) => String(a.body.error ?? `the editor answered HTTP ${a.status}`); + +/** POST and expect a job id back; a refusal throws with the editor's words. */ +export async function startJob(route: string, body: unknown): Promise<string> { + const a = await editorCall(route, { method: "POST", body }); + const id = typeof a.body.jobId === "string" ? a.body.jobId : null; + if (!a.ok || !id) throw new CaseError(`the editor refused it: ${refusalText(a)}`, a.status >= 400 ? a.status : 400); + return id; +} + +export type JobState = { status: string; done: boolean; tail: string[] }; + +export const isJobId = (id: string) => /^[A-Za-z0-9_-]{1,80}$/.test(id); + +/** Where a job is, and its last lines. */ +export async function jobState(jobId: string, tail = 80): Promise<JobState> { + if (!isJobId(jobId)) throw new CaseError(`"${jobId}" is not a job id`, 400); + const a = await editorCall(`/api/ops/job/${jobId}?tail=${tail}`); + if (!a.ok) throw new CaseError(`the editor has no job ${jobId}: ${refusalText(a)}`, a.status === 404 ? 404 : 502); + const status = String((a.body.job as { status?: string } | undefined)?.status ?? "unknown"); + const lines = Array.isArray(a.body.tail) ? a.body.tail.map(String) : []; + return { status, done: status === "done" || status === "failed" || status === "cancelled", tail: lines }; +} + +/** The JSON after `marker` on the last line that has it, or null. */ +export function resultLine<T>(tail: string[], marker: string): T | null { + const line = [...tail].reverse().find((l) => l.includes(marker)); + if (!line) return null; + try { + return JSON.parse(line.slice(line.indexOf(marker) + marker.length)) as T; + } catch { + return null; + } +} diff --git a/umtool/lib/research/case-evidence.ts b/umtool/lib/research/case-evidence.ts @@ -0,0 +1,316 @@ +import { readdir } from "node:fs/promises"; +import path from "node:path"; +import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; +import { + CASE_FILES, + EXCLUDED_SENTENCE, + evidenceLabel, + type CaseEvidence, + type FindingEvidence, + type FindingRow, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { CHANNELS_DIR } from "../paths.mjs"; +import { webpageChannels, type PagesChannel } from "../articles/importCapture"; +import { corpusMediaUrl } from "../articles/article"; +import { mutateFindings, readFindings, rowOf } from "./case-findings-store"; +import { CaseError, labelOf, readJsonFile, stageDir, stageFile, withFileLock, writeWhole } from "./case-stage-files"; +import { editorCall, jobState, refusalText, resultLine } from "./case-editor"; +import { postsChannels, type PostsChannel } from "./case-leads"; + +// --------------------------------------------------------------------------- +// STAGE 10, EVIDENCE CAPTURE (release 38 lane C): `<case>/evidence.json`, +// CaseEvidence[], one writer. +// +// wayback a target page at a chosen date: `wayback-lookup` to see +// whether the archive will show it at all (a 403 is +// EXCLUDED, "excluded from the Wayback Machine (cause +// unknown)", a row of its own, never an error), then +// `import-page {slug, url, at}` into a Wayback pages +// channel (picked, or created on no site for the host) -- +// the capture nearest the date, paced on archive.org's +// queue by the editor. +// forum-attachment a forum post's attachments and screenshot through +// `capture-posts`, shown in EVERY surface as "forum +// attachment, post #N, unverified" (forumAttachmentLabel): +// a forum's joke culture means it is looked at before it +// is described, and a finding it backs is quarantined until +// an independent source agrees. +// +// A row can be attached to findings (their `evidence`, through the findings +// writer). The case export (lane A's runExport) lists the rows in an Evidence +// section (common/lib/research/caseEvidence.ts evidenceSection). +// --------------------------------------------------------------------------- + +export const IMPORT_PAGE_MARKER = "@@import-page "; +const MAX_ROWS = 500; + +const DATE = /^(\d{4})-?(\d{2})-?(\d{2})$/; +/** A date as the editor's import-page takes it (YYYYMMDD), or null. */ +export function evidenceDate(v: string): string | null { + const m = DATE.exec(v.trim()); + return m ? `${m[1]}${m[2]}${m[3]}` : null; +} + +async function file(caseId: string) { + return stageFile(await stageDir(caseId), CASE_FILES.evidence); +} + +export async function readEvidence(caseId: string): Promise<CaseEvidence[]> { + const v = await readJsonFile<unknown>(await file(caseId), [], labelOf(caseId, CASE_FILES.evidence)); + if (!Array.isArray(v)) throw new CaseError(`${labelOf(caseId, CASE_FILES.evidence)} is not a list`, 409); + return v.filter((r): r is CaseEvidence => !!r && typeof r === "object" && typeof (r as CaseEvidence).id === "string"); +} + +async function mutateEvidence<T>(caseId: string, fn: (rows: CaseEvidence[]) => T | Promise<T>): Promise<T> { + const f = await file(caseId); + return withFileLock(f, async () => { + const rows = await readEvidence(caseId); + const out = await fn(rows); + await writeWhole(f, `${JSON.stringify(rows, null, 2)}\n`); + return out; + }); +} + +const nextId = (rows: CaseEvidence[]) => `e${rows.reduce((n, r) => Math.max(n, Number(/^e(\d+)$/.exec(r.id)?.[1] ?? 0)), 0) + 1}`; +const evidenceOf = (rows: CaseEvidence[], id: string) => { + const r = rows.find((x) => x.id === id); + if (!r) throw new CaseError(`no evidence ${id}`, 404); + return r; +}; + +// ── the view ── + +export type EvidenceRow = CaseEvidence & { label: string; fileUrls?: { name: string; url: string }[] }; +export type EvidenceView = { rows: EvidenceRow[]; pagesChannels: PagesChannel[]; forumChannels: PostsChannel[]; findings: { row: string; quote: string }[] }; + + +export function labelled(r: CaseEvidence): EvidenceRow { + const out: EvidenceRow = { ...r, label: evidenceLabel(r) }; + if (r.kind === "forum-attachment" && r.slug && r.post && r.files?.length) { + out.fileUrls = r.files.map((name) => ({ name, url: corpusMediaUrl(path.join(CHANNELS_DIR, r.slug!, "posts-media", r.post!, name)) })); + } + return out; +} + +export async function evidenceView(caseId: string): Promise<EvidenceView> { + const rows = await readEvidence(caseId); + const { rows: findings } = await readFindings(caseId); + const forum = (await postsChannels(caseId)).filter((c) => c.platform === "xenforo"); + return { + rows: rows.map(labelled), + pagesChannels: await webpageChannels(), + forumChannels: forum, + findings: findings.map((f) => ({ row: f.row, quote: f.quote.slice(0, 120) })), + }; +} + +// ── Wayback targets ── + +export async function addTargets(caseId: string, urls: string[], dates: string[], now = new Date()): Promise<CaseEvidence[]> { + const list = urls.map((u) => u.trim()).filter(Boolean); + if (!list.length) throw new CaseError("name at least one page URL", 400); + for (const u of list) if (!/^https?:\/\/[^\s]+$/.test(u)) throw new CaseError(`not an http(s) URL: ${u}`, 400); + const ats = dates.map((d) => d.trim()).filter(Boolean); + const parsed = ats.map((d) => evidenceDate(d) ?? (() => { throw new CaseError(`not a date: ${d} (YYYY-MM-DD)`, 400); })()); + const at = now.toISOString(); + return mutateEvidence(caseId, (rows) => { + const added: CaseEvidence[] = []; + for (const url of list) { + for (const d of parsed.length ? parsed : [undefined]) { + if (rows.some((r) => r.kind === "wayback" && r.url === url && r.at === d)) continue; + if (rows.length >= MAX_ROWS) throw new CaseError(`a case holds at most ${MAX_ROWS} evidence rows`, 400); + const row: CaseEvidence = { id: nextId(rows), kind: "wayback", url, ...(d ? { at: d } : {}), state: "planned", createdAt: at, updatedAt: at }; + rows.push(row); + added.push(row); + } + } + return added; + }); +} + +/** Ask whether the Wayback Machine will show the target at all (no capture is fetched). */ +export async function lookupTarget(caseId: string, id: string, now = new Date()): Promise<EvidenceRow> { + const row = evidenceOf(await readEvidence(caseId), id); + if (row.kind !== "wayback") throw new CaseError(`${id} is not a Wayback target`, 400); + const a = await editorCall("/api/ops/wayback-lookup", { method: "POST", body: { url: row.url, okOnly: true, limit: 500 } }); + return mutateEvidence(caseId, (rows) => { + const r = evidenceOf(rows, id); + r.updatedAt = now.toISOString(); + if (a.body.refusal === "excluded") { + r.state = "excluded"; + r.refusal = "excluded"; + r.message = EXCLUDED_SENTENCE; + } else if (!a.ok) { + r.state = "failed"; + r.message = refusalText(a); + } else { + const caps = Array.isArray(a.body.captures) ? (a.body.captures as { timestamp?: string }[]) : []; + const near = nearestTs(caps.map((c) => String(c.timestamp ?? "")).filter(Boolean), r.at); + delete r.refusal; + r.message = caps.length ? `${caps.length} capture${caps.length === 1 ? "" : "s"}${near ? `; nearest ${near.slice(0, 4)}-${near.slice(4, 6)}-${near.slice(6, 8)}` : ""}` : "no captures listed"; + if (r.state === "excluded" || r.state === "failed") r.state = "planned"; + } + return labelled(r); + }); +} + +function nearestTs(ts: string[], at?: string): string | undefined { + if (!ts.length) return undefined; + if (!at) return ts[ts.length - 1]; + const want = Number(at.padEnd(14, "0")); + return ts.reduce((best, t) => (Math.abs(Number(t.padEnd(14, "0")) - want) < Math.abs(Number(best.padEnd(14, "0")) - want) ? t : best)); +} + +/** Import the capture nearest the row's date into a Wayback pages channel (picked, or created on no site). */ +export async function captureTarget(caseId: string, id: string, into: { slug: string } | { create: { name: string } }, now = new Date()): Promise<EvidenceRow> { + const row = evidenceOf(await readEvidence(caseId), id); + if (row.kind !== "wayback") throw new CaseError(`${id} is not a Wayback target`, 400); + if (row.state === "excluded") throw new CaseError(`${row.url} is ${EXCLUDED_SENTENCE}`, 409); + let slug: string; + if ("create" in into) { + const name = into.create.name.trim(); + if (!name) throw new CaseError("give the new channel a name", 400); + const host = new URL(row.url).hostname; + // On no site: a site is the operator's to add. + const made = await editorCall("/api/ops/create-channel", { + method: "POST", + body: { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${host}/*` } }, + }); + if (!made.ok) throw new CaseError(`the editor would not create the channel: ${refusalText(made)}`, made.status >= 400 && made.status < 500 ? made.status : 502); + slug = String(made.body.slug); + } else { + slug = into.slug; + if (!(await webpageChannels()).some((c) => c.slug === slug)) throw new CaseError(`${slug} is not a Wayback pages channel`, 400); + } + const a = await editorCall("/api/ops/import-page", { method: "POST", body: { slug, url: row.url, ...(row.at ? { at: row.at } : {}) } }); + return mutateEvidence(caseId, (rows) => { + const r = evidenceOf(rows, id); + r.slug = slug; + r.updatedAt = now.toISOString(); + if (a.ok && typeof a.body.jobId === "string") { + r.state = "queued"; + r.job = a.body.jobId; + delete r.message; + delete r.refusal; + } else if (a.body.refusal === "excluded") { + r.state = "excluded"; + r.refusal = "excluded"; + r.message = EXCLUDED_SENTENCE; + } else { + r.state = "failed"; + r.message = refusalText(a); + } + return labelled(r); + }); +} + +// ── forum attachments ── + +export async function addForumAttachment(caseId: string, slug: string, post: string, now = new Date()): Promise<EvidenceRow> { + if (!/^[A-Za-z0-9_.@-]+$/.test(slug) || !/^[A-Za-z0-9_.@-]+$/.test(post)) throw new CaseError("name a forum channel and a post id", 400); + const posts = await readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug)); + const p = posts.find((x) => x.id === post); + if (!p) throw new CaseError(`no post ${post} in ${slug}`, 404); + const a = await editorCall("/api/ops/capture-posts", { method: "POST", body: { slug, ids: [post], shots: true, media: true } }); + const at = now.toISOString(); + return mutateEvidence(caseId, (rows) => { + const existing = rows.find((r) => r.kind === "forum-attachment" && r.slug === slug && r.post === post); + const r: CaseEvidence = existing ?? { + id: nextId(rows), + kind: "forum-attachment", + url: p.url, + slug, + post, + ...(p.forum?.position ? { position: p.forum.position } : {}), + state: "planned", + createdAt: at, + updatedAt: at, + }; + r.updatedAt = at; + if (a.ok && typeof a.body.jobId === "string") { + r.state = "queued"; + r.job = a.body.jobId; + delete r.message; + } else { + r.state = "failed"; + r.message = refusalText(a); + } + if (!existing) rows.push(r); + return labelled(r); + }); +} + +async function capturedFiles(slug: string, post: string): Promise<string[]> { + const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "posts-media", post); + const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]); + return names.filter((n) => !n.startsWith(".") && !n.endsWith(".json")).sort(); +} + +// ── where a queued row is ── + +export async function refreshEvidence(caseId: string, id: string, now = new Date()): Promise<EvidenceRow> { + const row = evidenceOf(await readEvidence(caseId), id); + if (row.state !== "queued" || !row.job) return labelled(row); + const st = await jobState(row.job); + if (!st.done) return labelled(row); + const files = row.kind === "forum-attachment" && row.slug && row.post ? await capturedFiles(row.slug, row.post) : []; + const res = row.kind === "wayback" ? resultLine<{ ok?: boolean; captureTs?: string; records?: string[]; refusal?: string; error?: string }>(st.tail, IMPORT_PAGE_MARKER) : null; + return mutateEvidence(caseId, (rows) => { + const r = evidenceOf(rows, id); + r.updatedAt = now.toISOString(); + if (r.kind === "wayback") { + if (res?.ok) { + r.state = "captured"; + if (res.captureTs) r.captureTs = res.captureTs; + if (res.records?.length) r.records = res.records; + } else if (res?.refusal === "excluded") { + r.state = "excluded"; + r.refusal = "excluded"; + r.message = EXCLUDED_SENTENCE; + } else { + r.state = "failed"; + r.message = res?.error ?? `the import job ${st.status}`; + if (res?.refusal) r.refusal = res.refusal; + } + } else if (st.status === "done" && files.length) { + r.state = "captured"; + r.files = files; + } else { + r.state = "failed"; + r.message = st.status === "done" ? "the capture job finished with no file for the post" : `the capture job ${st.status}`; + } + return labelled(r); + }); +} + +// ── evidence for a finding ── + +export function findingEvidenceOf(r: CaseEvidence): FindingEvidence { + if (r.kind === "forum-attachment") { + return { kind: "forum-attachment", url: r.url, evidence: r.id, ...(r.post ? { post: r.post } : {}), ...(r.position ? { position: r.position } : {}) }; + } + const url = r.captureTs ? `https://web.archive.org/web/${r.captureTs}/${r.url}` : r.url; + return { kind: "wayback", url, evidence: r.id, ...(r.captureTs ? { capturedAt: r.captureTs } : {}) }; +} + +/** Attach an evidence row to a finding (both sides recorded). */ +export async function attachEvidence(caseId: string, id: string, findingRow: string): Promise<{ evidence: EvidenceRow; finding: FindingRow }> { + const r = evidenceOf(await readEvidence(caseId), id); + if (r.state === "excluded") throw new CaseError(`${r.url} is ${EXCLUDED_SENTENCE}: there is nothing to attach`, 409); + const fe = findingEvidenceOf(r); + const { result: finding } = await mutateFindings(caseId, (rows) => { + const f = rowOf(rows, findingRow); + f.evidence = [...(f.evidence ?? []).filter((e) => e.evidence !== id), fe]; + return f; + }); + const evidence = await mutateEvidence(caseId, (rows) => { + const e = evidenceOf(rows, id); + e.findings = [...new Set([...(e.findings ?? []), findingRow])]; + return labelled(e); + }); + return { evidence, finding }; +} + +// ── the export's Evidence section: common's (caseEvidence.ts), which lane A's export calls ── + +export { evidenceLine, evidenceSection } from "yt-dlp-transcript-common/lib/research/caseEvidence"; diff --git a/umtool/lib/research/case-findings-store.ts b/umtool/lib/research/case-findings-store.ts @@ -0,0 +1,48 @@ +import { CASE_FILES, type FindingRow } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { readFindings as readAt } from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { assertNoPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { rowGateText } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { CaseError, labelOf, privateHashes, stageDir, stageFile, withFileLock, writeWhole } from "./case-stage-files"; + +// --------------------------------------------------------------------------- +// FINDINGS, AS VERIFY CHANGES THEM (release 38 lane C, stage 7), on lane A's +// store: rows read by its readFindings (every line checked), and the file +// rewritten whole under ITS lock (`findings.jsonl.lock`, the one appendFindings +// and writeFindings hold) and ITS privacy gate (rowGateText → PrivacyBlocked, +// counts and row ids, never the name). Read-change-write happens inside the +// one lock, so an append landing meanwhile is never lost. A file with a line +// that does not check is never rewritten (it would be dropped): 409, the line +// named. +// --------------------------------------------------------------------------- + +export type FindingsRead = { rows: FindingRow[]; bad: { line: number; error: string }[] }; + +export async function readFindings(caseId: string): Promise<FindingsRead> { + const r = await readAt(await stageDir(caseId)); + return { rows: r.rows, bad: r.invalid.map((x) => ({ line: x.line, error: x.errors.join("; ") })) }; +} + +/** Read every row, let `fn` change them in place, gate them, and write the file whole. */ +export async function mutateFindings<T>(caseId: string, fn: (rows: FindingRow[]) => T | Promise<T>): Promise<{ rows: FindingRow[]; result: T }> { + const dir = await stageDir(caseId); + const hashes = await privateHashes(caseId); + const file = stageFile(dir, CASE_FILES.findings); + return withFileLock(file, async () => { + const r = await readAt(dir); + if (r.invalid.length) { + const b = r.invalid[0]; + throw new CaseError(`${labelOf(caseId, CASE_FILES.findings)} line ${b.line} does not check (${b.errors.join("; ")}); it is never rewritten until it is fixed`, 409); + } + const result = await fn(r.rows); + assertNoPrivateNames("the findings", r.rows.map((x) => ({ id: x.row, text: rowGateText(x) })), hashes); + await writeWhole(file, r.rows.map((x) => JSON.stringify(x)).join("\n") + (r.rows.length ? "\n" : "")); + return { rows: r.rows, result }; + }); +} + +/** One row, or a 404. */ +export function rowOf(rows: FindingRow[], row: string): FindingRow { + const hit = rows.find((r) => r.row === row); + if (!hit) throw new CaseError(`no finding ${row}`, 404); + return hit; +} diff --git a/umtool/lib/research/case-leads.ts b/umtool/lib/research/case-leads.ts @@ -0,0 +1,376 @@ +import { readFile, readdir } from "node:fs/promises"; +import path from "node:path"; +import type { Post } from "yt-dlp-transcript-common/lib/posts"; +import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; +import { + CASE_FILES, + LEAD_DISPOSITIONS, + isLeadDisposition, + type CaseLead, + type LeadDisposition, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { privateNameHash } from "yt-dlp-transcript-common/lib/research/privateNames-server"; +import { assertNoPrivateNames, withholdPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { CHANNELS_DIR } from "../paths.mjs"; +import { + CaseError, + feedPrivateNameHash, + labelOf, + privateHashes, + readJsonFile, + scopeChannels, + stageDir, + stageFile, + withFileLock, + writeWhole, +} from "./case-stage-files"; +import { editorCall, refusalText, startJob } from "./case-editor"; + +// --------------------------------------------------------------------------- +// STAGE 8, LEADS (release 38 lane C): over a posts or forum channel in the +// case's scope, the accounts and URLs its posts link most, counted by post, +// with context snippets on demand. Each lead gets a role note and one of +// `archive | watch | never-archive`: +// +// never-archive the lead's NAME (the handle, the user, the page's last +// segment) is fed to the case's private names as its hash +// (privateNameHash) and the lead itself is kept only as that +// hash -- `key: "hash:<sha256>"`, no URL -- so no file holds +// it. A later scan withholds every lead whose name hashes to a +// private name, and every snippet is redacted the same way. +// archive the channel is created through the editor's create-channel +// op, ON NO SITE (X never on a site, by rule; a site is the +// operator's to add), its first fetch started with it; the +// older walk is a second button once it has posts. +// watch kept, nothing started. +// +// leads.json is CaseLead[], one writer (case-stage-files.ts). +// --------------------------------------------------------------------------- + +export const HASH_KEY_PREFIX = "hash:"; +export const MAX_LEADS = 200; +const SNIPPET_CHARS = 280; + +export type LeadCandidate = { key: string; url: string; platform: string; name: string }; + +const X_HOSTS = new Set(["twitter.com", "www.twitter.com", "mobile.twitter.com", "x.com", "www.x.com", "mobile.x.com"]); +const X_NOT_HANDLES = new Set(["i", "intent", "share", "search", "hashtag", "home", "explore", "settings", "login", "signup", "messages", "notifications", "tos", "privacy"]); +const YT_HOSTS = new Set(["youtube.com", "www.youtube.com", "m.youtube.com"]); + +/** What a linked URL is a lead to: an account where the platform has one, else the page (host + path). */ +export function leadOf(raw: string): LeadCandidate | null { + let u: URL; + try { + u = new URL(raw); + } catch { + return null; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + const host = u.hostname.toLowerCase(); + const segs = u.pathname.split("/").filter(Boolean); + if (X_HOSTS.has(host)) { + const h = segs[0]; + if (!h || X_NOT_HANDLES.has(h.toLowerCase()) || !/^[A-Za-z0-9_]{1,15}$/.test(h)) return null; + return { key: `x:@${h.toLowerCase()}`, url: `https://x.com/${h}`, platform: "x", name: h }; + } + if (YT_HOSTS.has(host)) { + const m = /^(@[^/]+)$/.exec(segs[0] ?? "") ?? (["c", "user", "channel"].includes(segs[0] ?? "") && segs[1] ? [segs[1], segs[1]] : null); + if (!m) return null; + const name = m[1]; + const at = segs[0].startsWith("@") ? segs[0] : `${segs[0]}/${segs[1]}`; + return { key: `youtube:${at.toLowerCase()}`, url: `https://www.youtube.com/${at}`, platform: "youtube", name: name.replace(/^@/, "") }; + } + if (host === "bsky.app" && segs[0] === "profile" && segs[1]) { + return { key: `bluesky:${segs[1].toLowerCase()}`, url: `https://bsky.app/profile/${segs[1]}`, platform: "bluesky", name: segs[1].split(".")[0] }; + } + const sub = (suffix: string) => (host.endsWith(suffix) ? host.slice(0, -suffix.length) : ""); + for (const [suffix, platform] of [[".tumblr.com", "tumblr"], [".newgrounds.com", "newgrounds"], [".deviantart.com", "deviantart"]] as const) { + const s = sub(suffix); + if (s && s !== "www" && !s.includes(".")) return { key: `${platform}:${s}`, url: `https://${s}${suffix}/`, platform, name: s }; + } + if ((host === "reddit.com" || host.endsWith(".reddit.com")) && (segs[0] === "u" || segs[0] === "user") && segs[1]) { + return { key: `reddit:u/${segs[1].toLowerCase()}`, url: `https://www.reddit.com/user/${segs[1]}`, platform: "reddit", name: segs[1] }; + } + if ((host === "instagram.com" || host === "www.instagram.com") && segs[0] && !["p", "reel", "explore"].includes(segs[0])) { + return { key: `instagram:${segs[0].toLowerCase()}`, url: `https://www.instagram.com/${segs[0]}/`, platform: "instagram", name: segs[0] }; + } + if ((host === "tiktok.com" || host === "www.tiktok.com") && segs[0]?.startsWith("@")) { + return { key: `tiktok:${segs[0].toLowerCase()}`, url: `https://www.tiktok.com/${segs[0]}`, platform: "tiktok", name: segs[0].slice(1) }; + } + const bare = host.replace(/^www\./, ""); + const p = segs.join("/"); + return { key: `${bare}${p ? `/${p}` : ""}`.toLowerCase(), url: `${u.protocol}//${host}${u.pathname.replace(/\/+$/, "") || "/"}`, platform: "web", name: segs.length ? segs[segs.length - 1] : bare.split(".")[0] }; +} + +const nameHash = (c: Pick<LeadCandidate, "name">) => privateNameHash(c.name.replace(/^@/, "")); + +// ── the channels a scan can read ── + +export type PostsChannel = { slug: string; name: string; platform: string; inScope: boolean }; + +const SOCIAL_PLATFORMS = new Set(["xenforo", "twitter", "bluesky", "webpage", "x-search"]); + +async function configOf(slug: string): Promise<Record<string, unknown> | null> { + if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) return null; + try { + return JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8")); + } catch { + return null; + } +} + +/** Every posts/forum channel the editor holds, the case's scope first. */ +export async function postsChannels(caseId: string): Promise<PostsChannel[]> { + const scope = new Set(await scopeChannels(caseId)); + const names = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR).catch(() => [] as string[]); + const out: PostsChannel[] = []; + for (const slug of names.sort()) { + if (slug.startsWith(".")) continue; + const c = await configOf(slug); + const platform = typeof c?.platform === "string" ? c.platform : ""; + if (c?.sourceKind !== "social" && !SOCIAL_PLATFORMS.has(platform)) continue; + out.push({ slug, name: typeof c?.name === "string" ? c.name : slug, platform: platform || "social", inScope: scope.has(slug) }); + } + return out.sort((a, b) => Number(b.inScope) - Number(a.inScope) || a.slug.localeCompare(b.slug)); +} + +// ── the scan ── + +export type LeadRow = CaseLead & { withheld?: boolean; posts?: string[] }; +export type LeadsView = { + channel: string | null; + channels: PostsChannel[]; + leads: LeadRow[]; + /** Leads whose names hash to the case's private names: counted, never listed. */ + withheld: number; + posts: number; + dispositions: readonly LeadDisposition[]; +}; + +type Tally = LeadCandidate & { count: number; posts: string[] }; + +/** The leads a channel's posts link, by how many posts link each (the channel's own forum host left out). */ +export function tallyLeads(posts: Post[], ownHosts: Set<string>): Tally[] { + const by = new Map<string, Tally>(); + for (const p of posts) { + const seen = new Set<string>(); + for (const link of p.links ?? []) { + const c = leadOf(link); + if (!c || seen.has(c.key)) continue; + try { + if (ownHosts.has(new URL(link).hostname.toLowerCase())) continue; + } catch { + continue; + } + seen.add(c.key); + const t = by.get(c.key) ?? { ...c, count: 0, posts: [] }; + t.count++; + if (t.posts.length < 50) t.posts.push(p.id); + by.set(c.key, t); + } + } + return [...by.values()].sort((a, b) => b.count - a.count || a.key.localeCompare(b.key)); +} + +function hostsOf(posts: Post[], config: Record<string, unknown> | null): Set<string> { + const out = new Set<string>(); + for (const p of posts.slice(0, 50)) if (p.forum?.host) out.add(p.forum.host.toLowerCase()); + const url = typeof config?.url === "string" ? config.url : ""; + try { + if (url && config?.platform === "xenforo") out.add(new URL(url).hostname.toLowerCase()); + } catch { + // no URL + } + for (const h of [...out]) out.add(h.startsWith("www.") ? h.slice(4) : `www.${h}`); + return out; +} + +async function leadsFile(caseId: string) { + return stageFile(await stageDir(caseId), CASE_FILES.leads); +} + +export async function readLeads(caseId: string): Promise<CaseLead[]> { + const v = await readJsonFile<unknown>(await leadsFile(caseId), [], labelOf(caseId, CASE_FILES.leads)); + if (!Array.isArray(v)) throw new CaseError(`${labelOf(caseId, CASE_FILES.leads)} is not a list of leads`, 409); + return v.filter((l): l is CaseLead => !!l && typeof l === "object" && typeof (l as CaseLead).key === "string"); +} + +async function postsOf(slug: string): Promise<Post[]> { + if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) throw new CaseError(`not a channel: ${slug}`, 400); + return readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug)); +} + +/** Scan `channel` (default: the scope's first posts channel) and merge the counts into the case's leads. */ +export async function leadsView(caseId: string, channel?: string | null): Promise<LeadsView> { + const channels = await postsChannels(caseId); + const slug = channel || channels.find((c) => c.inScope)?.slug || null; + const hashes = new Set(await privateHashes(caseId)); + const saved = await readLeads(caseId); + if (!slug) return { channel: null, channels, leads: saved, withheld: 0, posts: 0, dispositions: LEAD_DISPOSITIONS }; + if (!channels.some((c) => c.slug === slug)) throw new CaseError(`${slug} is not a posts or forum channel`, 404); + const posts = await postsOf(slug); + const tally = tallyLeads(posts, hostsOf(posts, await configOf(slug))); + let withheld = 0; + const savedBy = new Map(saved.map((l) => [l.key, l])); + const rows: LeadRow[] = []; + for (const t of tally) { + const h = nameHash(t); + if (hashes.has(h) || savedBy.has(`${HASH_KEY_PREFIX}${h}`)) { + withheld++; + continue; + } + const prev = savedBy.get(t.key); + rows.push({ ...(prev ?? {}), key: t.key, url: t.url, platform: t.platform, count: t.count, posts: t.posts }); + if (rows.length >= MAX_LEADS) break; + } + // Decided leads the scan no longer finds stay listed (a person decided them), after the rest. + const listed = new Set(rows.map((r) => r.key)); + for (const l of saved) if (!listed.has(l.key) && l.disposition && !l.key.startsWith(HASH_KEY_PREFIX)) rows.push({ ...l }); + const never = saved.filter((l) => l.key.startsWith(HASH_KEY_PREFIX)).map((l) => ({ ...l, url: "", withheld: true })); + return { channel: slug, channels, leads: [...rows, ...never], withheld, posts: posts.length, dispositions: LEAD_DISPOSITIONS }; +} + +// ── context, on demand ── + +export type LeadContext = { key: string; snippets: { post: string; date: string; author: string; text: string; url: string; position?: number }[] }; + +/** The posts that link `key`, each a snippet around the link, private names withheld. */ +export async function leadContext(caseId: string, channel: string, key: string, limit = 8): Promise<LeadContext> { + if (key.startsWith(HASH_KEY_PREFIX)) throw new CaseError("a never-archive lead has no context to show", 400); + const hashes = await privateHashes(caseId); + const posts = (await postsOf(channel)).sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + const out: LeadContext["snippets"] = []; + for (const p of posts) { + const link = (p.links ?? []).find((l) => leadOf(l)?.key === key); + if (!link) continue; + const text = p.text ?? ""; + const c = leadOf(link)!; + let at = text.indexOf(link); + if (at < 0) at = text.toLowerCase().indexOf(c.name.toLowerCase()); + const from = Math.max(0, (at < 0 ? 0 : at) - SNIPPET_CHARS / 2); + let snip = text.slice(from, from + SNIPPET_CHARS).replace(/\s+/g, " ").trim(); + if (from > 0) snip = `… ${snip}`; + if (from + SNIPPET_CHARS < text.length) snip = `${snip} …`; + out.push({ + post: p.id, + date: p.uploadDate, + author: withholdPrivateNames(p.author ?? "", hashes).text, + text: withholdPrivateNames(snip, hashes).text, + url: p.url, + ...(p.forum?.position ? { position: p.forum.position } : {}), + }); + if (out.length >= limit) break; + } + return { key, snippets: out }; +} + +// ── a decision ── + +/** `url` and `count`: the scan's, for a lead decided before it is saved (its key must be what the URL makes). */ +export type LeadDecision = { key: string; disposition?: string | null; role?: string; name?: string; url?: string; count?: number }; + +function channelFieldsFor(lead: Pick<CaseLead, "platform" | "url" | "key">, name: string): { fields: Record<string, unknown>; start: Record<string, boolean> } { + if (lead.platform === "x") return { fields: { name, handling: "transcribe", url: lead.url }, start: { fetchPostsNow: true } }; + if (lead.platform === "bluesky") return { fields: { name, handling: "transcribe", url: lead.url }, start: { fetchPostsNow: true } }; + if (lead.platform === "youtube") return { fields: { name, handling: "youtube", url: `${lead.url}/videos` }, start: { fetchPlaylist: true } }; + // Anything else is a page: a Wayback pages channel scoped to it (its captures through the evidence stage). + const target = lead.url.replace(/^https?:\/\//, ""); + return { fields: { name, handling: "transcribe", url: `https://web.archive.org/web/*/${target}*` }, start: {} }; +} + +/** + * Set a lead's role and disposition. never-archive feeds its name's hash to the case's private names and keeps + * the lead only as the hash; archive creates its channel (on no site) and starts the first fetch. + */ +export async function decideLead(caseId: string, d: LeadDecision): Promise<{ lead: CaseLead; created?: { slug: string; jobIds: string[] } }> { + const disposition = d.disposition === null || d.disposition === "" ? undefined : d.disposition; + if (disposition !== undefined && !isLeadDisposition(disposition)) { + throw new CaseError(`not a disposition: ${JSON.stringify(d.disposition)} (one of ${LEAD_DISPOSITIONS.join(", ")})`, 400); + } + const role = typeof d.role === "string" ? d.role.replace(/\s+/g, " ").trim().slice(0, 300) : undefined; + const hashes = await privateHashes(caseId); + if (role) assertNoPrivateNames("the lead's role note", [{ id: d.key.startsWith(HASH_KEY_PREFIX) ? "a withheld lead" : d.key, text: role }], hashes); + if (d.key.startsWith(HASH_KEY_PREFIX)) { + // A withheld lead is never un-withheld here; only its role note can change. + if (disposition && disposition !== "never-archive") throw new CaseError("a never-archive lead stays never-archive: its name is a private name now", 400); + } + const file = await leadsFile(caseId); + const cand = d.key.startsWith(HASH_KEY_PREFIX) ? null : candidateOf(d.key, await readLeads(caseId), d.url, d.count); + let created: { slug: string; jobIds: string[] } | undefined; + if (disposition === "archive" && cand) { + const prev = (await readLeads(caseId)).find((l) => l.key === d.key); + if (!prev?.channel) { + const name = (d.name ?? "").trim() || defaultChannelName(cand); + const { fields, start } = channelFieldsFor(cand, name); + // ON NO SITE: no `sites` is sent, ever (X never on a site; a site is the operator's). + const a = await editorCall("/api/ops/create-channel", { method: "POST", body: { fields, ...start } }); + if (!a.ok) throw new CaseError(`the editor would not create the channel: ${refusalText(a)}`, a.status >= 400 && a.status < 500 ? a.status : 502); + created = { slug: String(a.body.slug), jobIds: Array.isArray(a.body.jobIds) ? a.body.jobIds.map(String) : [] }; + } + } + if (disposition === "never-archive" && cand) await feedPrivateNameHash(caseId, nameHash(cand)); + const lead = await withFileLock(file, async () => { + const all = await readLeads(caseId); + let i = all.findIndex((l) => l.key === d.key); + const base: CaseLead = i >= 0 ? all[i] : cand ? { key: cand.key, url: cand.url, platform: cand.platform, count: cand.count ?? 0 } : (() => { + throw new CaseError(`no lead ${d.key}`, 404); + })(); + let next: CaseLead = { ...base, ...(role !== undefined ? { role } : {}) }; + if (disposition) next.disposition = disposition; + else if (d.disposition === null || d.disposition === "") delete next.disposition; + if (created) next.channel = created.slug; + if (disposition === "never-archive" && cand) { + // Kept only as its hash: no key, no URL, no channel. + next = { key: `${HASH_KEY_PREFIX}${nameHash(cand)}`, url: "", platform: cand.platform, count: next.count, disposition: "never-archive", ...(next.role ? { role: next.role } : {}) }; + const dup = all.findIndex((l) => l.key === next.key); + if (dup >= 0 && dup !== i) { + all.splice(dup, 1); + if (dup < i) i--; + } + } + if (i >= 0) all[i] = next; + else all.push(next); + await writeWhole(file, `${JSON.stringify(all, null, 2)}\n`); + return next; + }); + return { lead, ...(created ? { created } : {}) }; +} + +/** The older walk of an archived lead's channel (a social channel with posts now). */ +export async function startOlderWalk(caseId: string, key: string): Promise<{ jobId: string; slug: string }> { + const lead = (await readLeads(caseId)).find((l) => l.key === key); + if (!lead?.channel) throw new CaseError(`${key} has no channel yet: archive it first`, 400); + const jobId = await startJob("/api/ops/fetch-posts", { slug: lead.channel, older: true }); + return { jobId, slug: lead.channel }; +} + +function candidateOf(key: string, saved: CaseLead[], hintUrl?: string, hintCount?: number): (LeadCandidate & { count?: number }) | null { + const s = saved.find((l) => l.key === key); + const fromUrl = s?.url ? leadOf(s.url) : null; + if (fromUrl) return { ...fromUrl, key, count: s?.count }; + const hinted = hintUrl ? leadOf(hintUrl) : null; + if (hinted && hinted.key === key) return { ...hinted, ...(Number.isFinite(hintCount) ? { count: Math.max(0, Math.floor(hintCount!)) } : {}) }; + // A key straight from a scan (not saved yet): rebuild it from its URL shape. + const url = key.startsWith("x:@") + ? `https://x.com/${key.slice(3)}` + : key.startsWith("youtube:") + ? `https://www.youtube.com/${key.slice(8)}` + : key.startsWith("bluesky:") + ? `https://bsky.app/profile/${key.slice(8)}` + : key.startsWith("reddit:u/") + ? `https://www.reddit.com/user/${key.slice(9)}` + : /^(tumblr|newgrounds|deviantart):/.test(key) + ? `https://${key.split(":")[1]}.${key.split(":")[0]}.com/` + : /^(instagram|tiktok):/.test(key) + ? `https://www.${key.split(":")[0]}.com/${key.split(":")[1]}` + : `https://${key}`; + const c = leadOf(url); + return c ? { ...c, key } : null; +} + +function defaultChannelName(c: LeadCandidate): string { + if (c.platform === "x") return `${c.name} (X)`; + if (c.platform === "youtube") return c.name; + if (c.platform === "web") return c.key.split("/")[0]; + return `${c.name} (${c.platform})`; +} diff --git a/umtool/lib/research/case-stage-files.ts b/umtool/lib/research/case-stage-files.ts @@ -0,0 +1,75 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { readDefinition, withFileLock as caseFileLock, writeAtomic } from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { CaseError, caseDir, isCaseId, readCase, storedPath } from "./cases.mjs"; +import { changePrivateNames } from "./pipeline"; + +// --------------------------------------------------------------------------- +// LANE C's STAGE FILES (release 38: verify, leads, evidence), on lane A's +// seams. The case's directory is the board's; its pipeline files are lane A's +// store's (common/lib/research/caseStore-server.ts): the same cross-process +// lock files (`<file>.lock`, O_EXCL) and whole-file writes (temp + rename). +// What lane C writes: +// +// findings.jsonl verify's changes, read and rewritten whole under the +// findings lock and the privacy gate (case-findings-store.ts) +// leads.json CaseLead[] (case-leads.ts) +// evidence.json CaseEvidence[] (case-evidence.ts) +// pipeline.json ONE thing: a never-archive lead's name as its hash, through +// lane A's changePrivateNames (which also withholds it from +// the candidates and batches already stored) +// +// A file that does not parse is never overwritten: a write refuses with 409. +// --------------------------------------------------------------------------- + +export { CaseError }; + +/** The case's directory, once the case is known to exist (its case.json reads). */ +export async function stageDir(caseId: string): Promise<string> { + if (!isCaseId(caseId)) throw new CaseError(`not a case id: ${JSON.stringify(caseId)}`, 400); + await readCase(REPORTS_ROOT, caseId); + return caseDir(REPORTS_ROOT, caseId); +} + +export const stageFile = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name); + +/** Run `fn` holding `file`'s lock (lane A's lock file beside it, so the CLI and the page never write at once). */ +export const withFileLock = <T>(file: string, fn: () => Promise<T>): Promise<T> => caseFileLock(`${file}.lock`, fn); + +/** Write `text` to `file` whole: a temp name, then a rename. */ +export const writeWhole = (file: string, text: string) => writeAtomic(file, text); + +/** A JSON file's value; `fallback` when there is no file; a 409 when it does not parse. */ +export async function readJsonFile<T>(file: string, fallback: T, label: string): Promise<T> { + let text: string; + try { + text = await readFile(/* turbopackIgnore: true */ file, "utf8"); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") return fallback; + throw new CaseError(`${label} cannot be read: ${(e as Error).message}`, 409); + } + try { + return JSON.parse(text) as T; + } catch (e) { + throw new CaseError(`${label} is not JSON (${(e as Error).message}); it is never overwritten until it is fixed`, 409); + } +} + +export const labelOf = (caseId: string, name: string) => `${storedPath(caseId)}${name}`; + +/** The case's private-name hashes (none when it has no definition). A definition that does not read refuses. */ +export async function privateHashes(caseId: string): Promise<string[]> { + return (await readDefinition(await stageDir(caseId), caseId))?.privateNames.sha256 ?? []; +} + +/** The scope's channels, as the definition names them (none when it has none). */ +export async function scopeChannels(caseId: string): Promise<string[]> { + return (await readDefinition(await stageDir(caseId), caseId))?.scope.channels ?? []; +} + +/** Add `hash` to the case's private names (a never-archive lead), through lane A's writer. Answers whether it was new. */ +export async function feedPrivateNameHash(caseId: string, hash: string): Promise<boolean> { + if (!/^[0-9a-f]{64}$/.test(hash)) throw new CaseError("a private name is fed as its sha256, lowercase hex", 400); + return (await changePrivateNames(caseId, { add: [hash] })).changed > 0; +} diff --git a/umtool/lib/research/case-stage-hrefs.ts b/umtool/lib/research/case-stage-hrefs.ts @@ -0,0 +1,9 @@ +// The APIs of a case's lane C stages (release 38: verify, leads, evidence). The stages are panels of the case's +// pipeline page (/research/<case>/pipeline#stage-verify|leads|evidence, hrefs.ts researchCasePipelineHref); their +// routes are under /api/research/cases/<case>/stages/. +const enc = encodeURIComponent; + +export const CASE_STAGE_PANELS = ["verify", "leads", "evidence"] as const; + +export const caseStageApi = (id: string, stage: "verify" | "verify/captions" | "verify/audio" | "leads" | "leads/context" | "leads/older" | "evidence") => + `/api/research/cases/${enc(id)}/stages/${stage}`; diff --git a/umtool/lib/research/case-stages.test.ts b/umtool/lib/research/case-stages.test.ts @@ -0,0 +1,249 @@ +// Release 38 lane C's stages over the e2e fixture case (e2e/fixtures/case-stages-fixture.mjs), as the routes run +// them, against the e2e suite's own stand-in editor routes (editor-stub-case-stages.mjs, editor-stub-import-page.mjs): +// verify (both tracks lit, a correction that keeps the reader's words, the private-name gate, the audio check), +// leads (counts, never-archive as a hash, archive on no site, context withheld), evidence (an excluded target, a +// capture, a forum attachment marked unverified, attached to a finding) and the export's sections. +// +// Run with: pnpm --filter umtool exec tsx --test lib/research/case-stages.test.ts +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; + +let tmp: string; +let editor: http.Server; +// The case stages' stub records {path, body}; the intake stub (capture-posts) records {route, ...body}. +const asked: ({ path: string; body: Record<string, unknown> } & { route?: string })[] = []; +let lib: { + verify: typeof import("./case-verify"); + leads: typeof import("./case-leads"); + evidence: typeof import("./case-evidence"); + findings: typeof import("./case-findings-store"); + fixture: typeof import("../../e2e/fixtures/case-stages-fixture.mjs"); +}; +let CASE: string; +let caseDir: string; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-case-stages-")); + const research = await import("../../e2e/fixtures/research-fixture.mjs"); + const fixture = await import("../../e2e/fixtures/case-stages-fixture.mjs"); + const channels = path.join(tmp, "channels"); + const { pub } = research.makeResearchFixture({ dest: tmp, channels }); + const made = fixture.makeCaseStagesFixture({ reportsRoot: path.join(tmp, "reports"), channels, pub }); + CASE = made.id; + caseDir = made.dir; + const { caseStagesRoute } = await import("../../e2e/fixtures/editor-stub-case-stages.mjs"); + const { importPageRoute } = await import("../../e2e/fixtures/editor-stub-import-page.mjs"); + // capture-posts is the intake stub's (shared with U4's Add post). + const { intakeRoute } = await import("../../e2e/fixtures/editor-stub-intake.mjs"); + const json = (res: http.ServerResponse, status: number, body: unknown) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }; + const readBody = (req: http.IncomingMessage, then: (b: Record<string, unknown> | null) => void) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => then(raw ? JSON.parse(raw) : null)); + }; + const ctx = { channels, json, readBody, push: (r: { path: string; body: Record<string, unknown> }) => asked.push(r as (typeof asked)[number]) }; + editor = http.createServer((req, res) => { + const url = new URL(req.url ?? "/", "http://stub"); + if (caseStagesRoute(req, res, url, ctx)) return; + if (importPageRoute(req, res, url, ctx)) return; + if (intakeRoute(req, res, url, ctx)) return; + json(res, 404, { ok: false, error: `no route ${url.pathname}` }); + }); + await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r)); + process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`; + process.env.WORKER_TOKEN = "t"; + process.env.TRANSCRIPT_LOCAL_DIR = pub; + process.env.CHANNELS_DIR = channels; + process.env.SITES_DIR = path.join(tmp, "sites"); + process.env.ARTICLES_DIR = path.join(tmp, "articles"); + process.env.REPORTS_DIR = path.join(tmp, "reports"); + process.env.SONG_REPORTS_DIR = path.join(tmp, "reports", "song"); + lib = { + verify: await import("./case-verify"), + leads: await import("./case-leads"), + evidence: await import("./case-evidence"), + findings: await import("./case-findings-store"), + fixture, + }; +}); + +after(async () => { + await new Promise((r) => editor.close(r)); + await rm(tmp, { recursive: true, force: true }); +}); + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +test("verify: the findings, a forum one flagged; both tracks side by side with the quote lit where it lands", async () => { + const v = await lib.verify.verifyView(CASE); + assert.deepEqual(v.rows.map((r) => r.row), ["f1", "f2", "f3"]); + assert.deepEqual(v.rows.map((r) => r.status), ["unverified", "unverified", "unverified"]); + assert.deepEqual(v.rows.map((r) => r.forum), [false, false, true]); + const c = await lib.verify.findingCaptions(CASE, "f1"); + assert.deepEqual(c.tracks.map((t) => t.track), ["en-orig", "en"], "en-orig first"); + const [orig, en] = c.tracks; + assert.equal(en.holds, true, "the quote is the en track's words"); + assert.equal(orig.holds, false); + assert.equal(orig.matched, 4, "en-orig says 'called in': four of five words"); + const lit = (t: (typeof c.tracks)[number]) => t.cues.flatMap((q) => q.parts.filter((p) => p.hit).map((p) => p.text)).join(" "); + assert.equal(lit(en), "the lighthouse keeper rang in"); + assert.equal(lit(orig), "the lighthouse keeper in"); + const post = await lib.verify.findingCaptions(CASE, "f3"); + assert.equal(post.tracks.length, 1); + assert.match(post.tracks[0].label, /^forum post #3 by deckhand$/); + assert.equal(post.tracks[0].holds, true); +}); + +test("verify: corrected by hand keeps the reader's words, once; the private-name gate; status rules", async () => { + await assert.rejects(lib.verify.setVerify(CASE, "f1", { status: "verified", quote: "the lighthouse keeper called in" }), /status corrected/); + await assert.rejects(lib.verify.setVerify(CASE, "f1", { status: "fine" }), /not a status/); + await assert.rejects( + lib.verify.setVerify(CASE, "f1", { status: "corrected", note: `asked ${lib.fixture.PRIVATE_NAME} about it` }), + (e: Error & { status?: number }) => e.status === 409 && /privacy gate blocked the findings: 1 private-name hit in 1 item \(f1\)/.test(e.message) && !e.message.includes(lib.fixture.PRIVATE_NAME), + ); + const r = await lib.verify.setVerify(CASE, "f1", { status: "corrected", quote: "the lighthouse keeper called in", note: "en-orig and the audio agree" }); + assert.equal(r.quote, "the lighthouse keeper called in"); + assert.deepEqual(r.verify?.original, { quote: "the lighthouse keeper rang in", speaker: "host" }); + assert.equal(r.verify?.how, "hand"); + const again = await lib.verify.setVerify(CASE, "f1", { status: "corrected", quote: "the lighthouse keeper called in tonight" }); + assert.deepEqual(again.verify?.original?.quote, "the lighthouse keeper rang in", "the first reader's words, never the last correction's"); + const { rows } = await lib.findings.readFindings(CASE); + assert.equal(rows.length, 3, "rewritten whole, nothing lost"); + const q = await lib.verify.setVerify(CASE, "f3", { status: "quarantined", note: "a forum joke until shown otherwise" }); + assert.equal(q.status, "quarantined"); +}); + +test("verify: the audio check transcribes the held window through the editor, while paused when asked, and diffs it", async () => { + const before = asked.length; + const a = await lib.verify.audioStep(CASE, "f2", { whilePaused: true }); + assert.equal(a.state, "transcribing"); + const req = asked.slice(before).find((r) => r.path === "/api/ops/transcribe")!; + assert.match(String(req.body.path), /harbor-radio\/data\/hr-2022a\/audio\.m4a$/); + assert.equal(req.body.start, 2039); + assert.equal(req.body.end, 2074); + assert.equal(req.body.whilePaused, true); + let step: import("./case-verify").AudioAnswer = a; + for (let i = 0; i < 20 && step.state === "transcribing"; i++) { + await wait(200); + step = await lib.verify.audioStep(CASE, "f2", { job: (step as { job: string }).job }); + } + assert.equal(step.state, "done"); + if (step.state !== "done") return; + assert.equal(step.audio.matched, 9); + assert.equal(step.audio.words, 9); + assert.equal(step.audio.worker, "stub parakeet"); + assert.ok(step.ops.every((o: { op: string }) => o.op === "same")); + const row = (await lib.verify.verifyView(CASE)).rows.find((r) => r.row === "f2")!; + assert.equal(row.verify?.audio?.matched, 9, "kept on the finding"); + assert.equal(row.status, "unverified", "the check informs; a person sets the status"); + const v = await lib.verify.setVerify(CASE, "f2", { status: "verified", how: "audio" }); + assert.equal(v.verify?.how, "audio"); + assert.equal(v.verify?.audio?.matched, 9, "a status keeps the audio check"); +}); + +test("leads: counted by post, the forum's own links left out, a private name withheld", async () => { + const v = await lib.leads.leadsView(CASE); + assert.equal(v.channel, lib.fixture.FORUM, "the scope's posts channel"); + assert.equal(v.posts, 7); + const counts = Object.fromEntries(v.leads.map((l) => [l.key, l.count])); + assert.deepEqual(counts, { + "x:@harborwatch": 3, + "harbor-radio.example/archive": 2, + "x:@tidewatcher": 2, + "newgrounds:pocketfox": 1, + "youtube:@harborradio": 1, + }); + assert.equal(v.withheld, 1, "the private name's account is counted, never listed"); + assert.ok(!JSON.stringify(v).toLowerCase().includes(lib.fixture.PRIVATE_NAME.toLowerCase())); + const ctx = await lib.leads.leadContext(CASE, lib.fixture.FORUM, "x:@harborwatch"); + assert.equal(ctx.snippets.length, 3); + assert.deepEqual(ctx.snippets.map((s) => s.position), [1, 2, 4]); +}); + +test("leads: never-archive feeds the name as a hash and keeps the lead only as it; archive creates on no site", async () => { + const r = await lib.leads.decideLead(CASE, { key: "x:@tidewatcher", disposition: "never-archive", role: "the account the forum blames", url: "https://x.com/TideWatcher", count: 2 }); + assert.equal(r.lead.key, `hash:${lib.fixture.nameHash("TideWatcher")}`); + assert.equal(r.lead.url, ""); + const pipeline = JSON.parse(await readFile(path.join(caseDir, "pipeline.json"), "utf8")); + assert.ok(pipeline.privateNames.sha256.includes(lib.fixture.nameHash("TideWatcher"))); + assert.equal(pipeline.subjects[0].name, "Harbor Radio", "the rest of the definition kept"); + const leadsText = await readFile(path.join(caseDir, "leads.json"), "utf8"); + assert.ok(!/tidewatcher/i.test(leadsText), "no file holds the name"); + const v = await lib.leads.leadsView(CASE); + assert.equal(v.withheld, 2); + assert.ok(!v.leads.some((l) => l.key === "x:@tidewatcher")); + assert.equal(v.leads.filter((l) => l.withheld).length, 1); + // Its snippet elsewhere now withholds it too. + const ctx = await lib.leads.leadContext(CASE, lib.fixture.FORUM, "x:@harborwatch"); + assert.ok(!JSON.stringify(ctx).toLowerCase().includes("tidewatcher")); + await assert.rejects(lib.leads.decideLead(CASE, { key: r.lead.key, disposition: "watch" }), /stays never-archive/); + await assert.rejects(lib.leads.decideLead(CASE, { key: "x:@harborwatch", role: `${lib.fixture.PRIVATE_NAME}'s friend` }), /privacy gate blocked the lead's role note/); + + const before = asked.length; + const a = await lib.leads.decideLead(CASE, { key: "x:@harborwatch", disposition: "archive", url: "https://x.com/HarborWatch", count: 3 }); + const create = asked.slice(before).find((x) => x.path === "/api/ops/create-channel")!; + assert.equal((create.body.fields as { url: string }).url, "https://x.com/HarborWatch"); + assert.equal("sites" in create.body, false, "X on no site, by rule"); + assert.equal(create.body.fetchPostsNow, true); + assert.equal(a.lead.channel, a.created?.slug); + const roleOnly = await lib.leads.decideLead(CASE, { key: "x:@harborwatch", role: "posts the council minutes" }); + assert.equal(roleOnly.lead.disposition, "archive", "a role alone leaves the disposition as it was"); + assert.equal(roleOnly.lead.channel, a.lead.channel); + assert.equal(roleOnly.created, undefined, "nothing is created twice"); + const undecided = await lib.leads.decideLead(CASE, { key: "youtube:@harborradio", disposition: "watch", url: "https://www.youtube.com/@HarborRadio" }); + assert.equal(undecided.lead.disposition, "watch"); + assert.equal((await lib.leads.decideLead(CASE, { key: "youtube:@harborradio", disposition: null })).lead.disposition, undefined); + const older = await lib.leads.startOlderWalk(CASE, "x:@harborwatch"); + assert.equal(older.slug, a.lead.channel); + assert.deepEqual(asked[asked.length - 1].body, { slug: a.lead.channel, older: true }); +}); + +test("evidence: an excluded target, a capture at a date, a forum attachment marked unverified, attached to a finding", async () => { + const added = await lib.evidence.addTargets(CASE, [lib.fixture.EXCLUDED_URL, lib.fixture.TARGET_URL], ["2014-03-04"]); + assert.deepEqual(added.map((r) => [r.id, r.at, r.state]), [["e1", "20140304", "planned"], ["e2", "20140304", "planned"]]); + const gone = await lib.evidence.lookupTarget(CASE, "e1"); + assert.equal(gone.state, "excluded"); + assert.equal(gone.label, "excluded from the Wayback Machine (cause unknown)"); + await assert.rejects(lib.evidence.captureTarget(CASE, "e1", { slug: lib.fixture.PAGES }), /excluded from the Wayback Machine/); + const found = await lib.evidence.lookupTarget(CASE, "e2"); + assert.match(found.message ?? "", /2 captures; nearest 2014-03-04/); + const q = await lib.evidence.captureTarget(CASE, "e2", { slug: lib.fixture.PAGES }); + assert.equal(q.state, "queued"); + let row = q; + for (let i = 0; i < 20 && row.state === "queued"; i++) { + await wait(200); + row = await lib.evidence.refreshEvidence(CASE, "e2"); + } + assert.equal(row.state, "captured"); + assert.equal(row.captureTs, "20140304120000"); + assert.equal(row.label, "Wayback capture, 2014-03-04"); + + const f = await lib.evidence.addForumAttachment(CASE, lib.fixture.FORUM, "70003"); + assert.equal(f.label, "forum attachment, post #3, unverified"); + assert.deepEqual(asked.filter((x) => x.route === "capture-posts").at(-1), { route: "capture-posts", slug: lib.fixture.FORUM, ids: ["70003"], shots: true, media: true }); + let fr = f; + for (let i = 0; i < 20 && fr.state === "queued"; i++) { + await wait(200); + fr = await lib.evidence.refreshEvidence(CASE, f.id); + } + assert.equal(fr.state, "captured"); + assert.deepEqual(fr.files, ["minutes.png", "shot.png"]); + const att = await lib.evidence.attachEvidence(CASE, f.id, "f3"); + assert.deepEqual(att.finding.evidence, [{ kind: "forum-attachment", url: lib.fixture.FORUM_POSTS[2].url, evidence: f.id, post: "70003", position: 3 }]); + const v = await lib.verify.verifyView(CASE); + assert.deepEqual(v.rows.find((r) => r.row === "f3")?.evidenceLabels, ["forum attachment, post #3, unverified"]); + + const md = lib.evidence.evidenceSection(await lib.evidence.readEvidence(CASE)).join("\n"); + assert.match(md, /^## Evidence\n/); + assert.match(md, /- excluded from the Wayback Machine \(cause unknown\) — http:\/\/gone\.harbor-radio\.example\/, asked for 2014-03-04/); + assert.match(md, /- Wayback capture, 2014-03-04 — \[http:\/\/harbor-radio\.example\/archive\]\(https:\/\/web\.archive\.org\/web\/20140304120000\/http:\/\/harbor-radio\.example\/archive\)/); + assert.match(md, /- forum attachment, post #3, unverified — \[the post\]\(.+post-70003\), 2 files captured \(for f3\)/); +}); diff --git a/umtool/lib/research/case-verify.ts b/umtool/lib/research/case-verify.ts @@ -0,0 +1,370 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { findVideo } from "yt-dlp-transcript-mcp/research"; +import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; +import { cuesOfTrack, trackKind, trackLabel } from "yt-dlp-transcript-common/lib/captionTracks"; +import { holdsWords, wordsOf } from "yt-dlp-transcript-common/lib/report/quoteWords"; +import { + QUOTE_WORDS_MAX, + VERIFY_STATUSES, + evidenceLabel, + isVerifyStatus, + type AudioCheck, + type FindingRow, + type FindingVerify, + type VerifyStatus, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { withholdPrivateNames } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { quoteWordDiff, type WordOp } from "yt-dlp-transcript-common/lib/research/wordDiff"; +import { CHANNELS_DIR, REPORTS_ROOT } from "../paths.mjs"; +import { readCase } from "./cases.mjs"; +import { mutateFindings, readFindings, rowOf } from "./case-findings-store"; +import { CaseError, privateHashes } from "./case-stage-files"; +import { jobState, resultLine, startJob } from "./case-editor"; +import { fetchForReader } from "./fetch"; +import { localDir, openSource } from "./sources"; + +// --------------------------------------------------------------------------- +// STAGE 7, VERIFY (release 38 lane C): per finding, the window's captions in +// both tracks side by side with the quote's words lit; an AUDIO CHECK -- the +// window transcribed through the editor (`transcribe`, a transcribe-file job +// on a local worker; never a hand-run whisper) and its words diffed with the +// quote; and a status, `verified | corrected | disputed | unverified | +// quarantined`. A quote corrected by hand keeps the reader's words in +// `verify.original`. Every change is a whole rewrite of findings.jsonl +// through lane A's store and privacy gate (case-findings-store.ts): a +// hand-written quote or note that names a private name is refused (counts and +// the row id, never the name). +// --------------------------------------------------------------------------- + +/** How far before and after a finding's `t` its window reaches (seconds). */ +export const WINDOW_BEFORE = 15; +export const WINDOW_AFTER = 35; +/** The audio check's window: a little before the quote, enough after it for 45 words. */ +export const AUDIO_BEFORE = 5; +export const AUDIO_AFTER = 30; + +const MEDIA_EXT = /\.(?:m4a|mp3|opus|ogg|oga|wav|flac|aac|mp4|mkv|webm|mov)$/i; + +// ── who the finding came from ── + +async function channelPlatform(slug: string): Promise<string | null> { + if (!/^[A-Za-z0-9_.@-]+$/.test(slug)) return null; + try { + const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(CHANNELS_DIR, slug, "config.json"), "utf8")); + return typeof c?.platform === "string" ? c.platform : null; + } catch { + return null; + } +} + +/** First seen on a forum: the row is from a forum channel, or its evidence is a forum attachment. */ +export function forumSourced(row: FindingRow, platformOfSlug: string | null): boolean { + return platformOfSlug === "xenforo" || (row.evidence ?? []).some((e) => e.kind === "forum-attachment"); +} + +// ── the list ── + +export type VerifyRow = FindingRow & { status: VerifyStatus; forum: boolean; evidenceLabels: string[] }; +export type VerifyView = { + rows: VerifyRow[]; + counts: Record<VerifyStatus, number>; + bad: { line: number; error: string }[]; + statuses: readonly VerifyStatus[]; +}; + +export async function verifyView(caseId: string): Promise<VerifyView> { + const { rows, bad } = await readFindings(caseId); + const platforms = new Map<string, string | null>(); + for (const r of rows) if (!platforms.has(r.slug)) platforms.set(r.slug, await channelPlatform(r.slug)); + const counts = Object.fromEntries(VERIFY_STATUSES.map((s) => [s, 0])) as Record<VerifyStatus, number>; + const out: VerifyRow[] = rows.map((r) => { + const status = r.verify?.status ?? "unverified"; + counts[status]++; + return { + ...r, + status, + forum: forumSourced(r, platforms.get(r.slug) ?? null), + evidenceLabels: (r.evidence ?? []).map((e) => evidenceLabel({ kind: e.kind, position: e.position, post: e.post, capturedAt: e.capturedAt })), + }; + }); + return { rows: out, counts, bad, statuses: VERIFY_STATUSES }; +} + +// ── the captions, both tracks ── + +export type CaptionPart = { text: string; hit: boolean }; +export type CaptionCue = { start: number; end: number; parts: CaptionPart[] }; +export type CaptionTrack = { track: string; label: string; kind: string; cues: CaptionCue[]; holds: boolean; matched: number; words: number }; +export type CaptionsView = { row: string; quote: string; t: number; title: string; tracks: CaptionTrack[]; note?: string }; + +type Tok = { text: string; cue: number; norm: string[] }; + +/** + * Which of `words` the quote lands on: the stretch (about the quote's length) that holds the most of its words in + * order, the nearest to the finding's moment on a tie; its matched words are the hits. + */ +export function alignQuote(quote: string[], words: string[], nearIndex = 0): { hits: Set<number>; matched: number } { + const n = quote.length; + if (!n || !words.length) return { hits: new Set(), matched: 0 }; + const span = Math.min(words.length, Math.max(n + 4, Math.ceil(n * 1.5))); + let best = { start: 0, matched: -1, dist: Infinity }; + for (let s = 0; s + span <= words.length || s === 0; s++) { + const w = words.slice(s, s + span); + const m = lcsLen(quote, w); + const dist = Math.abs(s - nearIndex); + if (m > best.matched || (m === best.matched && dist < best.dist)) best = { start: s, matched: m, dist }; + if (s + span >= words.length) break; + } + const w = words.slice(best.start, best.start + span); + const hits = new Set<number>(); + for (const j of lcsPairs(quote, w)) hits.add(best.start + j); + return { hits, matched: Math.max(0, best.matched) }; +} + +function lcsTable(a: string[], b: string[]): number[][] { + const t: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) t[i][j] = a[i] === b[j] ? t[i + 1][j + 1] + 1 : Math.max(t[i + 1][j], t[i][j + 1]); + return t; +} +const lcsLen = (a: string[], b: string[]) => lcsTable(a, b)[0][0]; +function lcsPairs(a: string[], b: string[]): number[] { + const t = lcsTable(a, b); + const out: number[] = []; + let i = 0; + let j = 0; + while (i < a.length && j < b.length) { + if (a[i] === b[j]) { + out.push(j); + i++; + j++; + } else if (t[i + 1][j] >= t[i][j + 1]) i++; + else j++; + } + return out; +} + +/** One track's window, its words lit where the quote lands. */ +export function litTrack(cues: { start: number; end?: number; text: string }[], quote: string, t: number): Omit<CaptionTrack, "track" | "label" | "kind"> { + const win = cues.filter((c) => c.start >= t - WINDOW_BEFORE && c.start <= t + WINDOW_AFTER); + const toks: Tok[] = []; + win.forEach((c, i) => { + for (const piece of c.text.split(/\s+/).filter(Boolean)) toks.push({ text: piece, cue: i, norm: wordsOf(piece).split(" ").filter(Boolean) }); + }); + const flat: { tok: number; w: string }[] = []; + toks.forEach((tk, i) => tk.norm.forEach((w) => flat.push({ tok: i, w }))); + const q = wordsOf(quote).split(" ").filter(Boolean); + const nearCue = win.findIndex((c) => c.start >= t - 1); + const nearIndex = Math.max(0, flat.findIndex((f) => toks[f.tok].cue >= nearCue)); + const { hits, matched } = alignQuote(q, flat.map((f) => f.w), nearIndex); + const litTok = new Set([...hits].map((h) => flat[h].tok)); + const out: CaptionCue[] = win.map((c) => ({ start: c.start, end: c.end ?? c.start, parts: [] })); + toks.forEach((tk, i) => { + const parts = out[tk.cue].parts; + const hit = litTok.has(i); + const last = parts[parts.length - 1]; + if (last && last.hit === hit) last.text += ` ${tk.text}`; + else parts.push({ text: parts.length ? ` ${tk.text}` : tk.text, hit }); + }); + // A leading space belongs outside a lit run. + for (const c of out) { + for (let i = 1; i < c.parts.length; i++) { + if (c.parts[i].hit && c.parts[i].text.startsWith(" ")) { + c.parts[i].text = c.parts[i].text.slice(1); + c.parts[i - 1].text += " "; + } + } + } + return { cues: out, holds: holdsWords(win.map((c) => c.text).join(" "), quote), matched, words: q.length }; +} + +const trackOrder = (track: string) => ({ original: 0, uploaded: 1, transcription: 2 })[trackKind(track) as "original"] ?? 3; + +async function sourceOf(caseId: string): Promise<string> { + const doc = (await readCase(REPORTS_ROOT, caseId)) as { scope?: { source?: string } }; + return doc.scope?.source?.trim() || `local:${localDir()}`; +} + +async function postTrack(f: FindingRow, hashes: string[]): Promise<CaptionTrack | null> { + const platform = await channelPlatform(f.slug); + if (!platform || !["xenforo", "twitter", "bluesky", "webpage"].includes(platform)) return null; + const posts = await readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, f.slug)).catch(() => []); + const p = posts.find((x) => x.id === f.id); + if (!p) return null; + const lit = litTrack([{ start: 0, end: 0, text: withholdPrivateNames(p.text, hashes).text }], f.quote, 0); + const author = withholdPrivateNames(p.author, hashes).text; + const label = platform === "xenforo" ? `forum post${p.forum?.position ? ` #${p.forum.position}` : ""} by ${author}` : `post by ${author}`; + return { track: "post", label, kind: "post", ...lit }; +} + +export async function findingCaptions(caseId: string, row: string): Promise<CaptionsView> { + const { rows } = await readFindings(caseId); + const f = rowOf(rows, row); + const opened = await openSource(await sourceOf(caseId)); + // A post (a forum's, an X account's): its text is the "track", read from the editor's corpus. + // Text from the corpus is shown with the case's private names withheld. + const hashes = await privateHashes(caseId); + const asPost = await postTrack(f, hashes); + if (asPost) return { row, quote: f.quote, t: f.t, title: f.title, tracks: [asPost] }; + const found = await findVideo(opened.source, f.id, f.slug).catch(() => null); + if (!found) return { row, quote: f.quote, t: f.t, title: f.title, tracks: [], note: `${f.slug}/${f.id} is not in ${opened.option.label}` }; + const rec = found.record as { track?: string; altTracks?: { track: string }[]; transcriptFormat?: string }; + const primary = rec.track ?? (rec.transcriptFormat && rec.transcriptFormat !== "vtt" ? "transcription" : "captions"); + const ids = [primary, ...(rec.altTracks ?? []).map((a) => a.track)]; + const tracks: CaptionTrack[] = []; + for (const id of [...new Set(ids)].sort((a, b) => trackOrder(a) - trackOrder(b)).slice(0, 3)) { + const cues = ((cuesOfTrack(found.record, id === primary ? rec.track : id) ?? []) as { start: number; end: number; text: string }[]).filter( + (c) => c && typeof c.start === "number", + ); + if (!cues.length) continue; + const shown = hashes.length ? cues.map((c) => ({ ...c, text: withholdPrivateNames(c.text, hashes).text })) : cues; + tracks.push({ track: id, label: trackLabel(id), kind: trackKind(id), ...litTrack(shown, f.quote, f.t) }); + } + return { row, quote: f.quote, t: f.t, title: f.title, tracks }; +} + +// ── a status, and a correction by hand ── + +export type VerifyPatch = { status: string; note?: string; quote?: string; speaker?: string; how?: string }; + +export async function setVerify(caseId: string, row: string, patch: VerifyPatch, now = new Date()): Promise<VerifyRow> { + if (!isVerifyStatus(patch.status)) throw new CaseError(`not a status: ${JSON.stringify(patch.status)} (one of ${VERIFY_STATUSES.join(", ")})`, 400); + const note = typeof patch.note === "string" ? patch.note.replace(/\s+/g, " ").trim().slice(0, 1000) : undefined; + const quote = typeof patch.quote === "string" ? patch.quote.replace(/\s+/g, " ").trim() : undefined; + const speaker = typeof patch.speaker === "string" ? patch.speaker.replace(/\s+/g, " ").trim().slice(0, 120) : undefined; + if (quote !== undefined && !quote) throw new CaseError("a corrected quote cannot be empty", 400); + if (quote && quote.split(" ").length > QUOTE_WORDS_MAX) throw new CaseError(`a quote is at most ${QUOTE_WORDS_MAX} words, verbatim`, 400); + // The privacy gate is the findings writer's (case-findings-store.ts): a hand-written quote, speaker or note + // that names a private name refuses the whole write (409, counts and the row id, never the name). + const r = await mutateFindings(caseId, (rows) => { + const f = rowOf(rows, row); + const changesWords = (quote !== undefined && quote !== f.quote) || (speaker !== undefined && speaker !== f.speaker); + if (changesWords && patch.status !== "corrected") throw new CaseError("a quote or speaker changed by hand is status corrected", 400); + const prev = f.verify; + const next: FindingVerify = { + status: patch.status as VerifyStatus, + at: now.toISOString(), + how: changesWords ? "hand" : patch.how === "audio" && prev?.audio ? "audio" : "captions", + ...(note ? { note } : {}), + ...(prev?.original ? { original: prev.original } : {}), + ...(prev?.audio ? { audio: prev.audio } : {}), + }; + if (changesWords) { + // The reader's words are kept once: a second correction never loses them. + next.original ??= { quote: f.quote, ...(f.speaker ? { speaker: f.speaker } : {}) }; + if (quote !== undefined) f.quote = quote; + if (speaker !== undefined) f.speaker = speaker; + } + f.verify = next; + return f; + }); + const platform = await channelPlatform(r.result.slug); + return { + ...r.result, + status: r.result.verify!.status, + forum: forumSourced(r.result, platform), + evidenceLabels: (r.result.evidence ?? []).map((e) => evidenceLabel(e)), + }; +} + +// ── the audio check ── + +/** The held media to transcribe the window from: the video's own file, else a fetched clip window covering it. */ +export async function heldMedia(slug: string, id: string, from: number, to: number): Promise<{ file: string; offset: number } | null> { + if (!/^[A-Za-z0-9_.@-]+$/.test(slug) || !/^[A-Za-z0-9_.@-]+$/.test(id)) return null; + const dir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "data", id); + const names = await readdir(/* turbopackIgnore: true */ dir).catch(() => [] as string[]); + const media = names.filter((n) => MEDIA_EXT.test(n) && !n.startsWith(".")).sort((a, b) => Number(b.startsWith("audio.")) - Number(a.startsWith("audio."))); + if (media.length) return { file: path.join(dir, media[0]), offset: 0 }; + const clips = await readdir(/* turbopackIgnore: true */ path.join(dir, "clips")).catch(() => [] as string[]); + let best: { file: string; offset: number; len: number } | null = null; + for (const n of clips) { + const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)\.(?:mp4|m4a|webm|mkv)$/.exec(n); + if (!m) continue; + const a = Number(m[1]); + const b = Number(m[2]); + if (a <= from && b >= to && (!best || b - a < best.len)) best = { file: path.join(dir, "clips", n), offset: a, len: b - a }; + } + return best ? { file: best.file, offset: best.offset } : null; +} + +export type AudioAnswer = + | { state: "fetching"; fetchJob: string; message: string } + | { state: "transcribing"; job: string; message: string } + | { state: "done"; audio: AudioCheck; ops: WordOp[] } + | { state: "failed"; message: string; job?: string }; + +export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result "; + +async function queueTranscribe(file: string, start: number, end: number, whilePaused: boolean): Promise<AudioAnswer> { + const job = await startJob("/api/ops/transcribe", { + path: file, + start: Math.max(0, Math.round(start * 10) / 10), + end: Math.round(end * 10) / 10, + ...(whilePaused ? { whilePaused: true } : {}), + }); + return { state: "transcribing", job, message: "the window is queued on a local transcription worker" }; +} + +/** + * One step of a finding's audio check. With no job: find the window's media (held, or a clip fetched through the + * editor's fetch-window, exactly as the reader's Fetch clip asks) and queue its transcription. With `fetchJob`: once + * the clip is in, queue it. With `job`: once the transcription is done, diff it and keep it on the finding. + */ +export async function audioStep( + caseId: string, + row: string, + opts: { whilePaused?: boolean; fetchJob?: string; job?: string }, + now = new Date(), +): Promise<AudioAnswer> { + const { rows } = await readFindings(caseId); + const f = rowOf(rows, row); + const from = Math.max(0, f.t - AUDIO_BEFORE); + const to = f.t + AUDIO_AFTER; + const whilePaused = opts.whilePaused === true; + if (opts.job) { + const st = await jobState(opts.job); + if (!st.done) return { state: "transcribing", job: opts.job, message: `the transcription is ${st.status}` }; + const res = resultLine<{ text?: string; cues?: { text: string }[]; worker?: { name?: string; id?: string } }>(st.tail, TRANSCRIBE_RESULT_MARKER); + if (st.status !== "done" || !res) { + return { state: "failed", job: opts.job, message: `the transcription ${st.status}${st.tail.length ? `: ${st.tail[st.tail.length - 1]}` : ""}` }; + } + const heard = res.text ?? (res.cues ?? []).map((c) => c.text).join(" "); + const diff = quoteWordDiff(f.quote, heard); + const hashes = await privateHashes(caseId); + const audio: AudioCheck = { + at: now.toISOString(), + job: opts.job, + text: withholdPrivateNames(heard.replace(/\s+/g, " ").trim(), hashes).text.slice(0, 4000), + matched: diff.matched, + words: diff.words, + ...(res.worker?.name || res.worker?.id ? { worker: String(res.worker?.name ?? res.worker?.id) } : {}), + }; + await mutateFindings(caseId, (all) => { + const r = rowOf(all, row); + r.verify = { ...(r.verify ?? { status: "unverified" as const, at: audio.at }), audio }; + }); + return { state: "done", audio, ops: diff.ops }; + } + if (opts.fetchJob) { + const fetched = await fetchForReader({ job: opts.fetchJob }); + if (fetched.state === "queued") return { state: "fetching", fetchJob: opts.fetchJob, message: `the clip is ${fetched.status}` }; + if (fetched.state === "failed") return { state: "failed", message: fetched.message }; + const offset = fetched.from ?? from; + return queueTranscribe(fetched.file, from - offset, to - offset, whilePaused); + } + const held = await heldMedia(f.slug, f.id, from, to); + if (held) return queueTranscribe(held.file, from - held.offset, to - held.offset, whilePaused); + const fetched = await fetchForReader({ + source: await sourceOf(caseId), + channel: f.slug, + video: f.id, + start: from, + end: to, + reason: `research case ${caseId}: audio check of ${row}`, + }); + if (fetched.state === "queued") return { state: "fetching", fetchJob: fetched.job, message: "no media is held; the window is being fetched through the editor" }; + if (fetched.state === "failed") return { state: "failed", message: fetched.message }; + const offset = fetched.from ?? from; + return queueTranscribe(fetched.file, from - offset, to - offset, whilePaused); +} diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -45,6 +45,9 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // E2E_UMTOOL_OPEN_FOLDER_LOG set below on the app server: where the clip // export's Open folder records what it was asked to // show, in place of a file manager (lib/report/openFolder.mjs) +// E2E_CASE_STAGES_SHOTS a directory, set by whoever runs the suite: the +// research case stages' screenshots go there +// (case-stages.spec.ts, release 38 lane C) // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT");