import { readIteration, readIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; import { listTriageFiles, listTriageRuns, readTriageFile } from "yt-dlp-transcript-common/lib/report/draft/triage/store"; import { DEFAULT_TRIAGE_THRESHOLD, partialWords, precisionOf, suggestThreshold, type TriageFile, type TriageFlag, type TriageThreshold } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; import type { Schedule } from "yt-dlp-transcript-common/lib/report/schedule/types"; import { readScheduleById } from "yt-dlp-transcript-common/lib/report/schedule/store"; import { clock } from "yt-dlp-transcript-common/lib/search/window"; import { ARTICLES_KEY } from "../articles/key.mjs"; import { sitesPaths } from "../articles/sites"; import { articleHref, seriesHref, triageHref } from "../hrefs"; import { REPORTS_ROOT } from "../paths.mjs"; import { addQuote, CaseError } from "./cases.mjs"; import { createCase, mutateBoard, readCase } from "./boards"; import { citationText } from "./facets.mjs"; import { researchCaseHref } from "./hrefs"; import { isLocalOnly } from "./rules.mjs"; import { listSources } from "./sources"; import { runHref } from "./runs-hrefs"; import { marksOfRun, readMarks, setMark, MarksError } from "./triage-marks.mjs"; import type { CaseDoc, QuoteCite } from "./case-types"; import type { FlagMark, ScheduleTriage, TriageRunRow, TriageRunView, TriageTier2 } from "./triage-types"; // --------------------------------------------------------------------------- // TRIAGE FIRST, umtool's side (plans/umtool-redesign.md, R6). The editor runs // the triage (its `report-draft {"task":"triage"}` job) and is the one writer // of reports/.triage///; its tick records what it escalated to on // the schedule's tick line. umtool READS both, and writes only its own: // // the marks the operator's right / wrong on a flag, per schedule // (triage-marks.mjs): the watch's precision, and the threshold // it suggests -- a suggestion, never applied // the board an R2 case of the run's flags, pinned `by: "triage"`. UMTOOL IS // THE ONE WRITER OF THE CASE FILES: the editor's tick never // writes one. The board is made the first time umtool reads an // escalated watch tick (the Inbox's Worth researching card) or // when the operator asks (the triage page's Open as a board), // and is brought up to date the same way: what is on it already // is never touched. Its id is the article the escalation wrote // (so the board's article hand-off adds an iteration to it), else // `-t`. // // SERVER ONLY. // --------------------------------------------------------------------------- export { MarksError }; const round4 = (v: number) => Math.round(v * 10_000) / 10_000; /** The schedule's current threshold: its own, else its newest run's, else the default. */ export function thresholdOf(s: Pick, newest: TriageFile | null): TriageThreshold { return s.triage?.threshold ?? newest?.threshold ?? DEFAULT_TRIAGE_THRESHOLD; } async function scheduleOf(id: string): Promise { const r = await readScheduleById(id, sitesPaths()); if (!r) throw new CaseError(`no schedule "${id}"`, 404); if (!r.ok) throw new CaseError(`the schedule "${id}" does not read: ${r.problem}`, 409); return r.schedule; } /** The board's id: the article the escalation wrote, else `-t`. */ export function triageBoardId(s: Pick, k: number): string { const tick = [...s.ticks].reverse().find((t) => t.triage?.k === k && t.article); return tick?.article ?? `${s.id}-t${k}`.slice(0, 64); } /** Every marked flag of the schedule, as the precision reads them. */ async function allMarks(schedule: string): Promise { const doc = await readMarks(REPORTS_ROOT, schedule).catch(() => null); return doc ? (Object.values(doc.marks) as FlagMark[]) : []; } async function tier2Of(article: string, n: number): Promise { const paths = sitesPaths(); const it = await readIteration(article, n, paths).catch(() => null); const usd = it ? round4(Object.values(it.usage).reduce((x, u) => x + u.usd, 0)) : 0; let findings: number | null = null; const text = await readIterationFile(article, n, "report.json", paths).catch(() => null); if (text) { try { const doc = JSON.parse(text) as { citations?: Record }; findings = Object.values(doc.citations ?? {}).filter((c) => c?.quote).length; } catch { findings = null; } } return { article, n, status: it?.status ?? null, usd, findings, runHref: runHref(article, n), articleHref: articleHref({ site: ARTICLES_KEY, id: article }) }; } /** One run of a schedule's triage, for its page. */ export async function readTriageRunView(scheduleId: string, k: number): Promise { const s = await scheduleOf(scheduleId); const paths = sitesPaths(); const file = await readTriageFile(s.id, k, paths); if (!file) throw new CaseError(`${s.id} has no triage run ${k}`, 404); const runs = (await listTriageRuns(s.id, paths)).reverse(); const newest = runs.length ? await readTriageFile(s.id, runs[0]!, paths) : null; const tick = [...s.ticks].reverse().find((t) => t.triage?.k === k) ?? null; const tier2 = tick?.article && tick.iteration ? await tier2Of(tick.article, tick.iteration) : null; const marksDoc = await readMarks(REPORTS_ROOT, s.id).catch(() => null); const marks = (marksDoc ? marksOfRun(marksDoc, k) : {}) as Record; const precision = precisionOf(marksDoc ? (Object.values(marksDoc.marks) as FlagMark[]) : []); const threshold = thresholdOf(s, newest); const boardId = triageBoardId(s, k); const board = await readCase(boardId).catch(() => null); return { schedule: { id: s.id, shape: s.shape, topic: s.topic, href: s.shape === "living" ? articleHref({ site: ARTICLES_KEY, id: s.article ?? s.id }) : seriesHref(s.id), threshold }, k, runs, file, tick: tick ? { at: tick.at, status: tick.status, reason: tick.reason ?? null, usd: tick.usd, triage: tick.triage ?? null } : null, tier2, marks, precision, suggestion: suggestThreshold(precision, threshold), board: { id: boardId, href: researchCaseHref(boardId), exists: !!board && !!board.triage, quotes: board?.quotes.length ?? 0 }, }; } /** A schedule's triage runs (newest first), its precision and the threshold the marks suggest. */ export async function readScheduleTriage(s: Schedule): Promise { const files = await listTriageFiles(s.id, sitesPaths()).catch(() => [] as TriageFile[]); const tickOf = new Map(s.ticks.filter((t) => t.triage).map((t) => [t.triage!.k, t])); const runs: TriageRunRow[] = files.map((f) => { const t = tickOf.get(f.k); return { k: f.k, at: f.startedAt ?? f.createdAt, status: f.status, candidates: f.tier0?.candidates.length ?? 0, flagged: f.tier1?.flags.length ?? 0, dismissed: f.tier1?.dismissed.length ?? 0, escalated: t?.triage?.escalated ?? false, why: t?.triage?.capped ?? f.escalation?.why ?? f.summary, partial: partialWords(f.tier0), usd: { tier1: f.cost.tier1, tier2: t?.triage?.usd.tier2 ?? 0 }, href: triageHref(s.id, f.k), }; }); const precision = precisionOf(await allMarks(s.id)); const threshold = thresholdOf(s, files[0] ?? null); return { runs, precision, suggestion: suggestThreshold(precision, threshold), threshold }; } /** Mark one flag right or wrong (null: unmark). Answers the run's marks and the schedule's precision. */ export async function markFlag(scheduleId: string, k: number, f: string, verdict: "right" | "wrong" | null) { const s = await scheduleOf(scheduleId); const file = await readTriageFile(s.id, k, sitesPaths()); if (!file) throw new CaseError(`${s.id} has no triage run ${k}`, 404); const flag = (file.tier1?.flags ?? []).find((x) => x.f === f); if (!flag) throw new CaseError(`run ${k} has no flag ${JSON.stringify(f)}`, 404); const doc = await setMark(REPORTS_ROOT, s.id, { k, f, verdict, score: flag.score, id: flag.id, line: flag.line }); const precision = precisionOf(Object.values(doc.marks) as FlagMark[]); const newest = (await listTriageRuns(s.id, sitesPaths())).at(-1); const threshold = thresholdOf(s, newest ? await readTriageFile(s.id, newest, sitesPaths()) : null); return { marks: marksOfRun(doc, k) as Record, precision, suggestion: suggestThreshold(precision, threshold) }; } // ── the board ── const ymd8 = (d: string | null) => (d && /^\d{4}-\d{2}-\d{2}/.test(d) ? d.slice(0, 10).replace(/-/g, "") : undefined); /** The R1 source the board's quotes re-verify through: the run's when offered, else the first offered. */ async function sourceFor(runSource: string | null): Promise { const offered = await listSources().catch(() => []); if (runSource && offered.some((o) => o.handle === runSource)) return runSource; return offered[0]?.handle ?? runSource ?? ""; } export function citeOfFlag(f: TriageFlag, source: string): QuoteCite | null { if (!f.channel) return null; const date = ymd8(f.date); const title = f.title ?? f.id; return { kind: "video", source, channel: f.channel, video: f.id, title, ...(date ? { date } : {}), t: f.at, end: f.at, clock: clock(f.at), url: f.url ?? null, citation: citationText({ quote: f.line, title, clock: clock(f.at), url: f.url ?? null }), ...(isLocalOnly(f.channel) ? { localOnly: true } : {}), } as QuoteCite; } export type TriageBoardResult = { id: string; href: string; created: boolean; added: number; already: number; skipped: number }; /** * The run's flags as a board: the case made (titled for the schedule, its scope * the run's channels, its query the question) or brought up to date. Each flag * a quote `by: "triage"`, the judge's reason as its claim line, strong flags * before weak; what is on the board already is never touched. */ export async function openTriageBoard(scheduleId: string, k: number): Promise { const s = await scheduleOf(scheduleId); const file = await readTriageFile(s.id, k, sitesPaths()); if (!file) throw new CaseError(`${s.id} has no triage run ${k}`, 404); const flags = file.tier1?.flags ?? []; if (!flags.length) throw new CaseError(`${s.id} triage ${k} flagged nothing: no board to make`, 409); const id = triageBoardId(s, k); const source = await sourceFor(null); let created = false; try { await readCase(id); } catch (e) { if ((e as { status?: number }).status !== 404) throw e; await createCase({ id, title: `${s.topic} · triage ${(file.startedAt ?? file.createdAt).slice(0, 10)}`, scope: { source, channels: file.scope.channels, ...(file.scope.from ? { dateFrom: file.scope.from.replace(/-/g, "") } : {}) }, query: file.terms ?? file.question, }); created = true; } const r = await mutateBoard(id, (doc: CaseDoc) => { doc.triage = { schedule: s.id, k, at: new Date().toISOString() }; let added = 0; let already = 0; let skipped = 0; const ensure = (title: string) => { let sec = doc.sections.find((x) => x.title === title); if (!sec) { sec = { id: `s${++doc.counters.section}`, title }; doc.sections.push(sec); } return sec.id; }; const ordered = [...flags].sort((a, b) => b.score - a.score); for (const f of ordered) { const cite = citeOfFlag(f, source); if (!cite) { skipped++; continue; } const section = ensure(f.strength === "strong" ? "Strong flags" : "Weak flags"); const out = addQuote(doc, { text: f.line, cite, claim: f.reason, section, query: file.terms ?? file.question, by: "triage" }) as { duplicate: boolean }; if (out.duplicate) already++; else added++; } return { added, already, skipped }; }); return { id, href: researchCaseHref(id), created, ...r.result }; } /** * The boards an escalated watch tick is owed, made now (the Inbox reads its * card's board from here): every escalated watch tick whose board does not * exist yet. Idempotent; a failure leaves the card on the triage page. */ export async function ensureTriageBoards(schedules: Pick[]): Promise> { const out = new Map(); for (const s of schedules) { if (s.shape !== "watch") continue; for (const t of s.ticks) { if (!t.triage?.escalated || t.status !== "done") continue; const key = `${s.id}/${t.triage.k}`; const id = triageBoardId(s, t.triage.k); const exists = await readCase(id).then( (d) => !!d.triage, () => false, ); if (exists) { out.set(key, researchCaseHref(id)); continue; } try { const made = await openTriageBoard(s.id, t.triage.k); out.set(key, made.href); } catch { // The card falls back to the triage page. } } } return out; }