// Triage first (umtool R6): tier 0 by id (a late transcript is new), the // digest topics, the cap; tier 1's judge over given windows with a stubbed // model (a strong flag, a weak one, an invented line dropped, a mention only, // a window not relevant, a line the cues do not hold); the threshold and the // suggestion; one run end to end over a temp store (triage.json, trace.jsonl, // seen.json — and a failed run keeps nothing seen). Stubs only: no model, no // corpus on disk. import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { EnumeratedAnswer, EnumerateFn } from "../refresh/delta"; import type { CorpusToolsLike } from "../tasks/types"; import { judgeCandidates } from "./judge"; import { createTriageRun, readTriageFile, readTriageSeen, triageTracePath, writeTriageSeen } from "./store"; import { runTriage, topicsFromMetadata } from "./task"; import { tagMatches, triageCandidates } from "./tier0"; import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_SEEN_FORMAT, TRIAGE_VERSION, escalationOf, precisionOf, suggestThreshold, tickTriageOf, thresholdWords, type TriageCandidate, type TriageFile, } from "./types"; const tmp = await mkdtemp(path.join(os.tmpdir(), "triage-")); after(() => rm(tmp, { recursive: true, force: true })); let n = 0; const store = () => ({ articlesDir: path.join(tmp, `reports-${++n}`) }); // ─── a corpus, stubbed ─── type Rec = { id: string; date: string; title: string; lines: string[]; tags?: string[] }; const CHAN = "synth-kitchen"; const NAME = "Synth Kitchen"; const RECS: Rec[] = [ { id: "bread-01", date: "20260105", title: "Bread day", lines: ["welcome back", "the oven ran hot again", "I paid for the mixer myself"] }, { id: "pie-02", date: "20260210", title: "Pie stream", lines: ["a lot of you asked about the contest", "I did not enter the contest this year", "the judges were friends of mine so it felt wrong"] }, // An OLD recording whose transcript landed late: new by id, not by date. { id: "late-03", date: "20250301", title: "Old stream, late transcript", lines: ["back then the contest was smaller", "I judged the contest that year myself", "we baked forty pies"] }, { id: "new-04", date: "20261012", title: "Contest results", lines: ["the contest results came out today", "I was not a judge at the contest this year either", "congratulations to the winner"] }, { id: "tag-05", date: "20261013", title: "Shop talk", lines: ["the second shop opens in the spring", "small place big oven"], tags: ["bakery business", "second shop"] }, ]; const ymd = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`; function enumerateOver(recs: Rec[]): EnumerateFn & { calls: Record[] } { const calls: Record[] = []; const fn = (async (args: Record): Promise => { calls.push(args); const q = String(args.query); const any = q === "." && args.regex === true; const rows = recs .map((r) => ({ r, n: any ? 1 : r.lines.filter((l) => l.toLowerCase().includes(q.toLowerCase())).length })) .filter((x) => x.n > 0) .map(({ r, n }) => ({ id: r.id, kind: "video" as const, channel: NAME, date: ymd(r.date), matches: n, title: r.title })); return { rows, partial: false, unreached: [] }; }) as EnumerateFn & { calls: Record[] }; fn.calls = calls; return fn; } const stamp = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}|${s}`; /** get_transcripts as the MCP answers it with link_style "base" (windows around the query, or the whole transcript). */ function corpusOver(recs: Rec[], o: { calls?: { name: string; args: Record }[] } = {}): CorpusToolsLike { return { source: "local:/fake/out", tools: [], async call(name, args = {}) { o.calls?.push({ name, args }); if (name === "get_transcripts") { const ids = (args.video_ids as string[]) ?? []; const qs = [...(Array.isArray(args.queries) ? (args.queries as string[]) : []), ...(typeof args.query === "string" ? [args.query] : [])].map((q) => q.toLowerCase()); return ids .map((id) => { const r = recs.find((x) => x.id === id); if (!r) return `## ${id}\n- video_id: ${id}\n(not found)`; const lines = r.lines.map((t, i) => ({ s: i * 5, t })).filter((l) => !qs.length || qs.some((q) => l.t.toLowerCase().includes(q))); return [`## ${r.title}`, `- video_id: ${id}`, `- moment_base: https://synth.example/?v=${CHAN}%2F${id}&t=`, ...lines.map((l) => `[${stamp(l.s)}] ${l.t}`)].join("\n"); }) .join("\n---\n"); } if (name === "get_video_metadata") { const r = recs.find((x) => x.id === args.video_id); if (!r) throw new Error("video not found"); return `{"id": "${r.id}"}${r.tags ? `\n\n## AI digest\n### Topic tags\n${r.tags.join(", ")}` : ""}`; } throw new Error(`the stub has no ${name}`); }, }; } const cuesOver = (recs: Rec[]) => async (_channel: string, id: string) => { const r = recs.find((x) => x.id === id); return r ? r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })) : null; }; // ─── tier 0 ─── test("tier 0: new by ID — an old recording whose transcript landed late is a candidate; the scan's ids become seen", async () => { const enumerate = enumerateOver(RECS); const known = new Set(["bread-01", "pie-02"]); const r = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known, since: null, max: 40 }, { enumerate }); assert.deepEqual(r.tier0.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]); assert.equal(r.tier0.newBy, "id"); assert.equal(r.tier0.newCount, 3); // late-03, new-04, tag-05 assert.deepEqual(r.seen?.sort(), RECS.map((x) => x.id).sort()); // The scope was scanned once with the "any recording" regex. assert.ok(enumerate.calls.some((c) => c.query === "." && c.regex === true)); // With no last run, new is by upload date from `since`: the late transcript is NOT new then. const byDate = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: enumerateOver(RECS) }); assert.deepEqual(byDate.tier0.candidates.map((c) => c.id), ["new-04"]); assert.equal(byDate.tier0.newBy, "date"); }); test("tier 0: digest topics put forward a recording no term matches; the cap leaves the rest new (not seen)", async () => { const corpus = corpusOver(RECS); const topicsOf = async (id: string) => topicsFromMetadata(await corpus.call("get_video_metadata", { video_id: id }).catch(() => "")); const r = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: ["second shop"], known: new Set(["bread-01"]), since: null, max: 40 }, { enumerate: enumerateOver(RECS), topicsOf }); const tag = r.tier0.candidates.find((c) => c.id === "tag-05"); assert.deepEqual(tag?.by, ["topics"]); assert.deepEqual(tag?.tags, ["second shop"]); assert.ok(tagMatches("Bakery Business", "bakery")); assert.ok(!tagMatches("bakery", "contest")); const capped = await triageCandidates({ scope: { channels: [CHAN] }, terms: null, topics: [], known: new Set(), since: null, max: 2 }, { enumerate: enumerateOver(RECS) }); assert.equal(capped.tier0.candidates.length, 2); assert.equal(capped.tier0.cut.length, 3); for (const id of capped.tier0.cut) assert.ok(!capped.seen!.includes(id), `${id} stays new`); assert.deepEqual(capped.tier0.candidates[0]!.by, ["new"]); }); // ─── tier 1 ─── const cand = (id: string, by: TriageCandidate["by"] = ["terms"]): TriageCandidate => { const r = RECS.find((x) => x.id === id)!; return { id, channel: NAME, title: r.title, date: ymd(r.date), matches: 1, by }; }; test("tier 1: the judge over given windows — a strong flag, a weak one, an invented line dismissed as not verbatim, a mention only, a window not relevant", async () => { const asked: string[] = []; const answers: Record = { "late-03": { relevant: true, items: [ { quote: "I judged the contest that year myself", claim: "She says she judged the contest that year.", on_topic: true, strength: 3 }, // Invented: not in the window — dismissed, kept with its reason. { quote: "I rigged the contest for my friends", claim: "She says she rigged it.", on_topic: true, strength: 3 }, ], }, "new-04": { relevant: true, items: [ { quote: "I was not a judge at the contest this year either", claim: "She says she was not a judge this year.", on_topic: true, strength: 2 }, { quote: "the contest results came out today", claim: "She mentions the results.", on_topic: true, strength: 1 }, ], }, "pie-02": { relevant: false, items: [] }, }; const ask = async (_s: string, user: string, _schema: object, what: string): Promise => { asked.push(what); const id = /^triage (\S+)@/.exec(what)![1]!; assert.match(user, /Research question: Did she judge the contest\?/); return answers[id] as T; }; const calls: { name: string; args: Record }[] = []; const j = await judgeCandidates( { question: "Did she judge the contest?", candidates: [cand("late-03"), cand("new-04"), cand("pie-02")], terms: "contest", topics: [], channels: [CHAN], // late-03: only its second line, by the caller's window. windows: { "late-03": [{ start: 5, end: 5 }] }, origin: "https://synth.example", }, { corpus: corpusOver(RECS, { calls }), ask, model: "qwen3:8b", cuesOf: cuesOver(RECS) }, ); assert.deepEqual( j.flags.map((f) => [f.id, f.strength, f.line, f.checked]), [ ["late-03", "strong", "I judged the contest that year myself", "cues"], ["new-04", "weak", "I was not a judge at the contest this year either", "cues"], ], ); assert.equal(j.flags[0]!.f, "f1"); assert.equal(j.flags[0]!.at, 5); assert.equal(j.flags[0]!.url, `https://synth.example/?v=${CHAN}%2Flate-03&t=5`); const why = (id: string) => j.dismissed.filter((d) => d.id === id).map((d) => `${d.stage}: ${d.reason}`); assert.deepEqual(why("late-03"), ["verbatim: not verbatim in its window"]); assert.equal(j.dismissed.find((d) => d.id === "late-03")!.line, "I rigged the contest for my friends"); assert.deepEqual(why("new-04"), ["score: a mention only — She mentions the results."]); assert.deepEqual(why("pie-02"), ["judge: not relevant to the question"]); // late-03 was read whole (its own window), the others around the terms. assert.deepEqual(calls.map((c) => [c.name, (c.args.video_ids as string[]).join(","), c.args.queries ?? null]), [ ["get_transcripts", "new-04,pie-02", ["contest"]], ["get_transcripts", "late-03", null], ]); }); test("tier 1: a line the window holds but the transcript's cues do not is dismissed (R2's word check)", async () => { const ask = async (): Promise => ({ relevant: true, items: [{ quote: "I was not a judge at the contest this year either", claim: "Not a judge.", on_topic: true, strength: 3 }] }) as T; // The cues now say something else at that second (a re-transcription). const cuesOf = async () => [ { start: 0, end: 4.8, text: "the contest results came out today" }, { start: 5, end: 9.8, text: "I was a judge at the contest this year" }, ]; const j = await judgeCandidates({ question: "q", candidates: [cand("new-04")], terms: "contest", topics: [], channels: [CHAN] }, { corpus: corpusOver(RECS), ask, model: "qwen3:8b", cuesOf }); assert.equal(j.flags.length, 0); assert.equal(j.dismissed[0]!.stage, "verbatim"); assert.match(j.dismissed[0]!.reason, /not in the transcript's cues near 0:05/); }); // ─── the threshold ─── test("the threshold: one strong flag, or N of any strength; 0 turns a rule off", () => { const strong = { strength: "strong" as const }; const weak = { strength: "weak" as const }; assert.equal(escalationOf([strong], DEFAULT_TRIAGE_THRESHOLD).escalate, true); assert.equal(escalationOf([weak, weak], DEFAULT_TRIAGE_THRESHOLD).escalate, false); assert.equal(escalationOf([weak, weak, weak], DEFAULT_TRIAGE_THRESHOLD).escalate, true); assert.equal(escalationOf([], DEFAULT_TRIAGE_THRESHOLD).why, "no flag (threshold: 1 strong or 3 weak)"); assert.equal(escalationOf([strong, weak], DEFAULT_TRIAGE_THRESHOLD).why, "1 strong flag, 1 weak flag (threshold: 1 strong or 3 weak)"); assert.equal(escalationOf([strong, strong], { strong: 3, weak: 0 }).escalate, false); assert.equal(escalationOf([weak, weak, weak], { strong: 1, weak: 0 }).escalate, false); assert.equal(thresholdWords({ strong: 1, weak: 0 }), "1 strong only"); assert.equal(thresholdWords({ strong: 0, weak: 0 }), "never"); }); test("precision and the suggested threshold (a suggestion: weak flags mostly wrong raise the weak count)", () => { const at = "2026-10-14T00:00:00Z"; const m = (verdict: "right" | "wrong", score: number) => ({ verdict, score, at }); const p = precisionOf([m("right", 3), m("right", 3), m("wrong", 2), m("wrong", 2), m("right", 2)]); assert.deepEqual([p.marked, p.right, p.wrong, p.precision], [5, 3, 2, 0.6]); const s = suggestThreshold(p, { strong: 1, weak: 3 }); assert.equal(s.changed, true); assert.deepEqual(s.threshold, { strong: 1, weak: 4 }); assert.match(s.why, /weak flags were right 1 of 3/); const none = suggestThreshold(precisionOf([]), { strong: 1, weak: 3 }); assert.equal(none.changed, false); assert.match(none.why, /mark 3 to get a suggestion/); const bad = suggestThreshold(precisionOf([m("wrong", 2), m("wrong", 2), m("wrong", 2)]), { strong: 1, weak: 3 }); assert.deepEqual(bad.threshold, { strong: 1, weak: 0 }); }); // ─── a run, end to end ─── function queued(owner: string, o: Partial = {}) { return (k: number): TriageFile => ({ format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner, k, status: "queued", model: "qwen3:8b", provider: "local", question: "Did she judge the contest?", scope: { channels: [CHAN] }, terms: "contest", regex: false, topics: [], threshold: DEFAULT_TRIAGE_THRESHOLD, since: "2026-10-01", knownCount: null, createdAt: "2026-10-14T00:00:00.000Z", cost: { tier0: 0, tier1: 0 }, summary: "queued", warnings: [], ...o, }); } test("a run end to end: triage.json (tiers, escalation), trace.jsonl (enumerate, batch, check, triage, cost), seen.json; the next run counts by id", async () => { const paths = store(); await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "watch-a", k: 0, at: "2026-10-07T00:00:00Z", ids: ["bread-01", "pie-02", "tag-05"] }, paths); const run = await createTriageRun(queued("watch-a"), paths, "watch-a"); assert.equal(run.k, 1); const ask = async (_s: string, user: string): Promise => (/judged the contest that year/.test(user) ? { relevant: true, items: [{ quote: "I judged the contest that year myself", claim: "She judged it that year.", on_topic: true, strength: 3 }] } : { relevant: false, items: [] }) as T; const { file } = await runTriage({ owner: "watch-a", k: 1 }, { llm: {} as never, corpus: corpusOver(RECS), enumerate: enumerateOver(RECS), paths, cuesOf: cuesOver(RECS), ask }); assert.equal(file.status, "done", file.error); assert.deepEqual(file.tier0!.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]); assert.equal(file.tier0!.newBy, "id"); assert.equal(file.knownCount, 3); assert.deepEqual(file.tier1!.flags.map((f) => f.id), ["late-03"]); assert.equal(file.escalation!.escalate, true); assert.equal(file.cost.tier1, 0); assert.match(file.summary, /2 candidates · 1 flagged · 1 dismissed — escalate: 1 strong flag/); const back = await readTriageFile("watch-a", 1, paths); assert.equal(back?.status, "done"); const seen = await readTriageSeen("watch-a", paths); assert.equal(seen?.k, 1); assert.deepEqual(seen?.ids.sort(), RECS.map((r) => r.id).sort()); const trace = (await readFile(triageTracePath(paths, "watch-a", 1), "utf8")).trim().split("\n").map((l) => JSON.parse(l) as { t: string; phase?: string; stage?: string; tier?: number; flagged?: string[] }); assert.deepEqual(trace[0], { ...trace[0], t: "run", phase: "start" }); for (const t of ["scope", "terms", "enumerate", "batch", "check", "triage", "cost"]) assert.ok(trace.some((e) => e.t === t), `trace has ${t}`); assert.deepEqual(trace.find((e) => e.t === "triage")!.flagged, ["late-03"]); assert.equal(trace.find((e) => e.t === "cost")!.tier, 1); assert.deepEqual(trace.at(-1), { ...trace.at(-1), t: "run", phase: "end" }); const line = tickTriageOf(file, { tier2Usd: 0.42 }); assert.deepEqual([line.k, line.candidates, line.flagged, line.escalated, line.ids, line.usd], [1, 2, 1, true, ["late-03"], { tier1: 0, tier2: 0.42 }]); // The next run: nothing new by id, nothing judged, $0. await createTriageRun(queued("watch-a"), paths, "watch-a"); const again = await runTriage({ owner: "watch-a", k: 2 }, { llm: {} as never, corpus: corpusOver(RECS), enumerate: enumerateOver(RECS), paths, ask: async () => assert.fail("no candidate: no model call") }); assert.equal(again.file.status, "done"); assert.equal(again.file.tier0!.candidates.length, 0); assert.equal(again.file.escalation!.escalate, false); }); test("a run that fails keeps nothing seen: the next sees the same recordings as new", async () => { const paths = store(); await createTriageRun(queued("watch-b"), paths, "watch-b"); const broken: CorpusToolsLike = { source: "x", tools: [], call: async () => { throw new Error("the build is gone"); } }; const { file } = await runTriage({ owner: "watch-b", k: 1 }, { llm: {} as never, corpus: broken, paths }); assert.equal(file.status, "failed"); assert.match(file.error!, /the build is gone/); assert.equal(await readTriageSeen("watch-b", paths), null); }); // ─── R6.1: a complete scope listing; bounded term queries; no silent zeros ─── import type { ListFn, RecordingListing } from "../refresh/delta"; // A scope LARGER THAN THE CAP: 60 old recordings, then the new ones, which // sort last — the order a channel's shards are read in. const BIG: Rec[] = [ ...Array.from({ length: 60 }, (_, i) => ({ id: `old-${String(i).padStart(2, "0")}`, date: `2024${String((i % 12) + 1).padStart(2, "0")}15`, title: `Old ${i}`, lines: ["the contest again", "flour"] })), ...RECS, ]; const CAP = 50; /** enumerate_matches with a cap of CAP rows, as the MCP answers a capped scan: the rows read first, partial, what it did not reach. `ids` restricts (bounds) the scan. */ function cappedEnumerate(recs: Rec[]): EnumerateFn & { calls: Record[] } { const inner = enumerateOver(recs); const fn = (async (args: Record): Promise => { const only = Array.isArray(args.ids) ? new Set(args.ids as string[]) : null; const from = typeof args.date_from === "string" ? args.date_from : null; const e = await inner(args); let rows = e.rows.filter((r) => (!only || only.has(r.id)) && (!from || (r.date ?? "") >= from)); const partial = rows.length > CAP; rows = rows.slice(0, CAP); return { rows, partial, unreached: partial ? [`${NAME} (stopped at page 3 of 4)`] : [] }; }) as EnumerateFn & { calls: Record[] }; fn.calls = inner.calls; return fn; } /** The corpus's listing: every recording, uncapped (the build's manifests). */ const listOver = (recs: Rec[], o: Partial = {}): ListFn & { calls: unknown[] } => { const calls: unknown[] = []; const fn = (async (args) => { calls.push(args); return { rows: recs.map((r) => ({ id: r.id, channel: NAME, channelSlug: CHAN, date: ymd(r.date), title: r.title })), complete: true, unreached: [], problems: [], ...o }; }) as ListFn & { calls: unknown[] }; fn.calls = calls; return fn; }; test("R6.1 tier 0: a scope larger than the cap whose new recordings sort last — listed in full, the terms read by id: the new ones are found, nothing partial", async () => { const enumerate = cappedEnumerate(BIG); const list = listOver(BIG); // First run: new by date from `since`. const first = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate, list }); assert.equal(first.tier0.partial, false); assert.equal(first.tier0.listedBy, "manifests"); assert.equal(first.tier0.scanned, BIG.length); assert.deepEqual(first.tier0.candidates.map((c) => c.id), ["new-04"]); // The terms query: restricted to the new ids, and dated from `since` — never the whole scope. const termCall = enumerate.calls.find((c) => c.query === "contest")!; assert.deepEqual(termCall.ids, ["new-04", "tag-05"]); assert.equal(termCall.date_from, "2026-10-01"); assert.ok(!enumerate.calls.some((c) => c.query === "."), "the scope is listed, not scanned with one capped '.'"); // Seen is the WHOLE scope (on a first run too), so the next run's "new" is by id. assert.equal(first.seen?.length, BIG.length); // By id: the late transcript (an old upload date) is new too. const byId = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: new Set(BIG.map((r) => r.id).filter((id) => id !== "late-03" && id !== "new-04")), since: null, max: 40 }, { enumerate: cappedEnumerate(BIG), list }); assert.deepEqual(byId.tier0.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]); assert.equal(byId.tier0.partial, false); }); test("R6.1 tier 0: a capped scan is partial — the channels named, seen not kept; through a run the earlier seen.json stands and the warning says so", async () => { // No listing (a corpus that cannot list): one capped "." per channel. const capped = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG) }); assert.equal(capped.tier0.partial, true); assert.equal(capped.tier0.listedBy, "enumerate"); assert.deepEqual(capped.tier0.unreached, [`${NAME} (stopped at page 3 of 4)`]); assert.equal(capped.seen, null, "a partial run's seen set is not kept"); assert.deepEqual(capped.tier0.candidates, [], "the newest were never reached — and that is said, not 0"); // A listing that is not complete (a channel's manifest does not read) is partial too. const holes = await triageCandidates({ scope: { channels: [CHAN, "gone"] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG), list: listOver(BIG, { complete: false, unreached: ["gone"], problems: ["gone: its transcripts manifest does not read (404)"] }) }); assert.equal(holes.tier0.partial, true); assert.deepEqual(holes.tier0.unreached, ["gone"]); assert.deepEqual(holes.tier0.candidates.map((c) => c.id), ["new-04"], "what was listed is still judged"); assert.equal(holes.seen, null); // Through a run: the earlier complete run's seen.json stands. const paths = store(); await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "watch-p", k: 0, at: "2026-10-07T00:00:00Z", ids: ["bread-01"] }, paths); await createTriageRun(queued("watch-p"), paths, "watch-p"); const { file } = await runTriage({ owner: "watch-p", k: 1 }, { llm: {} as never, corpus: corpusOver(BIG), enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask: async () => ({ relevant: false, items: [] }) as T }); assert.equal(file.status, "done", file.error); assert.equal(file.tier0!.partial, true); assert.match(file.summary, /^partial \(not reached: Synth Kitchen \(stopped at page 3 of 4\)\) · /); assert.ok(file.warnings.some((w) => /^partial — not reached: Synth Kitchen \(stopped at page 3 of 4\): .*this run's seen set is not kept \(the last complete run's stands\)$/.test(w)), JSON.stringify(file.warnings)); assert.deepEqual((await readTriageSeen("watch-p", paths))?.ids, ["bread-01"]); assert.equal(tickTriageOf(file).partial, "not reached: Synth Kitchen (stopped at page 3 of 4)"); }); test("R6.1 tier 0: the corpus tools' listRecordings is the default listing", async () => { const paths = store(); await createTriageRun(queued("watch-l"), paths, "watch-l"); const listed: unknown[] = []; const corpus = { ...corpusOver(BIG), listRecordings: async (a: unknown) => (listed.push(a), listOver(BIG)(a as never)) }; const { file } = await runTriage({ owner: "watch-l", k: 1 }, { llm: {} as never, corpus, enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask: async () => ({ relevant: false, items: [] }) as T }); assert.equal(file.tier0!.partial, false); assert.equal(file.tier0!.listedBy, "manifests"); assert.deepEqual(listed, [{ channels: [CHAN] }]); assert.equal((await readTriageSeen("watch-l", paths))?.ids.length, BIG.length); }); // ─── R6.2: seen means judge-able — an untranscribed recording stays new ─── import { listedWords } from "./types"; import { nextSeen, splitByTranscript } from "./tier0"; import { recordHasText, statHasText } from "../refresh/delta"; test("R6.2 the pieces: recordHasText, statHasText, splitByTranscript, nextSeen", () => { assert.equal(recordHasText({ cues: [{ start: 0, end: 1, text: "x" }] }), true); assert.equal(recordHasText({ cues: [] }), false); assert.equal(recordHasText({ cues: undefined }), false); assert.equal(recordHasText(null), false); assert.equal(statHasText({ hasTranscript: true }), true); assert.equal(statHasText({ hasTranscript: false }), false); assert.equal(statHasText({}), null, "an entry that does not say"); assert.equal(statHasText(undefined), null, "no entry"); const { judgeable, waiting } = splitByTranscript([{ id: "a", hasTranscript: true }, { id: "b", hasTranscript: false }, { id: "c", hasTranscript: null }, { id: "d" }]); assert.deepEqual(judgeable.map((r) => r.id), ["a", "c", "d"], "unknown is judge-able"); assert.deepEqual(waiting.map((r) => r.id), ["b"]); // known + judge-able, less cut and waiting (a known id now waiting is dropped: it heals). assert.deepEqual(nextSeen({ partial: false, known: new Set(["k", "b"]), judgeable: ["a", "c", "x"], cut: ["x"], waiting: ["b"] }), ["k", "a", "c"]); assert.deepEqual(nextSeen({ partial: false, known: null, judgeable: ["a"], cut: [], waiting: [] }), ["a"]); assert.equal(nextSeen({ partial: true, known: new Set(["k"]), judgeable: ["a"], cut: [], waiting: [] }), null, "a partial run stores nothing"); }); test("R6.2 tier 0: a recording listed with no transcript yet is neither new nor seen; on the run after its transcript lands it is new (by id) and a candidate; the counts are said", async () => { // late-03 is listed by the build's manifests before its transcript lands. const untranscribed = new Set(["late-03"]); const listWith = (waiting: Set): ListFn => async () => ({ rows: BIG.map((r) => ({ id: r.id, channel: NAME, channelSlug: CHAN, date: ymd(r.date), title: r.title, hasTranscript: !waiting.has(r.id) })), complete: true, unreached: [], problems: [], }); const lines: string[] = []; // First run (by date): late-03 is old AND untranscribed — not a candidate, not seen. const first = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG), list: listWith(untranscribed), log: (l) => lines.push(l) }); assert.equal(first.tier0.partial, false); assert.equal(first.tier0.scanned, BIG.length); assert.equal(first.tier0.untranscribed, 1); assert.deepEqual(first.tier0.untranscribedIds, ["late-03"]); assert.ok(first.seen && !first.seen.includes("late-03"), "an untranscribed recording is not stored as seen"); assert.equal(first.seen!.length, BIG.length - 1); assert.ok(lines.includes(`tier 0: ${BIG.length} listed · 1 without a transcript yet (not seen; new once transcribed)`), JSON.stringify(lines)); // By id, an untranscribed recording that is not known is not new either (nothing to judge yet). const waitingNew = new Set(["late-03", "new-04"]); const stillWaiting = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: new Set(first.seen), since: null, max: 40 }, { enumerate: cappedEnumerate(BIG), list: listWith(waitingNew) }); assert.equal(stillWaiting.tier0.newCount, 0, "new-04 has no text yet: not new"); assert.deepEqual(stillWaiting.tier0.candidates, []); assert.equal(stillWaiting.tier0.untranscribed, 2); assert.ok(!stillWaiting.seen!.includes("late-03") && !stillWaiting.seen!.includes("new-04")); // The next run: late-03's transcript has landed — new by id, and it matches the terms. const enumerate = cappedEnumerate(BIG); const next = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: new Set(first.seen), since: null, max: 40 }, { enumerate, list: listWith(new Set()) }); assert.equal(next.tier0.newCount, 1); assert.deepEqual(next.tier0.candidates.map((c) => c.id), ["late-03"]); assert.deepEqual(enumerate.calls.find((c) => c.query === "contest")!.ids, ["late-03"]); assert.equal(next.tier0.untranscribed, undefined); assert.equal(next.seen!.length, BIG.length); // A known id stored as seen while it had no text (before R6.2) is dropped from the set this run stores — it heals. const healed = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: new Set(BIG.map((r) => r.id)), since: null, max: 40 }, { enumerate: cappedEnumerate(BIG), list: listWith(untranscribed) }); assert.deepEqual(healed.tier0.candidates, []); assert.ok(!healed.seen!.includes("late-03")); // Unknown transcript state (no `hasTranscript`): judge-able, as before. const unknown = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG), list: listOver(BIG) }); assert.equal(unknown.tier0.untranscribed, undefined); assert.equal(unknown.seen!.length, BIG.length); }); test("R6.2 a run: seen.json leaves the untranscribed id out; the next run, its transcript landed, judges it", async () => { const paths = store(); let waiting = new Set(["late-03"]); const corpus = { ...corpusOver(BIG), listRecordings: async () => ({ rows: BIG.map((r) => ({ id: r.id, channel: NAME, channelSlug: CHAN, date: ymd(r.date), title: r.title, hasTranscript: !waiting.has(r.id) })), complete: true, unreached: [], problems: [] }), }; const judged: string[] = []; const ask = async (_s: string, user: string): Promise => { judged.push(user); return (/judged the contest that year/.test(user) ? { relevant: true, items: [{ quote: "I judged the contest that year myself", claim: "She judged it.", on_topic: true, strength: 3 }] } : { relevant: false, items: [] }) as T; }; await createTriageRun(queued("watch-t"), paths, "watch-t"); const one = await runTriage({ owner: "watch-t", k: 1 }, { llm: {} as never, corpus, enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask }); assert.equal(one.file.status, "done", one.file.error); assert.equal(one.file.tier0!.untranscribed, 1); const seen = await readTriageSeen("watch-t", paths); assert.equal(seen?.ids.length, BIG.length - 1); assert.ok(!seen!.ids.includes("late-03")); // The transcript lands. waiting = new Set(); await createTriageRun(queued("watch-t"), paths, "watch-t"); const two = await runTriage({ owner: "watch-t", k: 2 }, { llm: {} as never, corpus, enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask }); assert.equal(two.file.status, "done", two.file.error); assert.equal(two.file.tier0!.newBy, "id"); assert.deepEqual(two.file.tier0!.candidates.map((c) => c.id), ["late-03"]); assert.deepEqual(two.file.tier1!.flags.map((f) => f.id), ["late-03"]); assert.equal((await readTriageSeen("watch-t", paths))?.ids.length, BIG.length); }); test("R6.2 listedWords", () => { assert.equal(listedWords({ scanned: 23290, untranscribed: 8 }), "23,290 listed · 8 without a transcript yet (not seen; new once transcribed)"); assert.equal(listedWords({ scanned: 12 }), "12 listed"); });