// 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.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:` (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"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.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) } : {}), // R3: a finding an agent's sweep kept (lib/research/runs-board.ts), not a // person's pin; R6: a line a triage flagged (lib/research/triage.ts). ...(q.by === "agent" || q.by === "triage" ? { by: q.by } : {}), ...(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, // R3: the agent run a board was opened from (lib/research/runs-board.ts). ...(raw.run && typeof raw.run === "object" && typeof raw.run.article === "string" && Number.isInteger(raw.run.n) && raw.run.n > 0 ? { run: { article: raw.run.article.slice(0, 64), n: raw.run.n, at: str(raw.run.at, 40) } } : {}), // R6: the triage run a board was made from (lib/research/triage.ts). ...(raw.triage && typeof raw.triage === "object" && typeof raw.triage.schedule === "string" && Number.isInteger(raw.triage.k) && raw.triage.k > 0 ? { triage: { schedule: raw.triage.schedule.slice(0, 64), k: raw.triage.k, at: str(raw.triage.at, 40) } } : {}), 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 = tmpPathFor(file); 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) => T | Promise} fn * @param {{ now?: Date }} [opts] * @returns {Promise<{ case: ReturnType, 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} doc * @param {{ text: string, cite: object, claim?: string, note?: string, section?: string | null, query?: string, at?: number, by?: "agent" | "triage" }} 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, ...(snap.by === "agent" || snap.by === "triage" ? { by: snap.by } : {}), }, 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 } : {}) }); }