Archilyzer · Source

archilyzer

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

commit a1344020d40e7de7d189b7f5da2ed555469bad92
parent 77ec863c79c28801796f39708aa47a4a4b232708
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 04:53:58 -0400

umtool: research cases — the board store, pin as a snapshot, re-verify, export, hand-offs, and their API

REPORTS_ROOT/.umtool/research/<case>/case.json (lib/research/cases.mjs: the
lifecycle store's discipline). A pin reads the cue from the corpus and keeps
the words and the cite; re-verify reads them again through R1's window and
records drifted (old and new) and en vs en-orig, never changing a quote. The
export is cited markdown that converts as a /sweep report. Hand-offs plan,
then confirm: an article is a seeded report-draft sweep the editor runs, a
video a project scaffolded with the board's cue spans as its timeline.

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

Diffstat:
Aumtool/app/api/research/cases/[id]/export.md/route.ts | 26++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/handoff/route.ts | 35+++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/quotes/[qid]/route.ts | 32++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/quotes/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/route.ts | 29+++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/verify/route.ts | 20++++++++++++++++++++
Aumtool/app/api/research/cases/route.ts | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 4+++-
Mumtool/e2e/fixtures/research-fixture.mjs | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/projects/scaffold.mjs | 50++++++++++++++++++++++++++++++++++++++++++++++----
Aumtool/lib/research/board.mjs | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/board.test.mjs | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/boards.test.ts | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/boards.ts | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/case-types.ts | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/cases.mjs | 582++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/cases.test.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/handoff.ts | 239+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18 files changed, 2329 insertions(+), 5 deletions(-)

diff --git a/umtool/app/api/research/cases/[id]/export.md/route.ts b/umtool/app/api/research/cases/[id]/export.md/route.ts @@ -0,0 +1,26 @@ +import { exportCase } from "@/lib/research/boards"; +import { exportFileName } from "@/lib/research/board.mjs"; +import { fail } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// The board as cited markdown in the house format (lib/research/board.mjs +// exportMarkdown): `# title`, the summary, a `##` per section, one finding per +// quote -- claim, "quote" — [title @ m:ss](link) -- and `## Coverage`. It +// converts as a /sweep report. `?download=1` names it as a file. +export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const { doc, markdown } = await exportCase(id); + const download = new URL(request.url).searchParams.get("download") === "1"; + return new Response(markdown, { + headers: { + "content-type": "text/markdown; charset=utf-8", + "cache-control": "no-store", + ...(download ? { "content-disposition": `attachment; filename="${exportFileName(doc)}"` } : {}), + }, + }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/handoff/route.ts b/umtool/app/api/research/cases/[id]/handoff/route.ts @@ -0,0 +1,35 @@ +import { CaseError } from "@/lib/research/cases.mjs"; +import { confirmArticle, confirmVideo, planArticle, planVideo } from "@/lib/research/handoff"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// HAND-OFFS, plan then confirm (lib/research/handoff.ts; the API is +// documented in ../../route.ts). +// { to: "article", article?, model?, question? } -> { plan: ArticlePlan } +// { to: "article", confirm: true, … } -> { href, jobId, iteration } +// { to: "video", slug?, title? } -> { plan: VideoPlan } +// { to: "video", confirm: true, … } -> { href } +// An article is a seeded report-draft sweep the editor runs (it spends: the +// plan says on what model, under which cap); a video is a project scaffolded +// under the reports root (it writes one). +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> | null; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError('expected a JSON object: { to: "article" | "video", confirm? }'); + const s = (k: string) => (typeof b[k] === "string" && (b[k] as string).trim() ? (b[k] as string).trim() : undefined); + const confirm = b.confirm === true; + if (b.to === "article") { + const over = { ...(s("article") ? { article: s("article") } : {}), ...(s("model") ? { model: s("model") } : {}), ...(s("question") ? { question: s("question") } : {}) }; + return ok(confirm ? await confirmArticle(id, over) : { plan: (await planArticle(id, over)).plan }); + } + if (b.to === "video") { + const over = { ...(s("slug") ? { slug: s("slug") } : {}), ...(s("title") ? { title: s("title") } : {}) }; + return ok(confirm ? await confirmVideo(id, over) : { plan: await planVideo(id, over) }); + } + throw new CaseError('to is "article" or "video"'); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/quotes/[qid]/route.ts b/umtool/app/api/research/cases/[id]/quotes/[qid]/route.ts @@ -0,0 +1,32 @@ +import { caseView, deleteQuote, patchQuote } from "@/lib/research/boards"; +import { CaseError } from "@/lib/research/cases.mjs"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// One quote of a case (the API is documented in ../../../route.ts). +// PATCH { claim?, note?, section?, speakerChecked?, useCurrentWords? } -> { quote, case: CaseView } +// DELETE -> { quote, index, case: CaseView } +type Ctx = { params: Promise<{ id: string; qid: string }> }; + +export async function PATCH(request: Request, ctx: Ctx) { + try { + const { id, qid } = await ctx.params; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { claim?, note?, section?, speakerChecked?, useCurrentWords? }"); + const r = await patchQuote(id, qid, body); + return ok({ quote: r.quote, case: await caseView(id) }); + } catch (e) { + return fail(e); + } +} + +export async function DELETE(_request: Request, ctx: Ctx) { + try { + const { id, qid } = await ctx.params; + const r = await deleteQuote(id, qid); + return ok({ quote: r.quote, index: r.index, case: await caseView(id) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/quotes/route.ts b/umtool/app/api/research/cases/[id]/quotes/route.ts @@ -0,0 +1,46 @@ +import { caseView, pinQuote, type PinBody } from "@/lib/research/boards"; +import { CaseError } from "@/lib/research/cases.mjs"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// PIN a cite to the case as a snapshot quote (the API is documented in +// ../../route.ts): { source, channel, video, t, until?, track?, kind?, claim?, +// note?, section?, search?, scope?, at? } -> { quote, duplicate, case: CaseView } +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> | null; + if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError("expected a JSON object: { source, channel, video, t, … }"); + const s = (k: string) => (typeof b[k] === "string" && (b[k] as string).trim() ? (b[k] as string).trim() : undefined); + const source = s("source"); + const channel = s("channel"); + const video = s("video"); + if (!source || !channel || !video) throw new CaseError("a pin names its source, channel and video"); + const kind = b.kind === "post" ? "post" : "video"; + const t = Number(b.t ?? 0); + if (!Number.isFinite(t) || t < 0) throw new CaseError("t is a second, 0 or more"); + const until = b.until === undefined || b.until === null ? undefined : Number(b.until); + if (until !== undefined && (!Number.isFinite(until) || until < t)) throw new CaseError("until is a second at or after t"); + const obj = (k: string) => (b[k] && typeof b[k] === "object" && !Array.isArray(b[k]) ? (b[k] as Record<string, unknown>) : undefined); + const body: PinBody = { + source, + channel, + video, + t, + kind, + ...(until !== undefined ? { until } : {}), + ...(s("track") ? { track: s("track") } : {}), + ...(typeof b.claim === "string" ? { claim: b.claim } : {}), + ...(typeof b.note === "string" ? { note: b.note } : {}), + ...(typeof b.section === "string" || b.section === null ? { section: b.section as string | null } : {}), + ...(obj("search") ? { search: obj("search") as PinBody["search"] } : {}), + ...(obj("scope") ? { scope: obj("scope") as PinBody["scope"] } : {}), + ...(Number.isInteger(b.at) ? { at: b.at as number } : {}), + }; + const r = await pinQuote(id, body); + return ok({ quote: r.quote, duplicate: r.duplicate, case: await caseView(id) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/route.ts b/umtool/app/api/research/cases/[id]/route.ts @@ -0,0 +1,29 @@ +import { caseView, patchCase } from "@/lib/research/boards"; +import { CaseError } from "@/lib/research/cases.mjs"; +import { fail, ok } from "../../_respond"; + +export const dynamic = "force-dynamic"; + +// One case (the API is documented in ../route.ts). +// GET -> CaseView +// PATCH { title?, notes?, scope?, sections?, order? } -> CaseView +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await caseView(id)); + } catch (e) { + return fail(e); + } +} + +export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { title?, notes?, scope?, sections?, order? }"); + await patchCase(id, body); + return ok(await caseView(id)); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/verify/route.ts b/umtool/app/api/research/cases/[id]/verify/route.ts @@ -0,0 +1,20 @@ +import { caseView, verifyCase } from "@/lib/research/boards"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// RE-VERIFY (the API is documented in ../../route.ts): every quote (or the +// ones named) read again at its cite in the CURRENT transcript. Drifted or +// missing is recorded with what is there now; a quote's own words never +// change here. { quotes?: [qid] } -> { results: [{ id, verify }], case: CaseView } +export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const body = (await request.json().catch(() => ({}))) as { quotes?: unknown } | null; + const only = Array.isArray(body?.quotes) ? body.quotes.filter((x): x is string => typeof x === "string") : undefined; + const r = await verifyCase(id, only); + return ok({ results: r.results, case: await caseView(id) }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/route.ts b/umtool/app/api/research/cases/route.ts @@ -0,0 +1,83 @@ +import { createCase, listCases } from "@/lib/research/boards"; +import { CaseError } from "@/lib/research/cases.mjs"; +import { fail, ok } from "../_respond"; + +export const dynamic = "force-dynamic"; + +// --------------------------------------------------------------------------- +// THE BOARD API (plans/umtool-redesign.md, R2). Research cases, umtool-side +// under REPORTS_ROOT/.umtool/research/<case>/case.json (lib/research/cases.mjs) +// -- never in the corpus. A case's piece id is `c:<case>`. P5's Create +// consumes this; the shapes are lib/research/case-types.ts. Every answer is +// JSON, `no-store`; an error is `{ error }` in words with its status (400 bad +// input, 404 no such case or quote or recording, 409 a case.json that cannot +// be read -- never overwritten -- or a name taken, 502 a corpus or the editor +// that cannot be read). +// +// GET /api/research/cases +// -> { cases: [{ id, piece, title, quotes, sections, updatedAt, scope, drifted, error? }] } +// POST /api/research/cases { title?, id?, query?, scope?, notes? } +// a case from a query and scope (the title defaults to the query), +// or empty (a title); the id is the title's slug unless named +// -> { case: CaseDoc } +// GET /api/research/cases/<id> +// -> CaseView { case, piece, stored, sourceLabel, reading, localOnly } +// PATCH /api/research/cases/<id> { title?, notes?, scope?, sections?, order? } +// sections: the whole ordered list [{ id?, title }] (no id = new; +// left out = removed, its quotes to Unsorted); order: every quote +// [{ id, section }] in board order -> CaseView +// POST /api/research/cases/<id>/quotes +// { source, channel, video, t, until?, track?, kind?, claim?, note?, +// section?, search?, scope?, at? } +// PIN: the cite is read from the corpus NOW and kept as a snapshot +// (the words, the cite, the house-format citation); the same cite +// twice answers the quote already there with `duplicate: true`. +// `search` ({ session, query, total, complete, notReached, +// sourceLabel }) makes that search's reading log the case's. +// -> { quote, duplicate, case: CaseView } +// PATCH /api/research/cases/<id>/quotes/<qid> +// { claim?, note?, section?, speakerChecked?, useCurrentWords? } +// useCurrentWords: true takes the words the last re-verify read +// (only for a drifted quote; the old words kept in its history) +// -> { quote, case: CaseView } +// DELETE /api/research/cases/<id>/quotes/<qid> +// -> { quote, index, case: CaseView } (POST it back with `at` to undo) +// POST /api/research/cases/<id>/verify { quotes?: [qid] } +// re-read every quote (or those) at its cite in the CURRENT +// transcript (R1's window, ±30 s); drifted / missing with the words +// there now, and en vs en-orig where both exist. Never changes a +// quote's words. -> { results: [{ id, verify }], case: CaseView } +// GET /api/research/cases/<id>/export.md[?download=1] +// the board as cited markdown in the house format (text/markdown) +// POST /api/research/cases/<id>/handoff { to: "article" | "video", confirm?, ... } +// without confirm -> { plan } (ArticlePlan | VideoPlan; writes nothing) +// with confirm: true -> { href } (article: { href, jobId, iteration }) +// article: { article?, model?, question? } video: { slug?, title? } +// --------------------------------------------------------------------------- + +export async function GET() { + try { + return ok({ cases: await listCases() }); + } catch (e) { + return fail(e); + } +} + +export async function POST(request: Request) { + try { + const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!body || typeof body !== "object" || Array.isArray(body)) throw new CaseError("expected a JSON object: { title?, id?, query?, scope?, notes? }"); + const scope = body.scope && typeof body.scope === "object" && !Array.isArray(body.scope) ? (body.scope as Record<string, unknown>) : undefined; + return ok({ + case: await createCase({ + ...(typeof body.title === "string" ? { title: body.title } : {}), + ...(typeof body.id === "string" ? { id: body.id } : {}), + ...(typeof body.query === "string" ? { query: body.query } : {}), + ...(typeof body.notes === "string" ? { notes: body.notes } : {}), + ...(scope ? { scope } : {}), + }), + }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -29,7 +29,7 @@ import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs"; import { makeDeleteFixture } from "./delete-fixture.mjs"; import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; -import { makeResearchFixture } from "./research-fixture.mjs"; +import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1933,6 +1933,8 @@ makeDeleteFixture({ dest, articles: ARTICLES, reports }); // R1: Research's local corpus (research-public/, TRANSCRIPT_LOCAL_DIR) and the // held channels its inventory reads on disk. const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ 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 }); console.log(`fixture at ${dest}`); console.log(` SITES_DIR=${SITES}`); diff --git a/umtool/e2e/fixtures/research-fixture.mjs b/umtool/e2e/fixtures/research-fixture.mjs @@ -21,6 +21,12 @@ // harbor-radio-rumble v1abcd mirrors hr-2024a (folded); v2efgh matches // night-desk 3 recordings, transcribed; nd-2023 matches // candace-owens a LOCAL-ONLY slug (lib/research/rules.mjs): 1 match +// +// R2 (boards): hr-2022b's primary track is `en-orig` and it carries a served +// `en` alternate that rewrites one line (EN_REWRITE, at 900 s) -- the hazard +// re-verify checks for. makeBoardFixture writes a case whose quotes are a +// drifted one (the words changed since it was pinned), an intact one, and +// one quoted from the `en` track. import { mkdirSync, writeFileSync } from "node:fs"; import path from "node:path"; @@ -118,6 +124,15 @@ export const RESEARCH_CHANNELS = [ }, ]; +// The served `en` track's rewrite of hr-2022b's line at 900 s (its en-orig +// says "the lighthouse keeper called in"). +export const EN_REWRITE = { at: 900, orig: "the lighthouse keeper called in", en: "the lighthouse keeper rang in" }; +{ + const r = RESEARCH_CHANNELS[0].records.find((x) => x.id === "hr-2022b"); + r.track = "en-orig"; + r.altTracks = [{ track: "en", cues: r.cues.map((c) => (c.start === EN_REWRITE.at ? { ...c, text: EN_REWRITE.en } : { ...c })) }]; +} + const STATES = { "harbor-radio/hr-2024a": "deleted", "harbor-radio/hr-2026a": "unlisted" }; // The editor's disk for the "held" column: harbor-radio holds five of its six @@ -221,3 +236,59 @@ export function makeResearchFixture({ dest, channels }) { } return { pub }; } + +// The words a drifted quote was pinned with: hr-2022a says "eight to one" now. +export const DRIFTED_QUOTE = { video: "hr-2022a", at: 2044, was: `they voted the ${P} down nine to one`, now: `they voted the ${P} down eight to one` }; +export const BOARD_CASE = "fixture-board"; + +/** + * R2: a research case under `reportsRoot` (REPORTS_ROOT/.umtool/research/), + * as the board store writes one: three quotes pinned from the local corpus at + * `pub` -- one whose words have drifted since, one intact, one quoted from the + * served `en` track where en-orig says otherwise. + */ +export function makeBoardFixture({ reportsRoot, pub }) { + const source = `local:${pub}`; + const cite = (channel, channelName, id, title, date, t, extra = {}) => ({ + kind: "video", + source, + channel, + channelKey: channel, + channelName, + video: id, + title, + date, + t, + end: t + 3.8, + clock: `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`, + track: "captions", + url: `${ARCHIVE}/?v=${channel}%2F${id}&t=${t}`, + ...extra, + }); + const at = "2026-10-13T12:00:00.000Z"; + write(path.join(reportsRoot, ".umtool", "research", BOARD_CASE, "case.json"), `${JSON.stringify( + { + format: "umtool-research-case", + version: 1, + id: BOARD_CASE, + title: "Fixture board", + scope: { source, query: P }, + search: null, + sessions: [], + sections: [{ id: "s1", title: "The vote" }], + quotes: [ + { id: "q1", section: "s1", text: DRIFTED_QUOTE.was, cite: cite("harbor-radio", "Harbor Radio", "hr-2022a", "Harbor Radio 80: the council vote", "20220211", DRIFTED_QUOTE.at, { track: "transcript" }), claim: "The council vote on the budget", note: "", speakerChecked: false, pinnedAt: at }, + { id: "q2", section: null, text: `the keeper never saw the ${P}`, cite: cite("night-desk", "Night Desk", "nd-2023", "Night Desk: the keeper", "20230901", 400, { track: "transcript" }), claim: "", note: "the keeper's side", speakerChecked: true, pinnedAt: at }, + { id: "q3", section: null, text: EN_REWRITE.en, cite: cite("harbor-radio", "Harbor Radio", "hr-2022b", "Harbor Radio 91: call-in night", "20221103", EN_REWRITE.at, { trackId: "en" }), claim: "", note: "", speakerChecked: false, pinnedAt: at }, + ], + notes: "", + handoffs: [], + counters: { quote: 3, section: 1 }, + createdAt: at, + updatedAt: at, + }, + null, + 2, + )}\n`); + return { id: BOARD_CASE }; +} diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs @@ -22,7 +22,10 @@ export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/; * look finished and be wrong, and every clip would have to be opened anyway. * * (`--seed chapters` is the one exception, and it invents nothing: the windows - * it writes are the digest's own chapter boundaries.) + * it writes are the digest's own chapter boundaries. So is a research board's + * `timeline` (lib/research/handoff.ts): each window is the cue span of a quote + * a person pinned after reading it in its transcript -- a start AND an end the + * transcript gave, never a guess from one second.) */ export function skeleton(slug, title, provenance, { brand = null } = {}) { const doc = { @@ -105,6 +108,19 @@ export function citationsIn(text) { return out; } +const isBoardClip = (c) => + c && + c.type === "clip" && + typeof c.id === "string" && + /^[A-Za-z0-9_-]+$/.test(c.id) && + typeof c.channel === "string" && + c.channel !== "" && + typeof c.video === "string" && + c.video !== "" && + Number.isFinite(c.start) && + Number.isFinite(c.end) && + c.end > c.start; + const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null); /** @@ -158,9 +174,13 @@ export async function chaptersAsClips({ channelsDir, channel, video }) { * Write the project. Refuses an existing directory and a slug that will not * route; everything else it cannot know is written EMPTY so `check` blocks. * - * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string }} args + * `timeline` is a research board's clips (`{ type: "clip", id, channel, video, + * start, end, cite, quote, … }`, in board order), written as they are and + * unlocked; `timelineFrom` names the board in the README. + * + * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null }} args */ -export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR() }) { +export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null }) { if (!SLUG_RE.test(String(slug ?? ""))) { throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`); } @@ -178,6 +198,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site } if (seed && seed !== "chapters") throw new Error(`--seed must be "chapters", not "${seed}"`); if (seed && src?.kind !== "video") throw new Error("--seed chapters needs --from to be a video ref"); + if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed"); + if (timeline && (!Array.isArray(timeline) || !timeline.every(isBoardClip))) { + throw new Error("a timeline is a list of clips, each { type: \"clip\", id, channel, video, start, end }"); + } if (brand && !BRAND_IDS.includes(brand)) { throw new Error(`--brand must be one of ${BRAND_IDS.join(", ")}, not "${brand}"`); } @@ -215,6 +239,13 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site if (!clips.length) notes.push("the digest has no enabled chapters, so the timeline is empty"); } + if (timeline) { + doc.timeline = timeline.map((c) => ({ ...c })); + seeded = doc.timeline.length; + const channels = [...new Set(doc.timeline.map((c) => c.channel))]; + if (channels.length === 1 && !doc.provenance.channelSlug) doc.provenance.channelSlug = channels[0]; + } + await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8"); if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8"); @@ -226,7 +257,18 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site "purpose (with why — that is what a `lock` in the manifest means).", "", ]; - if (seeded) { + if (seeded && timeline) { + lines.push( + `## Clips from the research board${timelineFrom ? ` ${timelineFrom}` : ""} — review each`, + "", + "Every window below is the cue span of a quote pinned on the board: what the", + "transcript said there, not an edit. A cue ends where the caption line", + "wrapped, so a window can stop mid-thought. Open each in the bench, cut it", + "to the sentence that matters, and lock what you meant.", + "", + ...doc.timeline.map((c) => `- [ ] ${c.id} ${c.channel}/${c.video} ${c.start}–${c.end} ${String(c.quote ?? "").slice(0, 80)}`), + ); + } else if (seeded) { lines.push( "## Clips seeded from digest chapters — review each", "", diff --git a/umtool/lib/research/board.mjs b/umtool/lib/research/board.mjs @@ -0,0 +1,194 @@ +// THE BOARD, as data: its groups and order, the moves the keys and drag make, +// the export in the house format, and the words compare re-verify uses. +// Pure and browser-safe (no node built-ins), so the page, the routes and the +// tests agree. The store is cases.mjs. +import { isoDate } from "./facets.mjs"; +import { isLocalOnly } from "./rules.mjs"; + +/** The name of the group of quotes in no section. */ +export const UNSORTED = "Unsorted"; + +/** + * The board in order: Unsorted first (when it holds anything, or when there + * are no sections at all), then each section with its quotes. + * + * @param {{ sections: { id: string, title: string }[], quotes: { id: string, section: string | null }[] }} doc + */ +export function groupsOf(doc) { + const byId = new Map(doc.sections.map((s) => [s.id, { id: s.id, title: s.title, quotes: [] }])); + const unsorted = { id: null, title: UNSORTED, quotes: [] }; + for (const q of doc.quotes) (q.section && byId.get(q.section) ? byId.get(q.section) : unsorted).quotes.push(q); + const out = [...byId.values()]; + return unsorted.quotes.length || out.length === 0 ? [unsorted, ...out] : out; +} + +/** Every group, Unsorted included even when empty (the moves walk it). */ +function allGroups(doc) { + const g = groupsOf(doc); + return g[0]?.id === null ? g : [{ id: null, title: UNSORTED, quotes: [] }, ...g]; +} + +const arrangement = (doc, groups) => ({ + sections: doc.sections.map((s) => ({ id: s.id, title: s.title })), + order: groups.flatMap((g) => g.quotes.map((q) => ({ id: q.id, section: g.id }))), +}); + +/** + * Move a quote one place down (+1) or up (-1) in board order; past the end of + * its section it goes into the next (or the previous) one. Answers the new + * arrangement for PATCH, or null when it cannot move. + */ +export function moveQuote(doc, qid, dir) { + const groups = allGroups(doc).map((g) => ({ ...g, quotes: [...g.quotes] })); + const gi = groups.findIndex((g) => g.quotes.some((q) => q.id === qid)); + if (gi < 0) return null; + const g = groups[gi]; + const i = g.quotes.findIndex((q) => q.id === qid); + const [q] = g.quotes.splice(i, 1); + if (dir > 0) { + if (i < g.quotes.length) g.quotes.splice(i + 1, 0, q); + else if (gi < groups.length - 1) groups[gi + 1].quotes.unshift(q); + else return null; + } else { + if (i > 0) g.quotes.splice(i - 1, 0, q); + else if (gi > 0) groups[gi - 1].quotes.push(q); + else return null; + } + return arrangement(doc, groups); +} + +/** Put a quote in a section (null = Unsorted) at an index of it (drag and drop). */ +export function placeQuote(doc, qid, section, index) { + const groups = allGroups(doc).map((g) => ({ ...g, quotes: g.quotes.filter((q) => q.id !== qid) })); + const q = doc.quotes.find((x) => x.id === qid); + const to = groups.find((g) => g.id === (section ?? null)); + if (!q || !to) return null; + const at = Math.max(0, Math.min(to.quotes.length, Number.isInteger(index) ? index : to.quotes.length)); + to.quotes.splice(at, 0, q); + return arrangement(doc, groups); +} + +/** Move a section one place down (+1) or up (-1); null when it cannot. */ +export function moveSection(doc, sid, dir) { + const i = doc.sections.findIndex((s) => s.id === sid); + const j = i + (dir > 0 ? 1 : -1); + if (i < 0 || j < 0 || j >= doc.sections.length) return null; + const sections = doc.sections.map((s) => ({ id: s.id, title: s.title })); + [sections[i], sections[j]] = [sections[j], sections[i]]; + return { sections, order: doc.quotes.map((q) => ({ id: q.id, section: q.section })) }; +} + +// ── the words ── + +/** Words as a re-verify compares them: case, punctuation and spacing aside. */ +export function wordsOf(text) { + return String(text ?? "") + .toLowerCase() + .replace(/[‘’ʼ`]/g, "'") + .replace(/[^\p{L}\p{N}' ]+/gu, " ") + .replace(/'+/g, "'") + .replace(/\s+/g, " ") + .trim(); +} + +/** Do `inside`'s words hold `quote`'s, in order and whole? */ +export function holdsWords(inside, quote) { + const q = wordsOf(quote); + if (!q) return false; + return ` ${wordsOf(inside)} `.includes(` ${q} `); +} + +// ── the export: cited markdown in the house format ── + +const clean = (s) => String(s ?? "").replace(/\s+/g, " ").trim(); +// A claim never carries quotation marks (common's CLAIM_QUOTES_RULE): every +// quoted span before a link becomes THAT link's quote. +const claimText = (s) => clean(s).replace(/["“”]/g, "").replace(/[.:;,\s]+$/, ""); +// Inside the quote, a double quote would end it early for the converter. +const quoteText = (s) => clean(s).replace(/["“”]/g, "'"); + +/** The citation link of a quote, in the house format (facets.mjs citationText's label). */ +export function citeLink(q) { + const c = q.cite; + const label = c.kind === "post" ? `post by ${clean(c.author || c.channelName)}, ${isoDate(c.date)}` : `${clean(c.title).replace(/[[\]]/g, "")} @ ${c.clock || "0:00"}`; + return c.url ? `[${label}](${c.url})` : label; +} + +/** One finding: the claim in plain words, the quote, its link; our note under it. */ +export function findingOf(q) { + const claim = claimText(q.claim); + const lines = [`- ${claim ? `${claim}: ` : ""}"${quoteText(q.text)}" — ${citeLink(q)}`]; + const asides = []; + if (clean(q.note)) asides.push(clean(q.note).replace(/["“”]/g, "'")); + if (!q.speakerChecked && q.cite.kind !== "post") asides.push("Speaker not checked"); + if (q.verify?.status === "drifted") asides.push(`Drifted: the transcript read differently at the last re-verify (${(q.verify.at || "").slice(0, 10)})`); + if (q.verify?.status === "missing") asides.push("Missing: the recording was not found at the last re-verify"); + if (q.verify?.enOrig) asides.push(`The en-orig track differs here: check the audio`); + if (asides.length) lines.push(` Note: ${asides.join(". ")}.`); + return lines.join("\n"); +} + +/** + * The board as cited markdown, the shape a /sweep report has (it converts as + * one: common's convertSweep): `# title`, the summary, a `##` per section with + * one finding per quote, and `## Coverage`. + * + * @param {object} doc the case + * @param {{ sourceLabel?: string, read?: number }} [ctx] + */ +export function exportMarkdown(doc, ctx = {}) { + const out = [`# ${clean(doc.title)}`, ""]; + const notes = String(doc.notes ?? "").trim(); + if (notes) out.push(notes.replace(/^#+\s*/gm, ""), ""); + const recordings = new Set(doc.quotes.map((q) => `${q.cite.channel}/${q.cite.video}`)); + out.push( + `${doc.quotes.length} ${doc.quotes.length === 1 ? "quote" : "quotes"} from ${recordings.size} ${recordings.size === 1 ? "source" : "sources"}, pinned on a research board${doc.scope.query ? ` from the search “${clean(doc.scope.query).replace(/["“”]/g, "'")}”` : ""}. The quotes are verbatim snapshots; the claims and notes are ours.`, + "", + ); + const groups = groupsOf(doc).filter((g) => g.quotes.length); + const named = doc.sections.length > 0; + for (const g of groups) { + out.push(`## ${g.id === null ? (named ? UNSORTED : "Findings") : clean(g.title)}`, ""); + for (const q of g.quotes) out.push(findingOf(q)); + out.push(""); + } + out.push("## Coverage", "", coverageLine(doc, ctx), ""); + return out.join("\n"); +} + +/** The coverage paragraph: the scope, what was searched and read, what is pinned. */ +export function coverageLine(doc, ctx = {}) { + const s = doc.scope; + const where = ctx.sourceLabel || doc.search?.sourceLabel || (s.source ? s.source.replace(/^(local|remote|hub):/, "") : "an unrecorded source"); + const scope = [ + s.channels?.length ? `channels ${s.channels.join(", ")}` : "every channel", + s.dateFrom || s.dateTo ? `${s.dateFrom ? `from ${s.dateFrom}` : ""}${s.dateFrom && s.dateTo ? " " : ""}${s.dateTo ? `to ${s.dateTo}` : ""}` : "", + s.states?.length ? `states ${s.states.join(", ")}` : "", + s.mediaType ? `${s.mediaType}s only` : "", + s.posts ? "posts included" : "", + ].filter(Boolean); + const parts = [`Scope: ${where}, ${scope.join(", ")}.`]; + const se = doc.search; + if (se && se.total >= 0 && se.session) { + parts.push( + `Searched for ${se.query ? `“${se.query}”` : "the question"}: ${se.total} ${se.total === 1 ? "recording" : "recordings"}, ${se.complete ? "complete" : `PARTIAL (not reached: ${se.notReached.join(", ") || "unknown"})`}.`, + ); + if (Number.isFinite(ctx.read)) parts.push(`Read ${ctx.read} of ${se.total}.`); + } else { + parts.push("No search is recorded for this board."); + } + const drift = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; + const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length; + parts.push( + `${doc.quotes.length} pinned.` + + (drift ? ` ${drift} drifted or missing at the last re-verify.` : "") + + (unchecked ? ` ${unchecked} with the speaker not checked.` : ""), + ); + return parts.join(" "); +} + +/** Quotes from a local-only channel (Candace's): never in anything published. */ +export const localOnlyQuotes = (doc) => doc.quotes.filter((q) => q.cite.localOnly || isLocalOnly(q.cite.channel)); + +/** A safe file name for the download. */ +export const exportFileName = (doc) => `${doc.id}.md`; diff --git a/umtool/lib/research/board.test.mjs b/umtool/lib/research/board.test.mjs @@ -0,0 +1,83 @@ +// The board as data (board.mjs): its groups, the moves the keys and drag +// make, the words compare, and the export in the house format. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { coverageLine, exportMarkdown, findingOf, groupsOf, holdsWords, moveQuote, moveSection, placeQuote, wordsOf } from "./board.mjs"; + +const q = (id, section, extra = {}) => ({ + id, + section, + text: `words of ${id}`, + cite: { kind: "video", source: "remote:https://a.example", channel: "harbor-radio", video: `v-${id}`, title: `Episode ${id}`, date: "20240520", t: 10, end: 13.8, clock: "0:10", url: `https://a.example/?v=harbor-radio%2Fv-${id}&t=10` }, + claim: "", + note: "", + speakerChecked: false, + pinnedAt: "", + ...extra, +}); +const doc = (quotes, sections = [{ id: "s1", title: "First" }, { id: "s2", title: "Second" }]) => ({ + id: "board", + title: "Employee count", + scope: { source: "remote:https://a.example", query: "how many employees" }, + search: null, + sections, + quotes, + notes: "", +}); +const ids = (a) => a.order.map((o) => `${o.id}:${o.section ?? "-"}`).join(" "); + +test("groups: Unsorted first only when it holds anything (or there are no sections), then each section", () => { + assert.deepEqual(groupsOf(doc([q("q1", "s2"), q("q2", "s1")])).map((g) => [g.id, g.quotes.map((x) => x.id)]), [["s1", ["q2"]], ["s2", ["q1"]]]); + assert.deepEqual(groupsOf(doc([q("q1", null), q("q2", "s1")])).map((g) => g.id), [null, "s1", "s2"]); + assert.deepEqual(groupsOf(doc([], [])).map((g) => g.title), ["Unsorted"]); +}); + +test("alt+j/k: a quote moves within its section, then across into the next or the previous", () => { + const d = doc([q("q1", null), q("q2", "s1"), q("q3", "s1"), q("q4", "s2")]); + assert.equal(ids(moveQuote(d, "q2", 1)), "q1:- q3:s1 q2:s1 q4:s2"); + assert.equal(ids(moveQuote(d, "q3", 1)), "q1:- q2:s1 q3:s2 q4:s2", "past the end of s1 into the top of s2"); + assert.equal(ids(moveQuote(d, "q2", -1)), "q1:- q2:- q3:s1 q4:s2", "past the top of s1 into Unsorted's end"); + assert.equal(moveQuote(d, "q1", -1), null); + assert.equal(moveQuote(d, "q4", 1), null); + const noUnsorted = doc([q("q2", "s1")]); + assert.equal(ids(moveQuote(noUnsorted, "q2", -1)), "q2:-", "Unsorted is above the first section even when empty"); +}); + +test("drag: a quote placed in a section at an index; a section moved", () => { + const d = doc([q("q1", null), q("q2", "s1"), q("q3", "s1")]); + assert.equal(ids(placeQuote(d, "q1", "s1", 1)), "q2:s1 q1:s1 q3:s1"); + assert.equal(ids(placeQuote(d, "q3", "s2", 0)), "q1:- q2:s1 q3:s2"); + assert.deepEqual(moveSection(d, "s1", 1).sections.map((s) => s.id), ["s2", "s1"]); + assert.equal(moveSection(d, "s1", -1), null); +}); + +test("words: case, punctuation and spacing aside; whole words, in order", () => { + assert.equal(wordsOf(" How many EMPLOYEES? You fired them all, "), "how many employees you fired them all"); + assert.equal(holdsWords("okay so — How many employees? You fired them all, right", "how many employees you fired them all"), true); + assert.equal(holdsWords("they voted the budget down eight to one", "they voted the budget down nine to one"), false); + assert.equal(holdsWords("the budgets", "the budget"), false, "a word is whole"); + assert.equal(holdsWords("it’s fine", "it's fine"), true); +}); + +test("a finding: the claim (no quotation marks), the quote, its link; our notes after it", () => { + const f = findingOf(q("q1", null, { claim: 'He said "no".', note: "Panel, not Jeremy", text: 'a "quoted" word' })); + assert.equal( + f, + '- He said no: "a \'quoted\' word" — [Episode q1 @ 0:10](https://a.example/?v=harbor-radio%2Fv-q1&t=10)\n Note: Panel, not Jeremy. Speaker not checked.', + ); + assert.equal(findingOf(q("q2", null, { speakerChecked: true })), '- "words of q2" — [Episode q2 @ 0:10](https://a.example/?v=harbor-radio%2Fv-q2&t=10)'); + const post = findingOf(q("q3", null, { cite: { kind: "post", channel: "x", video: "p1", author: "Ann", date: "20250101", url: "https://a.example/?v=x%2Fp1&vm=post" } })); + assert.match(post, /^- "words of q3" — \[post by Ann, 2025-01-01\]\(https:\/\/a\.example\/\?v=x%2Fp1&vm=post\)$/); + assert.match(findingOf(q("q4", null, { verify: { status: "drifted", at: "2026-10-14T00:00:00Z" } })), /Drifted: the transcript read differently at the last re-verify \(2026-10-14\)/); +}); + +test("the export: title, summary, a heading per section (Findings when there are none), Coverage", () => { + const md = exportMarkdown(doc([q("q1", "s2"), q("q2", null, { speakerChecked: true }), q("q3", "s2")]), { sourceLabel: "Jeralyzer", read: 2 }); + const heads = md.split("\n").filter((l) => l.startsWith("#")); + assert.deepEqual(heads, ["# Employee count", "## Unsorted", "## Second", "## Coverage"]); + assert.match(md, /3 quotes from 3 sources, pinned on a research board from the search “how many employees”/); + assert.ok(md.indexOf("words of q1") < md.indexOf("words of q3"), "board order"); + const bare = exportMarkdown(doc([q("q1", null)], [])); + assert.ok(bare.includes("\n## Findings\n")); + assert.match(coverageLine({ ...doc([q("q1", null)]), search: { session: "FAKE-TEST-VALUE", query: "q", total: 27, complete: false, notReached: ["a"], at: "" } }, { read: 5 }), /27 recordings, PARTIAL \(not reached: a\)\. Read 5 of 27\. 1 pinned\. 1 with the speaker not checked\./); +}); diff --git a/umtool/lib/research/boards.test.ts b/umtool/lib/research/boards.test.ts @@ -0,0 +1,178 @@ +// Research boards (R2) over the e2e fixture corpus, as the routes run them: a +// pin reads the cite from the corpus and keeps it as a snapshot; re-verify +// reads it again and says what drifted (and where `en` and `en-orig` +// differ); the export converts as a /sweep report (common's converter); the +// hand-offs plan, and confirm -- an article as a seeded report-draft sweep +// the editor is asked for, a video as a scaffolded project. +// +// Run with: pnpm --filter umtool exec tsx --test lib/research/boards.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 pub: string; +let source: string; +let editor: http.Server; +const asked: { url: string; body: Record<string, unknown> }[] = []; +// The modules read their env at import, so they are imported after it is set. +let lib: { + boards: typeof import("./boards"); + handoff: typeof import("./handoff"); + fixture: typeof import("../../e2e/fixtures/research-fixture.mjs"); + sweepToReport: typeof import("yt-dlp-transcript-common/lib/report/convertSweep").sweepToReport; +}; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-boards-")); + const fixture = await import("../../e2e/fixtures/research-fixture.mjs"); + pub = fixture.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") }).pub; + source = `local:${pub}`; + fixture.makeBoardFixture({ reportsRoot: path.join(tmp, "reports"), pub }); + // A stand-in editor: the policy, and report-draft (it records what it was asked). + editor = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + asked.push({ url: req.url ?? "", body: raw ? JSON.parse(raw) : {} }); + res.setHeader("content-type", "application/json"); + if (req.url?.startsWith("/api/ops/settings")) { + res.end(JSON.stringify({ ok: true, value: { routes: { sweep: "code" }, models: { api: "claude-sonnet-5-5" }, caps: { sweep: 4, max: 10 } } })); + } else if (req.url === "/api/ops/report-draft") { + res.end(JSON.stringify({ ok: true, jobId: "job-1", iteration: 1 })); + } else { + res.statusCode = 404; + res.end(JSON.stringify({ error: "no route" })); + } + }); + }); + 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 = path.join(tmp, "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.SETTINGS_FILE = path.join(tmp, "settings.json"); + delete process.env.TRANSCRIPT_HUB_URL; + lib = { + boards: await import("./boards"), + handoff: await import("./handoff"), + fixture, + sweepToReport: (await import("yt-dlp-transcript-common/lib/report/convertSweep")).sweepToReport, + }; +}); + +after(async () => { + editor.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +test("a pin reads the cue from the corpus: the words, the cite, the house citation; twice is one quote", async () => { + const { boards } = lib; + const c = await boards.createCase({ query: "lighthouse budget", scope: { source } }); + assert.equal(c.id, "lighthouse-budget"); + const search = { session: "00112233aabbccdd", query: "lighthouse budget", total: 8, complete: true, notReached: [] }; + // 1213 s: the nearest cue starts at 1212 (a snippet's second is its cue's). + const r = await boards.pinQuote(c.id, { source, channel: "harbor-radio", video: "hr-2021a", t: 1213, search }); + assert.equal(r.duplicate, false); + assert.equal(r.quote.text, "who signed off on the lighthouse budget"); + assert.equal(r.quote.cite.t, 1212); + assert.equal(r.quote.cite.end, 1215.8); + assert.equal(r.quote.cite.url, "https://archive.example/?v=harbor-radio%2Fhr-2021a&t=1212"); + assert.equal(r.quote.cite.citation, '"who signed off on the lighthouse budget" [Harbor Radio 52: storm season @ 20:12](https://archive.example/?v=harbor-radio%2Fhr-2021a&t=1212)'); + assert.equal(r.case.search?.session, search.session); + const again = await boards.pinQuote(c.id, { source, channel: "harbor-radio", video: "hr-2021a", t: 1212 }); + assert.equal(again.duplicate, true); + // Several cues as one quote. + const two = await boards.pinQuote(c.id, { source, channel: "night-desk", video: "nd-2023", t: 400, until: 404 }); + assert.match(two.quote.text, /^the keeper never saw the lighthouse budget \S/); + // A Rumble mirror keeps the editor's directory id beside the archive's. + const rumble = await boards.pinQuote(c.id, { source, channel: "harbor-radio-rumble", video: "v2efgh", t: 32 }); + assert.equal(rumble.quote.cite.dirVideo, undefined, "the fixture's URL slug is the title, not an id: nothing mapped"); + // A local-only channel is marked. + const lo = await boards.pinQuote(c.id, { source, channel: "candace-owens", video: "lo-2025", t: 12 }); + assert.equal(lo.quote.cite.localOnly, true); + await assert.rejects(boards.pinQuote(c.id, { source, channel: "night-desk", video: "nope", t: 1 }), /no recording nope/); + await assert.rejects(boards.pinQuote(c.id, { source: "local:/elsewhere", channel: "night-desk", video: "nd-2023", t: 1 }), (e: Error & { status?: number }) => e.status === 400 || e.status === 404); +}); + +test("re-verify: an intact quote is ok, a changed one drifted with old and new, en vs en-orig flagged", async () => { + const { boards, fixture } = lib; + const { case: doc, results } = await boards.verifyCase(fixture.BOARD_CASE); + const by = Object.fromEntries(results.map((r) => [r.id, r.verify])); + assert.equal(by.q1.status, "drifted"); + assert.equal(by.q1.now, fixture.DRIFTED_QUOTE.now); + assert.equal(doc.quotes.find((q) => q.id === "q1")!.text, fixture.DRIFTED_QUOTE.was, "never silently updated"); + assert.equal(by.q2.status, "ok"); + assert.equal(by.q2.enOrig, undefined); + assert.equal(by.q3.status, "ok", "the en words are what the en track says"); + assert.deepEqual(by.q3.enOrig, { text: fixture.EN_REWRITE.orig, quoted: "en", other: fixture.EN_REWRITE.en }); + // The operator takes the current words: the old kept. + const took = await boards.patchQuote(fixture.BOARD_CASE, "q1", { useCurrentWords: true }); + assert.equal(took.quote.text, fixture.DRIFTED_QUOTE.now); + assert.equal(took.quote.history?.[0].text, fixture.DRIFTED_QUOTE.was); +}); + +test("the export is cited markdown that converts as a /sweep report: one citation per quote, verbatim", async () => { + const { boards, sweepToReport } = lib; + const { markdown } = await boards.exportCase("lighthouse-budget"); + assert.match(markdown, /^# lighthouse budget\n/); + assert.match(markdown, /## Coverage\n\nScope: Local corpus, every channel\. Searched for “lighthouse budget”: 8 recordings, complete\. Read 0 of 8\. 4 pinned\./); + const converted = await sweepToReport(markdown, { id: "lighthouse-budget" }); + assert.deepEqual(converted.problems, [], JSON.stringify(converted.problems)); + const cites = Object.values((converted.report as { citations: Record<string, { quote: string; id: string }> }).citations); + assert.equal(cites.length, 4); + assert.ok(cites.some((c) => c.quote === "who signed off on the lighthouse budget" && c.id === "hr-2021a"), JSON.stringify(cites)); +}); + +test("hand-off to an article: refused for a local-only board; else a plan, then a seeded sweep the editor is asked for", async () => { + const { boards, handoff } = lib; + const refused = await handoff.planArticle("lighthouse-budget"); + assert.match(refused.plan.refusals.join(" "), /local-only channel/); + await assert.rejects(handoff.confirmArticle("lighthouse-budget", {}), /local-only/); + + const doc = await boards.readCase("lighthouse-budget"); + const lo = doc.quotes.find((q) => q.cite.localOnly)!; + await boards.deleteQuote("lighthouse-budget", lo.id); + const { plan, seed } = await handoff.planArticle("lighthouse-budget"); + assert.deepEqual(plan.refusals, []); + assert.equal(plan.article, "lighthouse-budget"); + assert.equal(plan.question, "lighthouse budget"); + assert.deepEqual(plan.channels.sort(), ["harbor-radio", "harbor-radio-rumble", "night-desk"]); + assert.equal(plan.model, "claude-sonnet-5-5"); + assert.equal(plan.capUsd, 4); + assert.match(plan.warnings.join(" "), /routes sweeps to Claude Code; a seeded sweep runs the API agent/); + const before = asked.length; + const out = await handoff.confirmArticle("lighthouse-budget", {}); + assert.deepEqual(out, { href: "/articles/lighthouse-budget", jobId: "job-1", iteration: 1 }); + const sent = asked.slice(before).find((a) => a.url === "/api/ops/report-draft")!.body; + assert.equal(sent.task, "sweep"); + assert.equal(sent.seed, seed); + assert.equal(sent.source, source); + assert.equal((await boards.readCase("lighthouse-budget")).handoffs[0].href, "/articles/lighthouse-budget"); +}); + +test("hand-off to a video: a plan, then a project whose timeline is the board's cue spans", async () => { + const { boards, handoff } = lib; + const plan = await handoff.planVideo("lighthouse-budget"); + assert.deepEqual(plan.refusals, []); + assert.equal(plan.siteOrigin, "https://archive.example"); + assert.equal(plan.clips.length, 3); + assert.deepEqual(plan.clips[0], { id: "c00", channel: "harbor-radio", video: "hr-2021a", start: 1212, end: 1215.8, quote: "who signed off on the lighthouse budget" }); + const out = await handoff.confirmVideo("lighthouse-budget", {}); + assert.equal(out.href, "/projects/lighthouse-budget"); + const manifest = JSON.parse(await readFile(path.join(tmp, "reports", "lighthouse-budget", "video.manifest.json"), "utf8")); + assert.equal(manifest.provenance.siteOrigin, "https://archive.example"); + assert.deepEqual(manifest.timeline.map((c: { id: string; cite: number }) => [c.id, c.cite]), [["c00", 1212], ["c01", 400], ["c02", 32]]); + const readme = await readFile(path.join(tmp, "reports", "lighthouse-budget", "README.md"), "utf8"); + assert.match(readme, /## Clips from the research board “lighthouse budget” \(c:lighthouse-budget\) — review each/); + const again = await handoff.planVideo("lighthouse-budget"); + assert.match(again.refusals.join(" "), /already exists/); + assert.equal((await boards.readCase("lighthouse-budget")).handoffs.length, 2); +}); diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts @@ -0,0 +1,340 @@ +import { findPost, findVideo } from "yt-dlp-transcript-mcp/research"; +import { cuesOfTrack, trackKind } from "yt-dlp-transcript-common/lib/captionTracks"; +import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl"; +import { clock } from "yt-dlp-transcript-common/lib/search/window"; +import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes, wordsOf } from "./board.mjs"; +import { + CaseError, + addQuote, + arrangeCase, + createCase as createAt, + listCases as listAt, + mutateCase, + patchCaseFields, + patchQuote as patchQuoteIn, + readCase as readAt, + recordVerify, + removeQuote, + storedPath, +} from "./cases.mjs"; +import { windowOf } from "./corpus"; +import { citationText, isoDate, trackOf } from "./facets.mjs"; +import { readLog } from "./log.mjs"; +import { isLocalOnly } from "./rules.mjs"; +import { listSources, openSource, SourceError } from "./sources"; +import type { BoardGroup, CaseDoc, CaseScope, CaseSummary, CaseView, Quote, QuoteCite, QuoteVerify } from "./case-types"; + +// --------------------------------------------------------------------------- +// RESEARCH BOARDS, server side (plans/umtool-redesign.md, R2): the case store +// (cases.mjs) bound to REPORTS_ROOT and typed; a PIN, which reads the cited +// moment from the corpus and keeps it as a snapshot; RE-VERIFY, which reads +// it again; the board's view and its export. +// +// Read-only on the corpus, as all of Research: every read is the MCP engine's +// (findVideo, findPost, R1's windowOf). A case is umtool's own state. +// --------------------------------------------------------------------------- + +export { CaseError }; + +export const listCases = (): Promise<CaseSummary[]> => listAt(REPORTS_ROOT) as Promise<CaseSummary[]>; +export const readCase = (id: string): Promise<CaseDoc> => readAt(REPORTS_ROOT, id) as Promise<CaseDoc>; + +export type CreateCaseInput = { title?: string; id?: string; scope?: Partial<CaseScope>; query?: string; notes?: string }; +export const createCase = (input: CreateCaseInput): Promise<CaseDoc> => createAt(REPORTS_ROOT, input) as unknown as Promise<CaseDoc>; + +/** One change to a case, read and written inside the store's lock (cases.mjs mutateCase). */ +export async function mutateBoard<T>(id: string, fn: (doc: CaseDoc) => T | Promise<T>): Promise<{ case: CaseDoc; result: T }> { + return (await mutateCase(REPORTS_ROOT, id, fn as never)) as unknown as { case: CaseDoc; result: T }; +} +const mutate = mutateBoard; + +/** The board's groups in order (board.mjs groupsOf), typed. */ +export const boardGroups = (doc: CaseDoc): BoardGroup[] => groupsOf(doc) as unknown as BoardGroup[]; + +/** PATCH a case: title, notes, scope, and the board's arrangement (sections, order). */ +export async function patchCase(id: string, body: Record<string, unknown>): Promise<CaseDoc> { + const known = ["title", "notes", "scope", "sections", "order"]; + const unknown = Object.keys(body).filter((k) => !known.includes(k)); + if (unknown.length) throw new CaseError(`not a case field: ${unknown.join(", ")} (a case takes ${known.join(", ")})`); + return ( + await mutate(id, (doc) => { + patchCaseFields(doc, body); + if (body.sections !== undefined || body.order !== undefined) arrangeCase(doc, { sections: body.sections, order: body.order }); + }) + ).case; +} + +export async function patchQuote(id: string, qid: string, body: Record<string, unknown>): Promise<{ case: CaseDoc; quote: Quote }> { + const known = ["claim", "note", "section", "speakerChecked", "useCurrentWords"]; + const unknown = Object.keys(body).filter((k) => !known.includes(k)); + if (unknown.length) throw new CaseError(`not a quote field: ${unknown.join(", ")} (a quote takes ${known.join(", ")})`); + const r = await mutate(id, (doc) => patchQuoteIn(doc, qid, body) as Quote); + return { case: r.case, quote: r.result }; +} + +export async function deleteQuote(id: string, qid: string): Promise<{ case: CaseDoc; quote: Quote; index: number }> { + const r = await mutate(id, (doc) => removeQuote(doc, qid) as { quote: Quote; index: number }); + return { case: r.case, ...r.result }; +} + +// ── a pin: the cited moment, read from the corpus, kept as a snapshot ── + +export type PinRequest = { + source: string; + /** The channel's key in the source (a hub's `<site>:<slug>`), or its slug. */ + channel: string; + video: string; + /** The cited second (a snippet's, or the reader's lit cue's). */ + t: number; + /** The last cue's second, to pin several cues as one quote. */ + until?: number; + /** An alternate caption track, when the hit was in one. */ + track?: string; + kind?: "video" | "post"; +}; + +const VIDEO_ID = /^[\w-]{1,128}$/; +const MAX_PIN_CUES = 12; + +/** The words at a cite, and everything a citation needs, read now from the corpus. */ +export async function snapshotOf(req: PinRequest): Promise<{ text: string; cite: QuoteCite }> { + const opened = await openSource(req.source); + const { source, option } = opened; + if (req.kind === "post") { + const found = await findPost(source, req.video, req.channel); + if (!found) throw new SourceError(`no post ${req.video} in ${option.label}`, 404); + const { ch, post } = found; + const author = post.authorName || post.author; + const url = viewerPostUrl(ch.siteUrl ?? source.publicOrigin(), post.slug) ?? post.url ?? null; + return { + text: String(post.text ?? "").slice(0, 3000), + cite: { + kind: "post", + source: option.handle, + channel: ch.slug, + channelKey: ch.key, + channelName: ch.name, + ...(ch.siteTitle ? { site: ch.siteTitle } : {}), + video: post.id, + title: `Post by ${author}`, + date: post.uploadDate, + t: 0, + end: 0, + track: "post", + url, + citation: citationText({ quote: post.text, title: "", post: { author, date: isoDate(post.uploadDate) }, url }), + author, + ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), + }, + }; + } + const found = await findVideo(source, req.video, req.channel); + if (!found) throw new SourceError(`no recording ${req.video} in ${option.label}`, 404); + const { ch, record } = found; + const cues = (cuesOfTrack(record, req.track) ?? []).filter((c) => c && typeof c.start === "number"); + if (!cues.length) throw new SourceError(`${record.title} has no cues${req.track ? ` on the ${req.track} track` : ""} to quote`, 404); + const nearest = (t: number) => { + let best = 0; + for (let i = 1; i < cues.length; i++) if (Math.abs(cues[i].start - t) < Math.abs(cues[best].start - t)) best = i; + return best; + }; + const a = nearest(req.t); + const b = req.until !== undefined && Number.isFinite(req.until) ? Math.max(a, Math.min(nearest(req.until), a + MAX_PIN_CUES - 1)) : a; + const span = cues.slice(a, b + 1); + const text = span.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" ").trim(); + const start = span[0].start; + const end = Math.max(span[span.length - 1].end ?? start, start); + const url = momentUrl({ siteOrigin: ch.siteUrl ?? source.publicOrigin(), slug: record.slug, seconds: start, webpageUrl: record.webpageUrl, platform: record.platform }); + const mapped = record.webpageUrl ? extractVideoId(record.webpageUrl) : null; + const alt = req.track && req.track !== record.track ? req.track : undefined; + return { + text, + cite: { + kind: "video", + source: option.handle, + channel: ch.slug, + channelKey: ch.key, + channelName: ch.name, + ...(ch.siteTitle ? { site: ch.siteTitle } : {}), + video: record.id, + ...(mapped && mapped !== record.id && VIDEO_ID.test(mapped) ? { dirVideo: mapped } : {}), + title: record.title, + date: record.uploadDate, + t: start, + end, + clock: clock(start), + track: trackOf((record as { transcriptFormat?: unknown }).transcriptFormat), + ...(alt ? { trackId: alt } : {}), + url, + citation: citationText({ quote: text, title: record.title, clock: clock(start), url }), + ...(record.duration ? { duration: record.duration } : {}), + ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), + }, + }; +} + +export type PinBody = PinRequest & { + claim?: string; + note?: string; + section?: string | null; + /** The search the pin came from (its session, counts): the case takes its reading log. */ + search?: { session: string; query?: string; total?: number; complete?: boolean; notReached?: string[]; sourceLabel?: string }; + /** The search's scope: the case's, when it has none yet. */ + scope?: Partial<CaseScope>; + /** Where in the board order (an undo puts a quote back where it was). */ + at?: number; +}; + +/** Pin a cite to a case. A cite already on the board answers that quote, `duplicate`. */ +export async function pinQuote(id: string, body: PinBody): Promise<{ case: CaseDoc; quote: Quote; duplicate: boolean }> { + await readCase(id); // a missing case is a 404 before the corpus is read + const snap = await snapshotOf(body); + const r = await mutate(id, (doc) => + addQuote( + doc, + { ...snap, claim: body.claim, note: body.note, section: body.section ?? null, at: body.at }, + { search: body.search, scope: body.scope ? { ...body.scope, source: body.scope.source ?? body.source } : { source: body.source } }, + ) as { quote: Quote; duplicate: boolean }, + ); + return { case: r.case, ...r.result }; +} + +// ── re-verify ── + +export type VerifyResult = { id: string; verify: QuoteVerify }; + +const joined = (cs: { text: string }[]) => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" "); + +/** + * One quote against the CURRENT transcript at its cite: R1's window (±30 s) + * on the quote's track. The words found there -> ok (and where, when they + * moved); else drifted, with what the transcript says now. A record with + * both `en` and `en-orig` is read on both: the served `en` track can rewrite + * what was said (en-track-rewrites-content), so a difference is flagged. + */ +export async function verifyQuote(q: Quote, now = new Date()): Promise<QuoteVerify> { + const at = now.toISOString(); + const c = q.cite; + try { + const opened = await openSource(c.source); + if (c.kind === "post") { + const found = await findPost(opened.source, c.video, c.channelKey ?? c.channel); + if (!found) return { status: "missing", at, message: `no post ${c.video} in ${opened.option.label} now` }; + const text = String(found.post.text ?? ""); + return holdsWords(text, q.text) ? { status: "ok", at } : { status: "drifted", at, now: text.slice(0, 3000) }; + } + let win; + try { + win = await windowOf({ source: c.source, channel: c.channelKey ?? c.channel, video: c.video, t: c.t, span: 30, ...(c.trackId ? { track: c.trackId } : {}), kind: "video" }); + } catch (e) { + if (e instanceof SourceError && e.status === 404) return { status: "missing", at, message: e.message }; + throw e; + } + const cues = win.cues; + let status: QuoteVerify = { status: "ok", at }; + if (!cues.length) { + status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` }; + } else if (holdsWords(joined(cues), q.text)) { + // Where the words start now: the first run of cues that holds them. + let nowAt: number | null = null; + for (let i = 0; i < cues.length && nowAt === null; i++) { + for (let k = i; k < Math.min(cues.length, i + MAX_PIN_CUES); k++) { + if (holdsWords(joined(cues.slice(i, k + 1)), q.text)) { + nowAt = cues[i].t; + break; + } + } + } + if (nowAt !== null && Math.abs(nowAt - c.t) >= 1) status = { status: "ok", at, nowAt, message: `the words now start at ${clock(nowAt)} (pinned at ${clock(c.t)})` }; + } else { + // What the transcript says over the quote's own seconds now. + const lit = win.lit >= 0 ? win.lit : 0; + const length = Math.max(0, c.end - c.t); + const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit].t + length - 0.25); + status = { status: "drifted", at, now: joined(over).slice(0, 3000), nowAt: cues[lit].t }; + } + const enOrig = await enOrigCheck(opened.source, q); + return enOrig ? { ...status, enOrig } : status; + } catch (e) { + return { status: "unreadable", at, message: (e as Error).message }; + } +} + +async function enOrigCheck(source: Awaited<ReturnType<typeof openSource>>["source"], q: Quote): Promise<QuoteVerify["enOrig"] | undefined> { + const c = q.cite; + const found = await findVideo(source, c.video, c.channelKey ?? c.channel).catch(() => null); + if (!found) return undefined; + const rec = found.record as { track?: string; altTracks?: { track: string }[]; cues?: { start: number; end: number; text: string }[] }; + if (!rec.track) return undefined; // the primary's id unknown: nothing to say which is which + const ids = [rec.track, ...(rec.altTracks ?? []).map((t) => t.track)]; + const enId = ids.find((t) => t === "en"); + const origId = ids.find((t) => trackKind(t) === "original"); + if (!enId || !origId) return undefined; + const textOn = (track: string) => { + const cues = (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[]; + return joined(cues.filter((x) => x.end > c.t + 0.25 && x.start < Math.max(c.end, c.t + 1) - 0.25)); + }; + const en = textOn(enId); + const orig = textOn(origId); + if (wordsOf(en) === wordsOf(orig)) return undefined; + const quoted = c.trackId ?? rec.track; + return { text: orig, quoted, other: en }; +} + +/** Re-verify every quote (or the ones named), record what was found, answer it. */ +export async function verifyCase(id: string, only?: string[]): Promise<{ case: CaseDoc; results: VerifyResult[] }> { + const doc = await readCase(id); + const quotes = only?.length ? doc.quotes.filter((q) => only.includes(q.id)) : doc.quotes; + const results: VerifyResult[] = []; + const now = new Date(); + // A few at a time: each is a shard read, cached by the source. + for (let i = 0; i < quotes.length; i += 4) { + const batch = quotes.slice(i, i + 4); + results.push(...(await Promise.all(batch.map(async (q) => ({ id: q.id, verify: await verifyQuote(q, now) }))))); + } + const r = await mutate(id, (d) => recordVerify(d, results)); + return { case: r.case, results }; +} + +// ── the board's view, and its export ── + +export async function sourceLabelOf(handle: string): Promise<string | null> { + if (!handle) return null; + const sources = await listSources().catch(() => []); + return sources.find((s) => s.handle === handle)?.label ?? null; +} + +async function readingOf(doc: CaseDoc): Promise<CaseView["reading"]> { + if (!doc.search) return null; + const log = await readLog(REPORTS_ROOT, doc.search.session); + let read = 0; + let skipped = 0; + for (const m of Object.values(log.marks)) { + if (m.state === "read") read++; + else if (m.state === "skipped") skipped++; + } + return { read, skipped, ...(log.error ? { error: log.error } : {}) }; +} + +export async function caseView(id: string): Promise<CaseView> { + const doc = await readCase(id); + return { + case: doc, + piece: `c:${doc.id}`, + stored: storedPath(doc.id), + sourceLabel: (await sourceLabelOf(doc.scope.source)) ?? doc.search?.sourceLabel ?? null, + reading: await readingOf(doc), + localOnly: localOnlyQuotes(doc).length, + }; +} + +/** The board as cited markdown (house format; it converts as a /sweep report). */ +export async function exportCase(id: string): Promise<{ doc: CaseDoc; markdown: string }> { + const view = await caseView(id); + return { + doc: view.case, + markdown: exportMarkdown(view.case, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }), + }; +} diff --git a/umtool/lib/research/case-types.ts b/umtool/lib/research/case-types.ts @@ -0,0 +1,189 @@ +// The research CASE's shapes (lib/research/cases.mjs is the store), shared by +// the routes, the board page and P5's Create. Types only: safe for a client +// component. + +/** A case's scope: the R1 source handle and filters, and the query that found its quotes. */ +export type CaseScope = { + source: string; + channels?: string[]; + dateFrom?: string; + dateTo?: string; + states?: string[]; + mediaType?: "video" | "livestream"; + posts?: boolean; + query?: string; + regex?: boolean; +}; + +/** Where a quote was read: enough to cite it, re-read it, and clip it. */ +export type QuoteCite = { + kind: "video" | "post"; + /** The R1 source handle it was read through. */ + source: string; + /** The channel's slug (the corpus's directory name). */ + channel: string; + /** The source's channel key (a hub's is `<site>:<slug>`). */ + channelKey?: string; + channelName?: string; + site?: string; + /** The recording's id in the archive (Rumble: the embed id). */ + video: string; + /** The editor's directory id when it is not `video` (Rumble: the URL slug). */ + dirVideo?: string; + title?: string; + /** YYYYMMDD. */ + date?: string; + /** The first cue's start, seconds. */ + t: number; + /** The last cue's end, seconds. */ + end: number; + clock?: string; + /** transcript | captions | unknown | post. */ + track?: string; + /** An alternate caption track's id (`en`, `en-GB`, …) when not the primary. */ + trackId?: string; + /** The moment link (a viewer link on the source's origin), or null. */ + url: string | null; + /** The citation in the house format, as R1's Copy citation writes it. */ + citation?: string; + duration?: number; + author?: string; + localOnly?: boolean; +}; + +export type VerifyState = "ok" | "drifted" | "missing" | "unreadable"; + +/** What the last re-verify read at a quote's cite. Never applied to the quote by itself. */ +export type QuoteVerify = { + status: VerifyState; + at: string; + /** The words the transcript has there now (drifted). */ + now?: string; + /** Where those words start now, seconds. */ + nowAt?: number; + message?: string; + /** The record has both `en` and `en-orig` and they differ at the cite. */ + enOrig?: { text: string; quoted: string; other: string }; +}; + +export type Quote = { + /** `q<n>`. */ + id: string; + /** `s<n>`, or null: Unsorted. */ + section: string | null; + /** The words, verbatim, as the transcript had them when pinned. */ + text: string; + cite: QuoteCite; + /** Ours: what the quote shows, in plain words. */ + claim: string; + /** Ours. */ + note: string; + /** False until the operator checked who is speaking (co-hosts, panels). */ + speakerChecked: boolean; + pinnedAt: string; + query?: string; + verify?: QuoteVerify; + /** Earlier words, kept when the operator took the current ones. */ + history?: { text: string; at: string; why: string }[]; +}; + +export type CaseSection = { id: string; title: string }; + +/** A group of the board, in order (lib/research/board.mjs groupsOf): a section, or Unsorted (id null). */ +export type BoardGroup = { id: string | null; title: string; quotes: Quote[] }; + +/** The search a case's quotes were pinned from: its counts and its reading log. */ +export type CaseSearch = { + session: string; + query: string; + total: number; + complete: boolean; + notReached: string[]; + sourceLabel?: string; + at: string; +}; + +export type CaseHandoff = { to: "article" | "video"; href: string; at: string; what?: string }; + +export type CaseDoc = { + format: "umtool-research-case"; + version: 1; + id: string; + title: string; + scope: CaseScope; + search: CaseSearch | null; + sessions: string[]; + sections: CaseSection[]; + quotes: Quote[]; + notes: string; + handoffs: CaseHandoff[]; + counters: { quote: number; section: number }; + createdAt: string; + updatedAt: string; +}; + +/** GET /api/research/cases: one row. */ +export type CaseSummary = { + id: string; + /** `c:<case>`. */ + piece: string; + title: string; + quotes: number; + sections: number; + updatedAt: string; + scope: CaseScope; + /** Quotes the last re-verify found drifted or missing. */ + drifted: number; + /** A case.json that cannot be read: listed, never overwritten. */ + error?: string; +}; + +/** GET /api/research/cases/<id>: the case and what the board shows beside it. */ +export type CaseView = { + case: CaseDoc; + piece: string; + /** Relative to REPORTS_ROOT. */ + stored: string; + /** The source's label, when it is still offered. */ + sourceLabel: string | null; + /** The reading log of the case's search: read and skipped of `search.total`. */ + reading: { read: number; skipped: number; error?: string } | null; + /** Quotes from a local-only channel: no hand-off may target a public site. */ + localOnly: number; +}; + +export type ArticlePlan = { + to: "article"; + /** The article the sweep writes (the case id, unless the confirm names another). */ + article: string; + articleExists: boolean; + question: string; + channels: string[]; + dateFrom?: string; + dateTo?: string; + source: string; + model: string | null; + route: string | null; + capUsd: number | null; + /** The board as cited markdown: the sweep's report starts from it (seed.md). */ + seed: { chars: number; quotes: number }; + spends: true; + refusals: string[]; + warnings: string[]; + policyError?: string; +}; + +export type VideoPlan = { + to: "video"; + /** The project folder under REPORTS_ROOT. */ + slug: string; + title: string; + siteOrigin: string; + clips: { id: string; channel: string; video: string; start: number; end: number; quote: string }[]; + writes: string; + spends: false; + refusals: string[]; + warnings: string[]; +}; + +export type HandoffPlan = ArticlePlan | VideoPlan; diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs @@ -0,0 +1,582 @@ +// RESEARCH CASES -- the boards (plans/umtool-redesign.md, "Research, +// first-class" 5; phase R2). A case is a question being researched: its scope +// (the R1 source handle and filters, and the query), the quotes pinned from +// the results or the reader as SNAPSHOTS, their sections and order, the +// operator's claim line and note on each, and notes on the whole. +// +// REPORTS_ROOT/.umtool/research/<case>/case.json +// { format: "umtool-research-case", version: 1, id, title, scope, search, +// sessions, sections: [{ id, title }], quotes: [Quote], notes, handoffs, +// counters: { quote, section }, createdAt, updatedAt } +// +// A case's piece id is `c:<case>` (lib/pieces/ids.mjs). Umtool-side, NEVER in +// the corpus: REPORTS_ROOT's dot-dirs are state the project walk skips. The +// reading logs (sessions/) and the census (census/) live beside the cases, so +// their names are reserved, as are the pages under /research. +// +// A QUOTE IS A SNAPSHOT (lib/shortlist-types.ts `Pick`'s reasoning): the words +// as the transcript had them when pinned, and the cite they were read at. A +// re-transcription can change the words under a cite; re-verify (verify.ts) +// says so, with the old and the new, and never changes the quote by itself. +// Only the operator's explicit "use the current words" does, and the old text +// is kept in the quote's `history`. +// +// The lifecycle store's discipline (lib/lifecycle.mjs): one writer, serialised +// in-process; every write a whole file to a temp name and a rename; a file +// that does not parse is never overwritten (a write refuses with 409 until +// somebody fixes it; a list shows it with its error). +// +// Plain ESM: a unit test reads it the way the app does. +import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { PIECE_SEGMENT_RE, casePieceId } from "../pieces/ids.mjs"; + +export const CASE_FORMAT = "umtool-research-case"; +export const CASE_VERSION = 1; +export const CASE_FILE = "case.json"; + +/** Names under .umtool/research/ that are not cases, and the pages under /research. */ +export const RESERVED_CASE_IDS = Object.freeze(["sessions", "census", "archive", "runs", "cases", "new"]); + +export const TITLE_LIMIT = 120; +export const CLAIM_LIMIT = 400; +export const NOTE_LIMIT = 2000; +export const NOTES_LIMIT = 20_000; +export const QUOTE_LIMIT = 3000; +export const MAX_QUOTES = 500; +export const MAX_SECTIONS = 60; + +export class CaseError extends Error { + constructor(message, status = 400) { + super(message); + this.name = "CaseError"; + this.status = status; + } +} + +/** A case id: a piece segment (lowercase slug, ≤ 64) that is not reserved. */ +export const isCaseId = (id) => typeof id === "string" && PIECE_SEGMENT_RE.test(id) && !RESERVED_CASE_IDS.includes(id); + +/** A title's slug, cut to a piece segment ("" when nothing in it slugs). */ +export function slugOf(title) { + return String(title ?? "") + .toLowerCase() + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 56) + .replace(/-+$/, ""); +} + +export function researchDir(reportsRoot) { + return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research"); +} + +export function caseDir(reportsRoot, id) { + return path.join(/* turbopackIgnore: true */ researchDir(reportsRoot), id); +} + +export function caseFile(reportsRoot, id) { + return path.join(/* turbopackIgnore: true */ caseDir(reportsRoot, id), CASE_FILE); +} + +/** Where a case is stored, as the board's side panel says it (relative to REPORTS_ROOT). */ +export const storedPath = (id) => `.umtool/research/${id}/`; + +const str = (v, limit) => (typeof v === "string" ? v.slice(0, limit) : ""); +const trimmed = (v, limit) => str(v, limit * 2).replace(/\s+/g, " ").trim().slice(0, limit); +const DATE = /^\d{4}-\d{2}-\d{2}$/; + +/** + * A scope as a case keeps it: the R1 handle and filters, and the query that + * found the quotes. Unknown keys dropped. + */ +export function cleanScope(raw) { + const s = raw && typeof raw === "object" ? raw : {}; + const list = (v) => + (Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : []) + .filter((x) => typeof x === "string" && x.trim()) + .map((x) => x.trim().slice(0, 200)) + .slice(0, 200); + const out = { source: str(s.source, 2000).trim() }; + const channels = list(s.channels); + if (channels.length) out.channels = channels; + if (typeof s.dateFrom === "string" && DATE.test(s.dateFrom)) out.dateFrom = s.dateFrom; + if (typeof s.dateTo === "string" && DATE.test(s.dateTo)) out.dateTo = s.dateTo; + const states = list(s.states); + if (states.length) out.states = states; + if (s.mediaType === "video" || s.mediaType === "livestream") out.mediaType = s.mediaType; + if (s.posts === true) out.posts = true; + const q = trimmed(s.query, 500); + if (q) out.query = q; + if (s.regex === true) out.regex = true; + return out; +} + +const CITE_KEYS = { + kind: (v) => (v === "post" ? "post" : "video"), + source: (v) => str(v, 2000), + channel: (v) => str(v, 128), + channelKey: (v) => str(v, 200), + channelName: (v) => str(v, 200), + site: (v) => str(v, 200), + video: (v) => str(v, 128), + dirVideo: (v) => str(v, 128), + title: (v) => str(v, 500), + date: (v) => str(v, 8), + t: (v) => (Number.isFinite(v) && v >= 0 ? v : 0), + end: (v) => (Number.isFinite(v) && v >= 0 ? v : 0), + clock: (v) => str(v, 16), + track: (v) => str(v, 32), + trackId: (v) => str(v, 64), + url: (v) => (typeof v === "string" ? v.slice(0, 2000) : null), + citation: (v) => str(v, QUOTE_LIMIT + 2600), + duration: (v) => (Number.isFinite(v) && v > 0 ? v : 0), + author: (v) => str(v, 200), + localOnly: (v) => v === true, +}; + +function cleanCite(raw) { + const c = raw && typeof raw === "object" ? raw : {}; + const out = {}; + for (const [k, f] of Object.entries(CITE_KEYS)) { + if (c[k] === undefined) continue; + const v = f(c[k]); + if (v === "" || v === 0 || v === false || v === null) { + if (k === "t" || k === "end" || k === "url") out[k] = v; + continue; + } + out[k] = v; + } + out.kind ??= "video"; + out.t ??= 0; + out.end ??= out.t; + out.url ??= null; + return out; +} + +const VERIFY_STATES = ["ok", "drifted", "missing", "unreadable"]; + +function cleanVerify(v) { + if (!v || typeof v !== "object" || !VERIFY_STATES.includes(v.status)) return undefined; + return { + status: v.status, + at: str(v.at, 40), + ...(typeof v.now === "string" ? { now: v.now.slice(0, QUOTE_LIMIT) } : {}), + ...(Number.isFinite(v.nowAt) ? { nowAt: v.nowAt } : {}), + ...(typeof v.message === "string" ? { message: v.message.slice(0, 500) } : {}), + ...(v.enOrig && typeof v.enOrig === "object" && typeof v.enOrig.text === "string" + ? { enOrig: { text: v.enOrig.text.slice(0, QUOTE_LIMIT), quoted: str(v.enOrig.quoted, 64), other: str(v.enOrig.other, QUOTE_LIMIT) } } + : {}), + }; +} + +function cleanQuote(q, sectionIds) { + const history = (Array.isArray(q.history) ? q.history : []) + .filter((h) => h && typeof h.text === "string") + .slice(-20) + .map((h) => ({ text: h.text.slice(0, QUOTE_LIMIT), at: str(h.at, 40), why: str(h.why, 200) })); + const verify = cleanVerify(q.verify); + return { + id: str(q.id, 16), + section: typeof q.section === "string" && sectionIds.has(q.section) ? q.section : null, + text: str(q.text, QUOTE_LIMIT), + cite: cleanCite(q.cite), + claim: str(q.claim, CLAIM_LIMIT), + note: str(q.note, NOTE_LIMIT), + speakerChecked: q.speakerChecked === true, + pinnedAt: str(q.pinnedAt, 40), + ...(typeof q.query === "string" && q.query ? { query: q.query.slice(0, 500) } : {}), + ...(verify ? { verify } : {}), + ...(history.length ? { history } : {}), + }; +} + +function cleanSearch(s) { + if (!s || typeof s !== "object" || typeof s.session !== "string" || !/^[0-9a-f]{16}$/.test(s.session)) return null; + const n = (v) => (Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0); + return { + session: s.session, + query: str(s.query, 500), + total: n(s.total), + complete: s.complete !== false, + notReached: (Array.isArray(s.notReached) ? s.notReached : []).filter((x) => typeof x === "string").slice(0, 200), + ...(typeof s.sourceLabel === "string" && s.sourceLabel ? { sourceLabel: s.sourceLabel.slice(0, 200) } : {}), + at: str(s.at, 40), + }; +} + +/** + * A case document from what was read, every field checked and cut to size. + * Throws a CaseError when it is not a case at all. + */ +export function normaliseCase(raw, id) { + if (!raw || typeof raw !== "object" || raw.format !== CASE_FORMAT) throw new CaseError(`not a ${CASE_FORMAT} file`, 409); + if (raw.id !== id) throw new CaseError(`case.json names "${raw.id}" but is filed under "${id}"`, 409); + const sections = (Array.isArray(raw.sections) ? raw.sections : []) + .filter((s) => s && typeof s.id === "string" && /^s\d{1,6}$/.test(s.id)) + .slice(0, MAX_SECTIONS) + .map((s) => ({ id: s.id, title: trimmed(s.title, TITLE_LIMIT) || "Untitled section" })); + const ids = new Set(sections.map((s) => s.id)); + const seen = new Set(); + const quotes = []; + for (const q of Array.isArray(raw.quotes) ? raw.quotes : []) { + if (!q || typeof q.id !== "string" || !/^q\d{1,6}$/.test(q.id) || seen.has(q.id)) continue; + seen.add(q.id); + quotes.push(cleanQuote(q, ids)); + if (quotes.length >= MAX_QUOTES) break; + } + const counter = (v, floor) => Math.max(Number.isInteger(v) && v >= 0 ? v : 0, floor); + const maxOf = (arr, re) => arr.reduce((m, x) => Math.max(m, Number(re.exec(x.id)?.[1] ?? 0)), 0); + const handoffs = (Array.isArray(raw.handoffs) ? raw.handoffs : []) + .filter((h) => h && (h.to === "article" || h.to === "video") && typeof h.href === "string") + .slice(-50) + .map((h) => ({ to: h.to, href: h.href.slice(0, 500), at: str(h.at, 40), ...(typeof h.what === "string" ? { what: h.what.slice(0, 300) } : {}) })); + return { + format: CASE_FORMAT, + version: CASE_VERSION, + id, + title: trimmed(raw.title, TITLE_LIMIT) || id, + scope: cleanScope(raw.scope), + search: cleanSearch(raw.search), + sessions: (Array.isArray(raw.sessions) ? raw.sessions : []).filter((s) => typeof s === "string" && /^[0-9a-f]{16}$/.test(s)).slice(-50), + sections, + quotes, + notes: str(raw.notes, NOTES_LIMIT), + handoffs, + counters: { + quote: counter(raw.counters?.quote, maxOf(quotes, /^q(\d+)$/)), + section: counter(raw.counters?.section, maxOf(sections, /^s(\d+)$/)), + }, + createdAt: str(raw.createdAt, 40), + updatedAt: str(raw.updatedAt, 40), + }; +} + +/** What a list shows of a case (GET /api/research/cases). */ +export function summariseCase(c) { + return { + id: c.id, + piece: casePieceId(c.id), + title: c.title, + quotes: c.quotes.length, + sections: c.sections.length, + updatedAt: c.updatedAt, + scope: c.scope, + drifted: c.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length, + }; +} + +/** + * One case. A missing case is a 404; a file that does not parse is a 409 + * (fix or remove it: it is never overwritten). + */ +export async function readCase(reportsRoot, id) { + if (!isCaseId(id)) throw new CaseError(`not a case id: ${JSON.stringify(id)}`, 400); + let text; + try { + text = await readFile(/* turbopackIgnore: true */ caseFile(reportsRoot, id), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") throw new CaseError(`no case "${id}"`, 404); + throw new CaseError(`${storedPath(id)}${CASE_FILE} cannot be read: ${err?.message ?? err}`, 409); + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + throw new CaseError(`${storedPath(id)}${CASE_FILE} is not JSON: ${err.message}`, 409); + } + return normaliseCase(raw, id); +} + +/** + * Every case, newest change first. A case that cannot be read is listed with + * its error, never dropped (and never overwritten). + */ +export async function listCases(reportsRoot) { + const names = await readdir(/* turbopackIgnore: true */ researchDir(reportsRoot), { withFileTypes: true }).catch(() => []); + const out = []; + for (const d of names) { + if (!d.isDirectory() || !isCaseId(d.name)) continue; + try { + out.push(summariseCase(await readCase(reportsRoot, d.name))); + } catch (e) { + if (e?.status === 404) continue; // a directory with no case.json (a half-made one): not a case + out.push({ id: d.name, piece: casePieceId(d.name), title: d.name, quotes: 0, sections: 0, updatedAt: "", scope: { source: "" }, drifted: 0, error: e.message }); + } + } + return out.sort((a, b) => (b.updatedAt || "").localeCompare(a.updatedAt || "") || a.id.localeCompare(b.id)); +} + +let chain = Promise.resolve(); + +function serialised(fn) { + const run = chain.then(fn); + chain = run.catch(() => {}); + return run; +} + +async function writeCase(reportsRoot, doc) { + const file = caseFile(reportsRoot, doc.id); + await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(/* turbopackIgnore: true */ tmp, file); + } catch (err) { + await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); + throw err; + } +} + +/** + * Create a case. `id` when given must be free (409); else the title's slug, + * with -2, -3 … when taken. + * + * @param {string} reportsRoot + * @param {{ title?: string, id?: string, scope?: object, query?: string, notes?: string, now?: Date }} input + */ +export function createCase(reportsRoot, input = {}) { + return serialised(async () => { + const query = trimmed(input.query ?? input.scope?.query, 500); + const title = trimmed(input.title, TITLE_LIMIT) || query; + if (!title) throw new CaseError("a case needs a title or a query"); + let id; + if (input.id !== undefined) { + if (!isCaseId(input.id)) throw new CaseError(`not a case id: ${JSON.stringify(input.id)} (lowercase letters, digits and dashes${RESERVED_CASE_IDS.includes(input.id) ? `; "${input.id}" is reserved` : ""})`); + if (await exists(caseFile(reportsRoot, input.id))) throw new CaseError(`a case "${input.id}" already exists`, 409); + id = input.id; + } else { + const base = slugOf(title) || "case"; + const stem = RESERVED_CASE_IDS.includes(base) ? `${base}-case` : base; + for (let n = 1; n < 100 && !id; n++) { + const cand = n === 1 ? stem : `${stem}-${n}`; + if (isCaseId(cand) && !(await exists(caseDir(reportsRoot, cand)))) id = cand; + } + if (!id) throw new CaseError(`every id from "${stem}" to "${stem}-99" is taken: name the case`, 409); + } + const at = (input.now ?? new Date()).toISOString(); + const doc = normaliseCase( + { + format: CASE_FORMAT, + id, + title, + scope: { ...cleanScope(input.scope), ...(query ? { query } : {}) }, + sections: [], + quotes: [], + notes: str(input.notes, NOTES_LIMIT), + createdAt: at, + updatedAt: at, + }, + id, + ); + await writeCase(reportsRoot, doc); + return doc; + }); +} + +async function exists(p) { + try { + await readFile(/* turbopackIgnore: true */ p); + return true; + } catch (e) { + if (e?.code === "EISDIR") return true; + if (e?.code === "ENOENT") return false; + return true; + } +} + +/** + * One change to a case, read and written inside the lock. `fn(doc)` mutates + * the document it is given and answers what the caller returns; the result + * is checked again before it is written. + * + * @template T + * @param {string} reportsRoot + * @param {string} id + * @param {(doc: ReturnType<typeof normaliseCase>) => T | Promise<T>} fn + * @param {{ now?: Date }} [opts] + * @returns {Promise<{ case: ReturnType<typeof normaliseCase>, result: T }>} + */ +export function mutateCase(reportsRoot, id, fn, opts = {}) { + return serialised(async () => { + const doc = await readCase(reportsRoot, id); + const result = await fn(doc); + doc.updatedAt = (opts.now ?? new Date()).toISOString(); + const clean = normaliseCase(doc, id); + await writeCase(reportsRoot, clean); + return { case: clean, result }; + }); +} + +// ── the changes a route makes ── + +/** Title, notes, scope. */ +export function patchCaseFields(doc, body) { + if (body.title !== undefined) { + const t = trimmed(body.title, TITLE_LIMIT); + if (!t) throw new CaseError("a case's title is text"); + doc.title = t; + } + if (body.notes !== undefined) { + if (typeof body.notes !== "string") throw new CaseError("notes is text"); + doc.notes = body.notes.slice(0, NOTES_LIMIT); + } + if (body.scope !== undefined) { + if (!body.scope || typeof body.scope !== "object") throw new CaseError("scope is an object: { source, channels?, dateFrom?, dateTo?, states?, mediaType?, posts?, query? }"); + doc.scope = cleanScope(body.scope); + } +} + +/** + * The board's arrangement: `sections` is the whole ordered list (an entry + * without an id is a new section; a section left out is removed and its + * quotes go to Unsorted); `order` is every quote id, in board order, each + * with its section (null = Unsorted). + */ +export function arrangeCase(doc, { sections, order }) { + if (sections !== undefined) { + if (!Array.isArray(sections) || sections.length > MAX_SECTIONS) throw new CaseError(`sections is a list of up to ${MAX_SECTIONS} { id?, title }`); + const known = new Set(doc.sections.map((s) => s.id)); + const seen = new Set(); + const next = []; + for (const s of sections) { + if (!s || typeof s !== "object") throw new CaseError("a section is { id?, title }"); + const title = trimmed(s.title, TITLE_LIMIT); + if (!title) throw new CaseError("a section needs a title"); + let sid = s.id; + if (sid === undefined || sid === null || sid === "") sid = `s${++doc.counters.section}`; + else if (typeof sid !== "string" || !known.has(sid)) throw new CaseError(`no section ${JSON.stringify(sid)} in this case`); + if (seen.has(sid)) throw new CaseError(`section ${sid} is listed twice`); + seen.add(sid); + next.push({ id: sid, title }); + } + doc.sections = next; + for (const q of doc.quotes) if (q.section && !seen.has(q.section)) q.section = null; + } + if (order !== undefined) { + if (!Array.isArray(order)) throw new CaseError("order is every quote, in board order: [{ id, section }]"); + const byId = new Map(doc.quotes.map((q) => [q.id, q])); + const sids = new Set(doc.sections.map((s) => s.id)); + const ids = order.map((o) => (typeof o === "string" ? o : o?.id)); + if (ids.length !== byId.size || new Set(ids).size !== ids.length || ids.some((i) => !byId.has(i))) { + throw new CaseError("order must list every quote of the case exactly once"); + } + doc.quotes = order.map((o) => { + const q = byId.get(typeof o === "string" ? o : o.id); + if (typeof o === "object" && o && "section" in o) { + if (o.section !== null && !sids.has(o.section)) throw new CaseError(`no section ${JSON.stringify(o.section)} in this case`); + q.section = o.section; + } + return q; + }); + } +} + +/** Claim, note, section, speaker check, or the operator's "use the current words". */ +export function patchQuote(doc, qid, body, now = new Date()) { + const q = doc.quotes.find((x) => x.id === qid); + if (!q) throw new CaseError(`no quote ${JSON.stringify(qid)} in this case`, 404); + if (body.claim !== undefined) { + if (typeof body.claim !== "string") throw new CaseError("claim is text"); + q.claim = body.claim.replace(/\s+/g, " ").trim().slice(0, CLAIM_LIMIT); + } + if (body.note !== undefined) { + if (typeof body.note !== "string") throw new CaseError("note is text"); + q.note = body.note.trim().slice(0, NOTE_LIMIT); + } + if (body.section !== undefined) { + if (body.section !== null && !doc.sections.some((s) => s.id === body.section)) throw new CaseError(`no section ${JSON.stringify(body.section)} in this case`); + q.section = body.section; + } + if (body.speakerChecked !== undefined) { + if (typeof body.speakerChecked !== "boolean") throw new CaseError("speakerChecked is true or false"); + q.speakerChecked = body.speakerChecked; + } + if (body.useCurrentWords !== undefined) { + // Never silent: only when the operator asks, only to the words the last + // re-verify read, and the old words are kept. + if (body.useCurrentWords !== true) throw new CaseError("useCurrentWords is true"); + const v = q.verify; + if (v?.status !== "drifted" || typeof v.now !== "string" || !v.now.trim()) throw new CaseError("only a quote re-verify found drifted takes the current words", 409); + q.history = [...(q.history ?? []), { text: q.text, at: now.toISOString(), why: `replaced by the transcript's words read ${v.at}` }]; + q.text = v.now; + if (Number.isFinite(v.nowAt)) q.cite.t = v.nowAt; + q.verify = { status: "ok", at: v.at, message: "the current words, taken by the operator" }; + } + return q; +} + +/** Remove a quote; answers it (for an undo). */ +export function removeQuote(doc, qid) { + const i = doc.quotes.findIndex((x) => x.id === qid); + if (i < 0) throw new CaseError(`no quote ${JSON.stringify(qid)} in this case`, 404); + const [q] = doc.quotes.splice(i, 1); + return { quote: q, index: i }; +} + +/** Two pins of the same words: same recording, same second, same track. */ +export const sameCite = (a, b) => + a.kind === b.kind && a.channel === b.channel && a.video === b.video && Math.abs((a.t ?? 0) - (b.t ?? 0)) < 0.5 && (a.trackId ?? "") === (b.trackId ?? ""); + +/** + * Pin a snapshot. A cite already on the board is not added twice: the quote + * there is answered with `duplicate`. `at` (an index into the quotes) puts it + * back where an undo took it from. + * + * @param {ReturnType<typeof normaliseCase>} doc + * @param {{ text: string, cite: object, claim?: string, note?: string, section?: string | null, query?: string, at?: number }} snap + * @param {{ search?: object, scope?: object, now?: Date }} [ctx] + */ +export function addQuote(doc, snap, ctx = {}) { + const now = (ctx.now ?? new Date()).toISOString(); + const cite = cleanCite(snap.cite); + if (!cite.channel || !cite.video) throw new CaseError("a quote's cite names its channel and recording"); + if (typeof snap.text !== "string" || !snap.text.trim()) throw new CaseError("a quote has words"); + const dup = doc.quotes.find((q) => sameCite(q.cite, cite)); + // A search this pin came from becomes the case's: its reading log, its + // counts (searched N, read N of M) -- and its scope, when the case has none. + const search = cleanSearch(ctx.search); + if (search) { + doc.search = { ...search, at: search.at || now }; + if (!doc.sessions.includes(search.session)) doc.sessions.push(search.session); + } + if (!doc.scope.source && ctx.scope) { + doc.scope = cleanScope({ ...ctx.scope, query: ctx.scope.query ?? search?.query }); + } + if (dup) return { quote: dup, duplicate: true }; + if (doc.quotes.length >= MAX_QUOTES) throw new CaseError(`a case holds up to ${MAX_QUOTES} quotes`, 409); + const section = typeof snap.section === "string" && doc.sections.some((s) => s.id === snap.section) ? snap.section : null; + const q = cleanQuote( + { + id: `q${++doc.counters.quote}`, + section, + text: snap.text.trim(), + cite, + claim: snap.claim ?? "", + note: snap.note ?? "", + speakerChecked: false, + pinnedAt: now, + query: snap.query ?? search?.query ?? doc.scope.query, + }, + new Set(doc.sections.map((s) => s.id)), + ); + const at = Number.isInteger(snap.at) && snap.at >= 0 && snap.at <= doc.quotes.length ? snap.at : doc.quotes.length; + doc.quotes.splice(at, 0, q); + return { quote: q, duplicate: false }; +} + +/** Record what a re-verify found, per quote (never the quote's own words). */ +export function recordVerify(doc, results) { + const byId = new Map(results.map((r) => [r.id, r])); + for (const q of doc.quotes) { + const r = byId.get(q.id); + if (r) q.verify = cleanVerify(r.verify); + } +} + +/** A hand-off made from the case (an article's sweep, a video project). */ +export function recordHandoff(doc, h, now = new Date()) { + doc.handoffs.push({ to: h.to, href: h.href, at: now.toISOString(), ...(h.what ? { what: h.what } : {}) }); +} diff --git a/umtool/lib/research/cases.test.mjs b/umtool/lib/research/cases.test.mjs @@ -0,0 +1,133 @@ +// The research case store (cases.mjs): ids, the snapshot discipline, the +// arrangement, and the lifecycle store's rules -- serialised, atomic, an +// unreadable file never overwritten. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + CaseError, + addQuote, + arrangeCase, + caseFile, + createCase, + isCaseId, + listCases, + mutateCase, + patchQuote, + readCase, + removeQuote, + slugOf, +} from "./cases.mjs"; + +const root = () => mkdtemp(path.join(os.tmpdir(), "umtool-cases-")); +const cite = (video, t, extra = {}) => ({ kind: "video", source: "local:/x", channel: "harbor-radio", video, t, end: t + 3.8, url: `https://a.example/?v=harbor-radio%2F${video}&t=${t}`, title: "Ep", ...extra }); + +test("ids: a piece segment that is not reserved; a title's slug", () => { + assert.equal(isCaseId("employee-count"), true); + for (const bad of ["archive", "sessions", "census", "runs", "Bad", "-x", "", "a/b"]) assert.equal(isCaseId(bad), false, bad); + assert.equal(slugOf(" Employee count: “how many?” "), "employee-count-how-many"); + assert.equal(slugOf("Café déjà vu"), "cafe-deja-vu"); +}); + +test("create: from a query (the title), from a title; a taken slug gets -2; a named id must be free", async () => { + const r = await root(); + const a = await createCase(r, { query: "how many employees", scope: { source: "remote:https://j.example", channels: ["x"], dateFrom: "2024-01-01", junk: 1 } }); + assert.equal(a.id, "how-many-employees"); + assert.equal(a.title, "how many employees"); + assert.deepEqual(a.scope, { source: "remote:https://j.example", channels: ["x"], dateFrom: "2024-01-01", query: "how many employees" }); + const b = await createCase(r, { title: "How many employees" }); + assert.equal(b.id, "how-many-employees-2"); + await assert.rejects(createCase(r, { title: "x", id: "how-many-employees" }), /already exists/); + await assert.rejects(createCase(r, { title: "x", id: "archive" }), /reserved/); + await assert.rejects(createCase(r, {}), /needs a title or a query/); + const c = await createCase(r, { title: "Archive" }); + assert.equal(c.id, "archive-case", "a reserved slug is not a case id"); + const list = await listCases(r); + assert.deepEqual(list.map((x) => x.id).sort(), ["archive-case", "how-many-employees", "how-many-employees-2"]); + assert.equal(list.find((x) => x.id === "how-many-employees").piece, "c:how-many-employees"); +}); + +test("a pin is a snapshot; the same cite twice is one quote; a search's log becomes the case's", async () => { + const r = await root(); + await createCase(r, { title: "Board" }); + const search = { session: "FAKE-TEST-VALUE", query: "budget", total: 8, complete: true, notReached: [] }; + const one = await mutateCase(r, "board", (d) => addQuote(d, { text: "the budget was never approved", cite: cite("v1", 600) }, { search, scope: { source: "local:/x", channels: ["harbor-radio"] } })); + assert.equal(one.result.duplicate, false); + assert.equal(one.result.quote.id, "q1"); + assert.equal(one.case.search.session, search.session); + assert.deepEqual(one.case.sessions, [search.session]); + assert.deepEqual(one.case.scope, { source: "local:/x", channels: ["harbor-radio"], query: "budget" }, "the first pin's search scope becomes the case's"); + const again = await mutateCase(r, "board", (d) => addQuote(d, { text: "other words", cite: cite("v1", 600.2) })); + assert.equal(again.result.duplicate, true); + assert.equal(again.case.quotes.length, 1); + assert.equal(again.case.quotes[0].text, "the budget was never approved", "a duplicate pin never rewrites the snapshot"); + const alt = await mutateCase(r, "board", (d) => addQuote(d, { text: "on en", cite: cite("v1", 600, { trackId: "en" }) })); + assert.equal(alt.result.duplicate, false, "another track is another quote"); + await assert.rejects(mutateCase(r, "board", (d) => addQuote(d, { text: "", cite: cite("v2", 1) })), /has words/); +}); + +test("arrange: sections as a whole list, every quote in order; a removed section's quotes go to Unsorted", async () => { + const r = await root(); + await createCase(r, { title: "Board" }); + for (const t of [1, 2, 3]) await mutateCase(r, "board", (d) => addQuote(d, { text: `line ${t}`, cite: cite(`v${t}`, t) })); + const s = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ title: "First" }, { title: "Second" }] })); + assert.deepEqual(s.case.sections, [{ id: "s1", title: "First" }, { id: "s2", title: "Second" }]); + const o = await mutateCase(r, "board", (d) => + arrangeCase(d, { order: [{ id: "q3", section: "s1" }, { id: "q1", section: "s2" }, { id: "q2", section: null }] }), + ); + assert.deepEqual(o.case.quotes.map((q) => [q.id, q.section]), [["q3", "s1"], ["q1", "s2"], ["q2", null]]); + await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { order: ["q1", "q2"] })), /every quote/); + await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { order: [{ id: "q1", section: "s9" }, { id: "q2", section: null }, { id: "q3", section: null }] })), /no section/); + await assert.rejects(mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s9", title: "x" }] })), /no section/); + const gone = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s2", title: "Second, renamed" }] })); + assert.deepEqual(gone.case.sections, [{ id: "s2", title: "Second, renamed" }]); + assert.equal(gone.case.quotes.find((q) => q.id === "q3").section, null); + const added = await mutateCase(r, "board", (d) => arrangeCase(d, { sections: [{ id: "s2", title: "Second" }, { title: "Third" }] })); + assert.equal(added.case.sections[1].id, "s3", "a new section never reuses a removed one's id"); +}); + +test("a quote's claim, note, speaker check; the current words only on the operator's word, the old kept", async () => { + const r = await root(); + await createCase(r, { title: "Board" }); + await mutateCase(r, "board", (d) => addQuote(d, { text: "nine to one", cite: cite("v1", 10) })); + const p = await mutateCase(r, "board", (d) => patchQuote(d, "q1", { claim: " The vote ", note: "panel", speakerChecked: true })); + assert.deepEqual([p.result.claim, p.result.note, p.result.speakerChecked], ["The vote", "panel", true]); + await assert.rejects(mutateCase(r, "board", (d) => patchQuote(d, "q1", { useCurrentWords: true })), /only a quote re-verify found drifted/); + await mutateCase(r, "board", (d) => { + d.quotes[0].verify = { status: "drifted", at: "2026-10-14T00:00:00.000Z", now: "eight to one", nowAt: 11 }; + }); + const took = await mutateCase(r, "board", (d) => patchQuote(d, "q1", { useCurrentWords: true })); + assert.equal(took.result.text, "eight to one"); + assert.equal(took.result.cite.t, 11); + assert.equal(took.result.history[0].text, "nine to one"); + assert.equal(took.result.verify.status, "ok"); + const rm = await mutateCase(r, "board", (d) => removeQuote(d, "q1")); + assert.equal(rm.case.quotes.length, 0); + await assert.rejects(mutateCase(r, "board", (d) => patchQuote(d, "q1", { claim: "x" })), /no quote/); +}); + +test("a case.json that does not parse is never overwritten; a missing case is a 404", async () => { + const r = await root(); + await assert.rejects(readCase(r, "nope"), (e) => e instanceof CaseError && e.status === 404); + await mkdir(path.dirname(caseFile(r, "broken")), { recursive: true }); + await writeFile(caseFile(r, "broken"), "{ not json"); + await assert.rejects(mutateCase(r, "broken", () => {}), (e) => e.status === 409); + assert.equal(await readFile(caseFile(r, "broken"), "utf8"), "{ not json"); + const list = await listCases(r); + assert.equal(list.length, 1); + assert.match(list[0].error, /not JSON/); + // A directory with no case.json is not a case (a half-made one). + await mkdir(path.join(r, ".umtool", "research", "half"), { recursive: true }); + assert.equal((await listCases(r)).length, 1); +}); + +test("writes are serialised: concurrent pins all land", async () => { + const r = await root(); + await createCase(r, { title: "Board" }); + await Promise.all(Array.from({ length: 12 }, (_, i) => mutateCase(r, "board", (d) => addQuote(d, { text: `w${i}`, cite: cite(`v${i}`, i) })))); + const d = await readCase(r, "board"); + assert.equal(d.quotes.length, 12); + assert.equal(new Set(d.quotes.map((q) => q.id)).size, 12); +}); diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts @@ -0,0 +1,239 @@ +import { stat } from "node:fs/promises"; +import path from "node:path"; +import { articleDir } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { articleHref, ARTICLES_KEY } from "@/lib/articles/href"; +import { projectHref } from "@/lib/hrefs"; +import { askEditor, readPolicy } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { invalidateProjects } from "../projects"; +import { scaffoldReportVideo, SLUG_RE } from "../projects/scaffold.mjs"; +import { exportMarkdown, localOnlyQuotes } from "./board.mjs"; +import { CaseError, recordHandoff } from "./cases.mjs"; +import { boardGroups, caseView, mutateBoard } from "./boards"; +import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types"; + +// --------------------------------------------------------------------------- +// HAND-OFFS from a board (plans/umtool-redesign.md, R2), both PLAN THEN +// CONFIRM: POST without `confirm` answers the plan and writes nothing; POST +// with `confirm: true` (and anything the plan let the operator change) does it +// and answers `{ href }`. +// +// "Draft an article from this board" is a `report-draft` SWEEP (the editor's +// job, POST /api/ops/report-draft -- umtool writes nothing of the article +// store) over the board's question and channels, SEEDED with the board as +// cited markdown: the editor keeps it as the iteration's seed.md and the +// sweep's report starts from it (common/controller/reportDraft.ts `seed`, +// added for this hand-off -- the editor had no way to take a board's cites). +// A seeded sweep runs the API agent (the local pipeline writes its report from +// scratch), so the model is the policy's API model, whatever the sweep route. +// It spends money: the plan says on what, and under which cap. +// +// "Start a video from this board" scaffolds a report-video project under +// REPORTS_ROOT (lib/projects/scaffold.mjs, its `timeline`): one clip per +// pinned quote, in board order, its window the quote's cue span. It spends +// nothing; it writes a project. +// +// RESEARCH RULES: a board holding a local-only quote (Candace's channels, +// rules.mjs) never hands off to an article -- the article store publishes. +// Its video project is local, and the plan says it must stay so. +// --------------------------------------------------------------------------- + +const exists = (p: string) => stat(p).then(() => true, () => false); + +/** The board's channels (slugs): the scope's, else every quoted one. */ +function channelsOf(doc: CaseDoc): string[] { + const fromScope = (doc.scope.channels ?? []).map((k) => k.split(":").pop()!).filter(Boolean); + const quoted = [...new Set(doc.quotes.map((q) => q.cite.channel))]; + return fromScope.length ? [...new Set(fromScope)] : quoted; +} + +// ── the article ── + +export async function planArticle(id: string, over: { article?: string; model?: string; question?: string } = {}): Promise<{ plan: ArticlePlan; seed: string }> { + const view = await caseView(id); + const doc = view.case; + const refusals: string[] = []; + const warnings: string[] = []; + const article = (over.article ?? doc.id).trim(); + if (!isReportId(article)) refusals.push(`"${article}" is not an article id (lowercase letters, digits and dashes)`); + if (!doc.quotes.length) refusals.push("the board has no quotes: pin some first"); + const local = localOnlyQuotes(doc).length; + if (local) refusals.push(`${local} ${local === 1 ? "quote is" : "quotes are"} from a local-only channel: an article can be published, so this board never becomes one (export the markdown instead)`); + const channels = channelsOf(doc); + if (!channels.length) refusals.push("the board names no channel to sweep"); + const question = (over.question ?? doc.scope.query ?? doc.title).trim(); + const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; + if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`); + const unverified = doc.quotes.filter((q) => !q.verify).length; + if (unverified) warnings.push(`${unverified} ${unverified === 1 ? "quote was" : "quotes were"} never re-verified`); + const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length; + if (unchecked) warnings.push(`${unchecked} with the speaker not checked: the seed says so on each`); + const articleExists = isReportId(article) ? await exists(articleDir(sitesPaths(), article)) : false; + if (articleExists) warnings.push(`the article "${article}" exists: the sweep adds an iteration to it`); + + let model: string | null = null; + let route: string | null = null; + let capUsd: number | null = null; + let policyError: string | undefined; + try { + const p = await readPolicy(); + route = p.generation.routes.sweep; + model = over.model?.trim() || p.generation.models.api; + capUsd = Math.min(p.generation.caps.sweep, p.generation.caps.max); + if (route !== "api") warnings.push(`the policy routes sweeps to ${route === "code" ? "Claude Code" : "the local model"}; a seeded sweep runs the API agent on ${model}`); + } catch (e) { + policyError = (e as Error).message; + model = over.model?.trim() || null; + } + if (model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`); + + const seed = exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }); + return { + plan: { + to: "article", + article, + articleExists, + question, + channels, + ...(doc.scope.dateFrom ? { dateFrom: doc.scope.dateFrom } : {}), + ...(doc.scope.dateTo ? { dateTo: doc.scope.dateTo } : {}), + source: doc.scope.source, + model, + route, + capUsd, + seed: { chars: seed.length, quotes: doc.quotes.length }, + spends: true, + refusals, + warnings, + ...(policyError ? { policyError } : {}), + }, + seed, + }; +} + +export async function confirmArticle(id: string, over: { article?: string; model?: string; question?: string }): Promise<{ href: string; jobId: string; iteration: number }> { + const { plan, seed } = await planArticle(id, over); + if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409); + if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502); + const answer = await askEditor<{ jobId: string; iteration: number }>("/api/ops/report-draft", { + method: "POST", + body: { + task: "sweep", + article: plan.article, + question: plan.question, + channels: plan.channels, + ...(plan.dateFrom ? { from: plan.dateFrom } : {}), + ...(plan.dateTo ? { to: plan.dateTo } : {}), + ...(plan.source ? { source: plan.source } : {}), + ...(plan.model ? { model: plan.model } : {}), + seed, + }, + }); + const href = articleHref({ site: ARTICLES_KEY, id: plan.article }); + await mutateBoard(id, (doc) => + recordHandoff(doc, { to: "article", href, what: `${plan.article} i${answer.iteration}, job ${answer.jobId}` }), + ); + return { href, jobId: answer.jobId, iteration: answer.iteration }; +} + +// ── the video ── + +/** The viewer origin every quote's link shares, else "" (the project's `check` asks for it). */ +function originOf(doc: CaseDoc): string { + const origins = new Set<string>(); + for (const q of doc.quotes) { + if (q.cite.kind !== "video" || !q.cite.url) continue; + try { + const u = new URL(q.cite.url); + if (!u.searchParams.has("v")) return ""; + origins.add(u.origin); + } catch { + return ""; + } + } + return origins.size === 1 ? [...origins][0] : ""; +} + +const r2 = (n: number) => Math.round(n * 100) / 100; + +export function clipsOf(doc: CaseDoc): { clips: Record<string, unknown>[]; skipped: number } { + const clips: Record<string, unknown>[] = []; + let skipped = 0; + let n = 0; + for (const g of boardGroups(doc)) { + for (const q of g.quotes) { + if (q.cite.kind !== "video" || !(q.cite.end > q.cite.t)) { + skipped++; + continue; + } + const c = q.cite; + const date = /^\d{8}$/.test(c.date ?? "") ? `${c.date!.slice(0, 4)}-${c.date!.slice(4, 6)}-${c.date!.slice(6, 8)}` : undefined; + clips.push({ + type: "clip", + id: `c${String(n++).padStart(2, "0")}`, + // The editor's directory (a Rumble clip's URL slug); the archive's ids + // beside it when they differ, so its cues resolve (report-to-video/cues.mjs). + channel: c.channel, + video: c.dirVideo ?? c.video, + ...(c.dirVideo ? { siteVideo: c.video, siteChannel: c.channel } : {}), + start: r2(c.t), + end: r2(c.end), + cite: Math.floor(c.t), + quote: q.text, + ...(date ? { date } : {}), + ...(q.claim ? { note: q.claim } : {}), + ...(c.trackId ? { track: c.trackId } : {}), + }); + } + } + return { clips, skipped }; +} + +export async function planVideo(id: string, over: { slug?: string; title?: string } = {}): Promise<VideoPlan> { + const view = await caseView(id); + const doc = view.case; + const refusals: string[] = []; + const warnings: string[] = []; + const slug = (over.slug ?? doc.id).trim(); + if (!SLUG_RE.test(slug)) refusals.push(`"${slug}" will not route: lowercase letters, digits and dashes`); + else if (await exists(path.join(REPORTS_ROOT, slug))) refusals.push(`a project folder "${slug}" already exists under the reports root: name another`); + const { clips, skipped } = clipsOf(doc); + if (!clips.length) refusals.push("the board has no video quotes to clip"); + if (skipped) warnings.push(`${skipped} ${skipped === 1 ? "quote has" : "quotes have"} no window (a post, or no cue span) and ${skipped === 1 ? "is" : "are"} left out`); + const local = localOnlyQuotes(doc).length; + if (local) warnings.push(`${local} local-only ${local === 1 ? "quote" : "quotes"}: this project must never be published`); + const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; + if (drifted) warnings.push(`${drifted} drifted or missing at the last re-verify: their windows are the pinned seconds`); + const siteOrigin = originOf(doc); + if (!siteOrigin) warnings.push("no one viewer origin in the quotes' links: set provenance.siteOrigin before the build"); + return { + to: "video", + slug, + title: (over.title ?? doc.title).trim() || doc.title, + siteOrigin, + clips: clips.map((c) => ({ id: String(c.id), channel: String(c.channel), video: String(c.video), start: Number(c.start), end: Number(c.end), quote: String(c.quote) })), + writes: `${slug}/ (video.manifest.json, README.md) under the reports root`, + spends: false, + refusals, + warnings, + }; +} + +export async function confirmVideo(id: string, over: { slug?: string; title?: string }): Promise<{ href: string }> { + const plan = await planVideo(id, over); + if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409); + const doc = (await caseView(id)).case; + const { clips } = clipsOf(doc); + try { + await scaffoldReportVideo({ root: REPORTS_ROOT, slug: plan.slug, title: plan.title, siteOrigin: plan.siteOrigin || null, timeline: clips, timelineFrom: `“${doc.title}” (c:${doc.id})` }); + } catch (e) { + const msg = (e as Error).message; + throw new CaseError(msg, /already exists/.test(msg) ? 409 : 400); + } + invalidateProjects(); + const href = projectHref(plan.slug); + await mutateBoard(id, (d) => recordHandoff(d, { to: "video", href, what: `${clips.length} clips` })); + return { href }; +}