// THE TRIAGE STEP (umtool R6): one run over `reports/.triage///`, // which the editor's `report-draft {"task":"triage"}` job creates queued // (controller/reportDraft.ts) and this runs to its end: // // tier 0 the candidates (./tier0.ts): new since the owner's last completed // run, by id, matching the terms or the topics — or the ids named // tier 1 the window judge over their matching windows (./judge.ts), on the // run's model (local by default; the extractor allowed) // decide the flags against the threshold (./types.ts escalationOf). The // step only SAYS whether to escalate; the tick escalates // (controller/reportTick.ts), within the day's escalation cap // // Every stage is logged, traced (trace.jsonl: the scope, tier 0's enumerations, // one `batch` per read batch with the judge's lines, a `check` per flag and per // dismissed line with its reason, `triage` with the tiers, `cost` per tier) // and kept in triage.json. A completed run writes seen.json — what the next run // counts as known — so a run that fails or is cancelled leaves the next one to // see the same recordings as new. // // SERVER-ONLY (node:fs through the store). import { Meter, structuredAnswer, type LlmConfig, type ModelTally } from "../../../llm"; import type { WordCue } from "../../quoteWords"; import { enumerateViaTools, type EnumerateFn, type ListFn } from "../refresh/delta"; import { openTrace, NO_TRACE, type RunTracer } from "../tasks/trace"; import type { CorpusToolsLike } from "../tasks/types"; import { judgeCandidates } from "./judge"; import { confirmSpellings, countViaEnumerate, type CountPhrasesFn } from "./confirm"; import { coveredByTerms, joinedQuery, learnedWords, type LearnedSpelling } from "./learned"; import { readTriageFile, readTriageSeen, triageTracePath, writeTriageFile, writeTriageSeen, type TriagePaths } from "./store"; import { triageCandidates } from "./tier0"; import { TRIAGE_SEEN_FORMAT, escalationOf, partialWords, triageLine, type TriageFile, type TriageWindow } from "./types"; export const DEFAULT_MAX_CANDIDATES = 40; export type TriageRunInput = { owner: string; k: number; // Named by the caller: these are the candidates (no scan, seen.json untouched). ids?: string[]; windows?: Record; maxCandidates?: number; maxUsd?: number; origin?: string | null; // R6.3: the watch's learned spellings (active ones: their name is in the // terms) — escaped alternatives of the candidate query — and the watched // names the judge reports mis-hearings of; `known` (spelling keys: the // names, learned and removed spellings) are not reported again. learned?: LearnedSpelling[]; names?: string[]; known?: ReadonlySet; }; export type TriageRunDeps = { llm: LlmConfig; corpus: CorpusToolsLike; paths: TriagePaths; cuesOf?: (channel: string, id: string) => Promise; // A recording's digest topic tags (default: the corpus's get_video_metadata). topicsOf?: (id: string, channel: string | null) => Promise; // enumerate_matches as data (default: through the corpus tools). enumerate?: EnumerateFn; // Every recording in scope, uncapped (default: the corpus tools' listRecordings, when they have it). list?: ListFn; // R6.3: each phrase's uncapped count in scope (default: the corpus tools' // countPhrases, else the listing and enumerate_matches by ids). count?: CountPhrasesFn; // The model, stubbed (tests); default structuredAnswer on the run's model. ask?: (system: string, user: string, schema: object, what: string) => Promise; now?: () => Date; log?: (line: string) => void; progress?: (done: number, total: number) => void; signal?: AbortSignal; }; /** get_video_metadata's "### Topic tags" line as tags (the build's digest). */ export function topicsFromMetadata(text: string): string[] | null { const m = /### Topic tags\n([^\n]+)/.exec(text); if (!m) return null; return m[1]! .split(",") .map((t) => t.replace(/\s*\(human\)\s*$/, "").trim()) .filter(Boolean); } const round4 = (v: number) => Math.round(v * 10_000) / 10_000; /** Run triage `k` of `owner` (queued, or running: a resumed job) to its end. Answers the file as it ended. */ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Promise<{ file: TriageFile; byModel: Record }> { const { owner, k } = input; const paths = deps.paths; const now = () => (deps.now ?? (() => new Date()))(); const log = (l: string) => { try { deps.log?.(l); } catch { /* a listener never stops the run */ } }; const f0 = await readTriageFile(owner, k, paths); if (!f0) throw new Error(`no triage run ${owner}/${k}`); if (f0.status !== "queued" && f0.status !== "running") throw new Error(`triage ${owner}/${k} is ${f0.status}: only a queued run is run`); const file: TriageFile = { ...f0, status: "running", startedAt: now().toISOString(), warnings: [...(f0.warnings ?? [])] }; const save = () => writeTriageFile(file, paths).catch((e: Error) => log(`triage.json not kept: ${e.message}`)); await save(); const tracer: RunTracer = await openTrace({ article: owner, n: k, file: triageTracePath(paths, owner, k), now, log }).catch(() => NO_TRACE); const trace: RunTracer["emit"] = (e) => { try { tracer.emit(e); } catch { /* a trace never stops the run */ } }; const meter = new Meter({ ...(input.maxUsd !== undefined && Number.isFinite(input.maxUsd) ? { maxUsd: input.maxUsd } : {}) }); const t0 = Date.now(); trace({ t: "run", phase: "start", task: "triage", model: file.model, ...(file.jobId ? { jobId: file.jobId } : {}) }); trace({ t: "scope", source: deps.corpus.source, channels: file.scope.channels, ...(file.scope.from ? { from: file.scope.from } : {}), ...(file.scope.to ? { to: file.scope.to } : {}), question: file.question, model: file.model, ...(input.origin ? { origin: input.origin } : {}), ...(input.maxUsd !== undefined && Number.isFinite(input.maxUsd) ? { maxUsd: input.maxUsd } : {}), ...(input.ids?.length ? { ids: input.ids } : {}), }); if (file.terms || file.topics.length) trace({ t: "terms", terms: [...(file.terms ? [file.terms] : []), ...file.topics.map((t) => `topic: ${t}`)] }); const ask = deps.ask ?? ((system: string, user: string, schema: object) => structuredAnswer({ llm: deps.llm, model: file.model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}) })); const enumerateRaw = deps.enumerate ?? enumerateViaTools(deps.corpus); // Each enumeration, traced as tier 0's. const enumerate: EnumerateFn = async (args) => { const e = await enumerateRaw(args); trace({ t: "enumerate", query: String(args.query), n: e.rows.length, ids: e.rows.map((r) => r.id), partial: e.partial, unreached: e.unreached }); return e; }; const listRaw: ListFn | undefined = deps.list ?? (deps.corpus.listRecordings ? (a) => deps.corpus.listRecordings!(a) : undefined); const list: ListFn | undefined = listRaw ? async (args) => { const l = await listRaw(args); trace({ t: "enumerate", query: "(every recording, listed)", n: l.rows.length, ids: l.rows.map((r) => r.id), partial: !l.complete, unreached: l.unreached }); return l; } : undefined; const topicsOf = deps.topicsOf ?? (async (id: string, channel: string | null) => { try { return topicsFromMetadata(await deps.corpus.call("get_video_metadata", { video_id: id, ...(channel && file.scope.channels.includes(channel) ? { channel } : {}) })); } catch { return null; } }); let outcome: "done" | "failed" | "cancelled" = "done"; let seenIds: string[] | null = null; try { // ─── tier 0 ─── const seen = input.ids?.length ? null : await readTriageSeen(owner, paths); const known = seen ? new Set(seen.ids) : null; file.knownCount = seen ? seen.ids.length : null; const learned = (input.learned ?? []).map((l) => l.spelling); if (learned.length && file.terms) { file.learned = { n: learned.length, spellings: learned }; log(`tier 0: ${learnedWords(learned.length)} (${learned.map((x) => `"${x}"`).join(", ")})`); } const t0r = await triageCandidates( { scope: file.scope, terms: file.terms, regex: file.regex, topics: file.topics, known, since: file.since, ...(input.ids?.length ? { ids: input.ids } : {}), max: input.maxCandidates ?? DEFAULT_MAX_CANDIDATES, ...(learned.length ? { learned } : {}), }, { enumerate, ...(list ? { list } : {}), topicsOf, ...(deps.signal ? { signal: deps.signal } : {}), log }, ); file.tier0 = t0r.tier0; seenIds = t0r.seen; if (t0r.tier0.partial) { file.warnings.push( `partial — ${t0r.tier0.unreached.length ? `not reached: ${t0r.tier0.unreached.join(", ")}` : (t0r.tier0.problems ?? []).join("; ") || "a cap was hit"}: a recording it did not reach is not a candidate this time, and this run's seen set is not kept${seen ? " (the last complete run's stands)" : ` (the next run counts new from ${file.since ?? "its since"} again)`}`, ); } if (t0r.tier0.cut.length) file.warnings.push(`${t0r.tier0.cut.length} candidate(s) past the cap of ${input.maxCandidates ?? DEFAULT_MAX_CANDIDATES}: not judged, left new for the next run`); if (!seen && !input.ids?.length) file.warnings.push(file.since ? `no earlier triage: "new" is uploaded on or after ${file.since}` : "no earlier triage: every recording in scope is new"); await save(); log(`tier 0: ${t0r.tier0.candidates.length} candidate(s) of ${t0r.tier0.newCount} new (${t0r.tier0.scanned} in scope)`); // ─── tier 1 ─── // The judge's windows: around the terms and the learned spellings alike. const jq = joinedQuery(file.terms, file.regex, learned); const j = await judgeCandidates( { question: file.question, candidates: t0r.tier0.candidates, terms: jq?.query ?? file.terms, regex: jq?.regex ?? file.regex, topics: file.topics, channels: file.scope.channels, ...(input.windows ? { windows: input.windows } : {}), origin: input.origin ?? null, ...(input.names?.length ? { names: input.names } : {}), ...(input.known ? { known: input.known } : {}), ...(input.names?.length ? { covered: coveredByTerms(file.terms, file.regex) } : {}), }, { corpus: deps.corpus, ask, model: file.model, ...(deps.cuesOf ? { cuesOf: deps.cuesOf } : {}), usd: () => meter.usd, ...(deps.signal ? { signal: deps.signal } : {}), log, progress: (d, t) => deps.progress?.(d, t), trace: (e) => trace(e), stop: () => (meter.maxUsd !== undefined && meter.usd >= meter.maxUsd ? `the job's cap of $${meter.maxUsd.toFixed(2)} is reached` : null), }, ); file.tier1 = { model: file.model, flags: j.flags, dismissed: j.dismissed, read: j.read, windows: j.windows, chunks: j.chunks, usd: round4(meter.usd) }; if (j.stopped) { file.warnings.push(`tier 1 stopped: ${j.stopped.reason} — ${j.stopped.ids.length} candidate(s) not judged, left new for the next run`); const left = new Set(j.stopped.ids); if (seenIds) seenIds = seenIds.filter((id) => !left.has(id)); } // R6.3: what the judge heard as a watched name, confirmed by code and the // judge before anything is learned (the job writes what is kept). if (j.heard.length) file.heard = j.heard; if (j.heardDropped.length) file.heardDropped = j.heardDropped; if (j.heard.length && !j.stopped) { const count = deps.count ?? deps.corpus.countPhrases?.bind(deps.corpus) ?? (list ? countViaEnumerate(list, enumerate) : null); if (count) { log(`learn: ${j.heard.length} span(s) heard as a watched name — confirming`); const c = await confirmSpellings( { pending: j.heard.map((h) => ({ spelling: h.span, means: h.means, source: "heard" as const, k, heard: h })), question: file.question, scope: file.scope, at: now().toISOString(), origin: input.origin ?? null }, { corpus: deps.corpus, ask, count, ...(deps.cuesOf ? { cuesOf: deps.cuesOf } : {}), log, ...(deps.signal ? { signal: deps.signal } : {}) }, ); file.learning = { kept: c.kept, dropped: c.dropped }; file.tier1.usd = round4(meter.usd); } else { file.warnings.push(`${j.heard.length} heard span(s) not confirmed: this corpus cannot count them`); } } trace({ t: "cost", step: "tier 1", tier: 1, usd: round4(meter.usd), model: file.model, total: round4(meter.usd) }); // ─── the decision ─── file.escalation = escalationOf(j.flags, file.threshold); file.cost = { tier0: 0, tier1: round4(meter.usd) }; const part = partialWords(file.tier0); file.summary = `${part ? `partial (${part}) · ` : ""}${triageLine(file)}${file.learned ? ` · ${learnedWords(file.learned.n)}` : ""} — ${file.escalation.escalate ? "escalate" : "below the threshold"}: ${file.escalation.why}`; log(`tier 1: ${j.flags.length} flag(s), ${j.dismissed.length} dismissed; ${file.summary}`); trace({ t: "triage", owner, k, candidates: t0r.tier0.candidates.map((c) => c.id), flagged: [...new Set(j.flags.map((x) => x.id))], dismissed: j.dismissed.length, escalated: file.escalation.escalate, why: file.escalation.why, cost: file.cost, model: file.model, }); } catch (e) { const cancelled = !!deps.signal?.aborted; outcome = cancelled ? "cancelled" : "failed"; file.error = cancelled ? "cancelled" : (e as Error).message; file.summary = cancelled ? "cancelled" : `failed: ${(e as Error).message}`; file.cost = { tier0: 0, tier1: round4(meter.usd) }; log(`triage ${outcome}: ${file.error}`); } file.status = outcome; file.endedAt = now().toISOString(); if (outcome === "done" && seenIds) { await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner, k, at: file.endedAt, ids: seenIds }, paths).catch((e: Error) => { file.warnings.push(`seen.json not kept: ${e.message} — the next run sees these recordings as new again`); }); } trace({ t: "run", phase: "end", status: outcome, summary: file.summary.slice(0, 1000), usd: round4(meter.usd), minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 }); await tracer.flush(); await save(); return { file, byModel: meter.summary().byModel }; }