Archilyzer · Source

archilyzer

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

commit 2017cde0c613f9521095caedf9b934c87b9c6149
parent 83232b18fe3ff13eb327adfe10afa8e6d3933e23
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 15:53:48 -0400

umtool: triage first — Create's Watch and Triage first, the triage page (the tiers, each flag and dismissal with why, y/x marks), the run page's triage step, the watch page (found, triage runs, precision), the Worth researching card and its board (R6)

- lib/research/triage.ts: the run view (triage.json, its tick, tier 2), the
  schedule's runs, markFlag (triage-marks.mjs: per schedule, umtool's own),
  openTriageBoard / ensureTriageBoards: umtool is the one writer of case files,
  the editor's tick never writes one; the board's id is the escalation's article
- /series/<id>/triage/<k> (components/series/TriageView.tsx), the API under
  /api/research/triage/<schedule>/<k> (view, marks, board)
- the series page: a watch's Found, the Triage panel (runs, precision, the
  suggested threshold), the tick log's triage links
- Inbox kind worth-researching (Your call; settled by a hand-off or every flag
  marked); a watch's articles are its own (no iteration cards, not Work rows)
- the run page's triage step (the trace's triage line); a board's From triage
  and by triage
- opsStub: the triage step and the escalation's sweep; e2e triage-first.spec,
  editor report-draft.spec (a watch over the fake models) and ops-api.spec
- unit: lib/research/triage.test.ts (3), triage-marks.test.mjs (1),
  inbox/schedules.test.mjs (+1)

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

Diffstat:
Mcommon/testing/schedule/opsStub.ts | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/e2e/ops-api.spec.ts | 36++++++++++++++++++++++++++++++++++++
Meditor/e2e/report-draft.spec.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/triage/[schedule]/[k]/board/route.ts | 19+++++++++++++++++++
Aumtool/app/api/research/triage/[schedule]/[k]/marks/route.ts | 22++++++++++++++++++++++
Aumtool/app/api/research/triage/[schedule]/[k]/route.ts | 18++++++++++++++++++
Mumtool/app/series/[id]/page.tsx | 236++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Aumtool/app/series/[id]/triage/[k]/page.tsx | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/create/RecurringForm.tsx | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/components/research/BoardView.tsx | 11+++++++++++
Mumtool/components/research/QuoteSlip.tsx | 5+++++
Mumtool/components/research/RunView.tsx | 8++++++++
Aumtool/components/series/TriageView.tsx | 462+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/triage-first.spec.ts | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.ts | 5+++++
Mumtool/lib/inbox.ts | 55++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/inbox/groups.mjs | 5++++-
Mumtool/lib/inbox/schedules.mjs | 31++++++++++++++++++++++++++++++-
Mumtool/lib/inbox/schedules.test.mjs | 34++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/pieces.ts | 8++++++--
Mumtool/lib/research/case-types.ts | 6++++--
Mumtool/lib/research/cases.mjs | 13+++++++++----
Mumtool/lib/research/runs-types.ts | 19++++++++++++++++++-
Mumtool/lib/research/runs-view.ts | 29+++++++++++++++++++++++++++++
Aumtool/lib/research/triage-marks.mjs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/triage-marks.test.mjs | 34++++++++++++++++++++++++++++++++++
Aumtool/lib/research/triage-types.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/triage.test.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/triage.ts | 277+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
30 files changed, 2168 insertions(+), 62 deletions(-)

diff --git a/common/testing/schedule/opsStub.ts b/common/testing/schedule/opsStub.ts @@ -15,7 +15,15 @@ // refresh no change, $0 // generateEdition terms or question with "held" → held by the daily cap; // "fail" → failed; --quiet, or "quiet" → quiet; else a -// done iteration with a two-section report, $0.37 +// done iteration with a two-section report, $0.37 (with +// `ids`, R6's escalation: one finding citing the first +// flagged recording, and a trace whose first line after the +// start is the triage's tiers) +// triage (R6) a real triage run in reports/.triage/<id>/<k>/ — +// "quiet" in the terms or question → candidates, no flag +// (below the threshold); else a strong flag and a weak one +// on sitechan/sv1 and sv2, an invented line dismissed as +// not verbatim, a window not relevant; $0 (local) import { mkdir } from "node:fs/promises"; import path from "node:path"; @@ -23,6 +31,10 @@ import type { Paths } from "../../lib/paths"; import { sanitizeGeneration } from "../../lib/generationSettings"; import { createIteration, updateIteration, writeIterationFile } from "../../lib/report/iterations"; import { claimTick } from "../../controller/reportSchedule"; +import { createTriageRun, writeTriageFile } from "../../lib/report/draft/triage/store"; +import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, triageLine, type TriageFile, type TriageFlag } from "../../lib/report/draft/triage/types"; +import { writeFile } from "node:fs/promises"; +import { iterationFile } from "../../lib/report/iterations"; import { runTick, type TickDeps, type TickSteps } from "../../controller/reportTick"; import { reportScheduleAction } from "../../controller/reportScheduleOps"; @@ -52,6 +64,13 @@ await mkdir(articlesDir, { recursive: true }); const words = (s: { question: string; scope: { terms?: string } }) => `${s.question} ${s.scope.terms ?? ""}`.toLowerCase(); +// R6: the triage's flags (sitechan's fixture lines: sites-fixture.mjs). +const ORIGIN = "https://priv.example"; +const FLAGS: TriageFlag[] = [ + { f: "f1", id: "sv1", channel: "sitechan", title: "Site video one", date: "2024-03-15", window: { start: 0, end: 12 }, line: "The vote was rigged and everybody knew.", at: 3, score: 3, strength: "strong", reason: "The speaker says the vote was rigged (stub).", checked: "cues", url: `${ORIGIN}/?v=sitechan%2Fsv1&t=3` }, + { f: "f2", id: "sv2", channel: "sitechan", title: "Site video two", date: "2024-03-15", window: { start: 5, end: 15 }, line: "Then she said the opposite.", at: 8, score: 2, strength: "weak", reason: "She contradicts an earlier claim (stub).", checked: "cues", url: `${ORIGIN}/?v=sitechan%2Fsv2&t=8` }, +]; + const steps: TickSteps = { fetchAndBuild: async (_scope, ctx) => { ctx.log("fetched (stub)"); @@ -66,7 +85,50 @@ const steps: TickSteps = { return { status: "quiet", usd: 0, matched: 0, reason: `nothing in ${input.window.from} … ${input.window.to} matches (stub)` }; } const model = input.schedule.model ?? generation.models.api; - const it = await createIteration(input.article, { kind: "sweep", model, question: input.schedule.question, scope: { channels: input.schedule.scope.channels, from: input.window.from, to: input.window.to } }, paths); + const it = await createIteration( + input.article, + { + kind: "sweep", + model, + question: input.schedule.question, + scope: { channels: input.schedule.scope.channels, ...(input.ids?.length ? { ids: input.ids } : { from: input.window.from, to: input.window.to }), ...(input.triage ? { triage: input.triage } : {}) }, + }, + paths, + ); + if (input.ids?.length) { + // R6: the escalation's sweep of the flagged recordings — one finding, and its trace. + const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); + const flag = FLAGS.find((f) => f.id === input.ids![0]) ?? FLAGS[0]!; + await writeIterationFile( + input.article, + it.n, + "report.json", + { + format: "archilyzer-report", + version: 1, + id: input.article, + kind: "sweep", + title: input.title ?? input.schedule.topic, + summary: "One flagged recording holds it (stub).", + citations: { c1: { kind: "video", channel: flag.channel, id: flag.id, start: flag.at, end: flag.at + 3, quote: flag.line } }, + sections: [{ id: "s1", title: "What was found", body: `The speaker [says so](cite:c1).`, claims: [{ text: flag.reason, citations: ["c1"] }] }], + }, + paths, + ); + const lines = [ + { t: "run", at, run: 1, phase: "start", task: "sweep-agent", model }, + { t: "triage", at, run: 1, owner: input.triage?.owner ?? input.schedule.id, k: input.triage?.k ?? 1, candidates: ["sv1", "sv2", "sv3", "sv4"], flagged: input.ids, dismissed: 2, escalated: true, why: "1 strong flag, 1 weak flag (threshold: 1 strong or 3 weak)", cost: { tier0: 0, tier1: 0 }, model: generation.models.local }, + { t: "scope", at, run: 1, source: "local:/stub/out", channels: input.schedule.scope.channels, question: input.schedule.question, model, ids: input.ids }, + { t: "cost", at, run: 1, step: "turn 0", usd: 0.37, model, total: 0.37, turn: 0, phase: "agent", calls: ["get_transcripts"], tier: 2 }, + { t: "finding", at, run: 1, section: "What was found", claim: flag.reason, cites: [{ citation: "c1", channel: flag.channel, video: flag.id, start: flag.at, quote: flag.line }] }, + { t: "check", at, run: 1, quote: flag.line, cite: { citation: "c1", channel: flag.channel, video: flag.id, start: flag.at }, ok: true, stage: "final", reason: "verbatim (strict)" }, + { t: "run", at, run: 1, phase: "end", status: "done", summary: "1 finding (stub)", usd: 0.37, minutes: 0.1, coverage: { matched: input.ids.length, read: input.ids.length, partial: false, unreached: [] } }, + ]; + await writeFile(iterationFile(paths, input.article, it.n, "trace.jsonl"), lines.map((l) => JSON.stringify(l)).join("\n") + "\n"); + await updateIteration(input.article, it.n, { status: "done", usage: { [model]: { usd: 0.37, inputTokens: 1200, outputTokens: 300, calls: 4 } }, coverage: { matched: input.ids.length, read: input.ids.length, partial: false, unreached: [] } }, paths); + ctx.log(`sweep ${input.article} i${it.n} (the flagged ids): ~$0.37 so far`); + return { status: "done", iteration: it.n, usd: 0.37, jobId: `${jobId}-sweep` }; + } await writeIterationFile( input.article, it.n, @@ -88,6 +150,68 @@ const steps: TickSteps = { ctx.log(`sweep ${input.article} i${it.n}: ~$0.37 so far`); return { status: "done", iteration: it.n, usd: 0.37, matched: 2, jobId: `${jobId}-sweep` }; }, + triage: async (input, ctx) => { + const s = input.schedule; + const quiet = /quiet/.test(words(s)); + const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); + const threshold = s.triage?.threshold ?? { strong: generation.triage.strong ?? DEFAULT_TRIAGE_THRESHOLD.strong, weak: generation.triage.weak ?? DEFAULT_TRIAGE_THRESHOLD.weak }; + const run = await createTriageRun( + (k): TriageFile => ({ + format: TRIAGE_FORMAT, + version: TRIAGE_VERSION, + owner: s.id, + k, + status: "done", + jobId: `${jobId}-triage`, + model: generation.models.local, + provider: "local", + question: s.question, + scope: { channels: input.scope.channels }, + terms: s.scope.terms ?? null, + regex: s.scope.regex === true, + topics: s.scope.topics ?? [], + threshold, + since: input.since, + knownCount: 12, + createdAt: at, + startedAt: at, + endedAt: at, + tier0: { + candidates: ["sv1", "sv2", "sv3", "sv4"].map((id, i) => ({ id, channel: "Site Channel", title: `Site video ${["one", "two", "three", "four"][i]}`, date: "2024-03-15", matches: 2 - (i % 2), by: i === 3 ? ["topics"] : ["terms"], ...(i === 3 ? { tags: ["elections"] } : {}) })), + scanned: 16, + newCount: 4, + cut: [], + partial: false, + unreached: [], + perQuery: [{ query: "(any recording)", n: 16, partial: false }], + newBy: "id", + }, + tier1: { + model: generation.models.local, + flags: quiet ? [] : FLAGS, + dismissed: [ + { id: "sv3", title: "Site video three", channel: "sitechan", window: { start: 0, end: 30 }, line: "Everybody rigged the count on purpose.", at: 5, score: 3, stage: "verbatim", reason: "not verbatim in its window" }, + { id: "sv4", title: "Site video four", channel: "sitechan", window: { start: 0, end: 40 }, stage: "judge", reason: "not relevant to the question" }, + ...(quiet ? [{ id: "sv1", title: "Site video one", channel: "sitechan", window: { start: 0, end: 12 }, line: "The vote was rigged and everybody knew.", at: 3, score: 1, stage: "score" as const, reason: "a mention only — it names the vote (stub)" }] : []), + ], + read: 4, + windows: 4, + chunks: 5, + usd: 0, + }, + escalation: escalationOf(quiet ? [] : FLAGS, threshold), + cost: { tier0: 0, tier1: 0 }, + summary: "", + warnings: [], + }), + paths, + s.id, + ); + const f = { ...run, summary: `${triageLine(run)} — ${run.escalation!.escalate ? "escalate" : "below the threshold"}: ${run.escalation!.why}` }; + await writeTriageFile(f, paths); + ctx.log(`triage ${s.id}/${f.k} (stub): ${f.summary}`); + return { status: "done", file: f, jobId: `${jobId}-triage` }; + }, }; const deps: TickDeps = { diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts @@ -1001,3 +1001,39 @@ test("report-schedule: create (plan, then the schedule), list, tick now, pause, expect((gone.body as { confirmed?: boolean }).confirmed).toBe(true); expect(await pathExists(SERIES)).toBe(false); }); + +// --- triage first: a watch (umtool R6) ---------------------------------------- +// +// A WATCH over HTTP: create (its plan names the triage: the model, the +// threshold, the day's escalation cap), then Tick now — stage 1 through the +// editor's own door, then the triage as a `report-draft` job of its own, which +// finds no composed build to read: the run ends failed and the tick says why. +// A watch ticking over the fake models (below and above the threshold) is +// report-draft.spec's. +test("report-schedule: a watch — its plan names the triage; a tick with no build fails in its triage, saying so", async ({ request }) => { + test.setTimeout(120_000); + await resetData("empty"); + await settings(); + await writeChannelConfig("r6-chan", { name: "R6 channel" }); + const SERIES = `${testPaths().transcriptsDir}/reports/.series/r6-ops/series.json`; + const body = { action: "create", shape: "watch", topic: "R6 ops", id: "r6-ops", channels: ["r6-chan"], cadence: "daily 06:00", tz: "UTC", terms: "co-host", topics: ["guest"], threshold: { strong: 1, weak: 2 } }; + const plan = await ops(request, "report-schedule", { ...body, dryRun: true }); + expect(plan.status, plan.body.error).toBe(200); + expect((plan.body as { plan?: { triage?: unknown; article?: unknown } }).plan).toMatchObject({ article: null, triage: { provider: "local", threshold: { strong: 1, weak: 2 }, thresholdWords: "1 strong or 2 weak", topics: ["guest"], terms: "co-host" } }); + const triageFirst = await ops(request, "report-schedule", { ...body, triageFirst: true }); + expect(triageFirst.status).toBe(400); + expect(triageFirst.body.error).toMatch(/a watch always triages first/); + const made = await ops(request, "report-schedule", body); + expect(made.status, made.body.error).toBe(200); + const tick = await ops(request, "report-schedule", { action: "tick-now", id: "r6-ops" }); + expect(tick.status, tick.body.error).toBe(200); + await expect.poll(async () => (await readJson<{ ticks: unknown[] }>(SERIES)).ticks.length, { timeout: 90_000 }).toBeGreaterThan(0); + const s = await readJson<{ ticks: { status: string; reason?: string; triage?: { k: number; status: string } }[] }>(SERIES); + expect(s.ticks[0]).toMatchObject({ status: "failed", triage: { k: 1, status: "failed" } }); + expect(s.ticks[0].reason).toMatch(/^the triage failed: .*no composed build/); + const run = await readJson<{ status: string; error?: string; owner: string }>(`${testPaths().transcriptsDir}/reports/.triage/r6-ops/1/triage.json`); + expect(run).toMatchObject({ owner: "r6-ops", status: "failed" }); + expect(run.error).toMatch(/no composed build/); + const del = await ops(request, "report-schedule", { action: "delete", id: "r6-ops" }); + expect((del.body as { plan?: { removes: string; keeps: string[] } }).plan).toMatchObject({ removes: expect.stringContaining("the watch r6-ops"), keeps: [expect.stringContaining("its triage runs (reports/.triage/r6-ops/)")] }); +}); diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url"; // By relative path, as digest.spec.ts imports common: the test kit's fakes and // the synthetic corpus are plain .mjs. import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../common/testing/llm/fakeOllama.mjs"; import { LATE_RECORD, ORIGIN, withRecords, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; import { baseUrl } from "./baseUrl"; import { resetData, testPaths, writeChannelConfig, writeSettings } from "./helpers"; @@ -395,3 +396,97 @@ test("a living report ticks: R4's refresh runs its own stage 1, then nothing cha const cur = JSON.parse(await readFile(join(reportsDir(), "r5-living", "iterations", "current.json"), "utf8")); expect(cur.report).toBe(1); }); + +// ─── triage first: a watch (umtool R6) ─── +// +// `report-schedule` tick-now on a WATCH over the fake models: stage 1 through +// the editor's own door, then the triage — `report-draft {"task":"triage"}` on +// draft:local, the window judge on a fake OLLAMA (started here; the GPU +// arbiter in front of it), $0 — then, at or above the threshold, the sweep of +// the flagged ids on the fake Anthropic. Tick 1: a recording from yesterday +// is a candidate, the judge calls its line a mention only: below the +// threshold, no article, $0, the triage on the tick line. Tick 2: a recording +// UPLOADED LONG AGO is new BY ID (its transcript "landed late"), the judge +// flags it strong: escalated — a sweep restricted to it, as the watch's +// article, its trace's first line after the start the triage's tiers. + +test("a watch ticks over the fake models: below the threshold (a mention only) — no article, $0; a late transcript new by id, flagged strong — escalated to a sweep of it", async ({ request }) => { + test.setTimeout(240_000); + let ol: FakeOllama | null = null; + try { + ol = await startFakeOllama(); + await setup(); + // The triage runs on the local model: the fake ollama. + const settings = JSON.parse(await readFile(testPaths().settingsFile, "utf8")); + await writeSettings({ ...settings, generation: { ...settings.generation, ollamaUrl: ol.url } }); + await writeChannelConfig("synth-kitchen", { name: "Synth Kitchen" }); + const build = join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"); + const y = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10); + await writeDraftCorpus(build, { channels: withRecords([{ ...LATE_RECORD, uploadDate: y.replace(/-/g, "") }]) }); + const made = await schedule(request, { action: "create", shape: "watch", id: "r6-watch", topic: "Contest watch", question: "Did she judge the contest?", channels: ["synth-kitchen"], terms: "contest", cadence: "daily 06:00", tz: "UTC", model: "claude-sonnet-5-5" }); + expect(made.status, made.body.error).toBe(200); + + // Tick 1: the judge calls the new line a mention only. + ol.push(jsonReply({ relevant: true, items: [{ quote: "the contest results came out today", claim: "She mentions the results.", on_topic: true, strength: 1 }] })); + const before = api.requests.length; + const t1 = await schedule(request, { action: "tick-now", id: "r6-watch" }); + expect(t1.status, t1.body.error).toBe(200); + const job1 = await jobUntil(request, t1.body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 150_000); + const tail1 = (job1.tail ?? []).join("\n"); + expect(job1.job?.status ?? job1.status, tail1).toBe("done"); + let s = await seriesJson("r6-watch"); + const below = s.ticks.at(-1); + expect(below, tail1).toMatchObject({ status: "no-change", usd: 0, triage: { k: 1, status: "done", candidates: 1, flagged: 0, dismissed: 1, escalated: false } }); + expect(below.article).toBeUndefined(); + expect(below.reason).toMatch(/^triage: no flag \(threshold: 1 strong or 3 weak\) — below the threshold/); + expect(api.requests.length, "no API call below the threshold").toBe(before); + expect(ol.unloads.length).toBeGreaterThan(0); + const f1 = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "1", "triage.json"), "utf8")); + expect(f1).toMatchObject({ status: "done", provider: "local", cost: { tier0: 0, tier1: 0 }, tier0: { newBy: "date", candidates: [{ id: "contest-stream-04" }] } }); + expect(f1.tier1.dismissed[0]).toMatchObject({ id: "contest-stream-04", stage: "score", reason: "a mention only — She mentions the results." }); + const seen = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "seen.json"), "utf8")); + expect(seen.ids).toContain("contest-stream-04"); + + // Tick 2: an old recording whose transcript landed late — new by id; flagged strong. + const late = { ...LATE_RECORD, id: "contest-old-05", slug: "synth-kitchen/contest-old-05", title: "An old contest stream", uploadDate: "20250301", cues: [ + { start: 0, end: 4.8, text: "back then the contest was smaller" }, + { start: 5, end: 9.8, text: "I judged the contest that year myself" }, + { start: 10, end: 14.8, text: "we baked forty pies" }, + ] }; + await writeDraftCorpus(build, { channels: withRecords([{ ...LATE_RECORD, uploadDate: y.replace(/-/g, "") }, late]) }); + ol.push(jsonReply({ 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 }] })); + const link = `${ORIGIN}/?v=synth-kitchen%2Fcontest-old-05&t=5`; + api.push( + toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }), + toolTurn("write_report", { markdown: `# She judged it once\n\nAn old stream, newly transcribed.\n\n## The contest\n\n- She says she judged the contest that year: "I judged the contest that year myself" [An old contest stream @ 0:05](${link})\n` }), + textTurn("sweep.md: 1 finding."), + ); + const t2 = await schedule(request, { action: "tick-now", id: "r6-watch" }); + expect(t2.status, t2.body.error).toBe(200); + const job2 = await jobUntil(request, t2.body.jobId!, (st) => ["done", "failed", "cancelled"].includes(st), 180_000); + const tail2 = (job2.tail ?? []).join("\n"); + expect(job2.job?.status ?? job2.status, tail2).toBe("done"); + s = await seriesJson("r6-watch"); + const up = s.ticks.at(-1); + const article = `r6-watch-${new Date().toISOString().slice(0, 10)}`; + expect(up, tail2).toMatchObject({ status: "done", article, iteration: 1, triage: { k: 2, candidates: 1, flagged: 1, escalated: true, ids: ["contest-old-05"], usd: { tier1: 0 } } }); + expect(up.usd).toBeGreaterThan(0); + expect(up.triage.top[0]).toMatchObject({ id: "contest-old-05", line: "I judged the contest that year myself", score: 3 }); + const f2 = JSON.parse(await readFile(join(reportsDir(), ".triage", "r6-watch", "2", "triage.json"), "utf8")); + expect(f2).toMatchObject({ tier0: { newBy: "id", candidates: [{ id: "contest-old-05", date: "2025-03-01" }] }, escalation: { escalate: true, strong: 1 } }); + expect(f2.tier1.flags[0]).toMatchObject({ f: "f1", id: "contest-old-05", strength: "strong", checked: "cues", at: 5 }); + // The sweep: restricted to the flagged id, the triage named, its trace's first line after the start the tiers. + const it = await iterationJson(article, 1); + expect(it).toMatchObject({ kind: "sweep", status: "done", scope: { ids: ["contest-old-05"], triage: { owner: "r6-watch", k: 2 } } }); + const trace = (await readFile(join(reportsDir(), article, "iterations", "1", "trace.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + expect(trace[0]).toMatchObject({ t: "run", phase: "start" }); + expect(trace[1]).toMatchObject({ t: "triage", owner: "r6-watch", k: 2, flagged: ["contest-old-05"], escalated: true }); + const report = JSON.parse(await readFile(join(reportsDir(), article, "iterations", "1", "report.json"), "utf8")); + expect(report.title).toBe(`Contest watch · ${new Date().toISOString().slice(0, 10)}`); + expect(Object.values(report.citations).map((c) => (c as { id?: string }).id)).toEqual(["contest-old-05"]); + expect(api.remaining()).toBe(0); + expect(ol.remaining()).toBe(0); + } finally { + await ol?.close(); + } +}); diff --git a/umtool/app/api/research/triage/[schedule]/[k]/board/route.ts b/umtool/app/api/research/triage/[schedule]/[k]/board/route.ts @@ -0,0 +1,19 @@ +import { openTriageBoard } from "@/lib/research/triage"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// OPEN A TRIAGE AS A BOARD (R6; lib/research/triage.ts): POST makes, or brings +// up to date, the research case of the run's flags (`by: "triage"`) -- the +// escalation's article id, else `<schedule>-t<k>`. umtool is the one writer of +// case files; the editor's tick never writes one. +// POST -> { id, href, created, added, already, skipped } +// 409 the run flagged nothing (or a case.json that does not read) +export async function POST(_request: Request, ctx: { params: Promise<{ schedule: string; k: string }> }) { + try { + const { schedule, k } = await ctx.params; + return ok(await openTriageBoard(decodeURIComponent(schedule), Number(k))); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/triage/[schedule]/[k]/marks/route.ts b/umtool/app/api/research/triage/[schedule]/[k]/marks/route.ts @@ -0,0 +1,22 @@ +import { markFlag } from "@/lib/research/triage"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// MARK A FLAG (R6): the operator's right / wrong on one flag of a triage run, +// kept per schedule (umtool's own state, lib/research/triage-marks.mjs). +// POST {f: "f1", verdict: "right" | "wrong" | null} +// -> {marks (this run's, by flag), precision, suggestion} +// 400 a bad body; 404 no such run or flag; 409 a marks file that does not read +export async function POST(request: Request, ctx: { params: Promise<{ schedule: string; k: string }> }) { + try { + const { schedule, k } = await ctx.params; + const body = (await request.json().catch(() => null)) as { f?: unknown; verdict?: unknown } | null; + if (!body || typeof body.f !== "string") return Response.json({ error: 'send {"f": "<flag>", "verdict": "right" | "wrong" | null}' }, { status: 400 }); + const verdict = body.verdict === "right" || body.verdict === "wrong" ? body.verdict : body.verdict === null ? null : undefined; + if (verdict === undefined) return Response.json({ error: '"verdict" is "right", "wrong" or null' }, { status: 400 }); + return ok(await markFlag(decodeURIComponent(schedule), Number(k), body.f, verdict)); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/triage/[schedule]/[k]/route.ts b/umtool/app/api/research/triage/[schedule]/[k]/route.ts @@ -0,0 +1,18 @@ +import { readTriageRunView } from "@/lib/research/triage"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// ONE TRIAGE RUN (plans/umtool-redesign.md, R6; lib/research/triage.ts): +// GET -> TriageRunView (lib/research/triage-types.ts): the editor's +// triage.json, the tick that ran it, what it escalated to, the marks, +// the schedule's precision and the threshold the marks suggest +// 404 no such schedule or run +export async function GET(_request: Request, ctx: { params: Promise<{ schedule: string; k: string }> }) { + try { + const { schedule, k } = await ctx.params; + return ok(await readTriageRunView(decodeURIComponent(schedule), Number(k))); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/series/[id]/page.tsx b/umtool/app/series/[id]/page.tsx @@ -9,7 +9,12 @@ import { EmptyState } from "@/components/ui/empty-state"; import { Panel } from "@/components/ui/panel"; import { Table, TD, TH } from "@/components/ui/table"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; -import { articleHref, workHref } from "@/lib/hrefs"; +import { articleHref, triageHref, workHref } from "@/lib/hrefs"; +import { readScheduleTriage, triageBoardId } from "@/lib/research/triage"; +import { researchCaseHref } from "@/lib/research/hrefs"; +import type { ScheduleTriage } from "@/lib/research/triage-types"; +import { thresholdWords } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; +import { triagesFirst } from "yt-dlp-transcript-common/lib/report/schedule/types"; import { lifecycleOf, readLifecycle } from "@/lib/lifecycle"; import { readScheduleView } from "@/lib/schedules"; import type { Edition, ScheduleView, Tick } from "@/lib/schedule-types"; @@ -27,6 +32,11 @@ export const dynamic = "force-dynamic"; // spend, reason. The editor keeps the schedule (its report-schedule lane); // this page reads it from the article store and writes through the editor. // +// A WATCH (R6) has no editions: its page lists what its escalations FOUND +// (each tick's article and board), and every schedule that triages shows its +// triage runs (the tiers, each run's page), the precision of the flags the +// operator marked and the threshold the marks suggest. +// // A living report's schedule is its article's: /series/<article> goes there. // A static segment (`series`), so nothing else's catch-all takes it. // --------------------------------------------------------------------------- @@ -81,6 +91,9 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str const nextAt = v.nextTick ? Date.parse(v.nextTick) : NaN; const next = !v.paused && Number.isFinite(nextAt) ? editionWindowAt(v, nextAt) : null; const ticks = [...v.ticks].reverse(); + const watch = v.shape === "watch"; + const triage = triagesFirst(v) ? await readScheduleTriage(v).catch(() => null) : null; + const found = watch ? ticks.filter((t) => t.article && t.triage?.escalated) : []; return ( <div className="flex h-full flex-col"> <AppShell @@ -88,10 +101,17 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str crumbs={[...crumbs, { label: v.topic }]} meta={ <span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted" data-series-meta=""> - <span className={badgeVariants({ variant: "neutral", size: "sm" })}>series</span> - <span> - {editions.length} edition{editions.length === 1 ? "" : "s"} + <span className={badgeVariants({ variant: "neutral", size: "sm" })} data-series-shape={v.shape}> + {watch ? "watch" : "series"} </span> + {watch ? ( + <span>{found.length} found</span> + ) : ( + <span> + {editions.length} edition{editions.length === 1 ? "" : "s"} + </span> + )} + {triage && !watch && <span data-series-triage-first="">triage first</span>} <span className="font-mono text-meter" data-series-spent={v.spentUsd.toFixed(2)}> {usd(v.spentUsd)} spent </span> @@ -111,38 +131,55 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str /> <main className="deck-main flex flex-1 flex-col gap-4 px-4 pb-6 pt-3"> {v.running && !v.running.jobId.startsWith("pending-") && <TickProgress jobId={v.running.jobId} />} - <Panel - title="Editions" - aside={ - next ? ( - <span className="text-text-2" data-series-next=""> - {"window" in next ? ( - <> - next, {v.nextWords}: <span className="font-mono text-[11.5px]">{next.window.from} … {next.window.to}</span> - </> - ) : ( - nothingToCover(next.nextFrom) - )} - </span> + {watch ? ( + <Panel title="Found" aside={<span className="text-muted">{found.length ? "newest first" : triage ? `threshold ${thresholdWords(triage.threshold)}` : ""}</span>} className="w-full max-w-[1100px]" data-watch-found=""> + {found.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted" data-watch-empty=""> + Nothing escalated yet. {v.nextWords ? `The next tick is ${v.nextWords}.` : ""} + </p> ) : ( - <span className="text-muted">newest first</span> - ) - } - className="w-full max-w-[1100px]" - data-series-editions="" - > - {editions.length === 0 ? ( - <p className="m-0 text-[12.5px] text-muted" data-series-empty=""> - No edition yet. The first tick is {v.nextWords ?? "not planned (paused)"}; an edition covers whole days, up to the day before its tick. - </p> - ) : ( - <ol className="m-0 flex list-none flex-col p-0" aria-label="editions"> - {editions.map((e) => ( - <EditionRow key={e.n} e={e} /> - ))} - </ol> - )} - </Panel> + <ol className="m-0 flex list-none flex-col p-0" aria-label="found"> + {found.map((t) => ( + <FoundRow key={`${t.at}-${t.triage!.k}`} t={t} board={triageBoardId(v, t.triage!.k)} schedule={v.id} /> + ))} + </ol> + )} + </Panel> + ) : ( + <Panel + title="Editions" + aside={ + next ? ( + <span className="text-text-2" data-series-next=""> + {"window" in next ? ( + <> + next, {v.nextWords}: <span className="font-mono text-[11.5px]">{next.window.from} … {next.window.to}</span> + </> + ) : ( + nothingToCover(next.nextFrom) + )} + </span> + ) : ( + <span className="text-muted">newest first</span> + ) + } + className="w-full max-w-[1100px]" + data-series-editions="" + > + {editions.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted" data-series-empty=""> + No edition yet. The first tick is {v.nextWords ?? "not planned (paused)"}; an edition covers whole days, up to the day before its tick. + </p> + ) : ( + <ol className="m-0 flex list-none flex-col p-0" aria-label="editions"> + {editions.map((e) => ( + <EditionRow key={e.n} e={e} /> + ))} + </ol> + )} + </Panel> + )} + {triage && <TriagePanel id={v.id} t={triage} />} <Panel title="Ticks" aside={<span className="text-muted">{ticks.length} recorded</span>} className="w-full max-w-[1100px]" data-series-ticks=""> {ticks.length === 0 ? ( <p className="m-0 text-[12.5px] text-muted">Nothing has ticked yet.</p> @@ -160,7 +197,7 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str </thead> <tbody> {ticks.map((t, i) => ( - <TickRow key={`${t.at}-${i}`} t={t} /> + <TickRow key={`${t.at}-${i}`} t={t} schedule={v.id} /> ))} </tbody> </Table> @@ -200,7 +237,107 @@ function EditionRow({ e }: { e: Edition }) { ); } -function TickRow({ t }: { t: Tick }) { +function FoundRow({ t, board, schedule }: { t: Tick; board: string; schedule: string }) { + const top = t.triage?.top[0]; + return ( + <li data-found={t.article} className="grid grid-cols-[110px_minmax(0,1fr)_auto] items-baseline gap-x-3 border-b border-seam py-2 last:border-b-0"> + <span className="font-mono text-[11.5px] text-muted">{when(t.at)}</span> + <span className="min-w-0"> + <Link href={articleHref({ site: ARTICLES_KEY, id: t.article! })} prefetch={false} className="block truncate font-medium text-inherit hover:underline"> + {t.article} + </Link> + {top && <small className="block truncate font-serif text-[12.5px] text-text-2">“{top.line}” — {top.reason}</small>} + <small className="block text-[11.5px] text-muted-2"> + {t.triage!.flagged} flagged of {t.triage!.candidates} · {t.triage!.why} + </small> + </span> + <span className="flex items-center gap-2 text-[12px]"> + <Link href={researchCaseHref(board)} prefetch={false} className="ink-link" data-found-board={board}> + Board + </Link> + <Link href={triageHref(schedule, t.triage!.k)} prefetch={false} className="ink-link"> + Triage {t.triage!.k} + </Link> + <span className="font-mono text-meter">{usd(t.usd)}</span> + </span> + </li> + ); +} + +function TriagePanel({ id, t }: { id: string; t: ScheduleTriage }) { + const p = t.precision; + return ( + <Panel + title="Triage" + aside={ + <span className="text-text-2" data-precision={p.precision ?? ""}> + threshold {thresholdWords(t.threshold)} ·{" "} + {p.marked ? ( + <> + precision <span className="font-mono text-meter">{Math.round((p.precision ?? 0) * 100)}%</span> over {p.marked} marked + </> + ) : ( + "no flag marked yet" + )} + </span> + } + className="w-full max-w-[1100px]" + data-series-triage="" + > + <p className="m-0 mb-2 text-[12.5px] text-text-2" data-suggestion={t.suggestion.changed ? "change" : "keep"}> + {t.suggestion.changed ? ( + <> + Suggested threshold: <b className="font-semibold">{thresholdWords(t.suggestion.threshold)}</b> — {t.suggestion.why} + </> + ) : ( + t.suggestion.why + )} + </p> + {t.runs.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted">No triage has run yet.</p> + ) : ( + <Table aria-label="triage runs"> + <thead> + <tr> + <TH>Run</TH> + <TH>When</TH> + <TH>Tiers</TH> + <TH>Escalation</TH> + <TH className="text-right">Tier 1</TH> + <TH className="text-right">Tier 2</TH> + </tr> + </thead> + <tbody> + {t.runs.map((r) => ( + <tr key={r.k} data-triage-run={r.k} data-escalated={r.escalated ? "yes" : "no"}> + <TD> + <Link href={r.href} prefetch={false} className="ink-link font-mono text-[12px]"> + {id} · {r.k} + </Link> + </TD> + <TD className="whitespace-nowrap font-mono text-[11.5px]">{when(r.at)}</TD> + <TD className="text-[12px]"> + {r.status === "done" ? `${r.candidates} candidates · ${r.flagged} flagged · ${r.dismissed} dismissed` : r.status} + </TD> + <TD className="text-[12px]"> + <span className={badgeVariants({ variant: r.escalated ? "meter" : "info", size: "sm" })}>{r.escalated ? "escalated" : "below"}</span> <span className="text-text-2">{r.why}</span> + </TD> + <TD numeric className="text-meter"> + {usd(r.usd.tier1)} + </TD> + <TD numeric className="text-meter"> + {usd(r.usd.tier2)} + </TD> + </tr> + ))} + </tbody> + </Table> + )} + </Panel> + ); +} + +function TickRow({ t, schedule }: { t: Tick; schedule: string }) { return ( <tr data-tick-status={t.status}> <TD className="whitespace-nowrap font-mono text-[11.5px]">{when(t.at)}</TD> @@ -208,7 +345,14 @@ function TickRow({ t }: { t: Tick }) { <TD> <span className={badgeVariants({ variant: TICK_TONE[t.status] ?? "neutral", size: "sm" })}>{t.status}</span> </TD> - <TD className="font-mono text-[11.5px]">{t.edition ? `#${t.edition}` : t.iteration ? `i${t.iteration}` : "—"}</TD> + <TD className="font-mono text-[11.5px]"> + {t.edition ? `#${t.edition}` : t.iteration ? `i${t.iteration}` : "—"} + {t.triage && ( + <Link href={triageHref(schedule, t.triage.k)} prefetch={false} className="ink-link ml-2" data-tick-triage={t.triage.k}> + triage {t.triage.k} + </Link> + )} + </TD> <TD numeric className="text-meter"> {usd(t.usd)} {t.estimateUsd !== undefined && t.status === "held-by-cap" ? <small className="block text-muted">up to {usd(t.estimateUsd)}</small> : null} @@ -232,8 +376,22 @@ function Scope({ v }: { v: ScheduleView }) { <dd className="m-0 font-mono text-[12px]">{v.scope.case}</dd> </> )} - <dt className="text-muted">Window check</dt> + <dt className="text-muted">{triagesFirst(v) ? "Terms" : "Window check"}</dt> <dd className="m-0">{v.scope.terms ? <span className="font-mono text-[12px]">{v.scope.terms}</span> : "any recording in scope"}</dd> + {v.scope.topics?.length ? ( + <> + <dt className="text-muted">Topics</dt> + <dd className="m-0">{v.scope.topics.join(", ")}</dd> + </> + ) : null} + {triagesFirst(v) && ( + <> + <dt className="text-muted">Triage</dt> + <dd className="m-0" data-scope-triage=""> + {v.shape === "watch" ? "every tick" : "first, every tick"} · {v.triage?.threshold ? `threshold ${thresholdWords(v.triage.threshold)}` : "the policy's threshold"} + </dd> + </> + )} <dt className="text-muted">Cadence</dt> <dd className="m-0"> {v.cadenceWords} <span className="text-muted">({v.tz})</span> diff --git a/umtool/app/series/[id]/triage/[k]/page.tsx b/umtool/app/series/[id]/triage/[k]/page.tsx @@ -0,0 +1,47 @@ +import Link from "next/link"; +import AppHeader from "@/components/shell/AppHeader"; +import AppRail from "@/components/shell/AppRail"; +import TriageView from "@/components/series/TriageView"; +import { EmptyState } from "@/components/ui/empty-state"; +import { seriesHref, workHref } from "@/lib/hrefs"; +import { readTriageRunView } from "@/lib/research/triage"; +import type { TriageRunView } from "@/lib/research/triage-types"; + +export const dynamic = "force-dynamic"; + +// ONE TRIAGE RUN of a recurring report (plans/umtool-redesign.md, R6): its +// tiers -- the candidates, each flag and dismissal with its reason, what +// escalated and why, the spend per tier -- and the marks +// (components/series/TriageView.tsx). Under the series' static segment; a +// living report's runs are here too (its schedule's id is its article's). +export default async function TriagePage({ params }: { params: Promise<{ id: string; k: string }> }) { + const { id: raw, k } = await params; + const id = decodeURIComponent(raw); + let view: TriageRunView | null = null; + let error: { status: number; message: string } | null = null; + try { + view = await readTriageRunView(id, Number(k)); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + return ( + <div className="flex h-full flex-col"> + <AppRail active="work" /> + {view ? ( + <TriageView key={`${view.schedule.id}/${view.k}`} initial={view} /> + ) : ( + <> + <AppHeader crumbs={[{ href: workHref({ recurring: "1" }), label: "work" }, { href: seriesHref(id), label: id }, { label: `Triage · run ${k}` }]} /> + <div className="px-7 pt-6"> + <EmptyState title={error?.status === 404 ? `No triage run ${k} of ${id}` : "This triage run cannot be read"}> + <span role="alert">{error?.message}</span>{" "} + <Link prefetch={false} href={seriesHref(id)} className="ink-link"> + The schedule + </Link> + </EmptyState> + </div> + </> + )} + </div> + ); +} diff --git a/umtool/components/create/RecurringForm.tsx b/umtool/components/create/RecurringForm.tsx @@ -17,6 +17,12 @@ import type { Cadence } from "@/lib/schedule-types"; // // Living report one article kept current // Series a new dated edition each tick +// Watch (R6) no article until a triage finds something +// +// R6: a living report or a series may TRIAGE FIRST (the cheap pass: only what +// it flags reaches the sweep), at a threshold — "escalate on N strong flags +// or N of any strength"; a watch always does, over its terms and digest +// topics. // // -- then PLAN, THEN CONFIRM: "Plan the schedule" asks the editor what it // would make (its `report-schedule` create with dryRun: the first tick's time, @@ -28,12 +34,16 @@ import type { Cadence } from "@/lib/schedule-types"; // report", the radios "Living report" / "Series", the fields "topic", // "question", "window check", the scope radios "Channels" / "A board", the // board select "board", the plan region "plan recurring report", the buttons -// "Plan the schedule", "Start the schedule", "Change it". +// "Plan the schedule", "Start the schedule", "Change it"; R6: the radio +// "Watch", the checkbox "triage first", the fields "terms", "topics", +// "strong flags", "flags of any strength". // --------------------------------------------------------------------------- +type Shape = "living" | "series" | "watch"; + type Plan = { id: string; - shape: "living" | "series"; + shape: Shape; article: string | null; cadence: string; tz: string; @@ -46,12 +56,14 @@ type Plan = { capUsd: number | null; dailyCapUsd: number; existingArticle: boolean; + triage: { model: string; provider: "api" | "local"; threshold: { strong: number; weak: number }; thresholdWords: string; maxEscalationsPerDay: number; topics: string[]; terms: string | null } | null; warnings: string[]; }; const SHAPES = [ { id: "living", label: "Living report", sub: "One article kept current: each tick fetches what is new and updates it." }, { id: "series", label: "Series", sub: "A new dated edition each tick, over only the window since the last one." }, + { id: "watch", label: "Watch", sub: "No article until something is found: each tick triages what is new, and only what it flags is researched." }, ] as const; const usd = (n: number) => `$${n.toFixed(2)}`; @@ -71,7 +83,11 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: const router = useRouter(); const hydrated = useHydrated(); const boards = cases.filter((c) => (c.scope.channels ?? []).length > 0); - const [shape, setShape] = useState<"living" | "series">("series"); + const [shape, setShape] = useState<Shape>("series"); + const [triageFirst, setTriageFirst] = useState(false); + const [topics, setTopics] = useState(""); + const [strong, setStrong] = useState("1"); + const [weak, setWeak] = useState("3"); const [topic, setTopic] = useState(""); const [question, setQuestion] = useState(""); const [scopeBy, setScopeBy] = useState<"channels" | "board">(initialCase && boards.some((c) => c.id === initialCase) ? "board" : "channels"); @@ -93,14 +109,22 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: // A board's terms are its query, unless the operator typed their own. const windowTerms = terms.trim() || (scopeBy === "board" ? (chosen?.scope.query ?? "") : ""); + const triaged = shape === "watch" || triageFirst; + const threshold = () => { + const n = (v: string) => (/^\d{1,2}$/.test(v.trim()) ? Number(v.trim()) : NaN); + const t = { strong: n(strong), weak: n(weak) }; + return Number.isFinite(t.strong) && Number.isFinite(t.weak) ? t : null; + }; const body = () => ({ action: "create", shape, + ...(triageFirst && shape !== "watch" ? { triageFirst: true } : {}), + ...(triaged ? { ...(threshold() && (threshold()!.strong !== 1 || threshold()!.weak !== 3) ? { threshold: threshold() } : {}), ...(topics.trim() ? { topics: topics.split(",").map((t) => t.trim()).filter(Boolean) } : {}) } : {}), topic: topic.trim(), ...(question.trim() ? { question: question.trim() } : {}), channels: scopeChannels, ...(scopeBy === "board" && chosen ? { case: chosen.id, ...(chosen.scope.dateFrom ? { from: ymd(chosen.scope.dateFrom) } : {}), ...(chosen.scope.regex && !terms.trim() ? { regex: true } : {}) } : {}), - ...(shape === "series" && windowTerms ? { terms: windowTerms } : {}), + ...((shape === "series" || triaged) && windowTerms ? { terms: windowTerms } : {}), // On the editor's clock: it keeps the schedule (the plan names its zone). cadence, ...(shape === "living" && autoCurrent ? { autoMakeCurrent: true } : {}), @@ -109,6 +133,7 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: const ask = async () => { if (!topic.trim()) return setError("name the topic"); if (!scopeChannels.length) return setError(scopeBy === "board" ? "that board names no channel" : "pick at least one channel"); + if (triaged && !threshold()) return setError("the threshold is two whole numbers (0: that rule off)"); setBusy(true); setError(null); try { @@ -169,7 +194,7 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: ))} </fieldset> <div className="flex flex-wrap items-end gap-x-3 gap-y-2.5"> - <Field label="Topic" hint={shape === "series" ? "Each edition is titled “<topic> · week of <date>”" : "The article's name"} className="min-w-[16rem] flex-1"> + <Field label="Topic" hint={shape === "series" ? "Each edition is titled “<topic> · week of <date>”" : shape === "watch" ? "What it found is titled “<topic> · <date>”" : "The article's name"} className="min-w-[16rem] flex-1"> <Input autoFocus data-autofocus="" required value={topic} onChange={(e) => edit(setTopic)(e.target.value)} aria-label="topic" placeholder="e.g. Co-host updates" /> </Field> <Field label="Question" hint="What each tick asks; the topic, unless asked" className="min-w-[16rem] flex-[2]"> @@ -203,7 +228,11 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: </fieldset> <div className="flex flex-wrap items-end gap-x-5 gap-y-2.5"> <CadenceFields value={cadence} onChange={edit(setCadence)} disabled={busy} /> - {shape === "series" ? ( + {shape === "watch" ? ( + <Field label="Terms" hint="What makes a new recording a candidate (enumerate, aliases too)" className="min-w-[14rem] flex-1"> + <Input value={terms} onChange={(e) => edit(setTerms)(e.target.value)} aria-label="terms" placeholder={chosen?.scope.query ?? "e.g. co-host"} /> + </Field> + ) : shape === "series" ? ( <Field label="Window check" hint="What a window must match to be worth a sweep; empty: any recording" className="min-w-[14rem] flex-1"> <Input value={terms} onChange={(e) => edit(setTerms)(e.target.value)} aria-label="window check" placeholder={chosen?.scope.query ?? "e.g. co-host|guest"} /> </Field> @@ -214,10 +243,33 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: </label> )} </div> + <fieldset className="m-0 flex flex-wrap items-end gap-x-4 gap-y-2 border-0 p-0" aria-label="triage" data-triage-fields=""> + {shape !== "watch" && ( + <label className="flex items-center gap-1.5 pb-1 text-[12.5px]"> + <input type="checkbox" checked={triageFirst} onChange={(e) => edit(setTriageFirst)(e.target.checked)} aria-label="triage first" /> + Triage first + </label> + )} + {triaged && ( + <> + <Field label="Topics" hint="Digest topic tags that make a recording a candidate" className="min-w-[12rem] flex-1"> + <Input value={topics} onChange={(e) => edit(setTopics)(e.target.value)} aria-label="topics" placeholder="e.g. guest, panel" /> + </Field> + <Field label="Escalate on" hint="strong flags, or flags of any strength (0: off)"> + <span className="flex items-center gap-1.5 text-[12.5px]"> + <Input value={strong} onChange={(e) => edit(setStrong)(e.target.value)} aria-label="strong flags" inputMode="numeric" className="w-12 text-center" /> + strong or + <Input value={weak} onChange={(e) => edit(setWeak)(e.target.value)} aria-label="flags of any strength" inputMode="numeric" className="w-12 text-center" /> + any + </span> + </Field> + </> + )} + </fieldset> {plan && ( <section role="region" aria-label="plan recurring report" data-plan-schedule={plan.id} className="rounded-[3px] border border-seam-2 bg-ink p-3 text-[12.5px]"> <p className="m-0 font-medium" data-plan-first-tick={plan.firstTick}> - {plan.shape === "series" ? "Series" : "Living report"} <span className="font-mono">{plan.id}</span> · {plan.cadence} · first tick {plan.firstTickWords}{" "} + {plan.shape === "series" ? "Series" : plan.shape === "watch" ? "Watch" : "Living report"} <span className="font-mono">{plan.id}</span> · {plan.cadence} · first tick {plan.firstTickWords}{" "} <span className="text-muted">({plan.tz})</span> </p> <ul className="m-0 mt-1 list-disc pl-5 text-text-2"> @@ -231,6 +283,12 @@ export default function RecurringForm({ cases, initialCase, onCancel }: { cases: </li> )} {plan.shape === "living" && <li>{plan.existingArticle ? `keeps ${plan.article} current` : `a new article, ${plan.article}: its first tick is its first sweep`}</li>} + {plan.triage && ( + <li data-plan-triage={plan.triage.thresholdWords}> + triage first on {plan.triage.model} ({plan.triage.provider === "local" ? "$0" : "metered"}): escalates on {plan.triage.thresholdWords} · at most {plan.triage.maxEscalationsPerDay || "any number of"} escalation + {plan.triage.maxEscalationsPerDay === 1 ? "" : "s"} a day{plan.shape === "watch" ? "; no article until one does" : ""} + </li> + )} </ul> {plan.warnings.length > 0 && ( <ul aria-label="worth knowing" className="m-0 mt-1 list-disc pl-5 text-doubt-text"> diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -23,6 +23,7 @@ import { } from "@/lib/research/hrefs"; import HandoffDialog from "./HandoffDialog"; import { runHref } from "@/lib/research/runs-hrefs"; +import { triageHref } from "@/lib/hrefs"; import QuoteSlip, { quoteLineId } from "./QuoteSlip"; // --------------------------------------------------------------------------- @@ -572,6 +573,16 @@ export default function BoardView({ initial }: { initial: CaseView }) { </dd> </> )} + {doc.triage && ( + <> + <dt className="text-muted">From triage</dt> + <dd className="m-0 text-text-2" data-case-triage=""> + <Link prefetch={false} href={triageHref(doc.triage.schedule, doc.triage.k)} className="ink-link font-mono text-[11.5px]"> + {doc.triage.schedule} · run {doc.triage.k} + </Link> + </dd> + </> + )} </dl> <div className="grid gap-1.5"> <Link prefetch={false} href={researchFromCaseHref(doc)} className={`${buttonVariants({ variant: "outline", size: "sm" })} justify-self-start`}> diff --git a/umtool/components/research/QuoteSlip.tsx b/umtool/components/research/QuoteSlip.tsx @@ -190,6 +190,11 @@ export default function QuoteSlip({ by agent </span> )} + {q.by === "triage" && ( + <span data-by="triage" className="font-mono text-[11px] text-text-2" title="Flagged by a triage's window judge (the line checked verbatim); not a person's pin, not yet researched"> + by triage + </span> + )} {c.kind !== "post" && (q.speakerChecked ? ( <span data-speaker="checked" className="text-muted">Speaker checked</span> diff --git a/umtool/components/research/RunView.tsx b/umtool/components/research/RunView.tsx @@ -166,6 +166,14 @@ function Detail({ step }: { step: RunStep }) { ))} </dl> )} + {d.triage && ( + <section className="grid gap-1.5" data-run-triage={`${d.triage.owner}/${d.triage.k}`}> + {d.triage.flagged.length > 0 && <Ids ids={d.triage.flagged} max={40} />} + <Link prefetch={false} href={d.triage.href} className="ink-link justify-self-start text-[12.5px]"> + Triage {d.triage.owner} · run {d.triage.k}: each flag and dismissal with its reason + </Link> + </section> + )} {d.text && <p className="m-0 max-w-[72ch] whitespace-pre-wrap text-[12.5px] text-text-2" data-model-text="">{d.text}</p>} {d.calls.length > 0 && ( <ul className="m-0 grid list-none gap-0.5 p-0 font-mono text-[11.5px] text-text-2" data-calls=""> diff --git a/umtool/components/series/TriageView.tsx b/umtool/components/series/TriageView.tsx @@ -0,0 +1,462 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import AppHeader from "@/components/shell/AppHeader"; +import { buttonVariants } from "@/components/ui/button"; +import { badgeVariants } from "@/components/ui/badge"; +import { KeyHint } from "@/components/ui/kbd"; +import { LitList, type LitDetail } from "@/components/ui/lit-list"; +import { LitLine } from "@/components/ui/lit-line"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { triageHref, workHref } from "@/lib/hrefs"; +import type { FlagMark, TriageRunView } from "@/lib/research/triage-types"; +import { thresholdWords, type TriageDismissal, type TriageFlag } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// ONE TRIAGE RUN (plans/umtool-redesign.md, R6): the tiers of a recurring +// report's cheap pass, transparent -- +// +// tier 0 code, $0: what was new (by id since the last run), which of it +// matched the terms or the digest topics -- the candidates +// tier 1 the window judge (the local model, or the extractor): each FLAG +// with its verbatim line on the reader surface, its cite and the +// judge's reason; each DISMISSAL with why (not relevant, not +// verbatim, a mention only) +// tier 2 what escalated and why: the sweep of the flagged recordings (its +// run page, its findings, its spend) -- or that nothing did +// +// ONE lit list of the flags then the dismissals; `y` / `x` marks the lit flag +// right or wrong (`u` unmarks), kept per schedule: the schedule's precision +// and the threshold the marks suggest (a suggestion, never applied). `b` opens +// the flags as a research board (`by: triage`). The editor wrote the run; +// umtool writes only the marks and the board. +// --------------------------------------------------------------------------- + +const money = (v: number | null | undefined) => (typeof v === "number" ? `$${v.toFixed(2)}` : "—"); +const mmss = (s: number) => { + const t = Math.floor(s); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; +const when = (iso: string | null | undefined) => (iso ? `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC` : ""); +const pct = (v: number | null) => (v === null ? "—" : `${Math.round(v * 100)}%`); + +const STAGE_WORDS: Record<TriageDismissal["stage"], string> = { judge: "not relevant", verbatim: "not verbatim", score: "too weak", read: "not read" }; + +/** Source words: the reader surface. */ +function Paper({ children, className, ...props }: React.ComponentProps<"div">) { + return ( + <div className={cn("rounded-[2px] bg-reader px-3.5 py-2.5 text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]", className)} {...props}> + {children} + </div> + ); +} + +type Lit = { kind: "flag"; flag: TriageFlag } | { kind: "dismissal"; d: TriageDismissal; i: number }; + +export default function TriageView({ initial }: { initial: TriageRunView }) { + const hydrated = useHydrated(); + const [view, setView] = useState(initial); + const [litId, setLitId] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState<{ text: string; tone: "ok" | "error"; href?: string } | null>(null); + const listRef = useRef<HTMLDivElement>(null); + const f = view.file; + const flags = useMemo(() => [...(f.tier1?.flags ?? [])].sort((a, b) => b.score - a.score || Number(a.f.slice(1)) - Number(b.f.slice(1))), [f.tier1]); + const dismissed = f.tier1?.dismissed ?? []; + const items: { id: string; lit: Lit }[] = useMemo( + () => [...flags.map((x) => ({ id: x.f, lit: { kind: "flag" as const, flag: x } })), ...dismissed.map((d, i) => ({ id: `d${i + 1}`, lit: { kind: "dismissal" as const, d, i } }))], + [flags, dismissed], + ); + const lit = items.find((x) => x.id === litId)?.lit ?? items[0]?.lit ?? null; + const onLight = useCallback((d: LitDetail) => setLitId(d.id), []); + + const mark = useCallback( + async (flag: TriageFlag, verdict: "right" | "wrong" | null) => { + setBusy(true); + setStatus(null); + try { + const r = await fetch(`/api/research/triage/${encodeURIComponent(view.schedule.id)}/${view.k}/marks`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ f: flag.f, verdict }), + }); + const j = (await r.json().catch(() => null)) as { error?: string; marks?: Record<string, FlagMark>; precision?: TriageRunView["precision"]; suggestion?: TriageRunView["suggestion"] } | null; + if (!r.ok || !j?.marks) throw new Error(j?.error ?? `HTTP ${r.status}`); + setView((v) => ({ ...v, marks: j.marks!, precision: j.precision!, suggestion: j.suggestion! })); + setStatus({ tone: "ok", text: verdict ? `${flag.f} marked ${verdict}` : `${flag.f} unmarked` }); + } catch (e) { + setStatus({ tone: "error", text: (e as Error).message }); + } finally { + setBusy(false); + } + }, + [view.schedule.id, view.k], + ); + + const openBoard = useCallback(async () => { + setBusy(true); + setStatus(null); + try { + const r = await fetch(`/api/research/triage/${encodeURIComponent(view.schedule.id)}/${view.k}/board`, { method: "POST" }); + const j = (await r.json().catch(() => null)) as { error?: string; id?: string; href?: string; created?: boolean; added?: number; already?: number } | null; + if (!r.ok || !j?.href) throw new Error(j?.error ?? `HTTP ${r.status}`); + setStatus({ tone: "ok", href: j.href, text: `${j.created ? "Board made" : "Board updated"}: ${j.added ?? 0} ${j.added === 1 ? "flag" : "flags"} added${j.already ? `, ${j.already} already on it` : ""}` }); + setView((v) => ({ ...v, board: { ...v.board, exists: true, quotes: v.board.quotes + (j.added ?? 0) } })); + } catch (e) { + setStatus({ tone: "error", text: (e as Error).message }); + } finally { + setBusy(false); + } + }, [view.schedule.id, view.k]); + + // Keys: y right, x wrong, u unmark (the lit flag); b opens the board. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; + if ((e.target as HTMLElement | null)?.closest?.("input, textarea, select, [contenteditable], dialog")) return; + if (busy) return; + if (e.key === "b" && flags.length) { + e.preventDefault(); + void openBoard(); + return; + } + if (lit?.kind !== "flag") return; + const verdict = e.key === "y" ? "right" : e.key === "x" ? "wrong" : e.key === "u" ? null : undefined; + if (verdict === undefined) return; + e.preventDefault(); + void mark(lit.flag, verdict); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, [busy, flags.length, lit, mark, openBoard]); + + const t0 = f.tier0; + const t1 = f.tier1; + const esc = f.escalation; + const t2 = view.tier2; + const capped = view.tick?.triage?.capped ?? null; + const p = view.precision; + + return ( + <> + <AppHeader + crumbs={[{ href: workHref({ recurring: "1" }), label: "work" }, { href: view.schedule.href, label: view.schedule.topic }, { label: `Triage · run ${view.k}` }]} + meta={ + <span className="micro" data-triage-status={f.status}> + Triage · {view.schedule.shape} · {f.status} + </span> + } + actions={ + <> + {view.runs.length > 1 && ( + <nav aria-label="Runs" className="flex items-center gap-1" data-run-picker=""> + <span className="micro mr-1">Run</span> + {view.runs.slice(0, 12).map((k) => ( + <Link + key={k} + prefetch={false} + href={triageHref(view.schedule.id, k)} + aria-current={k === view.k ? "page" : undefined} + className={cn(buttonVariants({ variant: k === view.k ? "outline" : "quiet", size: "sm" }), "font-mono", k === view.k && "border-muted text-text")} + > + {k} + </Link> + ))} + </nav> + )} + <button type="button" disabled={!hydrated || busy || !flags.length} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void openBoard()} data-open-board=""> + {view.board.exists ? "Update the board" : "Open as a board"} <kbd>b</kbd> + </button> + </> + } + below={ + <div className="grid gap-1.5 pt-1"> + <p className="m-0 max-w-[90ch] text-[13px] text-text" data-triage-question=""> + {f.question} + </p> + <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12.5px] text-muted" data-triage-meta=""> + <span>{f.model}</span> + <span className="text-seam-2">·</span> + <span>{f.scope.channels.join(", ")}</span> + {f.terms && ( + <> + <span className="text-seam-2">·</span> + <span className="font-mono text-[12px]">{f.terms}</span> + </> + )} + {f.topics.length > 0 && ( + <> + <span className="text-seam-2">·</span> + <span>topics {f.topics.join(", ")}</span> + </> + )} + <span className="text-seam-2">·</span> + <span>{when(f.startedAt ?? f.createdAt)}</span> + <span className="text-seam-2">·</span> + <span>threshold {thresholdWords(f.threshold)}</span> + </div> + {(f.warnings.length > 0 || f.error) && ( + <div className="grid gap-0.5 text-[12px] text-muted-2" data-triage-notes=""> + {f.warnings.map((w) => ( + <p key={w} className="m-0"> + {w} + </p> + ))} + {f.error && <p className="m-0 text-reject-text">{f.error}</p>} + </div> + )} + </div> + } + /> + <div className="grid min-h-0 flex-1 grid-cols-[minmax(300px,380px)_minmax(0,1fr)] overflow-hidden"> + <div ref={listRef} className="min-h-0 overflow-auto border-r border-seam pb-4 pt-2"> + {items.length === 0 ? ( + <p className="m-0 px-4 py-3 text-[12.5px] text-muted" data-triage-empty=""> + {f.status === "done" ? (t0?.candidates.length ? "The judge flagged and dismissed nothing." : "No candidate: nothing new matched.") : `The run is ${f.status}.`} + </p> + ) : ( + <LitList label="Flags and dismissals" global onLight={onLight}> + {flags.length > 0 && <h2 className="micro m-0 px-4 pb-1 pt-1.5">Flags <span className="font-mono normal-case tracking-normal text-meter">{flags.length}</span></h2>} + {flags.map((x) => { + const m = view.marks[x.f]; + return ( + <LitLine key={x.f} id={x.f} data-flag={x.f} data-strength={x.strength} data-mark={m?.verdict ?? "none"} className="grid grid-cols-[30px_minmax(0,1fr)_auto] items-baseline gap-x-2 py-[7px]"> + <span className="font-mono text-[11px] text-muted-2">{x.f}</span> + <span className="min-w-0"> + <span className="block truncate font-serif text-[13.5px] text-text">“{x.line}”</span> + <small className="block truncate text-[11px] text-muted-2"> + {x.title ?? x.id} @ {mmss(x.at)} · {x.reason} + </small> + </span> + <span className="flex items-center gap-1"> + <span className={badgeVariants({ variant: x.strength === "strong" ? "meter" : "neutral", size: "sm" })}>{x.strength}</span> + {m && <span className={badgeVariants({ variant: m.verdict === "right" ? "on" : "blocking", size: "sm" })}>{m.verdict}</span>} + </span> + </LitLine> + ); + })} + {dismissed.length > 0 && <h2 className="micro m-0 px-4 pb-1 pt-3">Dismissed <span className="font-mono normal-case tracking-normal text-meter">{dismissed.length}</span></h2>} + {dismissed.map((d, i) => ( + <LitLine key={`d${i + 1}`} id={`d${i + 1}`} data-dismissal={d.stage} className="grid grid-cols-[30px_minmax(0,1fr)_auto] items-baseline gap-x-2 py-[6px] opacity-80"> + <span className="font-mono text-[11px] text-muted-2">d{i + 1}</span> + <span className="min-w-0"> + <span className={cn("block truncate text-[12.5px]", d.line ? "font-serif text-text-2" : "text-muted")}>{d.line ? `“${d.line}”` : `${d.title ?? d.id}${d.window ? ` @ ${mmss(d.window.start)}–${mmss(d.window.end)}` : ""}`}</span> + <small className="block truncate text-[11px] text-muted-2">{d.reason}</small> + </span> + <span className={badgeVariants({ variant: d.stage === "verbatim" ? "blocking" : "info", size: "sm" })}>{STAGE_WORDS[d.stage]}</span> + </LitLine> + ))} + </LitList> + )} + </div> + <div className="grid min-h-0 content-start gap-[18px] overflow-auto px-[26px] py-[18px]"> + <div className="grid grid-cols-3 gap-2.5" data-tiers=""> + <section className="rounded-[3px] border border-seam bg-panel px-3 py-2.5" data-tier="0"> + <span className="micro mb-1.5 flex justify-between"> + <span>Tier 0 · code</span> + <span className="font-mono normal-case tracking-normal text-meter">{money(f.cost.tier0)}</span> + </span> + <p className="m-0 text-[12.5px] text-text-2"> + {t0 ? ( + <> + <span className="font-mono text-meter">{t0.candidates.length}</span> candidate{t0.candidates.length === 1 ? "" : "s"} of{" "} + <span className="font-mono text-meter">{t0.newCount}</span> new{" "} + {t0.newBy === "id" ? "by id since the last run" : t0.newBy === "date" ? `since ${f.since ?? "the start"}` : "named"} + {t0.scanned ? ` · ${t0.scanned} in scope` : ""} + {t0.cut.length ? <span className="text-doubt-text"> · {t0.cut.length} past the cap</span> : null} + {t0.partial ? <span className="text-doubt-text"> · partial</span> : null} + </> + ) : ( + "not run" + )} + </p> + </section> + <section className="rounded-[3px] border border-seam bg-panel px-3 py-2.5" data-tier="1"> + <span className="micro mb-1.5 flex justify-between"> + <span>Tier 1 · {f.provider === "local" ? "local model" : "extractor"}</span> + <span className="font-mono normal-case tracking-normal text-meter" data-tier1-usd={f.cost.tier1}> + {money(f.cost.tier1)} + </span> + </span> + <p className="m-0 text-[12.5px] text-text-2"> + {t1 ? ( + <> + <span className="font-mono text-meter">{t1.flags.length}</span> flagged · <span className="font-mono text-meter">{t1.dismissed.length}</span> dismissed · {t1.read} read, {t1.chunks} window + {t1.chunks === 1 ? "" : "s"} judged + </> + ) : ( + "not run" + )} + </p> + </section> + <section className="rounded-[3px] border border-seam bg-panel px-3 py-2.5" data-tier="2" data-escalated={view.tick?.triage?.escalated ? "yes" : "no"}> + <span className="micro mb-1.5 flex justify-between"> + <span>Tier 2 · sweep</span> + <span className="font-mono normal-case tracking-normal text-meter">{money(t2?.usd ?? view.tick?.triage?.usd.tier2 ?? 0)}</span> + </span> + <p className="m-0 text-[12.5px] text-text-2"> + {t2 ? ( + <> + <Link prefetch={false} href={t2.runHref} className="ink-link font-mono text-[12px]" data-tier2-run=""> + {t2.article} i{t2.n} + </Link>{" "} + · {t2.status ?? "?"} + {t2.findings !== null ? ` · ${t2.findings} finding${t2.findings === 1 ? "" : "s"}` : ""} + </> + ) : capped ? ( + <span className="text-doubt-text">held: {capped}</span> + ) : esc?.escalate ? ( + "escalated (the step did not make an iteration)" + ) : ( + "not escalated: $0 API" + )} + </p> + </section> + </div> + <p className={cn("m-0 text-[13px]", esc?.escalate ? "text-text" : "text-text-2")} data-escalation={esc?.escalate ? "escalate" : "below"}> + <b className="font-semibold">{esc ? (esc.escalate ? (capped ? "Would escalate" : "Escalated") : "Below the threshold") : f.summary}</b> + {esc ? ` — ${esc.why}` : ""} + {view.tick ? <span className="text-muted"> · the tick ended {view.tick.status}, {money(view.tick.usd)} in all</span> : null} + </p> + {lit?.kind === "flag" && ( + <section className="grid gap-2" data-detail={lit.flag.f}> + <span className="micro"> + {lit.flag.f} · {lit.flag.strength} flag · score {lit.flag.score} · checked {lit.flag.checked === "cues" ? "against the cues" : "in its window"} + </span> + <Paper> + <p className="m-0 font-serif text-[15px] leading-[1.45]">“{lit.flag.line}”</p> + <div className="mt-1 truncate font-mono text-[10.5px] text-reader-dim"> + {lit.flag.url ? ( + <a href={lit.flag.url} target="_blank" rel="noreferrer" className="hover:underline"> + {lit.flag.title ?? lit.flag.id} @ {mmss(lit.flag.at)} + </a> + ) : ( + `${lit.flag.title ?? lit.flag.id} @ ${mmss(lit.flag.at)}` + )}{" "} + · {lit.flag.channel}/{lit.flag.id} + {lit.flag.date ? ` · ${lit.flag.date}` : ""} · window {mmss(lit.flag.window.start)}–{mmss(lit.flag.window.end)} + </div> + </Paper> + <p className="m-0 text-[12.5px] text-text-2">why: {lit.flag.reason}</p> + <div className="flex flex-wrap items-center gap-2" data-mark-controls=""> + <button type="button" disabled={!hydrated || busy} className={buttonVariants({ variant: view.marks[lit.flag.f]?.verdict === "right" ? "primary" : "outline", size: "sm" })} onClick={() => void mark(lit.flag, "right")} data-mark-right=""> + Right <kbd>y</kbd> + </button> + <button type="button" disabled={!hydrated || busy} className={buttonVariants({ variant: view.marks[lit.flag.f]?.verdict === "wrong" ? "destructive" : "outline", size: "sm" })} onClick={() => void mark(lit.flag, "wrong")} data-mark-wrong=""> + Wrong <kbd>x</kbd> + </button> + {view.marks[lit.flag.f] && ( + <button type="button" disabled={!hydrated || busy} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void mark(lit.flag, null)}> + Unmark <kbd>u</kbd> + </button> + )} + </div> + </section> + )} + {lit?.kind === "dismissal" && ( + <section className="grid gap-2" data-detail={`d${lit.i + 1}`}> + <span className="micro"> + d{lit.i + 1} · dismissed · {STAGE_WORDS[lit.d.stage]} + </span> + {lit.d.line && ( + <Paper> + <p className="m-0 font-serif text-[15px] leading-[1.45]">“{lit.d.line}”</p> + <div className="mt-1 truncate font-mono text-[10.5px] text-reader-dim"> + {lit.d.title ?? lit.d.id} + {lit.d.at !== undefined ? ` @ ${mmss(lit.d.at)}` : ""} + </div> + </Paper> + )} + {!lit.d.line && ( + <p className="m-0 text-[12.5px] text-text-2"> + {lit.d.title ?? lit.d.id} + {lit.d.window ? ` · window ${mmss(lit.d.window.start)}–${mmss(lit.d.window.end)}` : ""} + </p> + )} + <p className="m-0 text-[12.5px] text-text" data-dismissal-reason=""> + why: {lit.d.reason} + </p> + </section> + )} + <section className="grid gap-1.5" data-candidates=""> + <span className="micro"> + Candidates <span className="font-mono normal-case tracking-normal text-meter">{t0?.candidates.length ?? 0}</span> + </span> + {t0?.candidates.length ? ( + <ul className="m-0 grid list-none gap-0.5 p-0 text-[12px] text-text-2"> + {t0.candidates.map((c) => ( + <li key={c.id} className="flex min-w-0 items-baseline gap-2"> + <code className="font-mono text-[11px] text-muted-2">{c.id}</code> + <span className="truncate">{c.title ?? ""}</span> + <span className="shrink-0 text-muted-2"> + {c.date ?? ""} · {c.by.join(" + ")} + {c.tags?.length ? ` (${c.tags.join(", ")})` : ""} + {c.matches ? ` · ${c.matches} line${c.matches === 1 ? "" : "s"}` : ""} + </span> + </li> + ))} + </ul> + ) : ( + <p className="m-0 text-[12px] text-muted">none</p> + )} + </section> + <section className="grid gap-1 rounded-[3px] border border-seam bg-panel px-3 py-2.5 text-[12.5px]" data-precision={p.precision ?? ""}> + <span className="micro">Precision · {view.schedule.id}</span> + <p className="m-0 text-text-2"> + {p.marked ? ( + <> + <span className="font-mono text-meter">{pct(p.precision)}</span> right over <span className="font-mono text-meter">{p.marked}</span> marked flag{p.marked === 1 ? "" : "s"} (strong {p.byStrength.strong.right}/ + {p.byStrength.strong.right + p.byStrength.strong.wrong}, weak {p.byStrength.weak.right}/{p.byStrength.weak.right + p.byStrength.weak.wrong}) + </> + ) : ( + "no flag marked yet" + )} + </p> + <p className="m-0 text-text-2" data-suggestion={view.suggestion.changed ? "change" : "keep"}> + {view.suggestion.changed ? ( + <> + Suggested threshold: <b className="font-semibold">{thresholdWords(view.suggestion.threshold)}</b> (now {thresholdWords(view.schedule.threshold)}) — {view.suggestion.why}. A suggestion: the schedule&apos;s threshold is changed on its page. + </> + ) : ( + view.suggestion.why + )} + </p> + </section> + </div> + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam px-7 py-2 text-[11.5px] text-muted-2"> + <KeyHint keys={["j", "k"]}>flag</KeyHint> + <KeyHint keys={["y"]}>right</KeyHint> + <KeyHint keys={["x"]}>wrong</KeyHint> + <KeyHint keys={["u"]}>unmark</KeyHint> + <KeyHint keys={["b"]}>open as a board</KeyHint> + <Link prefetch={false} href={view.schedule.href} className="ink-link text-[12px]"> + {view.schedule.topic} + </Link> + {view.board.exists && ( + <Link prefetch={false} href={view.board.href} className="ink-link text-[12px]" data-triage-board={view.board.id}> + Board · {view.board.quotes} {view.board.quotes === 1 ? "quote" : "quotes"} + </Link> + )} + {status && ( + <span role={status.tone === "error" ? "alert" : "status"} data-triage-status-line="" className={`ml-auto text-[12px] ${status.tone === "error" ? "text-reject-text" : "text-text-2"}`}> + {status.text} + {status.href && ( + <> + {" · "} + <Link prefetch={false} href={status.href} className="ink-link"> + Open the board + </Link> + </> + )} + </span> + )} + </div> + </> + ); +} diff --git a/umtool/e2e/triage-first.spec.ts b/umtool/e2e/triage-first.spec.ts @@ -0,0 +1,249 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// TRIAGE FIRST (plans/umtool-redesign.md, R6) over the editor stub, which runs +// the REAL report-schedule action, store and tick over the fixture's article +// store, with a tick's steps stubbed (common/testing/schedule/opsStub.ts): a +// triage writes a real reports/.triage/<id>/<k>/triage.json -- "quiet" in the +// terms is candidates and no flag; else a strong flag (sitechan/sv1) and a +// weak one (sv2), an invented line dismissed as not verbatim, a window not +// relevant -- and an escalation's sweep a done iteration with its trace. +// (triage.spec.ts is the song deck's clip triage, a different thing.) +// +// Create → A recurring report → Watch (and Triage first on a series) · +// a quiet tick (below the threshold: no article, $0) · an escalating tick: +// the tiers on the triage page and on the run page · the Inbox's Worth +// researching card → its board (flags `by triage`, made by umtool) · `y` / +// `x` on the lit flag, the precision and the suggested threshold, the card +// gone once every flag is marked +// +// WRITES articles/.series/r6-*, articles/.triage/r6-*, articles/r6-*, +// .umtool/triage/r6-*, .umtool/research/r6-* (removed after) +// +// R6_SHOTS=<dir> also saves the screenshots (1366×768 and 1440×900, both themes). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const UMTOOL = path.join(FIXTURE, ".umtool"); +const SHOTS = process.env.R6_SHOTS ?? ""; +const series = (id: string) => JSON.parse(readFileSync(path.join(ARTICLES, ".series", id, "series.json"), "utf8")); + +function clean() { + for (const dir of [path.join(ARTICLES, ".series"), path.join(ARTICLES, ".triage"), ARTICLES, path.join(UMTOOL, "triage"), path.join(UMTOOL, "research")]) { + if (!existsSync(dir)) continue; + for (const n of readdirSync(dir).filter((x) => x.startsWith("r6-"))) rmSync(path.join(dir, n), { recursive: true, force: true }); + } +} + +async function shoot(page: Page, name: string) { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + const was = await page.evaluate(() => document.documentElement.getAttribute("data-theme")); + for (const theme of ["dark", "light"] as const) { + await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme); + for (const [w, h] of [ + [1366, 768], + [1440, 900], + ] as const) { + await page.setViewportSize({ width: w, height: h }); + await page.waitForTimeout(150); + await page.screenshot({ path: path.join(SHOTS, `${name}-${w}x${h}-${theme}.png`) }); + } + } + await page.evaluate((t) => (t ? document.documentElement.setAttribute("data-theme", t) : document.documentElement.removeAttribute("data-theme")), was); + await page.setViewportSize({ width: 1280, height: 720 }); +} + +async function api(page: Page, body: Record<string, unknown>) { + const r = await page.request.post("/api/schedules", { data: body }); + const b = (await r.json()) as Record<string, unknown>; + expect(r.ok(), JSON.stringify(b)).toBe(true); + return b; +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + clean(); + await warm(playwright, [urls.createHref({ make: "recurring" }), "/api/articles/channels", urls.seriesHref("r6-none"), urls.triageHref("r6-none", 1), "/"]); +}); +test.afterAll(() => clean()); + +test("Create → A recurring report → Watch: its terms, topics and threshold, planned (the triage named), then started; a series offers Triage first", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.createHref({ make: "recurring" })); + const form = page.getByRole("form", { name: "a recurring report" }); + await form.getByRole("radio", { name: "Series" }).check(); + await expect(form.getByRole("checkbox", { name: "triage first" })).not.toBeChecked(); + await form.getByRole("checkbox", { name: "triage first" }).check(); + await expect(form.getByRole("textbox", { name: "topics" })).toBeVisible(); + await form.getByRole("radio", { name: "Watch" }).check(); + await expect(form.getByRole("checkbox", { name: "triage first" })).toHaveCount(0); + await form.getByRole("textbox", { name: "topic" }).fill("R6 watch"); + await form.getByRole("textbox", { name: "question" }).fill("Who says the vote was rigged?"); + await form.getByRole("textbox", { name: "find a channel" }).fill("site"); + await form.getByRole("button", { name: /Site Channel/ }).click(); + await form.getByRole("textbox", { name: "terms" }).fill("vote"); + await form.getByRole("textbox", { name: "topics" }).fill("elections"); + await expect(form.getByRole("textbox", { name: "strong flags" })).toHaveValue("1"); + await expect(form.getByRole("textbox", { name: "flags of any strength" })).toHaveValue("3"); + await shoot(page, "create-watch"); + await form.getByRole("button", { name: "Plan the schedule" }).click(); + const plan = form.getByRole("region", { name: "plan recurring report" }); + await expect(plan).toContainText("Watch r6-watch · weekly · Mon 06:00"); + await expect(plan.locator("[data-plan-triage]")).toContainText(/triage first on \S+ \(\$0\): escalates on 1 strong or 3 weak · at most \d+ escalations? a day; no article until one does/); + expect(existsSync(path.join(ARTICLES, ".series", "r6-watch"))).toBe(false); + await shoot(page, "create-watch-plan"); + await expect(form.getByRole("button", { name: "Start the schedule" })).toBeFocused(); + await page.keyboard.press("Enter"); + await page.waitForURL(/\/series\/r6-watch$/, { timeout: 20_000 }); + await expect(page.locator("[data-series-shape]")).toHaveText("watch"); + await expect(page.locator("[data-watch-empty]")).toContainText("Nothing escalated yet"); + expect(series("r6-watch")).toMatchObject({ shape: "watch", topic: "R6 watch", scope: { channels: ["sitechan"], terms: "vote", topics: ["elections"] } }); +}); + +test("a quiet watch: the triage is below the threshold — no article, $0, the tiers on its triage page", async ({ page }) => { + test.setTimeout(90_000); + await page.goto("/"); + await api(page, { action: "create", shape: "watch", id: "r6-quiet", topic: "R6 quiet", channels: ["sitechan"], cadence: "weekly mon 06:00", terms: "quiet" }); + await api(page, { action: "tick-now", id: "r6-quiet" }); + const t = series("r6-quiet").ticks.at(-1); + expect(t).toMatchObject({ status: "no-change", usd: 0, triage: { k: 1, candidates: 4, flagged: 0, escalated: false } }); + expect(t.article).toBeUndefined(); + await page.goto(urls.seriesHref("r6-quiet")); + const run = page.locator("[data-series-triage] [data-triage-run='1']"); + await expect(run).toHaveAttribute("data-escalated", "no"); + await expect(run).toContainText("4 candidates · 0 flagged · 3 dismissed"); + await run.getByRole("link").click(); + await page.waitForURL(/\/series\/r6-quiet\/triage\/1$/); + await expect(page.locator("[data-escalation]")).toHaveAttribute("data-escalation", "below"); + await expect(page.locator("[data-tier='2']")).toContainText("not escalated: $0 API"); + await expect(page.locator("[data-dismissal]")).toHaveCount(3); + await expect(page.locator("[data-flag]")).toHaveCount(0); +}); + +test("an escalating tick: the flagged ids swept as r6-watch-<date>; the tiers on the triage page (each flag and dismissal with its reason) and on the run page", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.seriesHref("r6-watch")); + await page.getByRole("button", { name: "Tick now" }).click(); + await expect(page.locator("[data-found]")).toHaveCount(1, { timeout: 30_000 }); + const t = series("r6-watch").ticks.at(-1); + expect(t).toMatchObject({ status: "done", iteration: 1, usd: 0.37, triage: { k: 1, flagged: 2, escalated: true, ids: ["sv1", "sv2"], usd: { tier1: 0, tier2: 0.37 } } }); + expect(t.article).toMatch(/^r6-watch-\d{4}-\d{2}-\d{2}$/); + await expect(page.locator("[data-found]")).toHaveAttribute("data-found", t.article); + await expect(page.locator("[data-series-triage] [data-triage-run='1']")).toHaveAttribute("data-escalated", "yes"); + + await page.goto(urls.triageHref("r6-watch", 1)); + await expect(page.locator("[data-escalation]")).toHaveAttribute("data-escalation", "escalate"); + await expect(page.locator("[data-escalation]")).toContainText("Escalated — 1 strong flag, 1 weak flag (threshold: 1 strong or 3 weak)"); + await expect(page.locator("[data-tier='0']")).toContainText("4 candidates of 4 new by id since the last run"); + await expect(page.locator("[data-tier='1']")).toContainText("2 flagged · 2 dismissed"); + const tier2 = page.locator("[data-tier='2']"); + await expect(tier2).toHaveAttribute("data-escalated", "yes"); + await expect(tier2.locator("[data-tier2-run]")).toHaveText(`${t.article} i1`); + await expect(tier2).toContainText("done · 1 finding"); + // The lit flag's line on the reader, its cite and the judge's reason; a dismissal keeps its own. + await expect(page.locator("[data-flag='f1']")).toHaveAttribute("data-strength", "strong"); + await expect(page.locator("[data-detail='f1']")).toContainText("“The vote was rigged and everybody knew.”"); + await expect(page.locator("[data-detail='f1']")).toContainText("why: The speaker says the vote was rigged (stub)."); + await page.locator("[data-dismissal='verbatim']").click(); + await expect(page.locator("[data-dismissal-reason]")).toHaveText("why: not verbatim in its window"); + await expect(page.locator("[data-detail='d1']")).toContainText("Everybody rigged the count on purpose."); + await page.locator("[data-flag='f1']").click(); + await shoot(page, "triage-run"); + + // The run page of the escalated sweep: its first step is the triage's tiers. + await tier2.locator("[data-tier2-run]").click(); + await page.waitForURL(new RegExp(`/research/runs/${t.article}/1`)); + const step = page.locator("[data-lit-line][data-step='triage']"); + await expect(step).toContainText("triage first"); + await expect(step).toContainText("4 candidates · 2 flagged · 2 dismissed · escalated"); + await step.click(); + await expect(page.locator("[data-run-triage='r6-watch/1']")).toBeVisible(); + await shoot(page, "triage-run-page"); + await page.locator("[data-run-triage='r6-watch/1']").getByRole("link").click(); + await page.waitForURL(/\/series\/r6-watch\/triage\/1$/); +}); + +test("the Inbox: Worth researching (Your call) with the flags; its action opens the board umtool made of them, by triage", async ({ page }) => { + test.setTimeout(90_000); + await page.goto("/"); + const card = page.locator("[data-group=your-call] [data-lit-line][data-piece='s:r6-watch'][data-card='worth-researching']"); + await expect(card).toBeVisible(); + await expect(card).toContainText("2 flagged of 4 new"); + await expect(card).toContainText("The vote was rigged and everybody knew."); + await expect(card.locator("[data-action-link]")).toHaveText("Open the board"); + const article = series("r6-watch").ticks.at(-1).article as string; + await expect(card.locator("[data-action-link]")).toHaveAttribute("href", `/research/${article}`); + // The escalation's article is the watch's: no iteration card of its own. + await expect(page.locator(`[data-lit-line][data-piece='a:articles/${article}']`)).toHaveCount(0); + await shoot(page, "inbox-worth-researching"); + await card.locator("[data-action-link]").click(); + await page.waitForURL(new RegExp(`/research/${article}$`)); + await expect(page.locator("[data-by='triage']")).toHaveCount(2); + await expect(page.locator("[data-case-triage]")).toContainText("r6-watch · run 1"); + const doc = JSON.parse(readFileSync(path.join(UMTOOL, "research", article, "case.json"), "utf8")); + expect(doc.triage).toMatchObject({ schedule: "r6-watch", k: 1 }); + expect(doc.sections.map((s: { title: string }) => s.title)).toEqual(["Strong flags", "Weak flags"]); + expect(doc.quotes.map((q: { by?: string; cite: { video: string } }) => [q.by, q.cite.video])).toEqual([ + ["triage", "sv1"], + ["triage", "sv2"], + ]); + await shoot(page, "triage-board"); +}); + +test("marks: y and x on the lit flag, kept per watch; the precision and a suggested threshold (never applied); every flag marked settles the card", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.triageHref("r6-watch", 1)); + const f1 = page.locator("[data-flag='f1']"); + await expect(f1).toHaveAttribute("data-mark", "none"); + await expect(page.getByRole("button", { name: /Update the board|Open as a board/ })).toBeEnabled(); + await f1.click(); + await page.keyboard.press("y"); + await expect(f1).toHaveAttribute("data-mark", "right"); + await page.keyboard.press("j"); + await expect(page.locator("[data-flag='f2']")).toBeFocused(); + await page.keyboard.press("x"); + await expect(page.locator("[data-flag='f2']")).toHaveAttribute("data-mark", "wrong"); + await expect(page.locator("[data-precision]")).toHaveAttribute("data-precision", "0.5"); + await expect(page.locator("[data-precision]")).toContainText("50% right over 2 marked flags"); + await expect(page.locator("[data-suggestion]")).toContainText("mark 2 more to get a suggestion"); + const marks = JSON.parse(readFileSync(path.join(UMTOOL, "triage", "r6-watch.json"), "utf8")); + expect(Object.fromEntries(Object.entries(marks.marks).map(([k, m]) => [k, (m as { verdict: string }).verdict]))).toEqual({ "1/f1": "right", "1/f2": "wrong" }); + await page.reload(); + await expect(page.locator("[data-flag='f2']")).toHaveAttribute("data-mark", "wrong"); + await shoot(page, "triage-marked"); + // The watch's page: the precision; the schedule's threshold is untouched. + await page.goto(urls.seriesHref("r6-watch")); + await expect(page.locator("[data-series-triage] [data-precision]")).toContainText("precision 50% over 2 marked"); + await shoot(page, "watch-page"); + expect(series("r6-watch").triage).toBeUndefined(); + // Every flag of the run marked: the card is settled. + await page.goto("/"); + await expect(page.locator("[data-card='worth-researching'][data-piece='s:r6-watch']")).toHaveCount(0); +}); + +test("keys: the flags and dismissals are one lit list; y on a dismissal does nothing; u unmarks; Home and End", async ({ page }) => { + await page.goto(urls.triageHref("r6-watch", 1)); + const f1 = page.locator("[data-flag='f1']"); + await expect(page.getByRole("button", { name: /Update the board|Open as a board/ })).toBeEnabled(); + await f1.focus(); + await page.keyboard.press("u"); + await expect(f1).toHaveAttribute("data-mark", "none"); + await page.keyboard.press("End"); + await expect(page.locator("[data-dismissal]").last()).toBeFocused(); + await page.keyboard.press("y"); + await expect(page.locator("[data-flag][data-mark='right']")).toHaveCount(0); + await page.keyboard.press("Home"); + await expect(f1).toBeFocused(); + await page.keyboard.press("y"); + await expect(f1).toHaveAttribute("data-mark", "right"); +}); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -232,6 +232,11 @@ export function seriesHref(id: string): string { return `/series/${encodeURIComponent(id)}`; } +/** One triage run of a recurring report (R6): its tiers, flags and dismissals. */ +export function triageHref(schedule: string, k: number): string { + return `/series/${encodeURIComponent(schedule)}/triage/${k}`; +} + /** The evidence walk of one article. */ export function articleEvidenceHref(a: ArticleRef, q: { c?: string } = {}): string { return withQuery(`${articleBase(a)}/evidence`, q); diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -8,14 +8,18 @@ import { decisionsForSong, type Decision } from "./decisions"; import { openDecisions, projectRefs, summariseProject, type ProjectRef } from "./projects"; import { readManifest, reportSignature } from "./projects/report.mjs"; import { draftsView } from "./report/drafts.mjs"; -import { articleHref, generationPolicyHref, reviewHref } from "./hrefs"; +import { articleHref, generationPolicyHref, reviewHref, triageHref } from "./hrefs"; import { awaitingReview, draftsDecisions } from "./inbox/drafts.mjs"; import { readFieldProvenance } from "./report/draft-provenance.mjs"; import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; import { lifecycleOf, readLifecycle, type LifecycleRead } from "./lifecycle"; import { isMuted, readMutes } from "./mutes"; import { GROUPS, annotate, rankDecisions, summarizeGroups } from "./inbox/groups.mjs"; -import { currentIteration } from "yt-dlp-transcript-common/lib/report/iterations"; +import { currentIteration, readIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { ensureTriageBoards, triageBoardId } from "./research/triage"; +import { marksOfRun, readMarks } from "./research/triage-marks.mjs"; +import { readCase } from "./research/boards"; +import { REPORTS_ROOT } from "./paths.mjs"; import { scheduleDecisions } from "./inbox/schedules.mjs"; import { readSchedules } from "./schedules"; import type { ScheduleView } from "./schedule-types"; @@ -41,6 +45,10 @@ import { refreshDecisions } from "./inbox/refresh"; // edition-ready nothing current yet (Review) -- lib/inbox/schedules.mjs; // an edition's article raises no iteration cards of its // own (they are its series') +// worth-researching a watch's tick whose triage escalated (R6): Your call, +// its board (made here the first time, by umtool, the +// one writer of case files -- lib/research/triage.ts); +// its article raises no iteration cards of its own // refresh-available new recordings match an active article's current // refresh-held report since it was made (a cached daily check); a // refresh the cap held (lib/inbox/refresh.ts, R4) @@ -292,13 +300,50 @@ async function recurringDecisions(views: ScheduleView[]): Promise<Decision[]> { current.set(a, cur?.report ?? null); }), ); + const worth = await worthOf(views).catch(() => new Map<string, { href: string; settled: boolean; findings: number | null }>()); return scheduleDecisions(views, { current: (a: string) => current.get(a) ?? null, articleHref: (a: string) => articleHref({ site: ARTICLES_KEY, id: a }, { tab: "iterations" }), settingsHref: generationPolicyHref(), + worth: (schedule: string, k: number) => worth.get(`${schedule}/${k}`) ?? null, }) as Decision[]; } +/** + * A watch's escalated ticks (R6): each board (made now when it is not yet -- + * umtool is the one writer of case files), whether it is settled (a hand-off + * made from it, or every flag of the run marked), and what the sweep kept. + */ +async function worthOf(views: ScheduleView[]): Promise<Map<string, { href: string; settled: boolean; findings: number | null }>> { + const out = new Map<string, { href: string; settled: boolean; findings: number | null }>(); + const watches = views.filter((v) => v.shape === "watch" && v.ticks.some((t) => t.triage?.escalated && t.status === "done" && t.article)); + if (!watches.length) return out; + const boards = await ensureTriageBoards(watches); + for (const v of watches) { + const marks = await readMarks(REPORTS_ROOT, v.id).catch(() => null); + for (const t of v.ticks) { + if (!t.triage?.escalated || t.status !== "done" || !t.article) continue; + const key = `${v.id}/${t.triage.k}`; + const board = await readCase(triageBoardId(v, t.triage.k)).catch(() => null); + const marked = marks ? Object.keys(marksOfRun(marks, t.triage.k)).length : 0; + const settled = !!board?.handoffs.length || (t.triage.flagged > 0 && marked >= t.triage.flagged); + let findings: number | null = null; + if (t.iteration) { + const text = await readIterationFile(t.article, t.iteration, "report.json", sitesPaths()).catch(() => null); + if (text) { + try { + findings = Object.values((JSON.parse(text) as { citations?: Record<string, { quote?: string }> }).citations ?? {}).filter((c) => c?.quote).length; + } catch { + findings = null; + } + } + } + out.set(key, { href: boards.get(key) ?? triageHref(v.id, t.triage.k), settled, findings }); + } + } + return out; +} + /** The decisions read from disk beside openDecisions(): iterations, research, links, looks-done, drafts, recurring reports. */ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Promise<Decision[]> { const [spend, drafts, schedules] = await Promise.all([ @@ -307,7 +352,11 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro readSchedules().catch(() => ({ schedules: [] as ScheduleView[] })), ]); // An edition's article is its series' piece's business (one Review card there). - const editionArticles = new Set(schedules.schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [e.article] : [])))); + // A watch's tick article is its watch's (one Worth researching card there). + const editionArticles = new Set([ + ...schedules.schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [e.article] : []))), + ...schedules.schedules.flatMap((v) => (v.shape === "watch" ? v.ticks.flatMap((t) => (t.article ? [t.article] : [])) : [])), + ]); const perArticle = await Promise.all( storeArticles(graph) .filter((p) => !editionArticles.has(p.report as string)) diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -54,6 +54,8 @@ const KIND_CATEGORY = { "tick-failed": "spend", "tick-held": "spend", "edition-ready": "review", + // R6: a watch found something: the operator's call, research it or not. + "worth-researching": "spend", // R4: a refresh the cap held is money waiting on a yes or no; new // recordings since the current report are something to review. "refresh-held": "spend", @@ -86,7 +88,7 @@ export function groupOf(d) { // Within a group: the brief's order first (proposals before failed runs), then // everything else as equals. -const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0, "refresh-held": 2, "refresh-available": 2 }; +const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0, "refresh-held": 2, "refresh-available": 2 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -102,6 +104,7 @@ const ACTION_LABEL = { "tick-failed": "Tick now", "tick-held": "Raise cap", "edition-ready": "Review edition", + "worth-researching": "Open the board", "claim-unadjudicated": "Adjudicate claim", "claim-incoherent": "Rule on the flag", "clip-no-cues": "Fix the cue source", diff --git a/umtool/lib/inbox/schedules.mjs b/umtool/lib/inbox/schedules.mjs @@ -8,6 +8,11 @@ // job's over the policy's max) -- Your call: Raise cap // edition-ready a series' edition is done and its article has nothing // current yet -- Review: read it, make it current +// worth-researching (R6) a watch's tick whose triage escalated: the flags +// and what the sweep of them found -- Your call: open the +// board (an R2 case of the flags, `by: triage`), whose +// hand-offs make an article or a video. Gone once the board +// has a hand-off or every flag of the run is marked // // A living report's refresh lands an `iteration-ready` card of its own (the // article's iterations, lib/inbox.ts); only its failed or held ticks are here. @@ -23,7 +28,7 @@ const timeOf = (iso) => { /** * @param {Array<{ id: string, shape: string, topic: string, article?: string, href: string, piece: string, call: null | { at: string, status: string, reason?: string, estimateUsd?: number, usd: number }, editions?: Array<{ n: number, title: string, status: string, article?: string, usd: number, at: string, window: { from: string, to: string } }> }>} views - * @param {{ current: (article: string) => number | null, articleHref: (article: string) => string, settingsHref: string }} how + * @param {{ current: (article: string) => number | null, articleHref: (article: string) => string, settingsHref: string, worth?: (schedule: string, k: number) => { href: string, settled: boolean, findings: number | null } | null }} how */ export function scheduleDecisions(views, how) { const out = []; @@ -47,6 +52,30 @@ export function scheduleDecisions(views, how) { at: timeOf(call.at), }); } + if (v.shape === "watch") { + for (const t of v.ticks ?? []) { + const tri = t.triage; + if (!tri?.escalated || t.status !== "done" || !t.article) continue; + const w = how.worth?.(v.id, tri.k) ?? null; + if (w?.settled) continue; + const top = (tri.top ?? []).slice(0, 2).map((f) => `“${f.line}” — ${f.reason}`); + out.push({ + ...base, + kind: "worth-researching", + target: t.article, + why: [ + `${tri.flagged} flagged of ${tri.candidates} new`, + ...top, + w && w.findings !== null ? `the sweep kept ${w.findings} finding${w.findings === 1 ? "" : "s"}${t.usd ? ` · ${usd(t.usd)}` : ""}` : t.usd ? usd(t.usd) : null, + ] + .filter(Boolean) + .join(" · "), + href: w?.href ?? `/series/${encodeURIComponent(v.id)}/triage/${tri.k}`, + severity: "open", + at: timeOf(t.at), + }); + } + } if (!living) { for (const e of v.editions ?? []) { if (e.status !== "done" || !e.article) continue; diff --git a/umtool/lib/inbox/schedules.test.mjs b/umtool/lib/inbox/schedules.test.mjs @@ -57,3 +57,37 @@ test("a failed tick is Your call (Tick now, on the schedule's page); a held one assert.equal(whatOf("tick-failed"), "tick failed"); assert.equal(whatOf("tick-held"), "tick held by a cap"); }); + +test("a watch's escalated tick is Worth researching (Your call): the flags and what the sweep kept; its action the board; settled or below the threshold, none", () => { + const tick = (k, o = {}) => ({ + at: `2026-10-2${k}T10:00:00.000Z`, + status: "done", + article: `cowatch-2026-10-2${k}`, + iteration: 1, + usd: 0.42, + triage: { k, escalated: true, candidates: 6, flagged: 2, dismissed: 4, top: [{ f: "f1", id: "v1", line: "I was on the show last week", score: 3, reason: "She says she was a guest." }], usd: { tier1: 0, tier2: 0.42 } }, + ...o, + }); + const watch = { + id: "cowatch", + shape: "watch", + topic: "Co-host watch", + href: "/series/cowatch", + piece: "s:cowatch", + call: null, + ticks: [tick(1), tick(2), tick(3, { status: "no-change", article: undefined, triage: { k: 3, escalated: false, candidates: 2, flagged: 0, dismissed: 2, top: [], usd: { tier1: 0, tier2: 0 } } })], + }; + const worth = (s, k) => (k === 2 ? { href: "/research/cowatch-2026-10-22", settled: true, findings: 1 } : { href: `/research/cowatch-2026-10-2${k}`, settled: false, findings: 3 }); + const d = scheduleDecisions([watch], { ...how, worth }); + assert.deepEqual( + d.map((x) => [x.kind, x.target, x.href, x.piece, x.project]), + [["worth-researching", "cowatch-2026-10-21", "/research/cowatch-2026-10-21", "s:cowatch", "series/cowatch"]], + ); + assert.equal(d[0].why, "2 flagged of 6 new · “I was on the show last week” — She says she was a guest. · the sweep kept 3 findings · $0.42"); + const [row] = annotate(d, { pieceOf: () => null, lifecycleOf: () => "active" }); + assert.deepEqual([row.group, row.category, row.action.label], ["your-call", "spend", "Open the board"]); + assert.equal(whatOf("worth-researching"), "worth researching"); + // Without the board's word (it could not be made): the triage page. + const bare = scheduleDecisions([{ ...watch, ticks: [tick(1)] }], how); + assert.equal(bare[0].href, "/series/cowatch/triage/1"); +}); diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -15,6 +15,7 @@ export const WHAT = { "tick-failed": "tick failed", "tick-held": "tick held by a cap", "edition-ready": "edition ready", + "worth-researching": "worth researching", "refresh-available": "new recordings match", "refresh-held": "refresh held by the cap", "claim-unadjudicated": "claims never ruled", diff --git a/umtool/lib/pieces.ts b/umtool/lib/pieces.ts @@ -263,7 +263,11 @@ async function buildGraph(): Promise<PieceGraph> { // article while it is in the making. const schedules = (await readSchedules().catch(() => ({ schedules: [] as ScheduleView[] }))).schedules; const living = new Map(schedules.filter((v) => v.shape === "living").map((v) => [v.article ?? v.id, v])); - const editionOf = new Map(schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [[e.article, v.id] as const] : [])))); + // A series' edition, and what a watch's escalation wrote (R6), are the schedule's. + const editionOf = new Map([ + ...schedules.flatMap((v) => (v.editions ?? []).flatMap((e) => (e.article ? [[e.article, v.id] as const] : []))), + ...schedules.flatMap((v) => (v.shape === "watch" ? v.ticks.flatMap((t) => (t.article ? [[t.article, v.id] as const] : [])) : [])), + ]); const [sites, store, pending, summaries, its, cases] = await Promise.all([ listSiteRows().catch(() => []), readStoreRow().catch(() => ({ articles: [] as ArticleRow[] })), @@ -351,7 +355,7 @@ async function buildGraph(): Promise<PieceGraph> { // Work lists and the Inbox's edition and tick cards are on. for (const v of schedules) { if (v.shape === "living") continue; - const done = (v.editions ?? []).some((e) => e.status === "done"); + const done = (v.editions ?? []).some((e) => e.status === "done") || v.ticks.some((t) => t.article && t.triage?.escalated); const reached = { research: (v.editions ?? []).length > 0 || v.ticks.length > 0, article: done, video: false, deliver: false }; pieces.push({ id: v.piece, diff --git a/umtool/lib/research/case-types.ts b/umtool/lib/research/case-types.ts @@ -85,8 +85,8 @@ export type Quote = { verify?: QuoteVerify; /** Earlier words, kept when the operator took the current ones. */ history?: { text: string; at: string; why: string }[]; - /** R3: a finding an agent's sweep kept ("Open as a board" on a run), not a person's pin. */ - by?: "agent"; + /** R3: a finding an agent's sweep kept ("Open as a board" on a run), not a person's pin; R6: a line a triage flagged. */ + by?: "agent" | "triage"; }; export type CaseSection = { id: string; title: string }; @@ -121,6 +121,8 @@ export type CaseDoc = { handoffs: CaseHandoff[]; /** R3: the agent run this board was opened from (`/research/runs/<article>/<n>`). */ run?: { article: string; n: number; at: string }; + /** R6: the triage run this board was made from (`/series/<schedule>/triage/<k>`). */ + triage?: { schedule: string; k: number; at: string }; counters: { quote: number; section: number }; createdAt: string; updatedAt: string; diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs @@ -188,8 +188,9 @@ function cleanQuote(q, sectionIds) { 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. - ...(q.by === "agent" ? { by: "agent" } : {}), + // 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 } : {}), }; @@ -251,6 +252,10 @@ export function normaliseCase(raw, id) { ...(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+)$/)), @@ -532,7 +537,7 @@ export const sameCite = (a, b) => * 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, by?: "agent" }} snap + * @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 = {}) { @@ -565,7 +570,7 @@ export function addQuote(doc, snap, ctx = {}) { speakerChecked: false, pinnedAt: now, query: snap.query ?? search?.query ?? doc.scope.query, - ...(snap.by === "agent" ? { by: "agent" } : {}), + ...(snap.by === "agent" || snap.by === "triage" ? { by: snap.by } : {}), }, new Set(doc.sections.map((s) => s.id)), ); diff --git a/umtool/lib/research/runs-types.ts b/umtool/lib/research/runs-types.ts @@ -55,7 +55,22 @@ export type RunBatch = { cut: boolean; }; -export type RunStepKind = "scope" | "terms" | "turn" | "enumerate" | "batch" | "group" | "findings" | "checks" | "end"; +export type RunStepKind = "scope" | "terms" | "turn" | "enumerate" | "batch" | "group" | "findings" | "checks" | "end" | "triage"; + +/** R6: the triage a sweep escalated (its trace's `triage` line): the tiers before this run. */ +export type RunTriage = { + owner: string; + k: number; + /** The triage run's page (`/series/<owner>/triage/<k>`). */ + href: string; + candidates: string[]; + flagged: string[]; + dismissed: number; + escalated: boolean; + why: string | null; + model: string | null; + cost: { tier0: number; tier1: number } | null; +}; export type RunStep = { /** Stable within the run: `scope`, `t3`, `r0` (a repair turn), `e2`, `b1`, `checks` … */ @@ -83,6 +98,8 @@ export type RunStep = { checks: RunCheck[]; findings: RunFinding[]; notes: string[]; + /** R6: the triage this sweep escalates (a `triage` step). */ + triage?: RunTriage; }; }; diff --git a/umtool/lib/research/runs-view.ts b/umtool/lib/research/runs-view.ts @@ -357,6 +357,35 @@ export function stepsOfTrace(events: Json[]): Built { case "finding": findings.push({ section: str(e.section) ?? "", claim: str(e.claim) ?? "", cites: Array.isArray(e.cites) ? e.cites.map(citeOf) : [] }); break; + case "triage": { + // R6: the cheap pass this sweep escalated -- its tiers, before this run. + const owner = str(e.owner) ?? ""; + const k = num(e.k) ?? 0; + const cost = e.cost && typeof e.cost === "object" ? { tier0: num((e.cost as Json).tier0) ?? 0, tier1: num((e.cost as Json).tier1) ?? 0 } : null; + const tri = { + owner, + k, + href: `/series/${encodeURIComponent(owner)}/triage/${k}`, + candidates: strs(e.candidates), + flagged: strs(e.flagged), + dismissed: num(e.dismissed) ?? 0, + escalated: e.escalated === true, + why: str(e.why), + model: str(e.model), + cost, + }; + const s = emptyStep("triage", "triage", "—", "triage first"); + s.sub = `${plural(tri.candidates.length, "candidate")} · ${tri.flagged.length} flagged · ${tri.dismissed} dismissed${tri.escalated ? " · escalated" : ""}`; + s.detail.triage = tri; + s.detail.facts = [ + ["tier 0 · code", `${plural(tri.candidates.length, "candidate")} (new by id) · $${(cost?.tier0 ?? 0).toFixed(2)}`], + ["tier 1 · judge", `${tri.model ?? "?"} · ${tri.flagged.length} flagged, ${tri.dismissed} dismissed · $${(cost?.tier1 ?? 0).toFixed(2)}`], + ["tier 2 · this run", "the sweep of the flagged recordings (its spend is this run's)"], + ...(tri.why ? ([["escalated", tri.why]] as [string, string][]) : []), + ]; + steps.push(s); + break; + } case "note": { const host = turnOf(e) ?? steps.at(-1); if (host && str(e.text)) host.detail.notes.push(str(e.text)!); diff --git a/umtool/lib/research/triage-marks.mjs b/umtool/lib/research/triage-marks.mjs @@ -0,0 +1,122 @@ +// A TRIAGE'S FLAGS, MARKED RIGHT OR WRONG (plans/umtool-redesign.md, R6). The +// operator's `y` / `x` on a lit flag (the triage page) is kept per schedule -- +// a watch's precision and the threshold it suggests come from them. +// +// REPORTS_ROOT/.umtool/triage/<schedule>.json +// { format: "umtool-triage-marks", version: 1, schedule, +// marks: { "<k>/<f>": { verdict: "right" | "wrong", score, at, id, line } }, +// updatedAt } +// +// Umtool-side state, never the corpus (the editor's triage runs are its own: +// reports/.triage/). The lifecycle store's discipline (lib/lifecycle.mjs): ONE +// writer, serialised in-process; a whole file to a temp name and a rename; a +// file that does not parse is never overwritten (a write refuses with 409). +// +// Plain ESM: the unit test reads it the way the app does. +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const MARKS_FORMAT = "umtool-triage-marks"; +export const MARKS_VERSION = 1; +const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; +const KEY_RE = /^[1-9]\d{0,6}\/f[1-9]\d{0,5}$/; + +export class MarksError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + } +} + +export const marksFile = (reportsRoot, schedule) => { + if (!ID_RE.test(schedule)) throw new MarksError(`not a schedule id: ${JSON.stringify(schedule)}`); + return path.join(reportsRoot, ".umtool", "triage", `${schedule}.json`); +}; + +/** A flag's key: its run and its flag id. */ +export const markKey = (k, f) => `${k}/${f}`; + +function clean(raw, schedule) { + const marks = {}; + for (const [key, m] of Object.entries(raw?.marks && typeof raw.marks === "object" ? raw.marks : {})) { + if (!KEY_RE.test(key) || !m || (m.verdict !== "right" && m.verdict !== "wrong")) continue; + marks[key] = { + verdict: m.verdict, + score: Number.isFinite(m.score) ? m.score : 2, + at: typeof m.at === "string" ? m.at.slice(0, 40) : "", + ...(typeof m.id === "string" ? { id: m.id.slice(0, 128) } : {}), + ...(typeof m.line === "string" ? { line: m.line.slice(0, 600) } : {}), + }; + } + return { format: MARKS_FORMAT, version: MARKS_VERSION, schedule, marks, updatedAt: typeof raw?.updatedAt === "string" ? raw.updatedAt : "" }; +} + +/** A schedule's marks (none: an empty set). A file that does not read is a 409. */ +export async function readMarks(reportsRoot, schedule) { + let text; + try { + text = await readFile(/* turbopackIgnore: true */ marksFile(reportsRoot, schedule), "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return clean(null, schedule); + if (err instanceof MarksError) throw err; + throw new MarksError(`the marks of ${schedule} cannot be read: ${err?.message ?? err}`, 409); + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + throw new MarksError(`.umtool/triage/${schedule}.json is not JSON: ${err.message}`, 409); + } + if (raw?.format !== MARKS_FORMAT) throw new MarksError(`.umtool/triage/${schedule}.json is not a ${MARKS_FORMAT} file`, 409); + return clean(raw, schedule); +} + +let chain = Promise.resolve(); +function serialised(fn) { + const run = chain.then(fn); + chain = run.catch(() => {}); + return run; +} + +/** + * Mark one flag right or wrong (`verdict` null: unmark). Answers the marks + * as written. + * + * @param {string} reportsRoot + * @param {string} schedule + * @param {{ k: number, f: string, verdict: "right" | "wrong" | null, score?: number, id?: string, line?: string, now?: Date }} m + * @returns {Promise<ReturnType<typeof clean>>} + */ +export function setMark(reportsRoot, schedule, m) { + return serialised(async () => { + const key = markKey(m.k, m.f); + if (!KEY_RE.test(key)) throw new MarksError(`not a flag: run ${JSON.stringify(m.k)}, flag ${JSON.stringify(m.f)}`); + if (m.verdict !== null && m.verdict !== "right" && m.verdict !== "wrong") throw new MarksError('"verdict" is "right", "wrong" or null'); + const doc = await readMarks(reportsRoot, schedule); + const at = (m.now ?? new Date()).toISOString(); + if (m.verdict === null) delete doc.marks[key]; + else doc.marks[key] = { verdict: m.verdict, score: Number.isFinite(m.score) ? m.score : 2, at, ...(m.id ? { id: m.id } : {}), ...(m.line ? { line: m.line.slice(0, 600) } : {}) }; + doc.updatedAt = at; + const file = marksFile(reportsRoot, schedule); + 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; + } + return doc; + }); +} + +/** The marks of one run, by flag id. */ +export function marksOfRun(doc, k) { + const out = {}; + for (const [key, m] of Object.entries(doc.marks)) { + const [run, f] = key.split("/"); + if (Number(run) === k) out[f] = m; + } + return out; +} diff --git a/umtool/lib/research/triage-marks.test.mjs b/umtool/lib/research/triage-marks.test.mjs @@ -0,0 +1,34 @@ +// A triage's marks (R6): set, unmark, per run, the file shape; a broken file +// is never overwritten. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { MarksError, marksFile, marksOfRun, readMarks, setMark } from "./triage-marks.mjs"; + +test("marks: right and wrong per flag, kept per schedule; unmark; a broken file refuses", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "triage-marks-")); + try { + assert.deepEqual((await readMarks(root, "co-host-watch")).marks, {}); + const now = new Date("2026-10-14T10:00:00Z"); + await setMark(root, "co-host-watch", { k: 2, f: "f1", verdict: "right", score: 3, id: "v1", line: "a line", now }); + await setMark(root, "co-host-watch", { k: 2, f: "f2", verdict: "wrong", score: 2, now }); + const doc = await setMark(root, "co-host-watch", { k: 3, f: "f1", verdict: "wrong", score: 2, now }); + assert.deepEqual(Object.keys(doc.marks).sort(), ["2/f1", "2/f2", "3/f1"]); + assert.deepEqual(marksOfRun(doc, 2), { f1: { verdict: "right", score: 3, at: now.toISOString(), id: "v1", line: "a line" }, f2: { verdict: "wrong", score: 2, at: now.toISOString() } }); + const after = await setMark(root, "co-host-watch", { k: 2, f: "f2", verdict: null }); + assert.deepEqual(Object.keys(after.marks).sort(), ["2/f1", "3/f1"]); + const onDisk = JSON.parse(await readFile(marksFile(root, "co-host-watch"), "utf8")); + assert.equal(onDisk.format, "umtool-triage-marks"); + await assert.rejects(setMark(root, "co-host-watch", { k: 2, f: "nope", verdict: "right" }), MarksError); + await assert.rejects(setMark(root, "Bad Id", { k: 1, f: "f1", verdict: "right" }), /not a schedule id/); + + await mkdir(path.dirname(marksFile(root, "broken")), { recursive: true }); + await writeFile(marksFile(root, "broken"), "{ nope"); + await assert.rejects(setMark(root, "broken", { k: 1, f: "f1", verdict: "right" }), (e) => e.status === 409); + assert.equal(await readFile(marksFile(root, "broken"), "utf8"), "{ nope"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/research/triage-types.ts b/umtool/lib/research/triage-types.ts @@ -0,0 +1,61 @@ +// A TRIAGE RUN, as umtool's pages read it (plans/umtool-redesign.md, R6): the +// editor's triage.json (common lib/report/draft/triage/types.ts) plus the tick +// that ran it, what it escalated to, the operator's marks and the schedule's +// precision. Types only: safe for a client component. + +import type { FlagMark, Precision, TickTriage, TriageFile, TriageThreshold } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; + +export type { FlagMark, Precision, TickTriage, TriageFile, TriageThreshold }; + +export type TriageTier2 = { + article: string; + n: number; + /** The iteration's status (queued, running, done, failed, cancelled), or null when it does not read. */ + status: string | null; + usd: number; + /** Kept findings (quoted citations of its report), when it has one. */ + findings: number | null; + /** The run page (`/research/runs/<article>/<n>`) and the article. */ + runHref: string; + articleHref: string; +}; + +export type TriageRunView = { + schedule: { id: string; shape: string; topic: string; href: string; threshold: TriageThreshold }; + k: number; + /** Every run of this schedule, newest first (the run picker). */ + runs: number[]; + file: TriageFile; + /** The tick that ran it (its line), when one did. */ + tick: { at: string; status: string; reason: string | null; usd: number; triage: TickTriage | null } | null; + /** What it escalated to (the tier 2 sweep), when it did. */ + tier2: TriageTier2 | null; + /** The operator's marks on this run's flags, by flag id. */ + marks: Record<string, FlagMark>; + /** The schedule's precision over every marked flag, and the threshold it suggests. */ + precision: Precision; + suggestion: { threshold: TriageThreshold; why: string; changed: boolean }; + /** The board made of the flags, when there is one; its id either way. */ + board: { id: string; href: string; exists: boolean; quotes: number }; +}; + +/** One run on the schedule's page. */ +export type TriageRunRow = { + k: number; + at: string; + status: string; + candidates: number; + flagged: number; + dismissed: number; + escalated: boolean; + why: string; + usd: { tier1: number; tier2: number }; + href: string; +}; + +export type ScheduleTriage = { + runs: TriageRunRow[]; + precision: Precision; + suggestion: { threshold: TriageThreshold; why: string; changed: boolean }; + threshold: TriageThreshold; +}; diff --git a/umtool/lib/research/triage.test.ts b/umtool/lib/research/triage.test.ts @@ -0,0 +1,122 @@ +// Triage first, umtool's side (R6): a watch's triage run read with the tick +// that ran it and what it escalated to; the marks (precision, the suggested +// threshold, never applied); the flags opened as a board by umtool (the one +// writer of case files) — idempotent, the operator's edits kept; the boards an +// Inbox read makes for escalated watch ticks. Temp stores only. +// +// Run with: pnpm --filter umtool exec tsx --test lib/research/triage.test.ts +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; +import { createSchedule, parseCreate, recordTick } from "yt-dlp-transcript-common/controller/reportSchedule"; +import { createIteration, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { createTriageRun } from "yt-dlp-transcript-common/lib/report/draft/triage/store"; +import { readSchedule } from "yt-dlp-transcript-common/lib/report/schedule/store"; +import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, tickTriageOf, type TriageFile, type TriageFlag } from "yt-dlp-transcript-common/lib/report/draft/triage/types"; + +let tmp: string; +let paths: Paths; +let lib: { triage: typeof import("./triage"); boards: typeof import("./boards") }; + +const FLAGS: TriageFlag[] = [ + { f: "f1", id: "v2", channel: "chan-a", title: "Weak one", date: "2026-10-12", window: { start: 0, end: 20 }, line: "she mentioned the show once", at: 10, score: 2, strength: "weak", reason: "A passing mention.", checked: "cues" }, + { f: "f2", id: "v1", channel: "chan-a", title: "Strong one", date: "2026-10-13", window: { start: 0, end: 30 }, line: "I was a guest on the show last week", at: 5, score: 3, strength: "strong", reason: "She says she was a guest.", checked: "cues", url: "https://x.example/?v=chan-a%2Fv1&t=5" }, +]; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-triage-")); + process.env.ARTICLES_DIR = path.join(tmp, "articles"); + process.env.REPORTS_DIR = path.join(tmp, "reports"); + process.env.SITES_DIR = path.join(tmp, "sites"); + process.env.CHANNELS_DIR = path.join(tmp, "channels"); + process.env.TRANSCRIPT_LOCAL_DIR = path.join(tmp, "no-corpus"); + process.env.TRANSCRIPT_HUB_URL = ""; + process.env.SETTINGS_FILE = path.join(tmp, "settings.json"); + paths = { articlesDir: path.join(tmp, "articles"), exportIndexDir: path.join(tmp, "idx") } as unknown as Paths; + await createSchedule(parseCreate({ shape: "watch", topic: "Guest watch", channels: ["chan-a"], cadence: "weekly mon 06:00", tz: "UTC", terms: "guest" }), { paths }); + const run = await createTriageRun( + (k): TriageFile => ({ + format: TRIAGE_FORMAT, + version: TRIAGE_VERSION, + owner: "guest-watch", + k, + status: "done", + model: "qwen3:8b", + provider: "local", + question: "Guest watch", + scope: { channels: ["chan-a"] }, + terms: "guest", + regex: false, + topics: [], + threshold: DEFAULT_TRIAGE_THRESHOLD, + since: "2026-10-07", + knownCount: 9, + createdAt: "2026-10-14T10:00:00.000Z", + startedAt: "2026-10-14T10:00:00.000Z", + tier0: { candidates: [{ id: "v1", channel: "Chan A", title: "Strong one", date: "2026-10-13", matches: 1, by: ["terms"] }, { id: "v2", channel: "Chan A", title: "Weak one", date: "2026-10-12", matches: 1, by: ["terms"] }], scanned: 11, newCount: 2, cut: [], partial: false, unreached: [], perQuery: [], newBy: "id" }, + tier1: { model: "qwen3:8b", flags: FLAGS, dismissed: [], read: 2, windows: 2, chunks: 2, usd: 0 }, + escalation: escalationOf(FLAGS, DEFAULT_TRIAGE_THRESHOLD), + cost: { tier0: 0, tier1: 0 }, + summary: "2 candidates · 2 flagged · 0 dismissed — escalate", + warnings: [], + }), + paths, + "guest-watch", + ); + // The escalation's sweep, done, with one kept finding. + const it = await createIteration("guest-watch-2026-10-14", { kind: "sweep", model: "claude-sonnet-5-5", question: "Guest watch", scope: { channels: ["chan-a"], ids: ["v1", "v2"], triage: { owner: "guest-watch", k: 1 } } }, paths); + await writeIterationFile("guest-watch-2026-10-14", it.n, "report.json", { format: "archilyzer-report", version: 1, id: "guest-watch-2026-10-14", kind: "sweep", title: "Guest watch · 2026-10-14", citations: { c1: { kind: "video", channel: "chan-a", id: "v1", start: 5, end: 8, quote: FLAGS[1]!.line } }, sections: [{ id: "s1", title: "Found", body: "She [was](cite:c1)." }] }, paths); + await updateIteration("guest-watch-2026-10-14", it.n, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.42, inputTokens: 1, outputTokens: 1 } } }, paths); + await recordTick("guest-watch", { at: "2026-10-14T10:00:00.000Z", trigger: "now", status: "done", jobId: "j1", article: "guest-watch-2026-10-14", iteration: it.n, usd: 0.42, triage: tickTriageOf(run, { tier2Usd: 0.42 }) }, { paths }); + lib = { triage: await import("./triage"), boards: await import("./boards") }; +}); + +after(async () => { + await rm(tmp, { recursive: true, force: true }); +}); + +test("a triage run, read: the tiers, the tick that ran it, what it escalated to, the board's id (the escalation's article)", async () => { + const v = await lib.triage.readTriageRunView("guest-watch", 1); + assert.deepEqual([v.k, v.runs, v.schedule.shape, v.file.tier1?.flags.length], [1, [1], "watch", 2]); + assert.deepEqual(v.tick && [v.tick.status, v.tick.triage?.escalated, v.tick.triage?.ids], ["done", true, ["v2", "v1"]]); + assert.deepEqual(v.tier2 && [v.tier2.article, v.tier2.n, v.tier2.status, v.tier2.usd, v.tier2.findings, v.tier2.runHref], ["guest-watch-2026-10-14", 1, "done", 0.42, 1, "/research/runs/guest-watch-2026-10-14/1"]); + assert.deepEqual([v.board.id, v.board.exists], ["guest-watch-2026-10-14", false]); + const t = await lib.triage.readScheduleTriage((await readSchedule("guest-watch", paths))!); + assert.deepEqual(t.runs.map((r) => [r.k, r.escalated, r.flagged, r.usd.tier2, r.href]), [[1, true, 2, 0.42, "/series/guest-watch/triage/1"]]); + await assert.rejects(lib.triage.readTriageRunView("guest-watch", 9), (e: { status?: number }) => e.status === 404); +}); + +test("marks: right and wrong per flag; the precision over the schedule; the suggestion (never applied)", async () => { + await lib.triage.markFlag("guest-watch", 1, "f2", "right"); + const out = await lib.triage.markFlag("guest-watch", 1, "f1", "wrong"); + assert.deepEqual(Object.fromEntries(Object.entries(out.marks).map(([f, m]) => [f, m.verdict])), { f1: "wrong", f2: "right" }); + assert.deepEqual([out.precision.marked, out.precision.precision], [2, 0.5]); + assert.equal(out.suggestion.changed, false); + await assert.rejects(lib.triage.markFlag("guest-watch", 1, "f9", "right"), /no flag "f9"/); + const v = await lib.triage.readTriageRunView("guest-watch", 1); + assert.equal(v.marks.f2!.verdict, "right"); + // The schedule's own threshold is untouched. + assert.deepEqual(v.schedule.threshold, DEFAULT_TRIAGE_THRESHOLD); +}); + +test("the flags as a board, by umtool: strong before weak, by triage, the reason as the claim; a second open adds nothing; the Inbox's ensure is idempotent", async () => { + const made = await lib.triage.openTriageBoard("guest-watch", 1); + assert.deepEqual([made.id, made.created, made.added, made.href], ["guest-watch-2026-10-14", true, 2, "/research/guest-watch-2026-10-14"]); + const doc = await lib.boards.readCase(made.id); + assert.deepEqual(doc.triage && [doc.triage.schedule, doc.triage.k], ["guest-watch", 1]); + assert.deepEqual(doc.sections.map((s) => s.title), ["Strong flags", "Weak flags"]); + assert.deepEqual(doc.quotes.map((q) => [q.text, q.by, q.claim, q.cite.video, q.cite.t]), [ + ["I was a guest on the show last week", "triage", "She says she was a guest.", "v1", 5], + ["she mentioned the show once", "triage", "A passing mention.", "v2", 10], + ]); + await lib.boards.patchQuote(made.id, "q1", { claim: "Ours" }); + const again = await lib.triage.openTriageBoard("guest-watch", 1); + assert.deepEqual([again.created, again.added, again.already], [false, 0, 2]); + assert.equal((await lib.boards.readCase(made.id)).quotes[0]!.claim, "Ours"); + const s = (await readSchedule("guest-watch", paths))!; + const ensured = await lib.triage.ensureTriageBoards([s]); + assert.deepEqual([...ensured], [["guest-watch/1", "/research/guest-watch-2026-10-14"]]); +}); diff --git a/umtool/lib/research/triage.ts b/umtool/lib/research/triage.ts @@ -0,0 +1,277 @@ +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, 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/<schedule>/<k>/; 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 +// `<schedule>-t<k>`. +// +// 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<Schedule, "triage">, newest: TriageFile | null): TriageThreshold { + return s.triage?.threshold ?? newest?.threshold ?? DEFAULT_TRIAGE_THRESHOLD; +} + +async function scheduleOf(id: string): Promise<Schedule> { + 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 `<schedule>-t<k>`. */ +export function triageBoardId(s: Pick<Schedule, "id" | "ticks">, 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<FlagMark[]> { + 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<TriageTier2> { + 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<string, { quote?: string }> }; + 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<TriageRunView> { + 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<string, FlagMark>; + 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<ScheduleTriage> { + 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, + 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<string, FlagMark>, 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<string> { + 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<TriageBoardResult> { + 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<Schedule, "id" | "shape" | "ticks">[]): Promise<Map<string, string>> { + const out = new Map<string, string>(); + 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; +}