Archilyzer · Source

archilyzer

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

commit 8d436cf30ffae89ae0c9af6bd854c5b0e39a1394
parent 21d1a980fb3712b3e16368ea862730d48ae8227c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 04:47:01 -0500

umtool research: a case's verify, leads and evidence stages -- pages, routes, one writer per file

Release 38 lane C, beside the board under /research/<case>/ (a Board/Verify/Leads/Evidence row of
links on every case page; lane A's stages join it):
- Verify: each finding's window in every caption track side by side (en-orig first, then en, a
  post's text for a post), the quote's words lit where it lands; the audio check -- the held media
  or a clip fetched through the editor, transcribed by the editor's `transcribe` (whilePaused by a
  checkbox), its words diffed with the quote and kept on the finding; a status of the five; a
  correction by hand that keeps the reader's words in verify.original once; a hand-written quote,
  speaker or note refused (422, a count) when it holds a private name.
- Leads: the accounts and pages a posts or forum channel links most, counted by post (the forum's
  own links left out), context snippets on demand with private names withheld; a role note and a
  disposition each. never-archive feeds the name's hash to pipeline.json's privateNames and keeps
  the lead only as that hash; archive creates the channel through create-channel on no site and
  starts its first fetch; Older walk is fetch-posts {older}.
- Evidence: Wayback targets at chosen dates (wayback-lookup: a 403 is an `excluded` row with the
  sentence; import-page into a Wayback pages channel), a forum post's attachments and screenshot
  through capture-posts marked "forum attachment, post #N, unverified", attached to findings;
  renderEvidenceSection and renderQuarantinedSection for the case export.
findings.jsonl has one writer (case-findings-store.ts: append, or rewrite whole under the file's
lock; a bad line is never rewritten). The e2e fixture case and the stand-in editor's routes for
transcribe, wayback-lookup, capture-posts and fetch-posts; the unit test runs over both.

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

Diffstat:
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 | 40++++++++++++++++++++++++++++++++++++++++
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++++++++++++++++++++++++++++++++
Aumtool/app/research/[case]/evidence/page.tsx | 25+++++++++++++++++++++++++
Aumtool/app/research/[case]/leads/page.tsx | 26++++++++++++++++++++++++++
Aumtool/app/research/[case]/verify/page.tsx | 28++++++++++++++++++++++++++++
Mumtool/components/research/BoardView.tsx | 2++
Aumtool/components/research/stages/CaseStagesNav.tsx | 36++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/EvidencePanel.tsx | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/LeadsPanel.tsx | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/StagePage.tsx | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/research/stages/VerifyPanel.tsx | 384+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/case-stages-fixture.mjs | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/editor-stub-case-stages.mjs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub-import-page.mjs | 19+++++++++++++++----
Mumtool/e2e/fixtures/editor-stub.mjs | 3+++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/lib/research/case-editor.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-evidence.ts | 353+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-findings-store.ts | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-leads.ts | 376+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-stage-files.ts | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-stage-hrefs.ts | 12++++++++++++
Aumtool/lib/research/case-stages.test.ts | 240+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-verify.ts | 372+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
29 files changed, 3238 insertions(+), 4 deletions(-)

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,40 @@ +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 ?? ""), + disposition: b.disposition === null ? null : str("disposition"), + 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]/evidence/page.tsx b/umtool/app/research/[case]/evidence/page.tsx @@ -0,0 +1,25 @@ +import StagePage from "@/components/research/stages/StagePage"; +import EvidencePanel from "@/components/research/stages/EvidencePanel"; +import { readCase } from "@/lib/research/boards"; +import { evidenceView, type EvidenceView } from "@/lib/research/case-evidence"; + +export const dynamic = "force-dynamic"; + +// STAGE 10, EVIDENCE CAPTURE (release 38 lane C): /research/<case>/evidence. +export default async function EvidencePage({ params }: { params: Promise<{ case: string }> }) { + const id = decodeURIComponent((await params).case); + let view: EvidenceView | null = null; + let title: string | null = null; + let error: { status: number; message: string } | null = null; + try { + title = (await readCase(id)).title; + view = await evidenceView(id); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + return ( + <StagePage id={id} title={title} stage="evidence" meta="Wayback captures and forum attachments, through the editor" error={error}> + {view && <EvidencePanel caseId={id} initial={view} />} + </StagePage> + ); +} diff --git a/umtool/app/research/[case]/leads/page.tsx b/umtool/app/research/[case]/leads/page.tsx @@ -0,0 +1,26 @@ +import StagePage from "@/components/research/stages/StagePage"; +import LeadsPanel from "@/components/research/stages/LeadsPanel"; +import { readCase } from "@/lib/research/boards"; +import { leadsView, type LeadsView } from "@/lib/research/case-leads"; + +export const dynamic = "force-dynamic"; + +// STAGE 8, LEADS (release 38 lane C): /research/<case>/leads[?channel=<slug>]. +export default async function LeadsPage({ params, searchParams }: { params: Promise<{ case: string }>; searchParams: Promise<{ channel?: string }> }) { + const id = decodeURIComponent((await params).case); + const { channel } = await searchParams; + let view: LeadsView | null = null; + let title: string | null = null; + let error: { status: number; message: string } | null = null; + try { + title = (await readCase(id)).title; + view = await leadsView(id, channel ?? null); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + return ( + <StagePage id={id} title={title} stage="leads" meta="The accounts and pages a posts or forum channel links most" error={error}> + {view && <LeadsPanel caseId={id} initial={view} />} + </StagePage> + ); +} diff --git a/umtool/app/research/[case]/verify/page.tsx b/umtool/app/research/[case]/verify/page.tsx @@ -0,0 +1,28 @@ +import StagePage from "@/components/research/stages/StagePage"; +import VerifyPanel from "@/components/research/stages/VerifyPanel"; +import { readCase } from "@/lib/research/boards"; +import { verifyView, type VerifyView } from "@/lib/research/case-verify"; + +export const dynamic = "force-dynamic"; + +// STAGE 7, VERIFY (release 38 lane C): /research/<case>/verify. The findings +// beside the board, each checked against its captions (both tracks), by ear +// (the editor's transcribe), and marked. +export default async function VerifyPage({ params }: { params: Promise<{ case: string }> }) { + const id = decodeURIComponent((await params).case); + let view: VerifyView | null = null; + let title: string | null = null; + let error: { status: number; message: string } | null = null; + try { + title = (await readCase(id)).title; + view = await verifyView(id); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + const meta = view ? `${view.rows.length} findings · ${view.counts.verified} verified · ${view.counts.corrected} corrected · ${view.counts.disputed} disputed · ${view.counts.quarantined} quarantined` : undefined; + return ( + <StagePage id={id} title={title} stage="verify" meta={meta} error={error}> + {view && <VerifyPanel caseId={id} initial={view} />} + </StagePage> + ); +} diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -22,6 +22,7 @@ import { researchHref, } from "@/lib/research/hrefs"; import HandoffDialog from "./HandoffDialog"; +import CaseStagesNav from "./stages/CaseStagesNav"; import { runHref } from "@/lib/research/runs-hrefs"; import { triageHref } from "@/lib/hrefs"; import QuoteSlip, { quoteLineId } from "./QuoteSlip"; @@ -518,6 +519,7 @@ export default function BoardView({ initial }: { initial: CaseView }) { <> <AppHeader crumbs={[{ href: researchHref(), label: "Research" }, { label: doc.title }]} + below={<CaseStagesNav id={doc.id} current="board" />} meta={ <> <span className="micro mr-2">Research · case</span> diff --git a/umtool/components/research/stages/CaseStagesNav.tsx b/umtool/components/research/stages/CaseStagesNav.tsx @@ -0,0 +1,36 @@ +import Link from "next/link"; +import { cn } from "@/lib/utils"; +import { researchCaseHref } from "@/lib/research/hrefs"; +import { caseStageHref, type CaseStagePage } from "@/lib/research/case-stage-hrefs"; + +// The case's pages as one row of links: the board, and lane C's stages +// (release 38: verify, leads, evidence). No hooks: the board's client header +// and the stage pages' server heads both draw it. Lane A's pipeline stages +// (coverage, candidates, batches, merge) join this row when they land. +const STAGES: { id: "board" | CaseStagePage; label: string }[] = [ + { id: "board", label: "Board" }, + { id: "verify", label: "Verify" }, + { id: "leads", label: "Leads" }, + { id: "evidence", label: "Evidence" }, +]; + +export default function CaseStagesNav({ id, current }: { id: string; current: "board" | CaseStagePage }) { + return ( + <nav aria-label="Case stages" className="flex flex-wrap items-center gap-1 text-[12.5px]"> + {STAGES.map((s) => ( + <Link + key={s.id} + href={s.id === "board" ? researchCaseHref(id) : caseStageHref(id, s.id)} + aria-current={s.id === current ? "page" : undefined} + prefetch={false} + className={cn( + "rounded-[3px] border px-2 py-[3px]", + s.id === current ? "border-muted bg-panel-2 text-text" : "border-transparent text-muted-2 hover:text-text hover:bg-panel-2", + )} + > + {s.label} + </Link> + ))} + </nav> + ); +} 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 className="px-5 py-4"> + <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="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,256 @@ +"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); + } + }; + + const decide = async (lead: LeadRow, disposition: LeadDisposition | "", 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: 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 className="px-5 py-4"> + <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, l.disposition ?? "", 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/StagePage.tsx b/umtool/components/research/stages/StagePage.tsx @@ -0,0 +1,50 @@ +import Link from "next/link"; +import AppHeader from "@/components/shell/AppHeader"; +import AppRail from "@/components/shell/AppRail"; +import { EmptyState } from "@/components/ui/empty-state"; +import { researchCaseHref, researchHref } from "@/lib/research/hrefs"; +import type { CaseStagePage } from "@/lib/research/case-stage-hrefs"; +import CaseStagesNav from "./CaseStagesNav"; + +const TITLES: Record<CaseStagePage, string> = { verify: "Verify", leads: "Leads", evidence: "Evidence" }; + +// A lane C stage page's frame (release 38): the rail, the head with the +// case's stages, and the stage's panel -- or the case's error in words. +export default function StagePage({ + id, + title, + stage, + meta, + error, + children, +}: { + id: string; + title: string | null; + stage: CaseStagePage; + meta?: React.ReactNode; + error?: { status: number; message: string } | null; + children?: React.ReactNode; +}) { + return ( + <div className="flex h-full flex-col"> + <AppRail active="research" /> + <AppHeader + crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: title ?? id }, { label: TITLES[stage] }]} + meta={meta} + below={<CaseStagesNav id={id} current={stage} />} + /> + {error ? ( + <div className="px-7 pt-6"> + <EmptyState title={error.status === 404 ? `No case “${id}”` : "This case cannot be read"}> + <span role="alert">{error.message}</span>{" "} + <Link href={researchHref()} className="ink-link"> + Research + </Link> + </EmptyState> + </div> + ) : ( + children + )} + </div> + ); +} diff --git a/umtool/components/research/stages/VerifyPanel.tsx b/umtool/components/research/stages/VerifyPanel.tsx @@ -0,0 +1,384 @@ +"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); + } 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 flex-1 grid-cols-1 gap-0 md:grid-cols-[minmax(260px,340px)_1fr]"> + <aside aria-label="Findings" className="min-h-0 overflow-y-auto border-r border-seam px-3 py-3"> + <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 px-5 py-4"> + <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/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,120 @@ +// 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/capture-posts {slug, ids} +// job; when done, posts-media/<id>/shot.png and the post's attachment +// written into the fixture corpus +// 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.) Never a +// worker, the Wayback Machine or a forum. Every request is recorded by the +// main stub's `record`. + +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { EXCLUDED_URL, HEARD } from "./case-stages-fixture.mjs"; + +const jobs = new Map(); +let next = 1; + +// A 1×1 PNG. +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64"); + +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/capture-posts", (body) => { + const ids = Array.isArray(body.ids) ? body.ids.map(String) : []; + if (!body.slug || !ids.length) return json(res, 400, { ok: false, error: "name a channel and its posts" }); + const id = job("capture-posts", [`Capture ${ids.length} post(s) of ${body.slug}`], () => { + for (const pid of ids) { + const dir = path.join(ctx.channels, body.slug, "posts-media", pid); + mkdirSync(dir, { recursive: true }); + writeFileSync(path.join(dir, "shot.png"), PNG); + writeFileSync(path.join(dir, "minutes.png"), PNG); + writeFileSync(path.join(dir, "capture.json"), JSON.stringify({ id: pid, shot: "shot.png", media: ["minutes.png"] })); + } + }); + json(res, 200, { ok: true, jobId: id }); + }) + ) + 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.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -24,6 +24,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"; @@ -1249,6 +1250,8 @@ const server = http.createServer((req, res) => { return json(res, 401, { error: "missing bearer token" }); } + // 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 { makeDigestContextFixture } from "./digest-context-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; @@ -2349,6 +2350,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 }); // R3: transparent runs -- a traced sweep, an imported turns-only one with two // run starts, and one still running. makeRunTraceFixture({ articles: ARTICLES, source: `local:${RESEARCH_PUBLIC}` }); 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,353 @@ +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, + forumAttachmentLabel, + 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) lists the rows in an Evidence section: +// renderEvidenceSection below is what it calls. +// --------------------------------------------------------------------------- + +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 (lane A's case export calls this) ── + +const md = (s: string) => s.replace(/([\\`*_[\]|<>])/g, "\\$1"); +const isoOf = (ts?: string) => (ts && /^\d{8}/.test(ts) ? `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : ""); + +/** The case's evidence as a markdown section: every row with its label, its link, and what it backs. */ +export function renderEvidenceSection(rows: CaseEvidence[], opts: { heading?: string } = {}): string { + const lines = [`## ${opts.heading ?? "Evidence"}`, ""]; + if (!rows.length) return [...lines, "No evidence captured.", ""].join("\n"); + for (const r of rows) { + const label = evidenceLabel(r); + const backs = r.findings?.length ? ` — for ${r.findings.join(", ")}` : ""; + if (r.kind === "forum-attachment") { + const files = r.files?.length ? ` (${r.files.length} file${r.files.length === 1 ? "" : "s"} captured)` : r.state === "captured" ? "" : ` (${r.state})`; + lines.push(`- **${forumAttachmentLabel(r.position, r.post)}** — [the post](${r.url})${files}${backs}`); + } else if (r.state === "excluded") { + lines.push(`- **${label}** — ${md(r.url)}${r.at ? ` (asked for ${isoOf(r.at)})` : ""}${backs}`); + } else if (r.state === "captured" && r.captureTs) { + lines.push(`- **${label}** — [${md(r.url)}](https://web.archive.org/web/${r.captureTs}/${r.url})${backs}`); + } else { + lines.push(`- **${r.state === "failed" ? "Wayback capture failed" : "Wayback capture not taken yet"}** — ${md(r.url)}${r.at ? ` (for ${isoOf(r.at)})` : ""}${r.message ? `: ${md(r.message)}` : ""}${backs}`); + } + } + lines.push(""); + return lines.join("\n"); +} + +/** Findings quarantined (first seen on a forum, uncorroborated) as their own section. */ +export function renderQuarantinedSection(findings: FindingRow[], opts: { heading?: string } = {}): string { + const q = findings.filter((f) => f.verify?.status === "quarantined"); + const lines = [`## ${opts.heading ?? "Quarantined: first seen on a forum, not corroborated"}`, ""]; + if (!q.length) return [...lines, "None.", ""].join("\n"); + for (const f of q) { + const ev = (f.evidence ?? []).map((e) => evidenceLabel({ kind: e.kind, position: e.position, post: e.post, capturedAt: e.capturedAt })).join("; "); + lines.push(`- ${f.row}: "${md(f.quote)}" — [${md(f.title || `${f.slug}/${f.id}`)}](${f.url})${ev ? ` — ${ev}` : ""}${f.verify?.note ? ` — ${md(f.verify.note)}` : ""}`); + } + lines.push(""); + return lines.join("\n"); +} diff --git a/umtool/lib/research/case-findings-store.ts b/umtool/lib/research/case-findings-store.ts @@ -0,0 +1,99 @@ +import { readFile } from "node:fs/promises"; +import { CASE_FILES, type FindingRow } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { CaseError, labelOf, stageDir, stageFile, withFileLock, writeWhole } from "./case-stage-files"; + +// --------------------------------------------------------------------------- +// FINDINGS, ONE WRITER (release 38 stage 4 appends, stages 5 and 7 rewrite): +// `<case>/findings.jsonl`, one FindingRow per line. Every change goes through +// here, under the file's lock: `appendFindings` (the read: by hand, case-read) +// adds lines; `mutateFindings` (verify, merge) reads every row, changes them, +// and writes the file whole. A file with a line that does not parse is never +// rewritten: the change refuses with 409 and names the line, so nothing a +// reader wrote is lost to a bad line. +// --------------------------------------------------------------------------- + +export type FindingsRead = { rows: FindingRow[]; bad: { line: number; error: string }[] }; + +const isRow = (v: unknown): v is FindingRow => + !!v && typeof v === "object" && typeof (v as FindingRow).row === "string" && typeof (v as FindingRow).id === "string"; + +export function parseFindings(text: string): FindingsRead { + const rows: FindingRow[] = []; + const bad: FindingsRead["bad"] = []; + text.split("\n").forEach((line, i) => { + if (!line.trim()) return; + try { + const v = JSON.parse(line); + if (isRow(v)) rows.push(v); + else bad.push({ line: i + 1, error: "not a finding row (no row or id)" }); + } catch (e) { + bad.push({ line: i + 1, error: (e as Error).message }); + } + }); + return { rows, bad }; +} + +async function readAt(file: string): Promise<FindingsRead> { + try { + return parseFindings(await readFile(/* turbopackIgnore: true */ file, "utf8")); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") return { rows: [], bad: [] }; + throw new CaseError(`findings cannot be read: ${(e as Error).message}`, 409); + } +} + +export async function readFindings(caseId: string): Promise<FindingsRead> { + return readAt(stageFile(await stageDir(caseId), CASE_FILES.findings)); +} + +const refuseBad = (caseId: string, r: FindingsRead) => { + if (r.bad.length) { + throw new CaseError( + `${labelOf(caseId, CASE_FILES.findings)} line ${r.bad[0].line} does not parse (${r.bad[0].error}); it is never rewritten until it is fixed`, + 409, + ); + } +}; + +/** Read every row, let `fn` change them (in place or by returning a new list), and write the file whole. */ +export async function mutateFindings<T>(caseId: string, fn: (rows: FindingRow[]) => T | Promise<T>): Promise<{ rows: FindingRow[]; result: T }> { + const file = stageFile(await stageDir(caseId), CASE_FILES.findings); + return withFileLock(file, async () => { + const r = await readAt(file); + refuseBad(caseId, r); + const result = await fn(r.rows); + const ids = new Set<string>(); + for (const row of r.rows) { + if (ids.has(row.row)) throw new CaseError(`two findings are ${row.row}: a row id is never reused`, 409); + ids.add(row.row); + } + await writeWhole(file, r.rows.map((x) => JSON.stringify(x)).join("\n") + (r.rows.length ? "\n" : "")); + return { rows: r.rows, result }; + }); +} + +/** Add rows (each with an id no row in the file has). */ +export async function appendFindings(caseId: string, rows: FindingRow[]): Promise<number> { + if (!rows.length) return 0; + const file = stageFile(await stageDir(caseId), CASE_FILES.findings); + return withFileLock(file, async () => { + const r = await readAt(file); + refuseBad(caseId, r); + const ids = new Set(r.rows.map((x) => x.row)); + for (const row of rows) { + if (!isRow(row)) throw new CaseError("not a finding row (no row or id)", 400); + if (ids.has(row.row)) throw new CaseError(`${row.row} is already a finding: a row id is never reused`, 409); + ids.add(row.row); + } + // Whole, as every write here: an append after a line with no newline would join the two. + await writeWhole(file, [...r.rows, ...rows].map((x) => JSON.stringify(x)).join("\n") + "\n"); + return rows.length; + }); +} + +/** 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, + NAME_WITHHELD, + isLeadDisposition, + type CaseLead, + type LeadDisposition, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { privateNameHash, privateNameHits, redactPrivateNames } from "yt-dlp-transcript-common/lib/research/privateNames-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: redactPrivateNames(p.author ?? "", hashes).text, + text: redactPrivateNames(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 && privateNameHits(role, hashes) > 0) throw new CaseError(`the role note matches the case's private names: write ${NAME_WITHHELD} instead`, 422); + 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,135 @@ +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + CASE_FILES, + CASE_PIPELINE_FORMAT, + CASE_PIPELINE_VERSION, + type CaseDefinition, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { CaseError, caseDir, isCaseId, readCase, storedPath } from "./cases.mjs"; + +// --------------------------------------------------------------------------- +// THE CASE PIPELINE'S FILES, for lane C's stages (release 38: verify, leads, +// evidence; plans/release-38/research-cases-and-assist.md). Each stage file +// sits beside the board's case.json (common/lib/research/caseTypes.ts, +// CASE_FILES), and each has ONE writer here: serialised in-process per file, +// written whole to a temp name and renamed, and never overwritten while it +// does not parse (a write refuses with 409 until somebody fixes it) -- the +// board store's discipline (cases.mjs). +// +// pipeline.json (the definition) is lane A's. Lane C writes ONE thing into it: +// a never-archive lead's name as a HASH in privateNames.sha256 +// (feedPrivateNameHash), through the same lock, keeping every other key as it +// was. When the case has no definition yet, a minimal valid one is written +// with only that hash, status "defining". +// --------------------------------------------------------------------------- + +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); + +// One chain per file, on globalThis so every route bundle shares it. +const g = globalThis as { __umtoolCaseStageLocks?: Map<string, Promise<unknown>> }; +const locks = (g.__umtoolCaseStageLocks ??= new Map()); + +/** Run `fn` with `file` to itself: one write at a time, in order. */ +export async function withFileLock<T>(file: string, fn: () => Promise<T>): Promise<T> { + const prev = locks.get(file) ?? Promise.resolve(); + const run = prev.then(fn, fn); + const tail = run.catch(() => {}); + locks.set(file, tail); + try { + return await run; + } finally { + if (locks.get(file) === tail) locks.delete(file); + } +} + +/** Write `text` to `file` whole: a temp name, then a rename. */ +export async function writeWhole(file: string, text: string): Promise<void> { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, text); + await rename(tmp, file); +} + +/** 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 definition: read by every stage, written here only for a hash ── + +export async function readDefinition(caseId: string): Promise<CaseDefinition | null> { + const dir = await stageDir(caseId); + const raw = await readJsonFile<CaseDefinition | null>(stageFile(dir, CASE_FILES.definition), null, labelOf(caseId, CASE_FILES.definition)); + return raw && typeof raw === "object" ? raw : null; +} + +/** The case's private-name hashes (none when it has no definition). */ +export async function privateHashes(caseId: string): Promise<string[]> { + const def = await readDefinition(caseId); + const list = def?.privateNames?.sha256; + return Array.isArray(list) ? list.filter((h): h is string => typeof h === "string" && /^[0-9a-f]{64}$/.test(h)) : []; +} + +/** The scope's channels, as the definition names them (none when it has none). */ +export async function scopeChannels(caseId: string): Promise<string[]> { + const def = await readDefinition(caseId); + return Array.isArray(def?.scope?.channels) ? def.scope.channels.filter((c) => typeof c === "string") : []; +} + +/** Add `hash` to the case's private names (a never-archive lead). Answers whether it was new. */ +export async function feedPrivateNameHash(caseId: string, hash: string, now = new Date()): Promise<boolean> { + if (!/^[0-9a-f]{64}$/.test(hash)) throw new CaseError("a private name is fed as its sha256, lowercase hex", 400); + const dir = await stageDir(caseId); + const file = stageFile(dir, CASE_FILES.definition); + return withFileLock(file, async () => { + const at = now.toISOString(); + const def = await readJsonFile<CaseDefinition | null>(file, null, labelOf(caseId, CASE_FILES.definition)); + const next: CaseDefinition = + def && typeof def === "object" + ? def + : { + format: CASE_PIPELINE_FORMAT, + version: CASE_PIPELINE_VERSION, + case: caseId, + subjects: [], + scope: { channels: [], groups: [], sites: [] }, + eras: [], + groups: [], + privateNames: { sha256: [], note: "" }, + readerPrompts: { common: "" }, + status: "defining", + createdAt: at, + updatedAt: at, + }; + const names = next.privateNames && Array.isArray(next.privateNames.sha256) ? next.privateNames : { sha256: [], note: next.privateNames?.note ?? "" }; + if (names.sha256.includes(hash)) return false; + next.privateNames = { ...names, sha256: [...names.sha256, hash].sort() }; + next.updatedAt = at; + await writeWhole(file, `${JSON.stringify(next, null, 2)}\n`); + return true; + }); +} diff --git a/umtool/lib/research/case-stage-hrefs.ts b/umtool/lib/research/case-stage-hrefs.ts @@ -0,0 +1,12 @@ +// The addresses of a case's lane C stages (release 38: verify, leads, evidence), beside the board's +// (hrefs.ts). Pages under /research/<case>/, their APIs under /api/research/cases/<case>/stages/. +import { researchCaseHref } from "./hrefs"; + +export const CASE_STAGE_PAGES = ["verify", "leads", "evidence"] as const; +export type CaseStagePage = (typeof CASE_STAGE_PAGES)[number]; + +const enc = encodeURIComponent; + +export const caseStageHref = (id: string, stage: CaseStagePage) => `${researchCaseHref(id)}/${stage}`; +export const caseStageApi = (id: string, stage: CaseStagePage | "verify/captions" | "verify/audio" | "leads/context" | "leads/older") => + `/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,240 @@ +// 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; +const asked: { path: string; body: Record<string, unknown> }[] = []; +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"); + 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) }; + 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; + 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 === 422 && !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` }), /private names/); + + 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 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.path === "/api/ops/capture-posts").at(-1)?.body, { 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.renderEvidenceSection(await lib.evidence.readEvidence(CASE)); + 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/); + const quarantined = lib.evidence.renderQuarantinedSection((await lib.findings.readFindings(CASE)).rows); + assert.match(quarantined, /- f3: "Tide Watcher says it was a joke" — .* — forum attachment, post #3, unverified — a forum joke until shown otherwise/); +}); diff --git a/umtool/lib/research/case-verify.ts b/umtool/lib/research/case-verify.ts @@ -0,0 +1,372 @@ +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 { privateNameHits, redactPrivateNames } from "yt-dlp-transcript-common/lib/research/privateNames-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 its one writer (case-findings-store.ts), and a hand-written quote or +// note is held to the case's private names (counts only, 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: redactPrivateNames(p.text, hashes).text }], f.quote, 0); + const author = redactPrivateNames(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: redactPrivateNames(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); + const hashes = await privateHashes(caseId); + const hits = privateNameHits([quote, speaker, note].filter(Boolean).join(" \n "), hashes); + if (hits > 0) { + throw new CaseError(`${hits} word${hits === 1 ? "" : "s or phrases"} match the case's private names: write [name withheld] instead`, 422); + } + 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: redactPrivateNames(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); +}