commit bdd7dc10349788440f36f0ba0e20429c14a4a314
parent e6bcf51f6876c0499fdb33f314ac118b3643aac1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 17:17:33 -0400
Merge main (R6 live, 409b8b24) into ux/board-race
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
71 files changed, 4941 insertions(+), 128 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,10 +145,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
-| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'` |
+| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
-| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'` |
+| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'` |
### Usage, flags and environment
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -987,6 +987,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. |
| `cut` | object — see below | The cut task's limits (below). |
| `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. |
+| `triage` | object — see below | Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below). |
#### `generation.routes`
@@ -1061,6 +1062,16 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `contradictedRecall` | `0` | The least share of the claims the operator ruled CONTRADICTED that the model must rule so. |
| `notFoundRecall` | `0` | The least share of the claims the operator ruled NOT_FOUND that the model must rule so. |
+#### `generation.triage`
+
+| Key | Default | Description |
+|---|---|---|
+| `model` | `"local"` | What the window judge runs on: `local` (`models.local`, through the GPU arbiter on `draft:local`, $0 marginal) or `extractor` (`models.extractor`, on the API, metered). |
+| `strong` | `1` | Escalate when this many STRONG flags (the judge's score 3: the line directly answers the question) are found. 0 = strong flags alone never escalate. A schedule may set its own. |
+| `weak` | `3` | Escalate when this many flags of any strength (score 2 or 3) are found. 0 = off. A schedule may set its own. |
+| `maxEscalationsPerDay` | `3` | The most escalations (tier 2 sweeps) a day (UTC) across every schedule. Past it a tick is held by the cap — a Your call card — with its flags kept. 0 = no cap. |
+| `maxCandidates` | `40` | The most candidates one triage judges; the rest stay new for the next tick. |
+
Default:
```json
@@ -1119,6 +1130,13 @@ Default:
"notFoundRecall": 0
},
"models": []
+ },
+ "triage": {
+ "model": "local",
+ "strong": 1,
+ "weak": 3,
+ "maxEscalationsPerDay": 3,
+ "maxCandidates": 40
}
}
```
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -38,7 +38,16 @@
// task "refresh" (umtool R4, ./reportRefresh.ts): re-fetch, see what changed,
// update — `iteration` (default: the current report's), `model`,
// `extractorModel`, `maxUsd`; `fetch: false` skips the fetch and the build;
-// `dryRun: true` answers the plan and writes nothing.
+// `dryRun: true` answers the plan and writes nothing; `ids` (umtool R6: what a
+// triage flagged) — the update reads these recordings, whatever else changed.
+//
+// task "triage" (umtool R6, ./reportTriage.ts): the cheap pass — `article` is
+// its OWNER (the schedule it is for), `question`, `channels`, `terms`
+// (`regex`), `topics`, `threshold`, `since`, `ids`, `windows`,
+// `maxCandidates`, `model` (default settings.generation.triage's). A run of
+// reports/.triage/<owner>/; the answer's `iteration` is the run's number.
+// A sweep's `triage` ("<owner>/<k>") names the triage it escalates (kept in
+// its scope; its trace's first line after the start is the triage's tiers).
//
// The iteration is created `queued` before the job, and the job's id set on it;
// the job runs the S5 task in process. Its queue is the model's provider's:
@@ -114,6 +123,14 @@ export const REPORT_DRAFT_BODY_KEYS = [
"ids",
"fetch",
"dryRun",
+ "terms",
+ "regex",
+ "topics",
+ "threshold",
+ "windows",
+ "since",
+ "maxCandidates",
+ "triage",
] as const;
// A seed's size: a board of a few hundred quotes, with room.
@@ -124,7 +141,9 @@ export class ReportDraftInputError extends Error {}
// A refresh (umtool R4) is a report-draft task with no route of its own: its
// update runs on the sweep route's model.
export const REFRESH_TASK = "refresh" as const;
-export type ReportDraftTask = GenerationTask | typeof REFRESH_TASK;
+// A triage (umtool R6) neither: it runs on settings.generation.triage's model.
+export const TRIAGE_DRAFT_TASK = "triage" as const;
+export type ReportDraftTask = GenerationTask | typeof REFRESH_TASK | typeof TRIAGE_DRAFT_TASK;
export type ReportDraftBody = {
task: ReportDraftTask;
@@ -149,6 +168,16 @@ export type ReportDraftBody = {
ids?: string[];
fetch?: boolean;
dryRun?: boolean;
+ // A triage's (umtool R6).
+ terms?: string;
+ regex?: boolean;
+ topics?: string[];
+ threshold?: { strong: number; weak: number };
+ windows?: Record<string, { start: number; end: number }[]>;
+ since?: string;
+ maxCandidates?: number;
+ // A sweep's: the triage it escalates ("<owner>/<k>").
+ triage?: { owner: string; k: number };
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -157,7 +186,7 @@ export function isKnownApiModel(model: string): boolean {
return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`));
}
-const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK];
+const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK, TRIAGE_DRAFT_TASK];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -243,11 +272,58 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
}
const ids = list("ids");
if (ids !== undefined) {
- if (out.task !== "sweep") fail('"ids" is a sweep\'s: the recordings it is restricted to');
+ if (out.task !== "sweep" && out.task !== REFRESH_TASK && out.task !== TRIAGE_DRAFT_TASK) fail('"ids" is a sweep\'s (the recordings it is restricted to), a refresh\'s or a triage\'s');
if (!ids.length) fail('"ids" names at least one recording');
if (ids.length > 2000) fail('"ids" is at most 2,000 recordings');
out.ids = [...new Set(ids)];
}
+ // A triage's own keys (umtool R6).
+ const triageKeys = ["terms", "regex", "topics", "threshold", "windows", "since", "maxCandidates"] as const;
+ const given = triageKeys.filter((k) => b[k] !== undefined && b[k] !== null);
+ if (given.length && out.task !== TRIAGE_DRAFT_TASK) fail(`${given.map((k) => `"${k}"`).join(", ")} ${given.length === 1 ? "is" : "are"} a triage's`);
+ if (out.task === TRIAGE_DRAFT_TASK) {
+ set("terms", text("terms"));
+ if (b.regex !== undefined && b.regex !== null) {
+ if (typeof b.regex !== "boolean") fail('"regex" is true or false');
+ out.regex = b.regex;
+ }
+ set("topics", list("topics"));
+ if (b.threshold !== undefined && b.threshold !== null) {
+ const t = b.threshold as Record<string, unknown>;
+ const ok = (v: unknown) => v === undefined || (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 50);
+ if (!t || typeof t !== "object" || Array.isArray(t) || !ok(t.strong) || !ok(t.weak)) fail('"threshold" is {"strong": n, "weak": n}: whole numbers 0–50 (0: that rule off)');
+ out.threshold = { strong: (t.strong as number | undefined) ?? 1, weak: (t.weak as number | undefined) ?? 3 };
+ }
+ const since = text("since");
+ if (since !== undefined && !ymd.test(since)) fail('"since" is a YYYY-MM-DD date');
+ set("since", since);
+ if (b.maxCandidates !== undefined && b.maxCandidates !== null) {
+ if (typeof b.maxCandidates !== "number" || !Number.isInteger(b.maxCandidates) || b.maxCandidates < 1 || b.maxCandidates > 500) fail('"maxCandidates" is a whole number, 1–500');
+ out.maxCandidates = b.maxCandidates;
+ }
+ if (b.windows !== undefined && b.windows !== null) {
+ const w = b.windows as Record<string, unknown>;
+ if (!w || typeof w !== "object" || Array.isArray(w)) fail('"windows" is {"<id>": [{"start": s, "end": s}, …]}');
+ const outW: Record<string, { start: number; end: number }[]> = {};
+ for (const [id, list] of Object.entries(w)) {
+ if (!Array.isArray(list) || !list.every((x) => x && typeof x === "object" && typeof (x as { start?: unknown }).start === "number" && typeof (x as { end?: unknown }).end === "number" && (x as { end: number }).end >= (x as { start: number }).start)) {
+ fail(`"windows.${id}" is a list of {"start", "end"} in seconds, end ≥ start`);
+ }
+ outW[id] = (list as { start: number; end: number }[]).map((x) => ({ start: x.start, end: x.end }));
+ }
+ out.windows = outW;
+ }
+ const extra = (["feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy", "iteration", "extractorModel"] as const).filter((k) => out[k] !== undefined);
+ if (extra.length) fail(`a triage takes no ${extra.join(", ")}`);
+ if (!out.question) fail("a triage needs its question");
+ if (!out.channels?.length) fail("a triage needs its channels");
+ }
+ if (b.triage !== undefined && b.triage !== null) {
+ if (out.task !== "sweep") fail('"triage" is a sweep\'s: the triage it escalates ("<owner>/<k>")');
+ const m = typeof b.triage === "string" ? /^([a-z0-9][a-z0-9-]{0,63})\/([1-9]\d{0,6})$/.exec(b.triage) : null;
+ if (!m) fail('"triage" names a triage run: "<owner>/<k>"');
+ out.triage = { owner: m![1]!, k: Number(m![2]) };
+ }
if (out.task === REFRESH_TASK) {
const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined);
if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`);
@@ -373,7 +449,8 @@ export async function resolveCorpus(
return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build };
}
-export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number; warnings?: string[] };
+// A triage's answer names its run (`iteration` is the run's number).
+export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number; warnings?: string[]; triage?: { owner: string; k: number } };
export async function enqueueReportDraft(raw: Record<string, unknown>, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
const paths = deps.paths;
@@ -385,6 +462,14 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return { result: { ok: false, error: (e as Error).message } };
}
const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ if (body.task === TRIAGE_DRAFT_TASK) {
+ try {
+ const { enqueueTriage } = await import("./reportTriage");
+ return await enqueueTriage(body, deps);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ }
if (body.task === REFRESH_TASK) {
if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)');
try {
@@ -473,7 +558,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
kind: kindOf(body.task),
model,
...(body.task === "sweep" || body.task === "research"
- ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}) } }
+ ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } }
: { parent: body.iteration!, feedback: body.feedback }),
},
paths,
@@ -586,8 +671,9 @@ async function runReportDraft(
let input: TaskInput;
switch (body.task) {
case "refresh":
- // A refresh is its own job (./reportRefresh.ts), never this one.
- throw new Error("a refresh runs as its own job");
+ case "triage":
+ // A refresh and a triage are their own jobs (./reportRefresh.ts, ./reportTriage.ts), never this one.
+ throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
provider === "api"
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -435,7 +435,7 @@ async function runRefreshJob(
let result: Awaited<ReturnType<typeof refreshTask>> | null = null;
try {
result = await refreshTask(
- { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, ...(body.fetch === false ? { fetch: false } : {}) },
+ { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, ...(body.fetch === false ? { fetch: false } : {}), ...(body.ids?.length ? { ids: body.ids } : {}) },
taskDeps,
);
} catch (e) {
diff --git a/common/controller/reportSchedule.test.ts b/common/controller/reportSchedule.test.ts
@@ -137,11 +137,13 @@ test("create: a series in .series/, a living report beside a NEW article that is
);
});
-test("create refuses: the reserved shape, no scope, an unknown channel, an edition flag on the wrong shape, a cap over max", async () => {
+test("create refuses: an unknown shape, no scope, an unknown channel, an edition flag on the wrong shape, a cap over max", async () => {
const paths = store();
const deps = depsOf(paths);
const ask = (b: Record<string, unknown>) => reportScheduleAction({ action: "create", topic: "T", channels: ["chan-a"], cadence: weekly, tz: TZ, shape: "series", ...b }, deps);
- assert.match(((await ask({ shape: "watch" })) as { error: string }).error, /reserved/);
+ assert.match(((await ask({ shape: "nope" })) as { error: string }).error, /"shape" is one of living, series, watch/);
+ assert.match(((await ask({ shape: "watch", triageFirst: true })) as { error: string }).error, /a watch always triages first/);
+ assert.match(((await ask({ threshold: { strong: 1 } })) as { error: string }).error, /"threshold" is/);
assert.match(((await ask({ channels: [] })) as { error: string }).error, /scope/);
assert.match(((await ask({ channels: ["nope"] })) as { error: string }).error, /no such channel in this editor: nope/);
assert.match(((await ask({ autoMakeCurrent: true })) as { error: string }).error, /living report/);
@@ -470,3 +472,178 @@ test("the wired tick: living updated + autoMakeCurrent is made current (only on
await runTick("wired", { trigger: "now", jobId: "j5" }, depsOf(paths, steps({ status: "no-change", usd: 0 })), ctx());
assert.equal(fetchCalls.length, 1);
});
+
+// ─── R6: triage first, and the watch ───
+
+import { escalationCapRefusal, triageStep, type EditionInput, type TriageStepInput, type TriageStepOutcome } from "./reportTick";
+import { TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, type TriageFile, type TriageFlag } from "../lib/report/draft/triage/types";
+
+const flag = (id: string, strength: "strong" | "weak", f = "f1"): TriageFlag => ({
+ f,
+ id,
+ channel: "chan-a",
+ title: id,
+ date: "2026-10-13",
+ window: { start: 0, end: 30 },
+ line: `a line of ${id} the judge flagged`,
+ at: 5,
+ score: strength === "strong" ? 3 : 2,
+ strength,
+ reason: `why ${id}`,
+ checked: "cues",
+});
+
+function triageFile(owner: string, k: number, flags: TriageFlag[], o: Partial<TriageFile> = {}): TriageFile {
+ const threshold = { strong: 1, weak: 3 };
+ return {
+ format: TRIAGE_FORMAT,
+ version: TRIAGE_VERSION,
+ owner,
+ k,
+ status: "done",
+ model: "qwen3:8b",
+ provider: "local",
+ question: "Q?",
+ scope: { channels: ["chan-a"] },
+ terms: "co-host",
+ regex: false,
+ topics: [],
+ threshold,
+ since: "2026-10-07",
+ knownCount: 10,
+ createdAt: NOW.toISOString(),
+ tier0: { candidates: [...new Set(flags.map((f) => f.id)), "quiet-1"].map((id) => ({ id, channel: "Chan A", title: id, date: "2026-10-13", matches: 1, by: ["terms"] })), scanned: 12, newCount: 3, cut: [], partial: false, unreached: [], perQuery: [], newBy: "id" },
+ tier1: { model: "qwen3:8b", flags, dismissed: [{ id: "quiet-1", stage: "judge", reason: "not relevant to the question" }], read: 2, windows: 2, chunks: 2, usd: 0 },
+ escalation: escalationOf(flags, threshold),
+ cost: { tier0: 0, tier1: 0 },
+ summary: "summary",
+ warnings: [],
+ ...o,
+ };
+}
+
+/** A triage step over a canned triage.json, recording what it was asked. */
+function triageOf(flags: TriageFlag[], asked: TriageStepInput[] = [], o: Partial<TriageFile> = {}): NonNullable<TickSteps["triage"]> {
+ let k = 0;
+ return async (input): Promise<TriageStepOutcome> => {
+ asked.push(input);
+ return { status: "done", file: triageFile(input.schedule.id, ++k, flags, o), jobId: `tj${k}` };
+ };
+}
+
+test("a watch: create (no article, its plan names the triage), then a tick below the threshold ends no-change, $0, its triage on the line", async () => {
+ const paths = store();
+ const deps = depsOf(paths);
+ const plan = await reportScheduleAction({ action: "create", dryRun: true, shape: "watch", topic: "Co-host watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", topics: ["guest"], threshold: { strong: 1, weak: 2 } }, deps);
+ assert.equal(plan.ok, true, JSON.stringify(plan));
+ assert.deepEqual(plan.plan.triage, { model: "qwen3:8b", provider: "local", threshold: { strong: 1, weak: 2 }, thresholdWords: "1 strong or 2 weak", maxEscalationsPerDay: 3, topics: ["guest"], terms: "co-host" });
+ assert.equal(plan.plan.article, null);
+ assert.equal(plan.plan.firstWindow, null);
+ const made = await reportScheduleAction({ action: "create", shape: "watch", topic: "Co-host watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", topics: ["guest"], threshold: { strong: 1, weak: 2 } }, deps);
+ assert.equal(made.ok, true, JSON.stringify(made));
+ assert.ok(existsSync(seriesFile(paths, "co-host-watch")));
+ assert.deepEqual(made.schedule.scope.topics, ["guest"]);
+ assert.deepEqual(made.schedule.triage, { threshold: { strong: 1, weak: 2 } });
+
+ const asked: TriageStepInput[] = [];
+ const editions: EditionInput[] = [];
+ const fetched: unknown[] = [];
+ const tick = await runTick(
+ "co-host-watch",
+ { trigger: "now", jobId: "w1" },
+ depsOf(paths, { fetchAndBuild: async (scope) => (fetched.push(scope), { ok: true }), triage: triageOf([flag("v1", "weak")], asked), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 1, iteration: 1 }) }),
+ ctx(),
+ );
+ assert.deepEqual(fetched, [{ channels: ["chan-a"] }]);
+ assert.deepEqual(asked[0]!.scope, { channels: ["chan-a"] });
+ // No last run: "new" counts from the cadence's length back.
+ assert.equal(asked[0]!.since, "2026-10-07");
+ assert.equal(tick.status, "no-change");
+ assert.equal(tick.usd, 0);
+ assert.match(tick.reason!, /^triage: 0 strong flags, 1 weak flag \(threshold: 1 strong or 3 weak\) — below the threshold, nothing escalated$/);
+ assert.deepEqual({ k: tick.triage!.k, candidates: tick.triage!.candidates, flagged: tick.triage!.flagged, escalated: tick.triage!.escalated }, { k: 1, candidates: 2, flagged: 1, escalated: false });
+ assert.equal(editions.length, 0);
+});
+
+test("a watch escalates: an API sweep of the flagged ids as <watch>-<date>, the triage named; usd is tier 1 + tier 2; the day's escalation cap holds the next", async () => {
+ const paths = store();
+ await createSchedule(parseCreate({ shape: "watch", topic: "Watch", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths));
+ const editions: EditionInput[] = [];
+ const steps = (): Partial<TickSteps> => ({
+ triage: triageOf([flag("v1", "strong"), flag("v2", "weak", "f2"), flag("v1", "weak", "f3")], [], { cost: { tier0: 0, tier1: 0.02 } }),
+ generateEdition: async (i) => (editions.push(i), { status: "done", usd: 0.9, iteration: 1, jobId: "sweep-1" }),
+ });
+ const gen1 = () => ({ generation: gen({ triage: { maxEscalationsPerDay: 1 } }) });
+ const tick = await runTick("watch", { trigger: "now", jobId: "w1" }, depsOf(paths, steps(), NOW, { settings: gen1 }), ctx());
+ assert.equal(tick.status, "done", tick.reason);
+ assert.equal(tick.article, "watch-2026-10-14");
+ assert.equal(tick.iteration, 1);
+ assert.equal(tick.usd, 0.92);
+ assert.deepEqual(editions[0]!.ids, ["v1", "v2"]);
+ assert.deepEqual(editions[0]!.triage, { owner: "watch", k: 1 });
+ assert.equal(editions[0]!.title, "Watch · 2026-10-14");
+ assert.equal(editions[0]!.quietCheck, false);
+ assert.deepEqual({ escalated: tick.triage!.escalated, ids: tick.triage!.ids, usd: tick.triage!.usd }, { escalated: true, ids: ["v1", "v2"], usd: { tier1: 0.02, tier2: 0.9 } });
+ assert.equal(tick.triage!.top[0]!.score, 3);
+
+ // The cap: one escalation a day, and one ran.
+ assert.match((await escalationCapRefusal(paths, NOW, 1))!, /the day's escalation cap is reached: 1 escalation today \(2026-10-14, UTC\), the cap 1/);
+ assert.equal(await escalationCapRefusal(paths, NOW, 0), null);
+ const held = await runTick("watch", { trigger: "now", jobId: "w2" }, depsOf(paths, steps(), NOW, { settings: gen1 }), ctx());
+ assert.equal(held.status, "held-by-cap");
+ assert.match(held.reason!, /escalation cap is reached/);
+ assert.equal(held.triage!.escalated, false);
+ assert.match(held.triage!.capped!, /escalation cap/);
+ assert.equal(editions.length, 1);
+});
+
+test("triage first: a series below the threshold is a quiet edition ($0); above, its edition sweeps the flagged ids (no window check); a living report's refresh reads them with no second fetch", async () => {
+ const paths = store();
+ await createSchedule(parseCreate({ shape: "series", topic: "Tri", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths));
+ const editions: EditionInput[] = [];
+ const quiet = await runTick("tri", { trigger: "now", jobId: "s1" }, depsOf(paths, { triage: triageOf([]), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 1, iteration: 1 }) }), ctx());
+ assert.equal(quiet.status, "quiet");
+ assert.equal(quiet.edition, 1);
+ const s1 = (await readSchedule("tri", paths))!;
+ assert.deepEqual({ status: s1.editions![0]!.status, window: s1.editions![0]!.window }, { status: "quiet", window: { from: "2026-10-07", to: "2026-10-13" } });
+ assert.equal(editions.length, 0);
+
+ // A week on: one strong flag, the edition sweeps it.
+ const later = new Date("2026-10-21T12:00:00.000Z");
+ const made = await runTick("tri", { trigger: "now", jobId: "s2" }, depsOf(paths, { triage: triageOf([flag("late-old", "strong")]), generateEdition: async (i) => (editions.push(i), { status: "done", usd: 0.7, iteration: 1 }) }, later), ctx());
+ assert.equal(made.status, "done", made.reason);
+ assert.deepEqual({ ids: editions[0]!.ids, quietCheck: editions[0]!.quietCheck, window: editions[0]!.window }, { ids: ["late-old"], quietCheck: false, window: { from: "2026-10-14", to: "2026-10-20" } });
+
+ await createSchedule(parseCreate({ shape: "living", topic: "Live tri", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths));
+ await doneIteration(paths, "live-tri");
+ const refreshed: Record<string, unknown>[] = [];
+ const fetched: unknown[] = [];
+ const living = await runTick(
+ "live-tri",
+ { trigger: "now", jobId: "l1" },
+ depsOf(paths, { fetchAndBuild: async (sc) => (fetched.push(sc), { ok: true }), triage: triageOf([flag("v9", "strong")]), refresh: async (_a, o) => (refreshed.push(o), { status: "done", usd: 0.5, iteration: 2 }) }),
+ ctx(),
+ );
+ assert.equal(living.status, "done");
+ assert.deepEqual(fetched, [{ channels: ["chan-a"] }]);
+ assert.deepEqual(refreshed, [{ ids: ["v9"], fetch: false }]);
+ const below = await runTick("live-tri", { trigger: "now", jobId: "l2" }, depsOf(paths, { triage: triageOf([]), refresh: async () => assert.fail("below the threshold: no refresh") }), ctx());
+ assert.deepEqual({ status: below.status, usd: below.usd }, { status: "no-change", usd: 0 });
+});
+
+test("triageStep: report-draft triage for the schedule (its terms, topics, threshold, since), awaited; its triage.json is the outcome", async () => {
+ const paths = store();
+ await createSchedule(parseCreate({ shape: "watch", topic: "Step", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host", regex: true, topics: ["guest"], threshold: { strong: 2, weak: 4 } }), depsOf(paths));
+ const s = (await readSchedule("step", paths))!;
+ const asked: Record<string, unknown>[] = [];
+ const draft = { paths, corpusTools: async () => assert.fail("no corpus") };
+ const step = triageStep(draft as never, {
+ enqueueReportDraft: (async (b: Record<string, unknown>) => (asked.push(b), { result: okJob("tj"), iteration: 3 })) as never,
+ readTriageFile: (async (owner: string, k: number) => triageFile(owner, k, [flag("v1", "strong")])) as never,
+ });
+ const out = await step({ schedule: s, scope: { channels: ["chan-a"] }, since: "2026-10-07" }, ctx());
+ assert.deepEqual(asked[0], { task: "triage", article: "step", question: "Step", channels: ["chan-a"], terms: "co-host", regex: true, topics: ["guest"], threshold: { strong: 2, weak: 4 }, since: "2026-10-07" });
+ assert.deepEqual({ status: out.status, k: out.file?.k, jobId: out.jobId }, { status: "done", k: 3, jobId: "tj" });
+ const refused = await triageStep(draft as never, { enqueueReportDraft: (async () => ({ result: { ok: false, error: "no composed build holds chan-a" } })) as never })({ schedule: s, scope: { channels: ["chan-a"] }, since: null }, ctx());
+ assert.deepEqual({ status: refused.status, reason: refused.reason }, { status: "failed", reason: "the triage could not start: no composed build holds chan-a" });
+});
diff --git a/common/controller/reportSchedule.ts b/common/controller/reportSchedule.ts
@@ -18,7 +18,8 @@ import type { Paths } from "../lib/paths";
import { writeJsonAtomic } from "../lib/jsonFile-server";
import { withArticleStoreLock, RESERVED_ARTICLE_IDS, ARTICLE_ITERATIONS_DIRNAME } from "../lib/report/registry";
import { isReportId } from "../lib/report/schema";
-import { capFor, type GenerationSettings } from "../lib/generationSettings";
+import { capFor, triageModelOf, type GenerationSettings } from "../lib/generationSettings";
+import { thresholdWords } from "../lib/report/draft/triage/types";
import { providerOf } from "../lib/llm";
import {
CadenceError,
@@ -139,6 +140,11 @@ export type CreateInput = {
autoMakeCurrent?: boolean;
model?: string;
maxUsd?: number;
+ // umtool R6: triage first (living, series; a watch always triages), its
+ // digest topics and its own threshold.
+ triageFirst?: boolean;
+ topics?: string[];
+ threshold?: { strong: number; weak: number };
};
const ymdRe = /^\d{4}-\d{2}-\d{2}$/;
@@ -146,7 +152,6 @@ const ymdRe = /^\d{4}-\d{2}-\d{2}$/;
/** The create body, judged without touching the disk. */
export function parseCreate(b: Record<string, unknown>): CreateInput {
const shape = b.shape;
- if (shape === "watch") fail('"watch" is reserved (triage first, R6): make a "living" report or a "series"');
if (typeof shape !== "string" || !(OFFERED_SHAPES as readonly string[]).includes(shape)) fail(`"shape" is one of ${OFFERED_SHAPES.join(", ")}`);
const text = (k: string) => {
const v = b[k];
@@ -185,6 +190,10 @@ export function parseCreate(b: Record<string, unknown>): CreateInput {
if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars');
maxUsd = b.maxUsd as number;
}
+ if (b.triageFirst !== undefined && typeof b.triageFirst !== "boolean") fail('"triageFirst" is true or false');
+ if (b.triageFirst === true && shape === "watch") fail('a watch always triages first: "triageFirst" is a living report\'s or a series\'');
+ const topics = parseTopics(b.topics);
+ const threshold = parseThreshold(b.threshold);
return {
shape: shape as ScheduleShape,
topic: topic!,
@@ -201,9 +210,31 @@ export function parseCreate(b: Record<string, unknown>): CreateInput {
...(b.autoMakeCurrent === true ? { autoMakeCurrent: true } : {}),
...(text("model") ? { model: text("model") } : {}),
...(maxUsd !== undefined ? { maxUsd } : {}),
+ ...(b.triageFirst === true ? { triageFirst: true } : {}),
+ ...(topics?.length ? { topics } : {}),
+ ...(threshold ? { threshold } : {}),
};
}
+/** A triage's digest topics: a list (or a comma-separated text) of tags. */
+function parseTopics(v: unknown): string[] | undefined {
+ if (v === undefined || v === null || v === "") return undefined;
+ const arr = typeof v === "string" ? v.split(",") : v;
+ if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string")) fail('"topics" is a list of digest topic tags');
+ const out = [...new Set((arr as string[]).map((x) => x.trim()).filter(Boolean))];
+ if (out.some((x) => x.length > 80)) fail('a topic is at most 80 characters');
+ return out.slice(0, 20);
+}
+
+/** A schedule's own triage threshold: {strong, weak}, whole numbers 0–50. */
+function parseThreshold(v: unknown): { strong: number; weak: number } | undefined {
+ if (v === undefined || v === null) return undefined;
+ const t = v as Record<string, unknown>;
+ const ok = (x: unknown) => typeof x === "number" && Number.isInteger(x) && x >= 0 && x <= 50;
+ if (!t || typeof t !== "object" || Array.isArray(t) || !ok(t.strong) || !ok(t.weak)) fail('"threshold" is {"strong": n, "weak": n}: whole numbers 0–50 (0: that rule off)');
+ return { strong: t.strong as number, weak: t.weak as number };
+}
+
export type SchedulePlan = {
id: string;
shape: ScheduleShape;
@@ -223,6 +254,8 @@ export type SchedulePlan = {
capUsd: number | null;
dailyCapUsd: number;
existingArticle: boolean;
+ // Triage first (umtool R6): its model, threshold and the day's escalation cap; null: none.
+ triage: { model: string; provider: "api" | "local"; threshold: { strong: number; weak: number }; thresholdWords: string; maxEscalationsPerDay: number; topics: string[]; terms: string | null } | null;
warnings: string[];
};
@@ -266,11 +299,15 @@ export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promis
const gen = deps.settings?.().generation;
const m = gen ? tickModel(gen, { ...(input.model ? { model: input.model } : {}), ...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}) }) : null;
if (m?.note) warnings.push(m.note);
- if (input.shape === "series" && !input.terms) warnings.push("no terms: a window is quiet only when no recording in scope falls in it");
+ if (input.shape === "series" && !input.terms && !input.triageFirst) warnings.push("no terms: a window is quiet only when no recording in scope falls in it");
+ const triaged = input.shape === "watch" || input.triageFirst === true;
+ if (triaged && !input.terms && !input.topics?.length) warnings.push(`no terms or topics: every new recording in scope is a candidate (up to ${gen?.triage.maxCandidates ?? 40} a tick)`);
const first = nextTickAfter(input.cadence, now.getTime(), input.tz, null);
const anchor = anchorFor(input.cadence, first, input.tz);
const fw = editionWindow({ cadence: input.cadence, editions: [], scope: { channels: input.channels, ...(input.from ? { from: input.from } : {}) } }, localDate(first, input.tz));
const firstWindow = input.shape === "series" && "window" in fw ? fw.window : null;
+ const threshold = input.threshold ?? (gen ? { strong: gen.triage.strong, weak: gen.triage.weak } : { strong: 1, weak: 3 });
+ const triageModel = gen ? triageModelOf(gen) : "";
const at = now.toISOString();
const schedule: Schedule = {
format: SCHEDULE_FORMAT,
@@ -286,6 +323,7 @@ export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promis
...(input.from ? { from: input.from } : {}),
...(input.terms ? { terms: input.terms } : {}),
...(input.regex ? { regex: true } : {}),
+ ...(input.topics?.length ? { topics: input.topics } : {}),
},
cadence: input.cadence,
tz: input.tz,
@@ -294,6 +332,8 @@ export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promis
...(input.shape === "living" ? { autoMakeCurrent: input.autoMakeCurrent === true } : {}),
...(input.model ? { model: input.model } : {}),
...(input.maxUsd ? { caps: { maxUsd: input.maxUsd } } : {}),
+ ...(input.triageFirst ? { triageFirst: true } : {}),
+ ...(input.threshold ? { triage: { threshold: input.threshold } } : {}),
createdAt: at,
updatedAt: at,
lastTick: null,
@@ -324,6 +364,17 @@ export async function planCreate(input: CreateInput, deps: ScheduleDeps): Promis
capUsd: m?.capUsd ?? null,
dailyCapUsd: gen?.caps.daily ?? 0,
existingArticle,
+ triage: triaged
+ ? {
+ model: triageModel,
+ provider: triageModel && providerOf(triageModel) === "local" ? "local" : "api",
+ threshold,
+ thresholdWords: thresholdWords(threshold),
+ maxEscalationsPerDay: gen?.triage.maxEscalationsPerDay ?? 0,
+ topics: input.topics ?? [],
+ terms: input.terms ?? null,
+ }
+ : null,
warnings,
},
};
@@ -373,6 +424,9 @@ export type UpdateInput = {
autoMakeCurrent?: boolean;
model?: string | null;
maxUsd?: number | null;
+ triageFirst?: boolean;
+ topics?: string[] | null;
+ threshold?: { strong: number; weak: number } | null;
};
export function parseUpdate(b: Record<string, unknown>): UpdateInput {
@@ -422,7 +476,13 @@ export function parseUpdate(b: Record<string, unknown>): UpdateInput {
if (b.maxUsd !== null && (typeof b.maxUsd !== "number" || !(b.maxUsd > 0))) fail('"maxUsd" is a positive number of dollars, or null');
out.maxUsd = b.maxUsd as number | null;
}
- if (!Object.keys(out).length) fail("nothing to change: send topic, question, cadence, tz, channels, from, terms, regex, autoMakeCurrent, model or maxUsd");
+ if (b.triageFirst !== undefined) {
+ if (typeof b.triageFirst !== "boolean") fail('"triageFirst" is true or false');
+ out.triageFirst = b.triageFirst as boolean;
+ }
+ if (b.topics !== undefined) out.topics = b.topics === null || b.topics === "" ? null : (parseTopics(b.topics) ?? null);
+ if (b.threshold !== undefined) out.threshold = b.threshold === null ? null : (parseThreshold(b.threshold) ?? null);
+ if (!Object.keys(out).length) fail("nothing to change: send topic, question, cadence, tz, channels, from, terms, regex, autoMakeCurrent, model, maxUsd, triageFirst, topics or threshold");
return out;
}
@@ -437,6 +497,7 @@ export async function updateSchedule(id: string, patch: UpdateInput, deps: Sched
if (gen && patch.maxUsd) capFor(gen.caps, "sweep", patch.maxUsd);
return mutateSchedule(id, deps, (s, now) => {
if (patch.autoMakeCurrent !== undefined && s.shape !== "living") fail('"autoMakeCurrent" is a living report\'s');
+ if (patch.triageFirst === true && s.shape === "watch") fail("a watch always triages first");
const cadence = patch.cadence ?? s.cadence;
const tz = patch.tz ?? s.tz;
const replan = patch.cadence !== undefined || patch.tz !== undefined;
@@ -458,7 +519,19 @@ export async function updateSchedule(id: string, patch: UpdateInput, deps: Sched
else scope.terms = patch.terms;
}
if (patch.regex !== undefined) scope.regex = patch.regex;
+ if (patch.topics !== undefined) {
+ if (patch.topics === null || !patch.topics.length) delete scope.topics;
+ else scope.topics = patch.topics;
+ }
const next: Schedule = { ...s, cadence, tz, anchor, nextTick, scope };
+ if (patch.triageFirst !== undefined) {
+ if (patch.triageFirst) next.triageFirst = true;
+ else delete next.triageFirst;
+ }
+ if (patch.threshold !== undefined) {
+ if (patch.threshold === null) delete next.triage;
+ else next.triage = { ...(s.triage ?? {}), threshold: patch.threshold };
+ }
if (patch.topic) next.topic = patch.topic;
if (patch.question) next.question = patch.question;
if (patch.autoMakeCurrent !== undefined) next.autoMakeCurrent = patch.autoMakeCurrent;
@@ -516,6 +589,20 @@ export async function planDelete(id: string, deps: ScheduleDeps): Promise<Delete
refused,
};
}
+ if (s.shape === "watch") {
+ const found = [...new Set(s.ticks.filter((t) => t.article).map((t) => t.article!))];
+ return {
+ id,
+ shape: s.shape,
+ file: r!.file,
+ removes: `the watch ${s.id} (${cadenceWords(s.cadence)}): its schedule and ${s.ticks.length} tick${s.ticks.length === 1 ? "" : "s"} recorded`,
+ keeps: [
+ ...(found.length ? [`${found.length} article${found.length === 1 ? "" : "s"} its escalations made, as articles: ${found.join(", ")}`] : []),
+ `its triage runs (reports/.triage/${s.id}/) and the boards made from them`,
+ ],
+ refused,
+ };
+ }
const eds = (s.editions ?? []).filter((e) => e.article);
const quiet = (s.editions ?? []).length - eds.length;
return {
diff --git a/common/controller/reportScheduleOps.ts b/common/controller/reportScheduleOps.ts
@@ -6,10 +6,15 @@
// {"action": "list", "id"?} every schedule (or one), with its
// chip, its call and its spend
// {"action": "create", …, "dryRun"?} the plan (first tick, model, cap)
-// with dryRun, else the schedule
+// with dryRun, else the schedule;
+// shape living | series | watch
+// (R6: no article until a triage
+// finds something); triageFirst,
+// topics, threshold {strong, weak}
// {"action": "update", "id", …} topic, question, cadence, tz,
// channels, from, terms, regex,
-// autoMakeCurrent, model, maxUsd
+// autoMakeCurrent, model, maxUsd,
+// triageFirst, topics, threshold
// {"action": "pause" | "resume", "id"} a resume re-plans from now
// {"action": "delete", "id", "confirm"?} the plan, unless confirm: true
// {"action": "tick-now", "id"} one tick now (refused while one
@@ -58,6 +63,9 @@ export const REPORT_SCHEDULE_BODY_KEYS = [
"maxUsd",
"confirm",
"dryRun",
+ "triageFirst",
+ "topics",
+ "threshold",
] as const;
export type ScheduleView = Schedule & {
diff --git a/common/controller/reportTick.ts b/common/controller/reportTick.ts
@@ -11,7 +11,10 @@
// generateEdition(...) a sweep over a window as a new article (the
// existing generate path with from/to), after a
// window check: nothing in it is a QUIET edition
-// triage?(...) reserved for R6 (triage first)
+// triage?(...) R6's cheap pass (`report-draft {"task":"triage"}`):
+// tier 0 (what is new by id, matching the terms or
+// topics) and tier 1 (the local window judge), and
+// whether its flags reach the threshold
//
// THE TICK, by shape:
// living refresh (R4's task: its own stage 1 over the report's scope and
@@ -29,6 +32,19 @@
// "<topic> · week of <start>" / "<topic> · <date>". A quiet window
// is recorded, no article, $0; an empty one (a Tick now right after
// a tick) makes no edition and says so.
+// watch (R6) fetchAndBuild over the scope → triage → at or above the
+// threshold, an API sweep of the flagged recordings as a new
+// article `<watch>-<YYYY-MM-DD>` ("<topic> · <date>"): the Inbox's
+// Worth researching card; below it, `no-change`, the triage log, $0 API
+//
+// TRIAGE FIRST (R6; a living report's or a series' `triageFirst`, always a
+// watch's): fetch → triage → (escalate) → the shape's step on the FLAGGED ids
+// only — a living report's refresh reads them (no second fetch), a series'
+// edition sweeps them (no date bound: a late transcript is in). Below the
+// threshold the tick ends with its triage log, $0 API (a series' edition is
+// quiet). An escalation past the day's cap (settings.generation.triage
+// .maxEscalationsPerDay, over every schedule) is held — the operator's call,
+// the flags kept. The tick line keeps the triage in brief (`triage`).
//
// Caps: the generation policy's per-job cap (the schedule's own, never above
// caps.max) and the daily cap; a refusal ends the tick `held-by-cap` — the
@@ -56,6 +72,10 @@ import { addDays, cadenceDays, localDate } from "../lib/report/schedule/cadence"
import { readSchedule } from "../lib/report/schedule/store";
import { editionTitle, editionWindow, nothingToCover, type Edition, type Schedule, type Tick, type TickStatus } from "../lib/report/schedule/types";
import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage";
+import { listSchedules } from "../lib/report/schedule/store";
+import { triagesFirst } from "../lib/report/schedule/types";
+import { readTriageFile } from "../lib/report/draft/triage/store";
+import { tickTriageOf, type TickTriage, type TriageFile } from "../lib/report/draft/triage/types";
import { enqueueReportDraft, type ReportDraftDeps } from "./reportDraft";
import { fetchScope, readRefreshFile } from "./reportRefresh";
import {
@@ -99,6 +119,8 @@ export type StepOutcome = {
matched?: number;
// What a step skipped and said (a refresh's fetch on a held platform).
warnings?: string[];
+ // The article the step wrote (a watch's escalation).
+ article?: string;
};
export type EditionInput = {
@@ -111,17 +133,27 @@ export type EditionInput = {
window: { from: string; to: string };
// A series' window check (a living report's first sweep has none).
quietCheck: boolean;
+ // R6: the sweep reads only these recordings (what a triage flagged) — no
+ // date bound, the window is the edition's label — and names the triage it
+ // escalates.
+ ids?: string[];
+ triage?: { owner: string; k: number };
};
+/** R6: the triage step's ask — the scope (no window: new is by id), and "new" with no last run. */
+export type TriageStepInput = { schedule: Schedule; scope: { channels: string[]; from?: string; to?: string }; since: string | null };
+export type TriageStepOutcome = { status: "done" | "failed" | "cancelled"; file: TriageFile | null; reason?: string; jobId?: string };
+
export type TickSteps = {
// Stage 1 over a scope: a series' edition (its window), a living report's
// first sweep. A living report's refresh runs its own stage 1 (over its
// report's scope and every channel its citations touch).
fetchAndBuild(scope: { channels: string[]; from?: string; to?: string }, ctx: StepCtx): Promise<FetchOutcome>;
- refresh(article: string, o: { model?: string; maxUsd?: number }, ctx: StepCtx): Promise<StepOutcome>;
+ // R6: `ids` — the update reads only these (a triage's flags); `fetch: false` — stage 1 ran already.
+ refresh(article: string, o: { model?: string; maxUsd?: number; ids?: string[]; fetch?: boolean }, ctx: StepCtx): Promise<StepOutcome>;
generateEdition(input: EditionInput, ctx: StepCtx): Promise<StepOutcome>;
- // R6: a cheap pass that flags what is worth a sweep (not called yet).
- triage?(input: { schedule: Schedule; window: { from: string; to: string } }, ctx: StepCtx): Promise<unknown>;
+ // R6: the cheap pass that flags what is worth a sweep (triage first, a watch).
+ triage?(input: TriageStepInput, ctx: StepCtx): Promise<TriageStepOutcome>;
};
// Steps that refuse, saying so: what a deps without R4's wiring (r4Steps
@@ -155,7 +187,7 @@ export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition"
const paths = deps.draft.paths;
const gen = settingsOf(deps.draft);
let matched: number | undefined;
- if (input.quietCheck && deps.countWindow) {
+ if (input.quietCheck && !input.ids?.length && deps.countWindow) {
const c = await deps.countWindow({
channels: s.scope.channels,
from: window.from,
@@ -192,8 +224,9 @@ export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition"
article: input.article,
question: s.question,
channels: s.scope.channels,
- from: window.from,
- to: window.to,
+ // A triage's flagged recordings: no date bound (a late transcript is in).
+ ...(input.ids?.length ? { ids: input.ids } : { from: window.from, to: window.to }),
+ ...(input.triage ? { triage: `${input.triage.owner}/${input.triage.k}` } : {}),
model: m.model,
...(m.capUsd !== null ? { maxUsd: m.capUsd } : {}),
},
@@ -310,7 +343,10 @@ export function r4Steps(draft: ReportDraftDeps, calls: Partial<R4Calls> = {}): P
return { ok: true, note: `stage 1: ${fetched} fetch${fetched === 1 ? "" : "es"} done${r.build?.site ? `, ${r.build.site} built (${r.build.status})` : ""}`, warnings };
},
refresh: async (article, o, ctx) => {
- const out = await c.enqueueReportDraft({ task: "refresh", article, ...(o.model ? { model: o.model } : {}), ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}) }, draft);
+ const out = await c.enqueueReportDraft(
+ { task: "refresh", article, ...(o.model ? { model: o.model } : {}), ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), ...(o.ids?.length ? { ids: o.ids } : {}), ...(o.fetch === false ? { fetch: false } : {}) },
+ draft,
+ );
if (!out.result.ok || !("iteration" in out)) {
const reason = (out.result as { error: string }).error;
return { status: isCapRefusal(reason) ? "held-by-cap" : "failed", usd: 0, reason };
@@ -385,6 +421,76 @@ async function editionArticle(s: Schedule, day: string, paths: Pick<Paths, "arti
throw new Error(`no free edition id after ${base}`);
}
+// ─── R6: the triage step (the seam, wired) ───
+
+/** What the triage wiring calls (injectable: the unit tests stub it). */
+export type TriageCalls = { enqueueReportDraft: typeof enqueueReportDraft; readTriageFile: typeof readTriageFile };
+
+/**
+ * The triage step over the editor: `report-draft {"task":"triage"}` for the
+ * schedule (its id the run's owner: reports/.triage/<id>/), awaited (a
+ * cancelled tick cancels it), its triage.json the outcome.
+ */
+export function triageStep(draft: ReportDraftDeps, calls: Partial<TriageCalls> = {}): NonNullable<TickSteps["triage"]> {
+ const c: TriageCalls = { enqueueReportDraft, readTriageFile, ...calls };
+ return async (input, ctx) => {
+ const s = input.schedule;
+ const out = await c.enqueueReportDraft(
+ {
+ task: "triage",
+ article: s.id,
+ question: s.question,
+ channels: input.scope.channels,
+ ...(input.scope.from ? { from: input.scope.from } : {}),
+ ...(input.scope.to ? { to: input.scope.to } : {}),
+ ...(s.scope.terms ? { terms: s.scope.terms, ...(s.scope.regex ? { regex: true } : {}) } : {}),
+ ...(s.scope.topics?.length ? { topics: s.scope.topics } : {}),
+ ...(s.triage?.threshold ? { threshold: s.triage.threshold } : {}),
+ ...(input.since ? { since: input.since } : {}),
+ },
+ draft,
+ );
+ if (!out.result.ok || !("iteration" in out)) return { status: "failed", file: null, reason: `the triage could not start: ${(out.result as { error: string }).error}` };
+ const result = out.result as Extract<StreamActionResult, { ok: true }>;
+ void result.stream.cancel();
+ const k = out.iteration;
+ ctx.log(`triage ${s.id}/${k}: job ${result.jobId}`);
+ const stop = () => getRegistry().cancel(result.jobId);
+ ctx.signal.addEventListener("abort", stop, { once: true });
+ try {
+ await result.done;
+ } finally {
+ ctx.signal.removeEventListener("abort", stop);
+ }
+ const f = await c.readTriageFile(s.id, k, draft.paths).catch(() => null);
+ if (!f) return { status: ctx.signal.aborted ? "cancelled" : "failed", file: null, jobId: result.jobId, reason: `triage ${s.id}/${k} left no triage.json` };
+ ctx.log(`triage ${s.id}/${k} ended ${f.status}: ${f.summary}`);
+ return {
+ status: f.status === "done" ? "done" : f.status === "cancelled" || ctx.signal.aborted ? "cancelled" : "failed",
+ file: f,
+ jobId: result.jobId,
+ ...(f.status !== "done" ? { reason: f.error ?? f.summary } : {}),
+ };
+ };
+}
+
+/** Escalations the ticks of every schedule ran on the UTC day of `now` (the day's escalation cap counts them). */
+export async function escalationsToday(paths: Pick<Paths, "articlesDir">, now: Date): Promise<number> {
+ const day = utcDay(now);
+ let n = 0;
+ for (const s of await listSchedules(paths).catch(() => [])) for (const t of s.ticks) if (t.triage?.escalated && t.at.slice(0, 10) === day) n++;
+ return n;
+}
+
+/** The day's escalation cap's refusal, or null. */
+export async function escalationCapRefusal(paths: Pick<Paths, "articlesDir">, now: Date, cap: number): Promise<string | null> {
+ if (!(cap > 0)) return null;
+ const n = await escalationsToday(paths, now);
+ return n >= cap
+ ? `the day's escalation cap is reached: ${n} escalation${n === 1 ? "" : "s"} today (${utcDay(now)}, UTC), the cap ${cap} (settings.generation.triage.maxEscalationsPerDay) — the flags are kept; it resets at midnight UTC`
+ : null;
+}
+
export type TickRun = { trigger: "schedule" | "now"; scheduledFor?: string; missed?: number; jobId: string };
/** Run one tick of schedule `id` and record it. Answers the history line it wrote. */
@@ -408,6 +514,10 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
};
const today = localDate(now.getTime(), s.tz);
let edition: Edition | null = null;
+ // The triage this tick ran (R6), for its line.
+ const tri: { file: TriageFile | null } = { file: null };
+ const triageLine = (o: { tier2Usd?: number; capped?: string } = {}): { triage?: TickTriage } => (tri.file ? { triage: tickTriageOf(tri.file, o) } : {});
+ const tier1Usd = () => tri.file?.cost.tier1 ?? 0;
try {
ctx.log(`${s.shape} ${id}: ${run.trigger === "now" ? "ticked now" : `the ${run.scheduledFor} window`}${run.missed ? ` (stands in for ${run.missed} missed)` : ""}`);
// Stage 1 over a scope; what it skipped is the tick's warnings.
@@ -425,16 +535,46 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
};
const warned = () => (warnings.length ? { warnings: [...new Set(warnings)] } : {});
+ // R6: the triage, after stage 1. Answers the flagged ids to escalate on,
+ // or the tick's end (below the threshold, the cap, a failure).
+ const triage = async (o: { onBelow: (why: string) => Promise<Tick> }): Promise<{ ids: string[]; ref: { owner: string; k: number } } | { done: Tick }> => {
+ if (!deps.steps.triage) return { done: await finish({ status: "failed", usd: 0, reason: "not wired: no triage step (R6) in this process", ...warned() }) };
+ const back = addDays(today, -cadenceDays(s.cadence));
+ const since = s.scope.from && s.scope.from > back ? s.scope.from : back;
+ const t = await deps.steps.triage({ schedule: s, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, since }, ctx);
+ tri.file = t.file;
+ if (t.status !== "done" || !t.file) {
+ return { done: await finish({ status: t.status === "cancelled" ? "cancelled" : "failed", usd: tier1Usd(), reason: `the triage ${t.status === "cancelled" ? "was cancelled" : "failed"}${t.reason ? `: ${t.reason}` : ""}`, ...triageLine(), ...warned() }) };
+ }
+ const esc = t.file.escalation;
+ if (!esc?.escalate) return { done: await o.onBelow(`triage: ${esc?.why ?? t.file.summary} — below the threshold, nothing escalated`) };
+ const gen = (deps.settings ?? getSettings)().generation;
+ const capped = await escalationCapRefusal(deps.paths, now, gen.triage.maxEscalationsPerDay);
+ if (capped) {
+ ctx.log(`escalation held: ${capped}`);
+ return { done: await finish({ status: "held-by-cap", usd: tier1Usd(), reason: capped, ...triageLine({ capped }), ...warned() }) };
+ }
+ const ids = [...new Set((t.file.tier1?.flags ?? []).map((f) => f.id))];
+ ctx.log(`escalate: ${esc.why} — tier 2 reads ${ids.length} recording(s): ${ids.slice(0, 10).join(", ")}`);
+ return { ids, ref: { owner: t.file.owner, k: t.file.k } };
+ };
+
if (s.shape === "living") {
const article = s.article ?? s.id;
let out: StepOutcome;
if (!(await hasReportToRefresh(article, deps.paths))) {
- ctx.log(`${article} has no report yet: its first sweep`);
+ ctx.log(`${article} has no report yet: its first sweep${triagesFirst(s) ? " (triage applies from the next tick)" : ""}`);
const back = addDays(today, -cadenceDays(s.cadence));
const window = { from: s.scope.from ?? back, to: today };
const stopped = await stage1({ channels: s.scope.channels, ...window });
if (stopped) return stopped;
out = await deps.steps.generateEdition({ schedule: s, article, title: null, window, quietCheck: false }, ctx);
+ } else if (triagesFirst(s)) {
+ const stopped = await stage1({ channels: s.scope.channels });
+ if (stopped) return stopped;
+ const t = await triage({ onBelow: (why) => finish({ status: "no-change", usd: tier1Usd(), article, reason: why, ...triageLine(), ...warned() }) });
+ if ("done" in t) return t.done;
+ out = await deps.steps.refresh(article, { ...(s.model ? { model: s.model } : {}), ...(s.caps?.maxUsd ? { maxUsd: s.caps.maxUsd } : {}), ids: t.ids, fetch: false }, ctx);
} else {
out = await deps.steps.refresh(article, { ...(s.model ? { model: s.model } : {}), ...(s.caps?.maxUsd ? { maxUsd: s.caps.maxUsd } : {}) }, ctx);
}
@@ -450,16 +590,39 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
}
return await finish({
status: out.status,
- usd: out.usd,
+ usd: Math.round((out.usd + tier1Usd()) * 10_000) / 10_000,
article,
...(out.iteration ? { iteration: out.iteration } : {}),
...(reason ? { reason } : {}),
...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}),
+ ...triageLine({ tier2Usd: out.usd }),
+ ...warned(),
+ });
+ }
+
+ if (s.shape === "watch") {
+ // No article until something is found (R6).
+ const stopped = await stage1({ channels: s.scope.channels });
+ if (stopped) return stopped;
+ const t = await triage({ onBelow: (why) => finish({ status: "no-change", usd: tier1Usd(), reason: why, ...triageLine(), ...warned() }) });
+ if ("done" in t) return t.done;
+ const article = await editionArticle(s, today, deps.paths);
+ const title = `${s.topic} · ${today}`;
+ const since = tri.file?.since ?? addDays(today, -cadenceDays(s.cadence));
+ const out = await deps.steps.generateEdition({ schedule: s, article, title, window: { from: since < today ? since : today, to: today }, quietCheck: false, ids: t.ids, triage: t.ref }, ctx);
+ const made = out.iteration !== undefined;
+ return await finish({
+ status: out.status === "quiet" ? "no-change" : out.status,
+ usd: Math.round((out.usd + tier1Usd()) * 10_000) / 10_000,
+ ...(made ? { article, iteration: out.iteration } : {}),
+ ...(out.reason ? { reason: out.reason } : {}),
+ ...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}),
+ ...triageLine({ tier2Usd: out.usd }),
...warned(),
});
}
- if (s.shape !== "series") return await finish({ status: "failed", usd: 0, reason: `a ${s.shape} schedule has no tick yet (R6)` });
+ if (s.shape !== "series") return await finish({ status: "failed", usd: 0, reason: `a ${s.shape} schedule has no tick` });
const w = editionWindow(s, today);
if ("empty" in w) {
// Nothing between the last edition and today: no edition, $0, no card.
@@ -472,10 +635,24 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
// Named for the tick's day (the window ends the day before it).
const article = await editionArticle(s, today, deps.paths);
const title = editionTitle(s.topic, s.cadence, window);
+ let flagged: { ids: string[]; ref: { owner: string; k: number } } | null = null;
+ if (triagesFirst(s)) {
+ // Below the threshold: a quiet edition (its window covered by the triage), $0 API.
+ const t = await triage({
+ onBelow: async (why) => {
+ const e: Edition = { n, at: now.toISOString(), window, title, status: "quiet", usd: tier1Usd(), reason: why, jobId: run.jobId };
+ await putEdition(id, e, deps);
+ return finish({ status: "quiet", usd: tier1Usd(), edition: n, reason: why, ...triageLine(), ...warned() });
+ },
+ });
+ if ("done" in t) return t.done;
+ flagged = t;
+ }
edition = { n, at: now.toISOString(), window, title, status: "running", article, usd: 0, jobId: run.jobId };
await putEdition(id, edition, deps);
- const out = await deps.steps.generateEdition({ schedule: s, article, title, window, quietCheck: true }, ctx);
+ const out = await deps.steps.generateEdition({ schedule: s, article, title, window, quietCheck: !flagged, ...(flagged ? { ids: flagged.ids, triage: flagged.ref } : {}) }, ctx);
const made = out.iteration !== undefined;
+ const usd = Math.round((out.usd + tier1Usd()) * 10_000) / 10_000;
if (out.status === "quiet" || made) {
edition = {
n,
@@ -484,7 +661,7 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
title,
status: out.status === "no-change" ? "done" : out.status,
...(out.status !== "quiet" ? { article, iteration: out.iteration } : {}),
- usd: out.usd,
+ usd,
...(out.jobId ? { jobId: out.jobId } : {}),
...(out.reason ? { reason: out.reason } : {}),
...(out.matched !== undefined ? { matched: out.matched } : {}),
@@ -496,17 +673,18 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
}
return await finish({
status: out.status,
- usd: out.usd,
+ usd,
...(out.status === "quiet" || made ? { edition: n } : {}),
...(made ? { article, iteration: out.iteration } : {}),
...(out.reason ? { reason: out.reason } : {}),
...(out.estimateUsd !== undefined ? { estimateUsd: out.estimateUsd } : {}),
+ ...triageLine({ tier2Usd: out.usd }),
...warned(),
});
} catch (e) {
const cancelled = ctx.signal.aborted;
if (edition?.status === "running") await dropEdition(id, edition.n, deps).catch(() => {});
- return finish({ status: cancelled ? "cancelled" : "failed", usd: 0, reason: cancelled ? "cancelled" : (e as Error).message });
+ return finish({ status: cancelled ? "cancelled" : "failed", usd: tier1Usd(), reason: cancelled ? "cancelled" : (e as Error).message, ...triageLine() });
}
}
diff --git a/common/controller/reportTriage.ts b/common/controller/reportTriage.ts
@@ -0,0 +1,220 @@
+// `report-draft {"task": "triage", …}` — the triage step as an editor job
+// (umtool R6; plans/umtool-redesign.md "R6 — Triage first"). The step is
+// lib/report/draft/triage/; this is the editor's side of it:
+//
+// enqueueTriage the run (reports/.triage/<owner>/<k>/triage.json, queued,
+// under the article store's lock), then ONE `report-draft`
+// job on the model's lane: `draft:local` (the default — every
+// ollama call through the GPU arbiter, yielding to
+// transcription; ollama unloaded when the job ends) or
+// `draft:api` (`models.extractor`: metered, held to its cap
+// and the daily cap, its usage in the ledger as task
+// `triage`)
+// the job runTriage over the MCP's corpus tools (the newest build
+// holding the channels, as a sweep reads), the cue reader
+// the quote checks use. Its log ends `@@report-draft {…,
+// task: "triage", triage: {k, status, candidates, flagged,
+// dismissed, escalate, why, usd}}`
+//
+// The body: `article` is the OWNER (the schedule — or article — the run is
+// for), `question`, `channels` (`from`/`to`), `terms` (`regex`), `topics`,
+// `threshold` {strong, weak}, `since` (YYYY-MM-DD: "new" with no last run),
+// `ids` (the candidates, named: no scan), `windows` ({id: [{start, end}]}),
+// `maxCandidates`, `model`, `maxUsd`, `source`/`build`.
+
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import type { JobProgress } from "../jobs/registry";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { getSettings } from "../lib/settings";
+import { capFor, triageModelOf } from "../lib/generationSettings";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
+import type { CorpusToolsLike } from "../lib/report/draft/tasks/types";
+import { createTriageRun, readTriageFile, writeTriageFile } from "../lib/report/draft/triage/store";
+import { runTriage } from "../lib/report/draft/triage/task";
+import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, cleanThreshold, type TriageFile } from "../lib/report/draft/triage/types";
+import { usageOf } from "../lib/report/draft/tasks/run";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, resolveCorpus, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft";
+
+export const TRIAGE_TASK = "triage" as const;
+
+/** The `triage` slice of the job's result marker. */
+export type TriageMarker = { k: number; status: string; candidates: number; flagged: number; dismissed: number; escalate: boolean; why: string; usd: number };
+
+export async function enqueueTriage(body: ReportDraftBody, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const model = triageModelOf(gen, body.model);
+ const provider = providerOf(model) === "local" ? "local" : "api";
+ let maxUsd: number | undefined;
+ if (provider === "api") {
+ try {
+ maxUsd = capFor(gen.caps, "sweep", body.maxUsd);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) return refuse(refusal);
+ }
+ const now = (deps.now?.() ?? new Date()).toISOString();
+ const threshold = cleanThreshold(body.threshold, { strong: gen.triage.strong ?? DEFAULT_TRIAGE_THRESHOLD.strong, weak: gen.triage.weak ?? DEFAULT_TRIAGE_THRESHOLD.weak });
+ let run: TriageFile;
+ try {
+ run = await createTriageRun(
+ (k) => ({
+ format: TRIAGE_FORMAT,
+ version: TRIAGE_VERSION,
+ owner: body.article,
+ k,
+ status: "queued",
+ model,
+ provider,
+ question: body.question!,
+ scope: { channels: body.channels ?? [], ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) },
+ terms: body.terms ?? null,
+ regex: body.regex === true,
+ topics: body.topics ?? [],
+ threshold,
+ since: body.since ?? null,
+ knownCount: null,
+ createdAt: now,
+ cost: { tier0: 0, tier1: 0 },
+ summary: "queued",
+ warnings: [],
+ }),
+ paths,
+ body.article,
+ );
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ const k = run.k;
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE,
+ paths,
+ fn: (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps),
+ });
+ const mark = async (patch: Partial<TriageFile>) => {
+ const cur = await readTriageFile(body.article, k, paths).catch(() => null);
+ if (cur) await writeTriageFile({ ...cur, ...patch }, paths).catch(() => {});
+ };
+ if (!result.ok) {
+ await mark({ status: "failed", error: result.error, summary: `failed: ${result.error}` });
+ return { result };
+ }
+ await mark({ jobId: result.jobId });
+ // A job cancelled (or refused) before it ran leaves its run queued: end it.
+ void result.done.then(async (d) => {
+ const cur = await readTriageFile(body.article, k, paths).catch(() => null);
+ if (cur?.status === "queued") await mark({ status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran`, summary: `the job ended ${d.status} before it ran` });
+ });
+ return { result, iteration: k, triage: { owner: body.article, k } };
+}
+
+async function runTriageJob(
+ o: {
+ body: ReportDraftBody;
+ k: number;
+ model: string;
+ provider: "api" | "local";
+ maxUsd?: number;
+ jobId: string;
+ onLog: (l: string) => void;
+ signal: AbortSignal;
+ setProgress?: (snap: JobProgress) => void;
+ },
+ deps: ReportDraftDeps,
+): Promise<void> {
+ const { body, k, model, provider, onLog, signal } = o;
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ onLog(`triage ${body.article}/${k} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model, through the GPU arbiter"})`);
+ if (provider === "api") {
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) throw new Error(refusal);
+ }
+ let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
+ let ran: Awaited<ReturnType<typeof runTriage>> | null = null;
+ try {
+ const where = await resolveCorpus(body, body.channels ?? [], paths, gen);
+ onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`);
+ corpus = await deps.corpusTools(where.source);
+ ran = await runTriage(
+ {
+ owner: body.article,
+ k,
+ ...(body.ids?.length ? { ids: body.ids } : {}),
+ ...(body.windows ? { windows: body.windows } : {}),
+ maxCandidates: body.maxCandidates ?? gen.triage.maxCandidates,
+ ...(o.maxUsd !== undefined ? { maxUsd: o.maxUsd } : {}),
+ origin: where.origin,
+ },
+ {
+ llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined),
+ corpus,
+ paths,
+ cuesOf: corpusCuesOf(corpus),
+ log: onLog,
+ progress: (done, total) => o.setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }),
+ signal,
+ ...(deps.now ? { now: deps.now } : {}),
+ },
+ );
+ } catch (e) {
+ // A run that never started (no build holds the channels, …) says why.
+ const cur = await readTriageFile(body.article, k, paths).catch(() => null);
+ if (cur && (cur.status === "queued" || cur.status === "running")) {
+ const msg = (e as Error).message;
+ await writeTriageFile({ ...cur, status: signal.aborted ? "cancelled" : "failed", error: msg, summary: signal.aborted ? "cancelled" : `failed: ${msg}`, endedAt: new Date().toISOString() }, paths).catch(() => {});
+ }
+ throw e;
+ } finally {
+ await corpus?.close().catch(() => {});
+ if (provider === "local") {
+ await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ }
+ if (provider === "api" && ran) {
+ const at = deps.now?.() ?? new Date();
+ const rows: GenerationUsageRow[] = Object.entries(ran.byModel)
+ .filter(([, t]) => t.calls > 0)
+ .map(([m, t]) => {
+ const u = usageOf(t);
+ return {
+ at: at.toISOString(),
+ day: utcDay(at),
+ jobId: o.jobId,
+ article: body.article,
+ iteration: k,
+ task: TRIAGE_TASK,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ };
+ });
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ const f = ran!.file;
+ const marker: TriageMarker = {
+ k,
+ status: f.status,
+ candidates: f.tier0?.candidates.length ?? 0,
+ flagged: f.tier1?.flags.length ?? 0,
+ dismissed: f.tier1?.dismissed.length ?? 0,
+ escalate: !!f.escalation?.escalate,
+ why: f.escalation?.why ?? f.summary,
+ usd: f.cost.tier1,
+ };
+ onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: k, task: TRIAGE_TASK, status: f.status, summary: f.summary, usd: f.cost.tier1, triage: marker })}`);
+ if (f.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (f.status === "failed") throw new Error(f.summary);
+}
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -63,6 +63,17 @@ export type GenerationCut = { maxClips: number };
// automatically. M8's verdict proposals run only on these.
export type GenerationVerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number };
export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[] };
+// Triage first (umtool R6): the cheap pass a recurring report may run before
+// its sweep — the model it judges on, the threshold it escalates at, and how
+// many escalations a day may run.
+export type GenerationTriage = {
+ model: "local" | "extractor";
+ strong: number;
+ weak: number;
+ maxEscalationsPerDay: number;
+ maxCandidates: number;
+};
+export const DEFAULT_GENERATION_TRIAGE: GenerationTriage = { model: "local", strong: 1, weak: 3, maxEscalationsPerDay: 3, maxCandidates: 40 };
export type GenerationSettings = {
preset: GenerationPreset | "custom";
@@ -79,6 +90,7 @@ export type GenerationSettings = {
research: GenerationResearch;
cut: GenerationCut;
verdicts: GenerationVerdicts;
+ triage: GenerationTriage;
};
export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] };
@@ -102,6 +114,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
research: { ...DEFAULT_GENERATION_RESEARCH },
cut: { maxClips: 20 },
verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] },
+ triage: { ...DEFAULT_GENERATION_TRIAGE },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
@@ -124,6 +137,16 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
cut: "The cut task's limits (below).",
verdicts:
"The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.",
+ triage:
+ "Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below).",
+};
+
+export const GENERATION_TRIAGE_FIELD_DOCS: FieldDocs<GenerationTriage> = {
+ model: "What the window judge runs on: `local` (`models.local`, through the GPU arbiter on `draft:local`, $0 marginal) or `extractor` (`models.extractor`, on the API, metered).",
+ strong: "Escalate when this many STRONG flags (the judge's score 3: the line directly answers the question) are found. 0 = strong flags alone never escalate. A schedule may set its own.",
+ weak: "Escalate when this many flags of any strength (score 2 or 3) are found. 0 = off. A schedule may set its own.",
+ maxEscalationsPerDay: "The most escalations (tier 2 sweeps) a day (UTC) across every schedule. Past it a tick is held by the cap — a Your call card — with its flags kept. 0 = no cap.",
+ maxCandidates: "The most candidates one triage judges; the rest stay new for the next tick.",
};
export const GENERATION_VERDICTS_FIELD_DOCS: FieldDocs<GenerationVerdicts> = {
@@ -273,9 +296,29 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
postWalksNeedApproval: typeof rs.postWalksNeedApproval === "boolean" ? rs.postWalksNeedApproval : dr.postWalksNeedApproval,
},
verdicts: sanitizeVerdicts(r.verdicts),
+ triage: sanitizeTriage(r.triage),
+ };
+}
+
+function sanitizeTriage(v: unknown): GenerationTriage {
+ const d = DEFAULT_GENERATION_TRIAGE;
+ const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ const int = (x: unknown, def: number, min: number, max: number) => (typeof x === "number" && Number.isInteger(x) && x >= min && x <= max ? x : def);
+ return {
+ model: o.model === "extractor" ? "extractor" : "local",
+ strong: int(o.strong, d.strong, 0, 50),
+ weak: int(o.weak, d.weak, 0, 50),
+ maxEscalationsPerDay: int(o.maxEscalationsPerDay, d.maxEscalationsPerDay, 0, 1000),
+ maxCandidates: int(o.maxCandidates, d.maxCandidates, 1, 500),
};
}
+/** The model a triage judges on: the asked one, else the settings' (`local` → models.local, `extractor` → models.extractor). */
+export function triageModelOf(gen: GenerationSettings, asked?: string): string {
+ if (asked) return asked;
+ return gen.triage.model === "extractor" ? gen.models.extractor : gen.models.local;
+}
+
function sanitizeVerdicts(v: unknown): GenerationVerdicts {
const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
const b = o.bar && typeof o.bar === "object" && !Array.isArray(o.bar) ? (o.bar as Record<string, unknown>) : {};
diff --git a/common/lib/report/docs.ts b/common/lib/report/docs.ts
@@ -50,7 +50,7 @@ export function renderReportMarkdown(): string {
"An article's `audience` (below) says which homepage build carries it: the public " +
"one only `\"public\"` articles, the private one every published article. An " +
"article may cite any channel of the corpus. An article may not be called `new` " +
- "(umtool's `/articles/new` is a page).",
+ "(umtool's `/articles/new` is an address: it opens Create's article form).",
);
out.push(
"- **A site's page** — `transcripts/sites/<siteId>/reports/<reportId>/report.json`, " +
diff --git a/common/lib/report/draft/refresh/task.ts b/common/lib/report/draft/refresh/task.ts
@@ -67,6 +67,10 @@ export type RefreshInput = {
maxUsd: number;
// false: no stage 1 (read the corpus as it stands).
fetch?: boolean;
+ // The recordings the update reads (umtool R6: what a triage flagged),
+ // instead of the new and changed ones; the update runs even when the delta
+ // found nothing else.
+ ids?: string[];
};
// ─── the estimate ───
@@ -259,11 +263,16 @@ async function refreshBody(h: TaskHandle, input: RefreshInput): Promise<TaskOutc
return { status: outcome, summary, patch: { refresh: outcomeOf(file) } };
};
- if (delta.status === "no-change") return finish("no-change", line);
+ const flagged = input.ids?.length ? [...new Set(input.ids)] : null;
+ if (delta.status === "no-change" && !flagged) return finish("no-change", line);
+ if (flagged) {
+ h.log(`the update reads the ${flagged.length} recording(s) a triage flagged`);
+ h.trace({ t: "note", text: `the update reads the ${flagged.length} recording(s) a triage flagged: ${flagged.slice(0, 20).join(", ")}` });
+ }
// ─── stage 3: the update ───
- const ids = [...new Set([...delta.newIds, ...delta.changed])];
+ const ids = flagged ?? [...new Set([...delta.newIds, ...delta.changed])];
const parentIt = await readIteration(h.article, basis.queriesOf, h.paths).catch(() => null);
const parentUsd = parentIt ? Object.values(parentIt.usage).reduce((s, u) => s + u.usd, 0) : null;
const estimate = estimateUpdateUsd({ recordings: ids.length, model: input.model, parentUsd, parentRead: parentIt?.coverage?.read ?? null });
diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts
@@ -21,6 +21,8 @@ import {
import { ArticleRegistryError } from "../../registry";
import type { IterationCoverage } from "../../iterations";
import { NO_TRACE, openTrace, type RunTracer, type TraceInput } from "./trace";
+import { readTriageFile } from "../triage/store";
+import { getPaths } from "../../../paths";
import type { StorePaths, TaskDeps, TaskProgress, TaskResult, TaskStatus } from "./types";
export class TaskInputError extends Error {}
@@ -143,6 +145,25 @@ export async function runOnIteration(
const tracer: RunTracer = o.trace ? await openTrace({ article, n, paths, now, log }).catch(() => NO_TRACE) : NO_TRACE;
if (o.trace) {
tracer.emit({ t: "run", phase: "start", task: o.trace.task, model: o.trace.model || it.model, ...(o.trace.extractor ? { extractor: o.trace.extractor } : {}), ...(it.jobId ? { jobId: it.jobId } : {}) });
+ // A sweep a triage escalated (umtool R6): the triage's tiers first.
+ const tri = it.scope?.triage;
+ if (tri) {
+ const f = await readTriageFile(tri.owner, tri.k, paths ?? getPaths()).catch(() => null);
+ if (f) {
+ tracer.emit({
+ t: "triage",
+ owner: f.owner,
+ k: f.k,
+ candidates: (f.tier0?.candidates ?? []).map((c) => c.id),
+ flagged: [...new Set((f.tier1?.flags ?? []).map((x) => x.id))],
+ dismissed: f.tier1?.dismissed.length ?? 0,
+ escalated: !!f.escalation?.escalate,
+ ...(f.escalation ? { why: f.escalation.why } : {}),
+ cost: f.cost,
+ model: f.model,
+ });
+ }
+ }
}
let coverageOf: (() => IterationCoverage) | null = null;
const handle: TaskHandle = {
diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts
@@ -25,6 +25,12 @@
// and an enumeration may carry `counts` (each id's matching lines), so the
// next refresh can tell a recording whose transcript changed.
//
+// A TRIAGE (umtool R6, draft/triage) — its own run's trace, and the first
+// line after the start of a sweep it escalated to — adds:
+// {t: "triage", owner, k, candidates, flagged, dismissed, escalated?, why?,
+// cost?: {tier0, tier1}, model?} the tiers in one line
+// and its `cost` lines name their `tier` (1: the judge; 2: the sweep).
+//
// Every line also carries `at` (ISO time) and `run` (1 for the file's first
// run; a resumed job's run is 2, …). An agent's events carry `turn` and
// `phase` ("agent" or "repair") so a step can be put on the turn that made it.
@@ -62,7 +68,7 @@ export type TraceCite = {
quote?: string;
};
-export type CheckStage = "extract" | "check" | "strict" | "final" | "drop";
+export type CheckStage = "extract" | "check" | "strict" | "final" | "drop" | "triage";
// What a task hands the tracer: the event, without `at` and `run`.
export type TraceInput =
@@ -88,10 +94,25 @@ export type TraceInput =
| { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record<string, number>; turn?: number; phase?: string; error?: string }
| { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string }
| { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string }
- | { t: "cost"; step: string; usd: number; model: string; total: number; turn?: number; phase?: string; calls?: string[]; text?: string }
+ | { t: "cost"; step: string; usd: number; model: string; total: number; turn?: number; phase?: string; calls?: string[]; text?: string; tier?: number }
| { t: "check"; quote: string; cite: TraceCite; ok: boolean; reason?: string; stage: CheckStage; dropped?: boolean; claim?: string; round?: number }
| { t: "finding"; section: string; claim: string; cites: TraceCite[] }
| { t: "note"; text: string; turn?: number; phase?: string }
+ // A triage's tiers (umtool R6): its candidates (ids), the flagged ids, how
+ // many lines and windows it dismissed, whether it escalated and why, and
+ // what each tier spent.
+ | {
+ t: "triage";
+ owner: string;
+ k: number;
+ candidates: string[];
+ flagged: string[];
+ dismissed: number;
+ escalated?: boolean;
+ why?: string;
+ cost?: { tier0: number; tier1: number };
+ model?: string;
+ }
// A refresh's stages (umtool R4).
| { t: "fetch"; channel: string; action: string; status: TraceStepStatus; jobId?: string; reason?: string; ids?: string[] }
| { t: "build"; site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string }
@@ -129,7 +150,7 @@ const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}…
export function boundEvent(e: TraceInput): TraceInput {
const o = { ...e } as Record<string, unknown>;
if (Array.isArray(o.ids)) o.ids = (o.ids as string[]).slice(0, TRACE_MAX_IDS);
- for (const k of ["newIds", "changed", "drifted", "deleted"]) if (Array.isArray(o[k])) o[k] = (o[k] as string[]).slice(0, TRACE_MAX_IDS);
+ for (const k of ["newIds", "changed", "drifted", "deleted", "candidates", "flagged"]) if (Array.isArray(o[k])) o[k] = (o[k] as string[]).slice(0, TRACE_MAX_IDS);
if (o.counts && typeof o.counts === "object") {
const entries = Object.entries(o.counts as Record<string, number>);
if (entries.length > TRACE_MAX_IDS) o.counts = Object.fromEntries(entries.slice(0, TRACE_MAX_IDS));
@@ -162,18 +183,20 @@ export function runStartsOf(text: string): number {
return n;
}
-// Open the trace of iteration `n` of `article` for a new run (appending).
+// Open the trace of iteration `n` of `article` for a new run (appending) —
+// or, given `file`, that trace (a triage run's, umtool R6).
export async function openTrace(o: {
article: string;
n: number;
paths?: StorePaths;
now?: () => Date;
log?: (line: string) => void;
+ file?: string;
}): Promise<RunTracer> {
const now = o.now ?? (() => new Date());
let file: string;
try {
- file = iterationFile(o.paths ?? getPaths(), o.article, o.n, TRACE_FILE);
+ file = o.file ?? iterationFile(o.paths ?? getPaths(), o.article, o.n, TRACE_FILE);
} catch (e) {
o.log?.(`trace not kept: ${(e as Error).message}`);
return NO_TRACE;
diff --git a/common/lib/report/draft/triage/index.ts b/common/lib/report/draft/triage/index.ts
@@ -0,0 +1,6 @@
+// Triage first (umtool R6): the cheap pass that flags what is worth researching.
+export * from "./types";
+export * from "./store";
+export { triageCandidates, tagMatches, type Tier0Input, type Tier0Deps, type Tier0Result } from "./tier0";
+export { judgeCandidates, TRIAGE_READ_BATCH, TRIAGE_CHUNKS_PER_RECORDING, TRIAGE_FLAGS_PER_RECORDING, type JudgeInput, type JudgeDeps, type JudgeResult } from "./judge";
+export { runTriage, topicsFromMetadata, DEFAULT_MAX_CANDIDATES, type TriageRunInput, type TriageRunDeps } from "./task";
diff --git a/common/lib/report/draft/triage/judge.ts b/common/lib/report/draft/triage/judge.ts
@@ -0,0 +1,265 @@
+// TRIAGE, TIER 1 — the window judge, on its own (umtool R6): the sweep
+// pipeline's judge (sweep-pipeline.ts EXTRACT_SYSTEM: relevant, items {quote,
+// claim, on_topic, strength}) over the candidates' MATCHING windows only —
+// get_transcripts' windows around the terms and topics (a caller's own windows
+// when it names them; a recording no word matched, put forward by a digest tag,
+// is read from its opening). Each window is cut to model-sized chunks, at most
+// a few per recording.
+//
+// What the model says is never taken on trust:
+// - its line must be VERBATIM in the window it read (the pipeline's `locate`)
+// and in the transcript's cues around that second (R2's word check,
+// lib/report/quoteWords.ts) — else it is dismissed as "not verbatim", the
+// invented line kept beside its reason
+// - strength 3 on topic is a STRONG flag, 2 a WEAK one; 1, or off topic, is
+// dismissed with the model's own claim as the reason
+// - a window it judges not relevant is dismissed as a window
+//
+// Pure over the corpus tools, the model (`ask`) and the cue reader it is handed.
+
+import { checkWordsInWindow, windowAround, type WordCue } from "../../quoteWords";
+import { mmss } from "../reportOps";
+import { chunksOf, EXTRACT_SCHEMA, EXTRACT_SYSTEM, locate, parseTranscripts, windowsOf, type ParsedTranscript } from "../tasks/sweep-pipeline";
+import { momentHref } from "../tasks/links";
+import type { CorpusToolsLike } from "../tasks/types";
+import { STRONG_SCORE, type TriageCandidate, type TriageDismissal, type TriageFlag, type TriageScore, type TriageWindow } from "./types";
+
+export const TRIAGE_READ_BATCH = 8;
+export const TRIAGE_CHUNKS_PER_RECORDING = 3;
+export const TRIAGE_FLAGS_PER_RECORDING = 3;
+export const TRIAGE_MIN_LINE_WORDS = 4;
+
+export type JudgeInput = {
+ question: string;
+ candidates: TriageCandidate[];
+ terms: string | null;
+ regex?: boolean;
+ topics: string[];
+ channels: string[];
+ // A caller's own windows per recording (seconds): only these are read.
+ windows?: Record<string, TriageWindow[]>;
+ origin?: string | null;
+ maxChunksPerRecording?: number;
+ maxFlagsPerRecording?: number;
+};
+
+export type JudgeTrace = (e: { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number } | { t: "check"; quote: string; cite: { channel?: string; video?: string; start?: number; url?: string }; ok: boolean; reason: string; stage: "triage"; dropped?: boolean; claim?: string }) => void;
+
+export type JudgeDeps = {
+ corpus: Pick<CorpusToolsLike, "call">;
+ // The model: a structured answer to the judge's prompt.
+ ask: <T>(system: string, user: string, schema: object, what: string) => Promise<T>;
+ model: string;
+ // A recording's cues (the verbatim check); null: unread, the window decides.
+ cuesOf?: (channel: string, id: string) => Promise<readonly WordCue[] | null>;
+ // The spend so far (USD), for each batch's line.
+ usd?: () => number;
+ signal?: AbortSignal;
+ log?: (line: string) => void;
+ progress?: (done: number, total: number) => void;
+ trace?: JudgeTrace;
+ // Why the judge must stop now (the job's cap reached), else null.
+ stop?: () => string | null;
+};
+
+export type JudgeResult = {
+ flags: TriageFlag[];
+ dismissed: TriageDismissal[];
+ read: number;
+ windows: number;
+ chunks: number;
+ // Why it stopped before every candidate was judged, and the ids not judged.
+ stopped?: { reason: string; ids: string[] };
+};
+
+type Line = [number, string];
+
+const clean = (s: unknown) =>
+ String(s ?? "")
+ .replace(/["“”]/g, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^\[[\d:]+\]\s*/, "");
+const oneLine = (s: unknown, max = 240) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, max);
+
+/** The window a chunk spans (its first line's second to its last's, plus one cue). */
+const spanOf = (ch: readonly Line[]): TriageWindow => ({ start: ch[0]![0], end: ch[ch.length - 1]![0] + 5 });
+
+// The channel slug of a recording: off a moment_base in the archive's form,
+// else the one channel, else the channel whose metadata names it.
+async function slugOf(p: ParsedTranscript | undefined, id: string, channels: string[], corpus: JudgeDeps["corpus"]): Promise<string | null> {
+ const m = p?.momentBase ? /[?&]v=([^&%/]+)(?:%2F|\/)/i.exec(p.momentBase) : null;
+ if (m) return decodeURIComponent(m[1]!);
+ if (channels.length === 1) return channels[0]!;
+ for (const c of channels) {
+ try {
+ await corpus.call("get_video_metadata", { video_id: id, channel: c });
+ return c;
+ } catch {
+ // not this channel's
+ }
+ }
+ return channels[0] ?? null;
+}
+
+/** The judge over the candidates' windows. */
+export async function judgeCandidates(i: JudgeInput, d: JudgeDeps): Promise<JudgeResult> {
+ const flags: TriageFlag[] = [];
+ const dismissed: TriageDismissal[] = [];
+ const maxChunks = i.maxChunksPerRecording ?? TRIAGE_CHUNKS_PER_RECORDING;
+ const maxFlags = i.maxFlagsPerRecording ?? TRIAGE_FLAGS_PER_RECORDING;
+ const terms = i.terms?.trim() || null;
+ const words = [...(terms && !i.regex ? [terms] : []), ...i.topics].map((t) => t.trim()).filter(Boolean).slice(0, 8);
+ const queryArgs: Record<string, unknown> = terms && i.regex ? { query: terms, regex: true, ...(words.length ? { queries: words } : {}) } : words.length ? { queries: words } : {};
+ const cueCache = new Map<string, Promise<readonly WordCue[] | null>>();
+ const cues = (slug: string, id: string) => {
+ const key = `${slug}/${id}`;
+ let p = cueCache.get(key);
+ if (!p) {
+ p = d.cuesOf ? d.cuesOf(slug, id).catch(() => null) : Promise.resolve(null);
+ cueCache.set(key, p);
+ }
+ return p;
+ };
+ let read = 0;
+ let nWindows = 0;
+ let nChunks = 0;
+ let done = 0;
+ const total = i.candidates.length;
+ d.progress?.(0, total);
+ const batches = Math.ceil(total / TRIAGE_READ_BATCH);
+ let stopped: JudgeResult["stopped"];
+ for (let b = 0; b < total && !stopped; b += TRIAGE_READ_BATCH) {
+ d.signal?.throwIfAborted();
+ const halt = d.stop?.() ?? null;
+ if (halt) {
+ stopped = { reason: halt, ids: i.candidates.slice(b).map((c) => c.id) };
+ break;
+ }
+ const batch = i.candidates.slice(b, b + TRIAGE_READ_BATCH);
+ const before = d.usd?.() ?? 0;
+ const lines: string[] = [];
+ const windowed = batch.filter((c) => !i.windows?.[c.id]?.length);
+ const parsed = windowed.length
+ ? parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: windowed.map((c) => c.id), ...queryArgs, link_style: "base", channels: i.channels }))
+ : new Map<string, ParsedTranscript>();
+ for (const c of batch) {
+ d.signal?.throwIfAborted();
+ let p = parsed.get(c.id);
+ let wins: Line[][] = p ? windowsOf(p.lines) : [];
+ let opening = false;
+ const own = i.windows?.[c.id];
+ if (own?.length || (!wins.length && (c.by.includes("topics") || !Object.keys(queryArgs).length))) {
+ // The caller's windows, or (no word matched: a digest tag put it forward) its opening.
+ const full = parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: [c.id], link_style: "base", channels: i.channels })).get(c.id);
+ p = full ?? p;
+ const all = (full?.lines ?? []).filter((l): l is Line => l !== null);
+ if (own?.length) {
+ wins = own.map((w) => all.filter(([s]) => s >= w.start - 5 && s <= w.end + 5)).filter((w) => w.length);
+ } else if (all.length) {
+ wins = [all];
+ opening = true;
+ }
+ }
+ const title = c.title ?? p?.title ?? c.id;
+ if (!wins.length) {
+ dismissed.push({ id: c.id, title, channel: c.channel, stage: "read", reason: p ? "no window matched the terms or topics" : "no transcript text returned" });
+ lines.push(`${c.id}: ${p ? "no window matched" : "no transcript text returned"}`);
+ d.progress?.(++done, total);
+ continue;
+ }
+ read++;
+ const slug = await slugOf(p, c.id, i.channels, d.corpus);
+ let kept = 0;
+ let chunksHere = 0;
+ outer: for (const win of wins) {
+ nWindows++;
+ for (const ch of chunksOf(win)) {
+ if (chunksHere >= maxChunks || kept >= maxFlags) break outer;
+ d.signal?.throwIfAborted();
+ if (d.stop?.()) break outer;
+ chunksHere++;
+ nChunks++;
+ const span = spanOf(ch);
+ const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n");
+ const user = `Research question: ${i.question}\n\nVideo: ${title}${c.channel ? ` (${c.channel}${c.date ? `, ${c.date}` : ""})` : ""}\n\nTranscript excerpt:\n${excerpt}`;
+ let ans: { relevant?: unknown; items?: unknown };
+ try {
+ ans = await d.ask(EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `triage ${c.id}@${ch[0]![0]}`);
+ } catch (e) {
+ if (d.signal?.aborted) throw e;
+ dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: `the model's answer failed: ${oneLine((e as Error).message, 160)}` });
+ lines.push(`${c.id} @ ${mmss(span.start)}: the model's answer failed — ${oneLine((e as Error).message, 160)}`);
+ continue;
+ }
+ const items = Array.isArray(ans.items) ? (ans.items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) : [];
+ if (!ans.relevant || !items.length) {
+ dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: opening ? "not relevant to the question (its opening read: no word matched)" : "not relevant to the question" });
+ lines.push(`${c.id} @ ${mmss(span.start)}–${mmss(span.end)}: not relevant`);
+ continue;
+ }
+ for (const raw of items.slice(0, 3)) {
+ const line = clean(raw.quote);
+ const reason = oneLine(raw.claim) || "(no reason given)";
+ const strength = Math.min(3, Math.max(1, Math.round(Number(raw.strength) || 2))) as TriageScore;
+ const sec = line ? locate(line, ch) : null;
+ const base = { id: c.id, title, channel: slug, window: span, line, score: strength };
+ let why: { stage: TriageDismissal["stage"]; reason: string } | null = null;
+ let at = sec ?? span.start;
+ let checked: TriageFlag["checked"] = "window";
+ if (!line) why = { stage: "verbatim", reason: "no line given" };
+ else if (sec === null) why = { stage: "verbatim", reason: "not verbatim in its window" };
+ else if (line.split(" ").filter(Boolean).length < TRIAGE_MIN_LINE_WORDS) why = { stage: "verbatim", reason: `too short to check (${line.split(" ").filter(Boolean).length} words)` };
+ else if (slug) {
+ const all = await cues(slug, c.id);
+ if (all?.length) {
+ const v = checkWordsInWindow(line, { t: sec, end: sec }, windowAround(all, sec, 30));
+ if (v.status === "ok") {
+ checked = "cues";
+ if (v.nowAt !== undefined) at = v.nowAt;
+ } else {
+ why = { stage: "verbatim", reason: `not in the transcript's cues near ${mmss(sec)}` };
+ }
+ }
+ }
+ if (!why && raw.on_topic === false) why = { stage: "score", reason: `off topic — ${reason}` };
+ if (!why && strength < 2) why = { stage: "score", reason: `a mention only — ${reason}` };
+ if (!why && flags.some((f) => f.id === c.id && f.line === line)) why = { stage: "score", reason: "the same line twice" };
+ const url = slug && p?.momentBase ? `${p.momentBase}${Math.floor(at)}` : slug && i.origin ? momentHref(i.origin.replace(/\/+$/, ""), slug, c.id, at) : undefined;
+ if (why) {
+ dismissed.push({ ...base, at, ...why });
+ lines.push(`${c.id} @ ${mmss(at)} “${line}” — ${reason} [dismissed: ${why.reason}]`);
+ d.trace?.({ t: "check", quote: line, cite: { ...(slug ? { channel: slug } : {}), video: c.id, start: at, ...(url ? { url } : {}) }, ok: false, reason: why.reason, stage: "triage", dropped: true, claim: reason });
+ continue;
+ }
+ if (kept >= maxFlags) break;
+ kept++;
+ const f: TriageFlag = {
+ f: `f${flags.length + 1}`,
+ id: c.id,
+ channel: slug,
+ title,
+ date: c.date,
+ window: span,
+ line,
+ at,
+ score: strength,
+ strength: strength >= STRONG_SCORE ? "strong" : "weak",
+ reason,
+ checked,
+ ...(url ? { url } : {}),
+ };
+ flags.push(f);
+ lines.push(`${c.id} @ ${mmss(at)} “${line}” — ${reason} [${f.strength} flag ${f.f}]`);
+ d.trace?.({ t: "check", quote: line, cite: { ...(slug ? { channel: slug } : {}), video: c.id, start: at, ...(url ? { url } : {}) }, ok: true, reason: `${f.strength} flag (score ${strength}), verbatim${checked === "cues" ? " in the cues" : " in its window"}`, stage: "triage", claim: reason });
+ }
+ }
+ }
+ d.log?.(` ${c.id}: ${kept} flag(s), ${chunksHere} chunk(s) judged`);
+ d.progress?.(++done, total);
+ }
+ const k = b / TRIAGE_READ_BATCH + 1;
+ d.trace?.({ t: "batch", k, of: batches, ids: batch.map((c) => c.id), lines, model: d.model, usd: (d.usd?.() ?? 0) - before });
+ }
+ return { flags, dismissed, read, windows: nWindows, chunks: nChunks, ...(stopped ? { stopped } : {}) };
+}
diff --git a/common/lib/report/draft/triage/store.ts b/common/lib/report/draft/triage/store.ts
@@ -0,0 +1,108 @@
+// WHERE A TRIAGE RUN LIVES (umtool R6). Server-only (node:fs).
+//
+// reports/.triage/<owner>/<k>/triage.json the run (./types.ts TriageFile)
+// reports/.triage/<owner>/<k>/trace.jsonl what it did, as it did it
+// reports/.triage/<owner>/seen.json the ids its last COMPLETED run saw
+//
+// A dot-directory of the article store: the registry lists only id-named
+// directories, so nothing reads a triage as an article. The owner is a
+// schedule's id (a series', a watch's, a living report's article); runs are
+// numbered 1, 2, … per owner. ONE writer: the editor's `report-draft
+// {"task":"triage"}` job (controller/reportDraft.ts creates the run under the
+// article store's lock; the job writes it to its end). umtool reads.
+
+import { mkdir, readdir } from "node:fs/promises";
+import path from "node:path";
+import type { Paths } from "../../../paths";
+import { readJsonFile, writeJsonAtomic } from "../../../jsonFile-server";
+import { withArticleStoreLock } from "../../registry";
+import { TRIAGE_FORMAT, TRIAGE_SEEN_FORMAT, type TriageFile, type TriageSeen } from "./types";
+
+export type TriagePaths = Pick<Paths, "articlesDir">;
+
+export const TRIAGE_DIRNAME = ".triage";
+export const TRIAGE_FILE = "triage.json";
+export const TRIAGE_TRACE_FILE = "trace.jsonl";
+export const TRIAGE_SEEN_FILE = "seen.json";
+
+// An owner is an article or schedule id.
+export const TRIAGE_OWNER_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+export const triageOwnerDir = (paths: TriagePaths, owner: string) => {
+ if (!TRIAGE_OWNER_RE.test(owner)) throw new Error(`"${owner}" is not a triage owner (an article or schedule id)`);
+ return path.join(paths.articlesDir, TRIAGE_DIRNAME, owner);
+};
+export const triageRunDir = (paths: TriagePaths, owner: string, k: number) => path.join(triageOwnerDir(paths, owner), String(k));
+export const triageFilePath = (paths: TriagePaths, owner: string, k: number) => path.join(triageRunDir(paths, owner, k), TRIAGE_FILE);
+export const triageTracePath = (paths: TriagePaths, owner: string, k: number) => path.join(triageRunDir(paths, owner, k), TRIAGE_TRACE_FILE);
+export const triageSeenPath = (paths: TriagePaths, owner: string) => path.join(triageOwnerDir(paths, owner), TRIAGE_SEEN_FILE);
+
+/** The runs an owner has, oldest first. */
+export async function listTriageRuns(owner: string, paths: TriagePaths): Promise<number[]> {
+ let names: string[] = [];
+ try {
+ names = (await readdir(triageOwnerDir(paths, owner), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
+ } catch {
+ return [];
+ }
+ return names.filter((n) => /^[1-9]\d{0,6}$/.test(n)).map(Number).sort((a, b) => a - b);
+}
+
+/** One run's triage.json, or null (absent, or not a triage file). */
+export async function readTriageFile(owner: string, k: number, paths: TriagePaths): Promise<TriageFile | null> {
+ let file: string;
+ try {
+ file = triageFilePath(paths, owner, k);
+ } catch {
+ return null;
+ }
+ const r = await readJsonFile(file);
+ if (!r.ok) return null;
+ const v = r.value as TriageFile;
+ return v && v.format === TRIAGE_FORMAT && v.owner === owner && v.k === k ? v : null;
+}
+
+/** Write a run's triage.json whole (the job's; atomically). */
+export async function writeTriageFile(f: TriageFile, paths: TriagePaths): Promise<void> {
+ await writeJsonAtomic(triageFilePath(paths, f.owner, f.k), f, { mkdir: true });
+}
+
+/** A new run: the next number, its directory and its triage.json (queued), under the article store's lock. */
+export async function createTriageRun(make: (k: number) => TriageFile, paths: TriagePaths, owner: string): Promise<TriageFile> {
+ return withArticleStoreLock(async () => {
+ const runs = await listTriageRuns(owner, paths);
+ const k = (runs.at(-1) ?? 0) + 1;
+ await mkdir(triageRunDir(paths, owner, k), { recursive: true });
+ const f = make(k);
+ await writeTriageFile(f, paths);
+ return f;
+ }, paths);
+}
+
+/** The ids the owner's last completed run saw, or null (none yet). */
+export async function readTriageSeen(owner: string, paths: TriagePaths): Promise<TriageSeen | null> {
+ let file: string;
+ try {
+ file = triageSeenPath(paths, owner);
+ } catch {
+ return null;
+ }
+ const r = await readJsonFile(file);
+ if (!r.ok) return null;
+ const v = r.value as TriageSeen;
+ return v && v.format === TRIAGE_SEEN_FORMAT && Array.isArray(v.ids) ? v : null;
+}
+
+export async function writeTriageSeen(seen: TriageSeen, paths: TriagePaths): Promise<void> {
+ await writeJsonAtomic(triageSeenPath(paths, seen.owner), seen, { mkdir: true });
+}
+
+/** An owner's runs, newest first (each that reads). */
+export async function listTriageFiles(owner: string, paths: TriagePaths): Promise<TriageFile[]> {
+ const out: TriageFile[] = [];
+ for (const k of (await listTriageRuns(owner, paths)).reverse()) {
+ const f = await readTriageFile(owner, k, paths);
+ if (f) out.push(f);
+ }
+ return out;
+}
diff --git a/common/lib/report/draft/triage/task.ts b/common/lib/report/draft/triage/task.ts
@@ -0,0 +1,226 @@
+// THE TRIAGE STEP (umtool R6): one run over `reports/.triage/<owner>/<k>/`,
+// which the editor's `report-draft {"task":"triage"}` job creates queued
+// (controller/reportDraft.ts) and this runs to its end:
+//
+// tier 0 the candidates (./tier0.ts): new since the owner's last completed
+// run, by id, matching the terms or the topics — or the ids named
+// tier 1 the window judge over their matching windows (./judge.ts), on the
+// run's model (local by default; the extractor allowed)
+// decide the flags against the threshold (./types.ts escalationOf). The
+// step only SAYS whether to escalate; the tick escalates
+// (controller/reportTick.ts), within the day's escalation cap
+//
+// Every stage is logged, traced (trace.jsonl: the scope, tier 0's enumerations,
+// one `batch` per read batch with the judge's lines, a `check` per flag and per
+// dismissed line with its reason, `triage` with the tiers, `cost` per tier)
+// and kept in triage.json. A completed run writes seen.json — what the next run
+// counts as known — so a run that fails or is cancelled leaves the next one to
+// see the same recordings as new.
+//
+// SERVER-ONLY (node:fs through the store).
+
+import { Meter, structuredAnswer, type LlmConfig, type ModelTally } from "../../../llm";
+import type { WordCue } from "../../quoteWords";
+import { enumerateViaTools, type EnumerateFn } from "../refresh/delta";
+import { openTrace, NO_TRACE, type RunTracer } from "../tasks/trace";
+import type { CorpusToolsLike } from "../tasks/types";
+import { judgeCandidates } from "./judge";
+import { readTriageFile, readTriageSeen, triageTracePath, writeTriageFile, writeTriageSeen, type TriagePaths } from "./store";
+import { triageCandidates } from "./tier0";
+import { TRIAGE_SEEN_FORMAT, escalationOf, triageLine, type TriageFile, type TriageWindow } from "./types";
+
+export const DEFAULT_MAX_CANDIDATES = 40;
+
+export type TriageRunInput = {
+ owner: string;
+ k: number;
+ // Named by the caller: these are the candidates (no scan, seen.json untouched).
+ ids?: string[];
+ windows?: Record<string, TriageWindow[]>;
+ maxCandidates?: number;
+ maxUsd?: number;
+ origin?: string | null;
+};
+
+export type TriageRunDeps = {
+ llm: LlmConfig;
+ corpus: CorpusToolsLike;
+ paths: TriagePaths;
+ cuesOf?: (channel: string, id: string) => Promise<readonly WordCue[] | null>;
+ // A recording's digest topic tags (default: the corpus's get_video_metadata).
+ topicsOf?: (id: string, channel: string | null) => Promise<string[] | null>;
+ // enumerate_matches as data (default: through the corpus tools).
+ enumerate?: EnumerateFn;
+ // The model, stubbed (tests); default structuredAnswer on the run's model.
+ ask?: <T>(system: string, user: string, schema: object, what: string) => Promise<T>;
+ now?: () => Date;
+ log?: (line: string) => void;
+ progress?: (done: number, total: number) => void;
+ signal?: AbortSignal;
+};
+
+/** get_video_metadata's "### Topic tags" line as tags (the build's digest). */
+export function topicsFromMetadata(text: string): string[] | null {
+ const m = /### Topic tags\n([^\n]+)/.exec(text);
+ if (!m) return null;
+ return m[1]!
+ .split(",")
+ .map((t) => t.replace(/\s*\(human\)\s*$/, "").trim())
+ .filter(Boolean);
+}
+
+const round4 = (v: number) => Math.round(v * 10_000) / 10_000;
+
+/** Run triage `k` of `owner` (queued, or running: a resumed job) to its end. Answers the file as it ended. */
+export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Promise<{ file: TriageFile; byModel: Record<string, ModelTally> }> {
+ const { owner, k } = input;
+ const paths = deps.paths;
+ const now = () => (deps.now ?? (() => new Date()))();
+ const log = (l: string) => {
+ try {
+ deps.log?.(l);
+ } catch {
+ /* a listener never stops the run */
+ }
+ };
+ const f0 = await readTriageFile(owner, k, paths);
+ if (!f0) throw new Error(`no triage run ${owner}/${k}`);
+ if (f0.status !== "queued" && f0.status !== "running") throw new Error(`triage ${owner}/${k} is ${f0.status}: only a queued run is run`);
+ const file: TriageFile = { ...f0, status: "running", startedAt: now().toISOString(), warnings: [...(f0.warnings ?? [])] };
+ const save = () => writeTriageFile(file, paths).catch((e: Error) => log(`triage.json not kept: ${e.message}`));
+ await save();
+ const tracer: RunTracer = await openTrace({ article: owner, n: k, file: triageTracePath(paths, owner, k), now, log }).catch(() => NO_TRACE);
+ const trace: RunTracer["emit"] = (e) => {
+ try {
+ tracer.emit(e);
+ } catch {
+ /* a trace never stops the run */
+ }
+ };
+ const meter = new Meter({ ...(input.maxUsd !== undefined && Number.isFinite(input.maxUsd) ? { maxUsd: input.maxUsd } : {}) });
+ const t0 = Date.now();
+ trace({ t: "run", phase: "start", task: "triage", model: file.model, ...(file.jobId ? { jobId: file.jobId } : {}) });
+ trace({
+ t: "scope",
+ source: deps.corpus.source,
+ channels: file.scope.channels,
+ ...(file.scope.from ? { from: file.scope.from } : {}),
+ ...(file.scope.to ? { to: file.scope.to } : {}),
+ question: file.question,
+ model: file.model,
+ ...(input.origin ? { origin: input.origin } : {}),
+ ...(input.maxUsd !== undefined && Number.isFinite(input.maxUsd) ? { maxUsd: input.maxUsd } : {}),
+ ...(input.ids?.length ? { ids: input.ids } : {}),
+ });
+ if (file.terms || file.topics.length) trace({ t: "terms", terms: [...(file.terms ? [file.terms] : []), ...file.topics.map((t) => `topic: ${t}`)] });
+
+ const ask =
+ deps.ask ??
+ (<T,>(system: string, user: string, schema: object) =>
+ structuredAnswer<T>({ llm: deps.llm, model: file.model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}) }));
+ const enumerateRaw = deps.enumerate ?? enumerateViaTools(deps.corpus);
+ // Each enumeration, traced as tier 0's.
+ const enumerate: EnumerateFn = async (args) => {
+ const e = await enumerateRaw(args);
+ trace({ t: "enumerate", query: String(args.query), n: e.rows.length, ids: e.rows.map((r) => r.id), partial: e.partial, unreached: e.unreached });
+ return e;
+ };
+ const topicsOf =
+ deps.topicsOf ??
+ (async (id: string, channel: string | null) => {
+ try {
+ return topicsFromMetadata(await deps.corpus.call("get_video_metadata", { video_id: id, ...(channel && file.scope.channels.includes(channel) ? { channel } : {}) }));
+ } catch {
+ return null;
+ }
+ });
+
+ let outcome: "done" | "failed" | "cancelled" = "done";
+ let seenIds: string[] | null = null;
+ try {
+ // ─── tier 0 ───
+ const seen = input.ids?.length ? null : await readTriageSeen(owner, paths);
+ const known = seen ? new Set(seen.ids) : null;
+ file.knownCount = seen ? seen.ids.length : null;
+ const t0r = await triageCandidates(
+ {
+ scope: file.scope,
+ terms: file.terms,
+ regex: file.regex,
+ topics: file.topics,
+ known,
+ since: file.since,
+ ...(input.ids?.length ? { ids: input.ids } : {}),
+ max: input.maxCandidates ?? DEFAULT_MAX_CANDIDATES,
+ },
+ { enumerate, topicsOf, ...(deps.signal ? { signal: deps.signal } : {}), log },
+ );
+ file.tier0 = t0r.tier0;
+ seenIds = t0r.seen;
+ if (t0r.tier0.partial) file.warnings.push(`the scan was partial${t0r.tier0.unreached.length ? ` (not reached: ${t0r.tier0.unreached.join(", ")})` : ""}: a recording it did not reach is not a candidate this time`);
+ if (t0r.tier0.cut.length) file.warnings.push(`${t0r.tier0.cut.length} candidate(s) past the cap of ${input.maxCandidates ?? DEFAULT_MAX_CANDIDATES}: not judged, left new for the next run`);
+ if (!seen && !input.ids?.length) file.warnings.push(file.since ? `no earlier triage: "new" is uploaded on or after ${file.since}` : "no earlier triage: every recording in scope is new");
+ await save();
+ log(`tier 0: ${t0r.tier0.candidates.length} candidate(s) of ${t0r.tier0.newCount} new (${t0r.tier0.scanned} in scope)`);
+
+ // ─── tier 1 ───
+ const j = await judgeCandidates(
+ { question: file.question, candidates: t0r.tier0.candidates, terms: file.terms, regex: file.regex, topics: file.topics, channels: file.scope.channels, ...(input.windows ? { windows: input.windows } : {}), origin: input.origin ?? null },
+ {
+ corpus: deps.corpus,
+ ask,
+ model: file.model,
+ ...(deps.cuesOf ? { cuesOf: deps.cuesOf } : {}),
+ usd: () => meter.usd,
+ ...(deps.signal ? { signal: deps.signal } : {}),
+ log,
+ progress: (d, t) => deps.progress?.(d, t),
+ trace: (e) => trace(e),
+ stop: () => (meter.maxUsd !== undefined && meter.usd >= meter.maxUsd ? `the job's cap of $${meter.maxUsd.toFixed(2)} is reached` : null),
+ },
+ );
+ file.tier1 = { model: file.model, flags: j.flags, dismissed: j.dismissed, read: j.read, windows: j.windows, chunks: j.chunks, usd: round4(meter.usd) };
+ if (j.stopped) {
+ file.warnings.push(`tier 1 stopped: ${j.stopped.reason} — ${j.stopped.ids.length} candidate(s) not judged, left new for the next run`);
+ const left = new Set(j.stopped.ids);
+ if (seenIds) seenIds = seenIds.filter((id) => !left.has(id));
+ }
+ trace({ t: "cost", step: "tier 1", tier: 1, usd: round4(meter.usd), model: file.model, total: round4(meter.usd) });
+
+ // ─── the decision ───
+ file.escalation = escalationOf(j.flags, file.threshold);
+ file.cost = { tier0: 0, tier1: round4(meter.usd) };
+ file.summary = `${triageLine(file)} — ${file.escalation.escalate ? "escalate" : "below the threshold"}: ${file.escalation.why}`;
+ log(`tier 1: ${j.flags.length} flag(s), ${j.dismissed.length} dismissed; ${file.summary}`);
+ trace({
+ t: "triage",
+ owner,
+ k,
+ candidates: t0r.tier0.candidates.map((c) => c.id),
+ flagged: [...new Set(j.flags.map((x) => x.id))],
+ dismissed: j.dismissed.length,
+ escalated: file.escalation.escalate,
+ why: file.escalation.why,
+ cost: file.cost,
+ model: file.model,
+ });
+ } catch (e) {
+ const cancelled = !!deps.signal?.aborted;
+ outcome = cancelled ? "cancelled" : "failed";
+ file.error = cancelled ? "cancelled" : (e as Error).message;
+ file.summary = cancelled ? "cancelled" : `failed: ${(e as Error).message}`;
+ file.cost = { tier0: 0, tier1: round4(meter.usd) };
+ log(`triage ${outcome}: ${file.error}`);
+ }
+ file.status = outcome;
+ file.endedAt = now().toISOString();
+ if (outcome === "done" && seenIds) {
+ await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner, k, at: file.endedAt, ids: seenIds }, paths).catch((e: Error) => {
+ file.warnings.push(`seen.json not kept: ${e.message} — the next run sees these recordings as new again`);
+ });
+ }
+ trace({ t: "run", phase: "end", status: outcome, summary: file.summary.slice(0, 1000), usd: round4(meter.usd), minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 });
+ await tracer.flush();
+ await save();
+ return { file, byModel: meter.summary().byModel };
+}
diff --git a/common/lib/report/draft/triage/tier0.ts b/common/lib/report/draft/triage/tier0.ts
@@ -0,0 +1,158 @@
+// TRIAGE, TIER 0 — code, $0 (umtool R6): the candidates.
+//
+// new a recording in scope the owner's last completed triage did NOT
+// see — by ID, not by publish date, so an old recording whose
+// transcript lands late is new (R5's late-transcript gap, closed).
+// With no last run, new is "uploaded on or after `since`".
+// candidate a new recording that matches the terms (enumerate_matches,
+// alias-aware; R4's deltaCandidates with `known` = the ids seen),
+// OR whose digest topic tags match the topics; with neither
+// terms nor topics, every new recording
+//
+// The scope is scanned once with enumerate_matches' "any recording" regex (the
+// same `.` R5's window check uses) for the set this run SAW, which becomes the
+// next run's `known` — less the candidates past the cap, which stay new.
+// Posts are not candidates (a triage reads transcript windows).
+//
+// Pure over the enumerate function and the topic reader it is handed.
+
+import { deltaCandidates, type EnumerateFn } from "../refresh/delta";
+import type { TriageCandidate, TriageTier0 } from "./types";
+
+export type Tier0Input = {
+ scope: { channels: string[]; from?: string; to?: string };
+ terms: string | null;
+ regex?: boolean;
+ topics: string[];
+ // The ids the last completed run saw; null: none yet (then `since`).
+ known: ReadonlySet<string> | null;
+ since: string | null;
+ // Named by the caller: no scan, these are the candidates.
+ ids?: string[];
+ // The most candidates tier 1 judges (the rest are cut, left new).
+ max: number;
+ // The most new recordings whose digest tags are read for the topics.
+ maxTopicReads?: number;
+};
+
+export type Tier0Deps = {
+ enumerate: EnumerateFn;
+ // A recording's digest topic tags (null: no digest). Absent: topics unread.
+ topicsOf?: (id: string, channel: string | null) => Promise<string[] | null>;
+ signal?: AbortSignal;
+ log?: (line: string) => void;
+};
+
+export type Tier0Result = {
+ tier0: TriageTier0;
+ // What the next run counts as known (null: leave seen.json as it is).
+ seen: string[] | null;
+ // The scope scan's ids (for the trace).
+ scannedIds: string[];
+};
+
+const ymdOf = (d: string | null | undefined): string | null => {
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim());
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+};
+
+const wordsOf = (s: string) =>
+ ` ${s
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, " ")
+ .trim()} `;
+
+/** Does a digest tag match a topic? Equal, or one holds the other as whole words (case and punctuation aside). */
+export function tagMatches(tag: string, topic: string): boolean {
+ const t = wordsOf(tag);
+ const p = wordsOf(topic);
+ if (t.trim() === "" || p.trim() === "") return false;
+ return t === p || t.includes(p) || p.includes(t);
+}
+
+export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tier0Result> {
+ const log = (l: string) => d.log?.(l);
+ if (i.ids?.length) {
+ const ids = [...new Set(i.ids)];
+ const candidates: TriageCandidate[] = ids.slice(0, i.max).map((id) => ({ id, channel: null, title: null, date: null, matches: null, by: ["ids"] }));
+ return {
+ tier0: { candidates, scanned: 0, newCount: ids.length, cut: ids.slice(i.max), partial: false, unreached: [], perQuery: [], newBy: "ids" },
+ seen: null,
+ scannedIds: [],
+ };
+ }
+ const { channels } = i.scope;
+ const dates = { ...(i.scope.from ? { date_from: i.scope.from } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}) };
+ // The scope, once: what this run saw.
+ const all = await d.enumerate({ query: ".", regex: true, ...(channels.length ? { channels } : {}), ...dates });
+ d.signal?.throwIfAborted();
+ const rows = all.rows.filter((r) => r.kind !== "post");
+ const perQuery: TriageTier0["perQuery"] = [{ query: "(any recording)", n: rows.length, partial: all.partial }];
+ const since = i.known ? null : ymdOf(i.since);
+ const isNew = (id: string, date: string | null) => (i.known ? !i.known.has(id) : since ? !!date && date >= since : true);
+ const fresh = rows.filter((r) => isNew(r.id, ymdOf(r.date)));
+ const byId = new Map(fresh.map((r) => [r.id, r]));
+ log(`tier 0: ${rows.length} recording(s) in scope, ${fresh.length} new ${i.known ? `since the last run (by id; ${i.known.size} known)` : since ? `uploaded on or after ${since}` : "(no last run, no since: all)"}`);
+ let partial = all.partial;
+ const unreached = new Set(all.unreached);
+
+ const found = new Map<string, TriageCandidate>();
+ const terms = i.terms?.trim() || null;
+ const topics = i.topics.map((t) => t.trim()).filter(Boolean);
+ if (terms) {
+ const knownRec = i.known ? Object.fromEntries([...i.known].map((id) => [id, null])) : undefined;
+ const c = await deltaCandidates({ queries: [{ query: terms, ...(i.regex ? { regex: true } : {}) }], scope: i.scope }, d.enumerate, {
+ ...(knownRec ? { known: knownRec } : { since: since ?? "0000-01-01" }),
+ ...(d.signal ? { signal: d.signal } : {}),
+ });
+ if (c.partial) partial = true;
+ for (const u of c.unreached) unreached.add(u);
+ perQuery.push(...c.perQuery);
+ for (const id of c.newIds) {
+ const row = c.rows.get(id);
+ found.set(id, { id, channel: row?.channel ?? byId.get(id)?.channel ?? null, title: row?.title ?? byId.get(id)?.title ?? null, date: row?.date ?? ymdOf(byId.get(id)?.date), matches: row?.matches ?? null, by: ["terms"] });
+ }
+ log(`tier 0: terms ${JSON.stringify(terms)}: ${c.newIds.length} new recording(s) match`);
+ }
+ if (topics.length && d.topicsOf) {
+ let reads = 0;
+ let hits = 0;
+ const max = i.maxTopicReads ?? 200;
+ for (const r of fresh) {
+ if (reads >= max) break;
+ d.signal?.throwIfAborted();
+ reads++;
+ const tags = await d.topicsOf(r.id, r.channel).catch(() => null);
+ const matched = (tags ?? []).filter((t) => topics.some((p) => tagMatches(t, p)));
+ if (!matched.length) continue;
+ hits++;
+ const had = found.get(r.id);
+ if (had) {
+ had.by.push("topics");
+ had.tags = matched;
+ } else {
+ found.set(r.id, { id: r.id, channel: r.channel, title: r.title, date: ymdOf(r.date), matches: null, by: ["topics"], tags: matched });
+ }
+ }
+ log(`tier 0: topics ${topics.join(", ")}: ${hits} of ${reads} new recording(s) read carry a matching digest tag${fresh.length > reads ? ` (${fresh.length - reads} not read: the cap)` : ""}`);
+ } else if (topics.length) {
+ log("tier 0: topics given but no digest reader here: topics not matched");
+ }
+ if (!terms && !topics.length) {
+ for (const r of fresh) found.set(r.id, { id: r.id, channel: r.channel, title: r.title, date: ymdOf(r.date), matches: null, by: ["new"] });
+ }
+ const ranked = [...found.values()].sort(
+ (a, b) => b.by.length - a.by.length || (b.matches ?? 0) - (a.matches ?? 0) || String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id),
+ );
+ const candidates = ranked.slice(0, i.max);
+ const cut = ranked.slice(i.max).map((c) => c.id);
+ const cutSet = new Set(cut);
+ const scannedIds = rows.map((r) => r.id);
+ // Seen: everything known, everything scanned, less what was cut (it stays new).
+ const seen = [...new Set([...(i.known ?? []), ...scannedIds])].filter((id) => !cutSet.has(id));
+ return {
+ tier0: { candidates, scanned: rows.length, newCount: fresh.length, cut, partial, unreached: [...unreached].sort(), perQuery, newBy: i.known ? "id" : "date" },
+ seen,
+ scannedIds,
+ };
+}
diff --git a/common/lib/report/draft/triage/triage.test.ts b/common/lib/report/draft/triage/triage.test.ts
@@ -0,0 +1,333 @@
+// Triage first (umtool R6): tier 0 by id (a late transcript is new), the
+// digest topics, the cap; tier 1's judge over given windows with a stubbed
+// model (a strong flag, a weak one, an invented line dropped, a mention only,
+// a window not relevant, a line the cues do not hold); the threshold and the
+// suggestion; one run end to end over a temp store (triage.json, trace.jsonl,
+// seen.json — and a failed run keeps nothing seen). Stubs only: no model, no
+// corpus on disk.
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { EnumeratedAnswer, EnumerateFn } from "../refresh/delta";
+import type { CorpusToolsLike } from "../tasks/types";
+import { judgeCandidates } from "./judge";
+import { createTriageRun, readTriageFile, readTriageSeen, triageTracePath, writeTriageSeen } from "./store";
+import { runTriage, topicsFromMetadata } from "./task";
+import { tagMatches, triageCandidates } from "./tier0";
+import {
+ DEFAULT_TRIAGE_THRESHOLD,
+ TRIAGE_FORMAT,
+ TRIAGE_SEEN_FORMAT,
+ TRIAGE_VERSION,
+ escalationOf,
+ precisionOf,
+ suggestThreshold,
+ tickTriageOf,
+ thresholdWords,
+ type TriageCandidate,
+ type TriageFile,
+} from "./types";
+
+const tmp = await mkdtemp(path.join(os.tmpdir(), "triage-"));
+after(() => rm(tmp, { recursive: true, force: true }));
+let n = 0;
+const store = () => ({ articlesDir: path.join(tmp, `reports-${++n}`) });
+
+// ─── a corpus, stubbed ───
+
+type Rec = { id: string; date: string; title: string; lines: string[]; tags?: string[] };
+const CHAN = "synth-kitchen";
+const NAME = "Synth Kitchen";
+
+const RECS: Rec[] = [
+ { id: "bread-01", date: "20260105", title: "Bread day", lines: ["welcome back", "the oven ran hot again", "I paid for the mixer myself"] },
+ { id: "pie-02", date: "20260210", title: "Pie stream", lines: ["a lot of you asked about the contest", "I did not enter the contest this year", "the judges were friends of mine so it felt wrong"] },
+ // An OLD recording whose transcript landed late: new by id, not by date.
+ { id: "late-03", date: "20250301", title: "Old stream, late transcript", lines: ["back then the contest was smaller", "I judged the contest that year myself", "we baked forty pies"] },
+ { id: "new-04", date: "20261012", title: "Contest results", lines: ["the contest results came out today", "I was not a judge at the contest this year either", "congratulations to the winner"] },
+ { id: "tag-05", date: "20261013", title: "Shop talk", lines: ["the second shop opens in the spring", "small place big oven"], tags: ["bakery business", "second shop"] },
+];
+
+const ymd = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`;
+
+function enumerateOver(recs: Rec[]): EnumerateFn & { calls: Record<string, unknown>[] } {
+ const calls: Record<string, unknown>[] = [];
+ const fn = (async (args: Record<string, unknown>): Promise<EnumeratedAnswer> => {
+ calls.push(args);
+ const q = String(args.query);
+ const any = q === "." && args.regex === true;
+ const rows = recs
+ .map((r) => ({ r, n: any ? 1 : r.lines.filter((l) => l.toLowerCase().includes(q.toLowerCase())).length }))
+ .filter((x) => x.n > 0)
+ .map(({ r, n }) => ({ id: r.id, kind: "video" as const, channel: NAME, date: ymd(r.date), matches: n, title: r.title }));
+ return { rows, partial: false, unreached: [] };
+ }) as EnumerateFn & { calls: Record<string, unknown>[] };
+ fn.calls = calls;
+ return fn;
+}
+
+const stamp = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}|${s}`;
+
+/** get_transcripts as the MCP answers it with link_style "base" (windows around the query, or the whole transcript). */
+function corpusOver(recs: Rec[], o: { calls?: { name: string; args: Record<string, unknown> }[] } = {}): CorpusToolsLike {
+ return {
+ source: "local:/fake/out",
+ tools: [],
+ async call(name, args = {}) {
+ o.calls?.push({ name, args });
+ if (name === "get_transcripts") {
+ const ids = (args.video_ids as string[]) ?? [];
+ const qs = [...(Array.isArray(args.queries) ? (args.queries as string[]) : []), ...(typeof args.query === "string" ? [args.query] : [])].map((q) => q.toLowerCase());
+ return ids
+ .map((id) => {
+ const r = recs.find((x) => x.id === id);
+ if (!r) return `## ${id}\n- video_id: ${id}\n(not found)`;
+ const lines = r.lines.map((t, i) => ({ s: i * 5, t })).filter((l) => !qs.length || qs.some((q) => l.t.toLowerCase().includes(q)));
+ return [`## ${r.title}`, `- video_id: ${id}`, `- moment_base: https://synth.example/?v=${CHAN}%2F${id}&t=`, ...lines.map((l) => `[${stamp(l.s)}] ${l.t}`)].join("\n");
+ })
+ .join("\n---\n");
+ }
+ if (name === "get_video_metadata") {
+ const r = recs.find((x) => x.id === args.video_id);
+ if (!r) throw new Error("video not found");
+ return `{"id": "${r.id}"}${r.tags ? `\n\n## AI digest\n### Topic tags\n${r.tags.join(", ")}` : ""}`;
+ }
+ throw new Error(`the stub has no ${name}`);
+ },
+ };
+}
+
+const cuesOver = (recs: Rec[]) => async (_channel: string, id: string) => {
+ const r = recs.find((x) => x.id === id);
+ return r ? r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })) : null;
+};
+
+// ─── tier 0 ───
+
+test("tier 0: new by ID — an old recording whose transcript landed late is a candidate; the scan's ids become seen", async () => {
+ const enumerate = enumerateOver(RECS);
+ const known = new Set(["bread-01", "pie-02"]);
+ const r = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known, since: null, max: 40 }, { enumerate });
+ assert.deepEqual(r.tier0.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]);
+ assert.equal(r.tier0.newBy, "id");
+ assert.equal(r.tier0.newCount, 3); // late-03, new-04, tag-05
+ assert.deepEqual(r.seen?.sort(), RECS.map((x) => x.id).sort());
+ // The scope was scanned once with the "any recording" regex.
+ assert.ok(enumerate.calls.some((c) => c.query === "." && c.regex === true));
+
+ // With no last run, new is by upload date from `since`: the late transcript is NOT new then.
+ const byDate = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: enumerateOver(RECS) });
+ assert.deepEqual(byDate.tier0.candidates.map((c) => c.id), ["new-04"]);
+ assert.equal(byDate.tier0.newBy, "date");
+});
+
+test("tier 0: digest topics put forward a recording no term matches; the cap leaves the rest new (not seen)", async () => {
+ const corpus = corpusOver(RECS);
+ const topicsOf = async (id: string) => topicsFromMetadata(await corpus.call("get_video_metadata", { video_id: id }).catch(() => ""));
+ const r = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: ["second shop"], known: new Set(["bread-01"]), since: null, max: 40 }, { enumerate: enumerateOver(RECS), topicsOf });
+ const tag = r.tier0.candidates.find((c) => c.id === "tag-05");
+ assert.deepEqual(tag?.by, ["topics"]);
+ assert.deepEqual(tag?.tags, ["second shop"]);
+ assert.ok(tagMatches("Bakery Business", "bakery"));
+ assert.ok(!tagMatches("bakery", "contest"));
+
+ const capped = await triageCandidates({ scope: { channels: [CHAN] }, terms: null, topics: [], known: new Set(), since: null, max: 2 }, { enumerate: enumerateOver(RECS) });
+ assert.equal(capped.tier0.candidates.length, 2);
+ assert.equal(capped.tier0.cut.length, 3);
+ for (const id of capped.tier0.cut) assert.ok(!capped.seen!.includes(id), `${id} stays new`);
+ assert.deepEqual(capped.tier0.candidates[0]!.by, ["new"]);
+});
+
+// ─── tier 1 ───
+
+const cand = (id: string, by: TriageCandidate["by"] = ["terms"]): TriageCandidate => {
+ const r = RECS.find((x) => x.id === id)!;
+ return { id, channel: NAME, title: r.title, date: ymd(r.date), matches: 1, by };
+};
+
+test("tier 1: the judge over given windows — a strong flag, a weak one, an invented line dismissed as not verbatim, a mention only, a window not relevant", async () => {
+ const asked: string[] = [];
+ const answers: Record<string, unknown> = {
+ "late-03": {
+ relevant: true,
+ items: [
+ { quote: "I judged the contest that year myself", claim: "She says she judged the contest that year.", on_topic: true, strength: 3 },
+ // Invented: not in the window — dismissed, kept with its reason.
+ { quote: "I rigged the contest for my friends", claim: "She says she rigged it.", on_topic: true, strength: 3 },
+ ],
+ },
+ "new-04": {
+ relevant: true,
+ items: [
+ { quote: "I was not a judge at the contest this year either", claim: "She says she was not a judge this year.", on_topic: true, strength: 2 },
+ { quote: "the contest results came out today", claim: "She mentions the results.", on_topic: true, strength: 1 },
+ ],
+ },
+ "pie-02": { relevant: false, items: [] },
+ };
+ const ask = async <T,>(_s: string, user: string, _schema: object, what: string): Promise<T> => {
+ asked.push(what);
+ const id = /^triage (\S+)@/.exec(what)![1]!;
+ assert.match(user, /Research question: Did she judge the contest\?/);
+ return answers[id] as T;
+ };
+ const calls: { name: string; args: Record<string, unknown> }[] = [];
+ const j = await judgeCandidates(
+ {
+ question: "Did she judge the contest?",
+ candidates: [cand("late-03"), cand("new-04"), cand("pie-02")],
+ terms: "contest",
+ topics: [],
+ channels: [CHAN],
+ // late-03: only its second line, by the caller's window.
+ windows: { "late-03": [{ start: 5, end: 5 }] },
+ origin: "https://synth.example",
+ },
+ { corpus: corpusOver(RECS, { calls }), ask, model: "qwen3:8b", cuesOf: cuesOver(RECS) },
+ );
+ assert.deepEqual(
+ j.flags.map((f) => [f.id, f.strength, f.line, f.checked]),
+ [
+ ["late-03", "strong", "I judged the contest that year myself", "cues"],
+ ["new-04", "weak", "I was not a judge at the contest this year either", "cues"],
+ ],
+ );
+ assert.equal(j.flags[0]!.f, "f1");
+ assert.equal(j.flags[0]!.at, 5);
+ assert.equal(j.flags[0]!.url, `https://synth.example/?v=${CHAN}%2Flate-03&t=5`);
+ const why = (id: string) => j.dismissed.filter((d) => d.id === id).map((d) => `${d.stage}: ${d.reason}`);
+ assert.deepEqual(why("late-03"), ["verbatim: not verbatim in its window"]);
+ assert.equal(j.dismissed.find((d) => d.id === "late-03")!.line, "I rigged the contest for my friends");
+ assert.deepEqual(why("new-04"), ["score: a mention only — She mentions the results."]);
+ assert.deepEqual(why("pie-02"), ["judge: not relevant to the question"]);
+ // late-03 was read whole (its own window), the others around the terms.
+ assert.deepEqual(calls.map((c) => [c.name, (c.args.video_ids as string[]).join(","), c.args.queries ?? null]), [
+ ["get_transcripts", "new-04,pie-02", ["contest"]],
+ ["get_transcripts", "late-03", null],
+ ]);
+});
+
+test("tier 1: a line the window holds but the transcript's cues do not is dismissed (R2's word check)", async () => {
+ const ask = async <T,>(): Promise<T> => ({ relevant: true, items: [{ quote: "I was not a judge at the contest this year either", claim: "Not a judge.", on_topic: true, strength: 3 }] }) as T;
+ // The cues now say something else at that second (a re-transcription).
+ const cuesOf = async () => [
+ { start: 0, end: 4.8, text: "the contest results came out today" },
+ { start: 5, end: 9.8, text: "I was a judge at the contest this year" },
+ ];
+ const j = await judgeCandidates({ question: "q", candidates: [cand("new-04")], terms: "contest", topics: [], channels: [CHAN] }, { corpus: corpusOver(RECS), ask, model: "qwen3:8b", cuesOf });
+ assert.equal(j.flags.length, 0);
+ assert.equal(j.dismissed[0]!.stage, "verbatim");
+ assert.match(j.dismissed[0]!.reason, /not in the transcript's cues near 0:05/);
+});
+
+// ─── the threshold ───
+
+test("the threshold: one strong flag, or N of any strength; 0 turns a rule off", () => {
+ const strong = { strength: "strong" as const };
+ const weak = { strength: "weak" as const };
+ assert.equal(escalationOf([strong], DEFAULT_TRIAGE_THRESHOLD).escalate, true);
+ assert.equal(escalationOf([weak, weak], DEFAULT_TRIAGE_THRESHOLD).escalate, false);
+ assert.equal(escalationOf([weak, weak, weak], DEFAULT_TRIAGE_THRESHOLD).escalate, true);
+ assert.equal(escalationOf([], DEFAULT_TRIAGE_THRESHOLD).why, "no flag (threshold: 1 strong or 3 weak)");
+ assert.equal(escalationOf([strong, weak], DEFAULT_TRIAGE_THRESHOLD).why, "1 strong flag, 1 weak flag (threshold: 1 strong or 3 weak)");
+ assert.equal(escalationOf([strong, strong], { strong: 3, weak: 0 }).escalate, false);
+ assert.equal(escalationOf([weak, weak, weak], { strong: 1, weak: 0 }).escalate, false);
+ assert.equal(thresholdWords({ strong: 1, weak: 0 }), "1 strong only");
+ assert.equal(thresholdWords({ strong: 0, weak: 0 }), "never");
+});
+
+test("precision and the suggested threshold (a suggestion: weak flags mostly wrong raise the weak count)", () => {
+ const at = "2026-10-14T00:00:00Z";
+ const m = (verdict: "right" | "wrong", score: number) => ({ verdict, score, at });
+ const p = precisionOf([m("right", 3), m("right", 3), m("wrong", 2), m("wrong", 2), m("right", 2)]);
+ assert.deepEqual([p.marked, p.right, p.wrong, p.precision], [5, 3, 2, 0.6]);
+ const s = suggestThreshold(p, { strong: 1, weak: 3 });
+ assert.equal(s.changed, true);
+ assert.deepEqual(s.threshold, { strong: 1, weak: 4 });
+ assert.match(s.why, /weak flags were right 1 of 3/);
+ const none = suggestThreshold(precisionOf([]), { strong: 1, weak: 3 });
+ assert.equal(none.changed, false);
+ assert.match(none.why, /mark 3 to get a suggestion/);
+ const bad = suggestThreshold(precisionOf([m("wrong", 2), m("wrong", 2), m("wrong", 2)]), { strong: 1, weak: 3 });
+ assert.deepEqual(bad.threshold, { strong: 1, weak: 0 });
+});
+
+// ─── a run, end to end ───
+
+function queued(owner: string, o: Partial<TriageFile> = {}) {
+ return (k: number): TriageFile => ({
+ format: TRIAGE_FORMAT,
+ version: TRIAGE_VERSION,
+ owner,
+ k,
+ status: "queued",
+ model: "qwen3:8b",
+ provider: "local",
+ question: "Did she judge the contest?",
+ scope: { channels: [CHAN] },
+ terms: "contest",
+ regex: false,
+ topics: [],
+ threshold: DEFAULT_TRIAGE_THRESHOLD,
+ since: "2026-10-01",
+ knownCount: null,
+ createdAt: "2026-10-14T00:00:00.000Z",
+ cost: { tier0: 0, tier1: 0 },
+ summary: "queued",
+ warnings: [],
+ ...o,
+ });
+}
+
+test("a run end to end: triage.json (tiers, escalation), trace.jsonl (enumerate, batch, check, triage, cost), seen.json; the next run counts by id", async () => {
+ const paths = store();
+ await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "watch-a", k: 0, at: "2026-10-07T00:00:00Z", ids: ["bread-01", "pie-02", "tag-05"] }, paths);
+ const run = await createTriageRun(queued("watch-a"), paths, "watch-a");
+ assert.equal(run.k, 1);
+ const ask = async <T,>(_s: string, user: string): Promise<T> =>
+ (/judged the contest that year/.test(user)
+ ? { relevant: true, items: [{ quote: "I judged the contest that year myself", claim: "She judged it that year.", on_topic: true, strength: 3 }] }
+ : { relevant: false, items: [] }) as T;
+ const { file } = await runTriage({ owner: "watch-a", k: 1 }, { llm: {} as never, corpus: corpusOver(RECS), enumerate: enumerateOver(RECS), paths, cuesOf: cuesOver(RECS), ask });
+ assert.equal(file.status, "done", file.error);
+ assert.deepEqual(file.tier0!.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]);
+ assert.equal(file.tier0!.newBy, "id");
+ assert.equal(file.knownCount, 3);
+ assert.deepEqual(file.tier1!.flags.map((f) => f.id), ["late-03"]);
+ assert.equal(file.escalation!.escalate, true);
+ assert.equal(file.cost.tier1, 0);
+ assert.match(file.summary, /2 candidates · 1 flagged · 1 dismissed — escalate: 1 strong flag/);
+ const back = await readTriageFile("watch-a", 1, paths);
+ assert.equal(back?.status, "done");
+ const seen = await readTriageSeen("watch-a", paths);
+ assert.equal(seen?.k, 1);
+ assert.deepEqual(seen?.ids.sort(), RECS.map((r) => r.id).sort());
+ const trace = (await readFile(triageTracePath(paths, "watch-a", 1), "utf8")).trim().split("\n").map((l) => JSON.parse(l) as { t: string; phase?: string; stage?: string; tier?: number; flagged?: string[] });
+ assert.deepEqual(trace[0], { ...trace[0], t: "run", phase: "start" });
+ for (const t of ["scope", "terms", "enumerate", "batch", "check", "triage", "cost"]) assert.ok(trace.some((e) => e.t === t), `trace has ${t}`);
+ assert.deepEqual(trace.find((e) => e.t === "triage")!.flagged, ["late-03"]);
+ assert.equal(trace.find((e) => e.t === "cost")!.tier, 1);
+ assert.deepEqual(trace.at(-1), { ...trace.at(-1), t: "run", phase: "end" });
+ const line = tickTriageOf(file, { tier2Usd: 0.42 });
+ assert.deepEqual([line.k, line.candidates, line.flagged, line.escalated, line.ids, line.usd], [1, 2, 1, true, ["late-03"], { tier1: 0, tier2: 0.42 }]);
+
+ // The next run: nothing new by id, nothing judged, $0.
+ await createTriageRun(queued("watch-a"), paths, "watch-a");
+ const again = await runTriage({ owner: "watch-a", k: 2 }, { llm: {} as never, corpus: corpusOver(RECS), enumerate: enumerateOver(RECS), paths, ask: async () => assert.fail("no candidate: no model call") });
+ assert.equal(again.file.status, "done");
+ assert.equal(again.file.tier0!.candidates.length, 0);
+ assert.equal(again.file.escalation!.escalate, false);
+});
+
+test("a run that fails keeps nothing seen: the next sees the same recordings as new", async () => {
+ const paths = store();
+ await createTriageRun(queued("watch-b"), paths, "watch-b");
+ const broken: CorpusToolsLike = { source: "x", tools: [], call: async () => { throw new Error("the build is gone"); } };
+ const { file } = await runTriage({ owner: "watch-b", k: 1 }, { llm: {} as never, corpus: broken, paths });
+ assert.equal(file.status, "failed");
+ assert.match(file.error!, /the build is gone/);
+ assert.equal(await readTriageSeen("watch-b", paths), null);
+});
diff --git a/common/lib/report/draft/triage/types.ts b/common/lib/report/draft/triage/types.ts
@@ -0,0 +1,327 @@
+// TRIAGE FIRST — a cheap pass that flags what is worth researching (umtool R6;
+// plans/umtool-redesign.md "R6 — Triage first"). The shapes, the threshold and
+// the words; pure (no node imports), so umtool's pages read them too.
+//
+// tier 0 code, $0: the candidates — recordings NEW SINCE THE LAST TRIAGE BY
+// ID (not by publish date: an old recording whose transcript lands
+// late is new) in scope, that match the terms (enumerate, alias
+// aware) or whose digest topic tags match the topics
+// tier 1 the local model ($0 marginal; `models.extractor` allowed): the
+// sweep pipeline's window judge over the candidates' matching
+// windows only. Each FLAG is a recording, a window, a line the code
+// found VERBATIM in the transcript, a score and a one-line reason;
+// each DISMISSAL keeps its reason
+// escalate at or above the threshold (default: one strong flag, or three
+// weak ones) the tick hands the flagged ids to the better model with
+// tools (tier 2: an API sweep restricted to them, R4's `ids`);
+// below it the tick ends with this log, $0 API
+//
+// One triage run is `reports/.triage/<owner>/<k>/` — `triage.json` (this
+// file's TriageFile) and `trace.jsonl` — and `reports/.triage/<owner>/seen.json`
+// is the ids the owner's last completed triage saw (./store.ts). The owner is
+// the schedule (a series', a watch's, a living report's id). The editor's
+// `report-draft {"task":"triage"}` job is their ONE writer.
+
+export const TRIAGE_FORMAT = "archilyzer-triage";
+export const TRIAGE_VERSION = 1;
+export const TRIAGE_SEEN_FORMAT = "archilyzer-triage-seen";
+
+// The judge's score: the sweep pipeline's strength (3 = the line directly
+// answers the question, 2 = it bears on it, 1 = it only mentions a word).
+// A 3 is a STRONG flag, a 2 a WEAK one; a 1 is dismissed.
+export type TriageScore = 1 | 2 | 3;
+export const STRONG_SCORE = 3;
+export const WEAK_SCORE = 2;
+
+// Escalate when the strong flags reach `strong`, or the weak ones `weak`
+// (strong flags count toward `weak` too). 0 turns a rule off: {strong: 1,
+// weak: 0} escalates on a strong flag only.
+export type TriageThreshold = { strong: number; weak: number };
+export const DEFAULT_TRIAGE_THRESHOLD: TriageThreshold = { strong: 1, weak: 3 };
+
+export const TRIAGE_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const;
+export type TriageStatus = (typeof TRIAGE_STATUSES)[number];
+
+export type TriageWindow = { start: number; end: number };
+
+/** A recording tier 0 put forward, and why. */
+export type TriageCandidate = {
+ id: string;
+ // The channel's name as the enumeration gives it (its slug once read).
+ channel: string | null;
+ title: string | null;
+ // YYYY-MM-DD.
+ date: string | null;
+ // Lines matching the terms (summed over them), when they were searched.
+ matches: number | null;
+ // terms: the terms (or aliases) match; topics: a digest topic tag matches;
+ // new: no terms or topics were given, so every new recording is one; ids:
+ // named by the caller.
+ by: ("terms" | "topics" | "new" | "ids")[];
+ // The digest tags that matched the topics.
+ tags?: string[];
+};
+
+/** A line tier 1 flagged: worth a look. */
+export type TriageFlag = {
+ // f1, f2, … within the run (a mark names a flag by it).
+ f: string;
+ id: string;
+ // The channel slug (the moment link's).
+ channel: string | null;
+ title: string | null;
+ date: string | null;
+ // The window the judge read.
+ window: TriageWindow;
+ // The line, verbatim (code-checked), and the second it starts at.
+ line: string;
+ at: number;
+ score: TriageScore;
+ strength: "strong" | "weak";
+ // The judge's one line (its claim).
+ reason: string;
+ // How the line was checked: against the transcript's cues (R2's word check),
+ // or — when the cues could not be read — against the window the judge read.
+ checked: "cues" | "window";
+ // A moment link, when the corpus gave one.
+ url?: string;
+};
+
+/** What tier 1 put aside, and why. */
+export type TriageDismissal = {
+ id: string;
+ title?: string | null;
+ channel?: string | null;
+ window?: TriageWindow;
+ // The line the judge offered (a dismissal of a line), else none (a window).
+ line?: string;
+ at?: number;
+ score?: number;
+ // judge: the window does not bear on the question; verbatim: the line is not
+ // in the transcript; score: off topic, or a mention only; read: nothing to read.
+ stage: "judge" | "verbatim" | "score" | "read";
+ reason: string;
+};
+
+export type TriageEscalation = {
+ escalate: boolean;
+ // One line: "1 strong flag (threshold: 1 strong or 3 weak)".
+ why: string;
+ strong: number;
+ weak: number;
+ threshold: TriageThreshold;
+};
+
+export type TriageTier0 = {
+ candidates: TriageCandidate[];
+ // Recordings in scope the scan saw, and how many were new.
+ scanned: number;
+ newCount: number;
+ // New recordings past the cap: not judged, left unseen for the next run.
+ cut: string[];
+ partial: boolean;
+ unreached: string[];
+ perQuery: { query: string; n: number; partial: boolean; error?: string }[];
+ // How "new" was decided: by id against the last run's set, or (no set yet)
+ // by upload date from `since`.
+ newBy: "id" | "date" | "ids";
+};
+
+export type TriageTier1 = {
+ model: string;
+ flags: TriageFlag[];
+ dismissed: TriageDismissal[];
+ // Recordings read, windows and model calls (chunks) judged.
+ read: number;
+ windows: number;
+ chunks: number;
+ usd: number;
+};
+
+export type TriageFile = {
+ format: typeof TRIAGE_FORMAT;
+ version: typeof TRIAGE_VERSION;
+ owner: string;
+ k: number;
+ status: TriageStatus;
+ jobId?: string;
+ model: string;
+ provider: "api" | "local";
+ question: string;
+ scope: { channels: string[]; from?: string; to?: string };
+ terms: string | null;
+ regex: boolean;
+ topics: string[];
+ threshold: TriageThreshold;
+ // The day "new" counts from when there is no last run (YYYY-MM-DD).
+ since: string | null;
+ // The ids the last completed run saw (how many), null: none yet.
+ knownCount: number | null;
+ createdAt: string;
+ startedAt?: string;
+ endedAt?: string;
+ tier0?: TriageTier0;
+ tier1?: TriageTier1;
+ escalation?: TriageEscalation;
+ // USD per tier this run spent (tier 0 is code: always 0).
+ cost: { tier0: number; tier1: number };
+ summary: string;
+ error?: string;
+ warnings: string[];
+};
+
+/** seen.json: the ids the owner's last completed triage saw in scope. */
+export type TriageSeen = { format: typeof TRIAGE_SEEN_FORMAT; owner: string; k: number; at: string; ids: string[] };
+
+// ─── the threshold ───
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+/** "1 strong or 3 weak", "a strong flag only". */
+export function thresholdWords(t: TriageThreshold): string {
+ const s = t.strong > 0 ? `${t.strong} strong` : "";
+ const w = t.weak > 0 ? `${t.weak} weak` : "";
+ if (s && w) return `${s} or ${w}`;
+ if (s) return `${s} only`;
+ if (w) return `${w} (weak or strong)`;
+ return "never";
+}
+
+/** A threshold from loose input, each rule 0–50 (0: off), else the default's. */
+export function cleanThreshold(v: unknown, d: TriageThreshold = DEFAULT_TRIAGE_THRESHOLD): TriageThreshold {
+ const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ const n = (x: unknown, def: number) => (typeof x === "number" && Number.isInteger(x) && x >= 0 && x <= 50 ? x : def);
+ return { strong: n(o.strong, d.strong), weak: n(o.weak, d.weak) };
+}
+
+/** Do these flags reach the threshold? */
+export function escalationOf(flags: readonly Pick<TriageFlag, "strength">[], threshold: TriageThreshold): TriageEscalation {
+ const strong = flags.filter((f) => f.strength === "strong").length;
+ const weak = flags.length - strong;
+ const byStrong = threshold.strong > 0 && strong >= threshold.strong;
+ const byAll = threshold.weak > 0 && strong + weak >= threshold.weak;
+ const escalate = byStrong || byAll;
+ const counted = flags.length ? `${plural(strong, "strong flag")}, ${plural(weak, "weak flag")}` : "no flag";
+ return { escalate, why: `${counted} (threshold: ${thresholdWords(threshold)})`, strong, weak, threshold };
+}
+
+/** "8 candidates · 2 flagged · 6 dismissed". */
+export function triageLine(f: Pick<TriageFile, "tier0" | "tier1">): string {
+ const c = f.tier0?.candidates.length ?? 0;
+ const flagged = f.tier1?.flags.length ?? 0;
+ const dismissed = f.tier1?.dismissed.length ?? 0;
+ return `${plural(c, "candidate")} · ${flagged} flagged · ${dismissed} dismissed`;
+}
+
+// ─── what a tick keeps of its triage (the schedule's tick line) ───
+
+export type TickTriage = {
+ owner: string;
+ k: number;
+ status: TriageStatus;
+ candidates: number;
+ flagged: number;
+ dismissed: number;
+ escalated: boolean;
+ why: string;
+ // The flagged ids (what tier 2 read), and the first few flags for a card.
+ ids: string[];
+ top: { f: string; id: string; line: string; score: number; reason: string }[];
+ // USD: tier 1's (0 on the local model), tier 2's (the escalated step's).
+ usd: { tier1: number; tier2: number };
+ // An escalation the day's cap refused.
+ capped?: string;
+};
+
+/** A run's slice for its tick line. */
+export function tickTriageOf(f: TriageFile, o: { tier2Usd?: number; capped?: string } = {}): TickTriage {
+ const flags = f.tier1?.flags ?? [];
+ const ranked = [...flags].sort((a, b) => b.score - a.score);
+ return {
+ owner: f.owner,
+ k: f.k,
+ status: f.status,
+ candidates: f.tier0?.candidates.length ?? 0,
+ flagged: flags.length,
+ dismissed: f.tier1?.dismissed.length ?? 0,
+ escalated: !!f.escalation?.escalate && !o.capped,
+ why: f.escalation?.why ?? f.summary,
+ ids: [...new Set(flags.map((x) => x.id))],
+ top: ranked.slice(0, 5).map((x) => ({ f: x.f, id: x.id, line: x.line.slice(0, 300), score: x.score, reason: x.reason.slice(0, 200) })),
+ usd: { tier1: Math.round((f.cost.tier1 ?? 0) * 10_000) / 10_000, tier2: Math.round((o.tier2Usd ?? 0) * 10_000) / 10_000 },
+ ...(o.capped ? { capped: o.capped } : {}),
+ };
+}
+
+// ─── marks: was a flag right? (umtool keeps them per schedule) ───
+
+export type FlagMark = { verdict: "right" | "wrong"; score: number; at: string };
+
+export type Precision = {
+ marked: number;
+ right: number;
+ wrong: number;
+ // right / marked, null when nothing is marked.
+ precision: number | null;
+ byStrength: { strong: { right: number; wrong: number }; weak: { right: number; wrong: number } };
+};
+
+export function precisionOf(marks: readonly FlagMark[]): Precision {
+ const by = { strong: { right: 0, wrong: 0 }, weak: { right: 0, wrong: 0 } };
+ for (const m of marks) {
+ const s = m.score >= STRONG_SCORE ? by.strong : by.weak;
+ if (m.verdict === "right") s.right++;
+ else s.wrong++;
+ }
+ const right = by.strong.right + by.weak.right;
+ const wrong = by.strong.wrong + by.weak.wrong;
+ const marked = right + wrong;
+ return { marked, right, wrong, precision: marked ? Math.round((right / marked) * 1000) / 1000 : null, byStrength: by };
+}
+
+// The fewest marks of a kind a suggestion is made on.
+export const SUGGEST_MIN_MARKS = 3;
+
+/**
+ * A threshold the marks suggest — a SUGGESTION, never applied. Weak flags that
+ * are mostly wrong raise the weak count (or turn it off); weak flags that are
+ * nearly all right lower it; strong flags mostly wrong raise the strong count.
+ * Too few marks: keep the threshold, and say how many more are needed.
+ */
+export function suggestThreshold(p: Precision, current: TriageThreshold): { threshold: TriageThreshold; why: string; changed: boolean } {
+ const w = p.byStrength.weak;
+ const s = p.byStrength.strong;
+ const nw = w.right + w.wrong;
+ const ns = s.right + s.wrong;
+ const next = { ...current };
+ const why: string[] = [];
+ if (ns >= SUGGEST_MIN_MARKS) {
+ const ps = s.right / ns;
+ if (ps < 0.5 && current.strong > 0) {
+ next.strong = current.strong + 1;
+ why.push(`strong flags were right ${s.right} of ${ns}: escalate on ${next.strong} strong`);
+ }
+ }
+ if (nw >= SUGGEST_MIN_MARKS) {
+ const pw = w.right / nw;
+ if (pw < 0.25 && current.weak > 0) {
+ next.weak = 0;
+ why.push(`weak flags were right ${w.right} of ${nw}: let weak flags alone not escalate`);
+ } else if (pw < 0.6 && current.weak > 0) {
+ next.weak = current.weak + 1;
+ why.push(`weak flags were right ${w.right} of ${nw}: escalate on ${next.weak} weak`);
+ } else if (pw >= 0.8 && current.weak > 1) {
+ next.weak = current.weak - 1;
+ why.push(`weak flags were right ${w.right} of ${nw}: escalate on ${next.weak} weak`);
+ } else if (pw >= 0.8 && current.weak === 0) {
+ next.weak = DEFAULT_TRIAGE_THRESHOLD.weak;
+ why.push(`weak flags were right ${w.right} of ${nw}: let ${next.weak} weak escalate`);
+ }
+ }
+ const changed = next.strong !== current.strong || next.weak !== current.weak;
+ if (!changed) {
+ const need = Math.max(0, SUGGEST_MIN_MARKS - Math.max(nw, ns));
+ why.push(p.marked === 0 ? `mark ${SUGGEST_MIN_MARKS} to get a suggestion` : need > 0 ? `mark ${need} more to get a suggestion` : `keep ${thresholdWords(current)}`);
+ }
+ return { threshold: next, why: why.join("; "), changed };
+}
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -133,6 +133,8 @@ export const iterationScopeSchema = z.looseObject({
to: ymd.optional(),
// A sweep restricted to these recordings (umtool R4: a refresh's new ones).
ids: z.array(z.string().min(1)).optional(),
+ // The triage run this sweep escalates (umtool R6): reports/.triage/<owner>/<k>/.
+ triage: z.looseObject({ owner: z.string().min(1), k: z.number().int().positive() }).optional(),
});
export type IterationScope = z.infer<typeof iterationScopeSchema>;
diff --git a/common/lib/report/schedule/types.ts b/common/lib/report/schedule/types.ts
@@ -15,21 +15,33 @@
// "<topic> · week of <date>" (weekly) or "<topic> · <date>"; a
// window nothing in scope matches is a QUIET edition: recorded,
// no article, $0
-// watch RESERVED for R6 (triage first: no article until something is
-// found). Not offered, refused by create.
+// watch no article until something is found (umtool R6): each tick
+// fetches, then TRIAGES what is new in scope (the cheap pass,
+// lib/report/draft/triage); only a triage at or above its threshold
+// escalates to an API sweep of the flagged recordings, as a new
+// article `<watch>-<date>` — an Inbox "Worth researching" card,
+// and a board umtool makes of the flags. Below it, the tick ends
+// with its triage log, $0 API
+//
+// A living report or a series may ask for TRIAGE FIRST (`triageFirst`): its
+// tick triages before its own step, and runs that step on the flagged
+// recordings only — or, below the threshold, ends $0 (a series' edition is
+// quiet). Stored with the series (a dot-directory) and its runs in
+// reports/.triage/<id>/.
//
// Safe for a client component: zod and ./cadence only.
import { z } from "zod";
import { addDays, cadenceDays, chipWords, localDate, parseCadence, type Cadence } from "./cadence";
+import { TRIAGE_STATUSES } from "../draft/triage/types";
export const SCHEDULE_FORMAT = "archilyzer-schedule";
export const SCHEDULE_VERSION = 1;
export const SCHEDULE_SHAPES = ["living", "series", "watch"] as const;
export type ScheduleShape = (typeof SCHEDULE_SHAPES)[number];
-// The shapes create offers (R6 adds "watch").
-export const OFFERED_SHAPES: readonly ScheduleShape[] = ["living", "series"];
+// The shapes create offers.
+export const OFFERED_SHAPES: readonly ScheduleShape[] = ["living", "series", "watch"];
export const TICK_STATUSES = ["done", "no-change", "quiet", "held-by-cap", "failed", "cancelled", "interrupted"] as const;
export type TickStatus = (typeof TICK_STATUSES)[number];
@@ -69,9 +81,28 @@ export const scheduleScopeSchema = z.looseObject({
// sweep (enumerate_matches' query). Absent: any recording in the window.
terms: z.string().min(1).optional(),
regex: z.boolean().optional(),
+ // A triage's digest topic tags (umtool R6): a new recording whose digest
+ // carries one is a candidate, whatever its words.
+ topics: z.array(z.string().min(1)).optional(),
});
export type ScheduleScope = z.infer<typeof scheduleScopeSchema>;
+// What a tick keeps of its triage (umtool R6; draft/triage/types.ts TickTriage).
+export const tickTriageSchema = z.looseObject({
+ owner: z.string().min(1),
+ k: z.number().int().positive(),
+ status: z.enum(TRIAGE_STATUSES),
+ candidates: z.number().int().nonnegative(),
+ flagged: z.number().int().nonnegative(),
+ dismissed: z.number().int().nonnegative(),
+ escalated: z.boolean(),
+ why: z.string(),
+ ids: z.array(z.string()),
+ top: z.array(z.looseObject({ f: z.string(), id: z.string(), line: z.string(), score: z.number(), reason: z.string() })),
+ usd: z.looseObject({ tier1: z.number().nonnegative(), tier2: z.number().nonnegative() }),
+ capped: z.string().optional(),
+});
+
export const tickSchema = z.looseObject({
at: isoTime,
// The window it ticked for (absent: Tick now).
@@ -93,6 +124,8 @@ export const tickSchema = z.looseObject({
minutes: z.number().nonnegative().optional(),
// What its fetch skipped and said (a held or cooling platform): never its failure.
warnings: z.array(z.string()).optional(),
+ // Its triage, when it ran one (umtool R6): the tiers in brief, and whether it escalated.
+ triage: tickTriageSchema.optional(),
});
export type Tick = z.infer<typeof tickSchema>;
@@ -138,6 +171,10 @@ export const scheduleSchema = z.looseObject({
// A tick's per-job cap (USD; never above the policy's max). Default: the
// policy's sweep cap.
caps: z.looseObject({ maxUsd: z.number().positive().optional() }).optional(),
+ // Living and series: triage first (umtool R6; a watch always triages).
+ triageFirst: z.boolean().optional(),
+ // The schedule's own triage threshold (default: settings.generation.triage's).
+ triage: z.looseObject({ threshold: z.looseObject({ strong: z.number().int().min(0).max(50), weak: z.number().int().min(0).max(50) }).optional() }).optional(),
createdAt: isoTime,
updatedAt: isoTime,
lastTick: isoTime.nullable(),
@@ -158,6 +195,9 @@ export function parseSchedule(raw: unknown): { ok: true; value: Schedule } | { o
// ─── what a reader derives ───
+/** Does this schedule's tick triage first? A watch always does. */
+export const triagesFirst = (s: Pick<Schedule, "shape" | "triageFirst">): boolean => s.shape === "watch" || s.triageFirst === true;
+
/** The cadence chip: "weekly · next Mon 06:00", "daily · paused". */
export const scheduleChip = (s: Pick<Schedule, "cadence" | "tz" | "nextTick" | "paused">, now?: number) => chipWords(s, now);
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -30,6 +30,7 @@ import {
GENERATION_RESEARCH_FIELD_DOCS,
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_CUT_FIELD_DOCS,
+ GENERATION_TRIAGE_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
GENERATION_VERDICTS_FIELD_DOCS,
@@ -301,6 +302,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.cut", docs: GENERATION_CUT_FIELD_DOCS, defaults: fromObject(d.generation.cut) },
{ path: "generation.verdicts", docs: GENERATION_VERDICTS_FIELD_DOCS, defaults: fromObject(d.generation.verdicts) },
{ path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) },
+ { path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -90,6 +90,7 @@ export {
GENERATION_WEB_FIELD_DOCS,
GENERATION_VERDICTS_FIELD_DOCS,
GENERATION_VERDICT_BAR_FIELD_DOCS,
+ GENERATION_TRIAGE_FIELD_DOCS,
type GenerationSettings,
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
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: [{ id: "k1", 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/CHANGELOG.md b/editor/CHANGELOG.md
@@ -16,6 +16,10 @@
- **Recurring reports.** umtool's Create has **A recurring report**: a topic, its scope (channels, or a research board's), a cadence (daily, weekly on a day, or every N days, at a time) and a shape — a **Living report** (one article kept current: each tick fetches what is new and updates it, the new iteration left for review unless "Make each update current without review" is on) or a **Series** (a new dated article each tick, "Co-host updates · week of 2026-10-12", over whole days — from the day after the last edition through the day before the tick, so weekly on Monday covers the Monday to Sunday before it and no day is read twice; a window nothing matches is a *quiet* edition — recorded, no article, $0; a Tick now with nothing new to cover makes no edition and says when the next one starts). **Plan the schedule** says the first tick, the model and the cap before anything is made. A series has its own page (the cadence chip "weekly · next Mon 06:00", Pause/Resume, **Tick now**, Edit cadence, Delete, the editions newest first, the tick log with each tick's spend); a living report wears the same chip in its article's head. Work has a **Recurring** facet; the Inbox puts a finished edition under Review and a failed or cap-held tick under Your call (**Tick now** / **Raise cap**). `umtool schedule list | show <id>` prints them. Needs a restart of umtool and of the editor.
- **The research board's `e`, `n` and `m` no longer lose the field.** Pressed while a move was still saving, the field took the focus and then lost it when the board redrew, and what was typed next landed on the board as commands (`s` toggled the speaker check, `x` asked to remove the quote). The field now takes the focus once the board has redrawn, and no key acts until it does.
- **The editor keeps the schedules.** A new `report-schedule` lane ticks each recurring report when its window comes — one `report-tick` job at a time, never two of one schedule, never on an idle boot; a window missed while the editor was down is caught up by ONE tick. Hold it with `pnpm ops lane '{"lane":"report-schedule","held":true}'` (`settings.reportSchedule.held`); a tick in flight finishes, and Tick now still runs. Drive it with `pnpm ops report-schedule` (`list`, `create` — with `dryRun` the plan —, `update`, `pause`, `resume`, `delete` — the plan unless `confirm: true` —, `tick-now`). Each tick first fetches what is new through the editor's own paced actions (Refresh's stage 1: the channels' syncs and posts, then a local build — never a deploy); a platform that is held or cooling down is skipped and said on the tick, not a failure. A living report's tick is a Refresh: no change costs nothing, an update is left for review (or made current with "make each update current"), and a refresh or sweep the cap holds is a Your call card.
+- **Triage first: a cheap pass flags what is worth researching, and only that reaches the sweep.** A recurring report can now be a **Watch** — no article until something is found — or a living report or series with **Triage first**. Each tick fetches what is new, then triages it: the recordings new since the last triage **by id** (an old recording whose transcript landed late counts as new) that match the terms or carry a matching digest topic tag are judged by the **local model** (the sweep pipeline's window judge over their matching windows only; `draft:local`, behind the GPU arbiter, $0) or, if you choose, by the extractor. A line becomes a **flag** only when the code finds it word for word in the window and in the transcript's cues; strong (it answers the question) or weak (it bears on it). Everything else is **dismissed with why**: not relevant, a mention only, off topic, not verbatim (an invented line is kept beside its reason). At or above the threshold (default one strong flag, or three of any strength) the tick escalates: an API sweep restricted to the flagged recordings — a watch's as a new article `<watch>-<date>`, a series' as its edition, a living report's as its Refresh's update — within the caps and a new **day's escalation cap**; below it the tick ends with its triage log and no API spend (a series' edition is quiet). Needs a restart of the editor and umtool.
+- **`pnpm ops report-draft --json '{"task": "triage", "article": "<schedule>", "question", "channels", "terms"?, "topics"?, "threshold"?, "ids"?}'`** runs the step on its own. A run lives in `reports/.triage/<schedule>/<k>/` (`triage.json`: the candidates, each flag and dismissal, the decision, the spend per tier; `trace.jsonl`), and `seen.json` beside it is what the next run counts as known, written only when a run completes. A sweep that escalates a triage names it (`"triage": "<schedule>/<k>"`), and its trace's first line after the start is the triage's tiers; a refresh takes `"ids"` (the update reads those). `pnpm ops report-schedule` creates a watch (`"shape": "watch"`) and takes `triageFirst`, `topics` and `threshold` `{strong, weak}`. New settings `generation.triage` (SETTINGS.md): the judge (`local` or `extractor`), `strong`, `weak`, `maxEscalationsPerDay` (default 3), `maxCandidates` (default 40); Settings → Generation edits them.
+- **umtool shows the tiers.** Create's **A recurring report** offers **Watch** and **Triage first** (with its topics and its threshold, said in the plan). Each run has a page, `/series/<id>/triage/<k>`: tier 0's candidates and why, each flag with its line on the reader and the judge's reason, each dismissal with why, whether it escalated and to what, the spend per tier. `y` / `x` marks the lit flag right or wrong (`u` unmarks), `b` opens the flags as a board. A watch's page lists what it **found**, every triage run, the precision of your marks and a **suggested threshold** (a suggestion: the schedule keeps its own). The escalated sweep's run page starts with a **triage first** step linking the run.
+- **Worth researching.** A watch that escalated is a **Your call** card in the Inbox with its flags and what the sweep kept; **Open the board** opens an R2 research case of the flags, each quote **by triage**, whose hand-offs make an article or a video. umtool makes the board (it is the only writer of boards; the editor never writes one), and the card goes once the board has a hand-off or every flag of the run is marked.
- **umtool's benches are one shell.** The clip bench, the claim bench, the narration script, the takes and the drafts review share one frame that fits 1366×768 with no rail: a top bar (← the piece, which bench, **N of M**, ‹ prev / next ›, the keys), the work, a **verdict bar** asking ONE question with its consequence before you choose, and the source on the reader at the right. On the clip bench the transcript is the reader — the cited cue lit, its cite thread, **Copy citation**, **Play clip** — and a clip that ends mid-sentence asks "Extend c04 to the end of the sentence? It would end at 4:31:21 (+12.1 s), covering all of c05." with **Extend to 4:31:21** (or **Fetch to …** past what is fetched) and **Keep the cut here** (lockEnd) before the walk's **Yes, confirmed** / **No, note what is wrong**. The claim bench's context is its reader (`j`/`k` move the lit cue and seek the player) and **Save ruling** its verdict bar, saying what is still missing. Narration asks about the card in hand (`j`/`k`, `a` approve, `r` reject with its note); takes about the take being listened to (`n`/`p`, `l` like, `m` maybe, `x` no). Needs a restart of umtool.
- **A report video's Media tab is one surface for every drafted field.** Each field is a line — its words, **where it came from** (the draft file, when, by what model, which attempt was kept, and the rule a refused attempt broke: "attempt 2 of 2 chosen · attempt 1 failed: ✕ text in quotation marks"), its review — with **Approve draft** and **Reject** (a note), the drafts kept aside with **Use this**, grouped by section (cut, on-screen, teaser, flips, threads, narration, YouTube), each headed by its **Draft with <model>**; **Approve all N**, **Draft everything** (the draft-all chain, on the model chosen) and section chips above. `j`/`k` light a field, `a` approves it, `r` rejects it. The on-screen panel moved here from Build, whole. A release-25 narration (no mark in the manifest) shows its `narration-draft.json` attempts too. Needs a restart of umtool.
- **The drafts review is a bench: `/projects/<p>/review`.** The same field list, walked one field at a time: the verdict bar asks about the lit field ("Approve the drafted on-screen text of m01? A final build refuses it until it is approved."), the reader shows the clip it is drawn over with its cited cue lit. The Iterations tab's **Narrate**, media drafts and **Draft everything** are now a **Media drafts →** link to the iteration's video's Media tab.
diff --git a/editor/app/api/ops/_reportRefresh.test.ts b/editor/app/api/ops/_reportRefresh.test.ts
@@ -84,7 +84,7 @@ async function doneSweep(article: string) {
await updateIteration(article, 1, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 1, read: 2, partial: false, unreached: [] } }, paths);
}
-test("the body: a refresh takes its iteration, model, caps, fetch and dryRun — never a question or a scope; ids are a sweep's", () => {
+test("the body: a refresh takes its iteration, model, caps, fetch and dryRun — never a question or a scope; ids are a sweep's, a refresh's (R6: a triage's flags) or a triage's", () => {
assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a" }), { task: "refresh", article: "a" });
assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a", iteration: 3, fetch: false, dryRun: true, maxUsd: 1, extractorModel: "claude-haiku-4-5" }), {
task: "refresh",
@@ -96,7 +96,19 @@ test("the body: a refresh takes its iteration, model, caps, fetch and dryRun —
dryRun: true,
});
assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", question: "q", channels: ["x"] }), /a refresh takes its question and scope from the iteration it refreshes — not question, channels/);
- assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", ids: ["x"] }), /"ids" is a sweep's/);
+ assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a", ids: ["x"], fetch: false }), { task: "refresh", article: "a", ids: ["x"], fetch: false });
+ assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f", ids: ["x"] }), /"ids" is a sweep's/);
+ // A triage (umtool R6): its own keys, and only its.
+ assert.deepEqual(
+ parseReportDraftBody({ task: "triage", article: "watch-a", question: "q", channels: ["x"], terms: "co-host", regex: true, topics: "guest, panel", threshold: { strong: 1, weak: 2 }, since: "2026-10-07", maxCandidates: 20, windows: { v1: [{ start: 5, end: 30 }] } }),
+ { task: "triage", article: "watch-a", question: "q", channels: ["x"], terms: "co-host", regex: true, topics: ["guest", "panel"], threshold: { strong: 1, weak: 2 }, since: "2026-10-07", maxCandidates: 20, windows: { v1: [{ start: 5, end: 30 }] } },
+ );
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], topics: ["t"] }), /"topics" is a triage's/);
+ assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q" }), /a triage needs its channels/);
+ assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q", channels: ["x"], threshold: { strong: -1 } }), /"threshold" is/);
+ assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q", channels: ["x"], windows: { v1: [{ start: 9, end: 2 }] } }), /end ≥ start/);
+ assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], ids: ["v1"], triage: "watch-a/3" }).triage, { owner: "watch-a", k: 3 });
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], triage: "nope" }), /names a triage run/);
assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], fetch: false }), /"fetch" is a refresh's/);
assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", dryRun: "yes" }), /"dryRun" is true or false/);
assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], ids: "v1, v2, v1" }).ids, ["v1", "v2"]);
diff --git a/editor/app/api/ops/_reportSchedule.ts b/editor/app/api/ops/_reportSchedule.ts
@@ -5,6 +5,7 @@ import { pickCorpusBuild } from "yt-dlp-transcript-common/lib/report/draft/tasks
import {
editionGenerator,
r4Steps,
+ triageStep,
type CountWindow,
type TickDeps,
} from "yt-dlp-transcript-common/controller/reportTick";
@@ -30,6 +31,9 @@ import { refreshEditor, researchEditor } from "./_researchEditor";
// refresh R4's `report-draft {"task":"refresh"}`, awaited; its
// refresh.json's status is the tick's outcome
// (common/controller/reportTick.ts r4Steps)
+// triage R6's cheap pass, `report-draft {"task":"triage"}` on
+// draft:local (or the extractor's draft:api), awaited; its
+// triage.json says whether to escalate (triageStep)
const countWindow: CountWindow = async (q) => {
const paths = getPaths();
@@ -62,6 +66,7 @@ export function reportScheduleDeps(): TickDeps {
steps: {
...r4Steps(draft),
generateEdition: editionGenerator({ draft, countWindow }),
+ triage: triageStep(draft),
},
};
}
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -41,7 +41,17 @@ export const dynamic = "force-dynamic";
// `fetch: false` skips the fetch and the build; `dryRun: true` answers
// `{ ok, plan }` and writes nothing. The log ends `@@report-draft {…,
// refresh: {status, newIds, changed, drifted, deleted, summary}}`;
-// - `ids` on a sweep: only those recordings (kept in its scope).
+// - `ids` on a sweep: only those recordings (kept in its scope); on a
+// refresh (umtool R6): the update reads those (a triage's flags);
+// - "triage" (umtool R6): the cheap pass for an OWNER (`article`: the
+// schedule it is for) — tier 0 (what is new in `channels` by id since its
+// last run, matching `terms` or digest `topics`; or `ids` named) and tier
+// 1 (the window judge on settings.generation.triage's model: local on
+// `draft:local` through the GPU arbiter, or the extractor on
+// `draft:api`), then whether its flags reach `threshold` {strong, weak}.
+// A run of reports/.triage/<owner>/<k>/ (triage.json, trace.jsonl);
+// answers `{ ok, jobId, iteration: k, triage: {owner, k} }`. A sweep's
+// `triage: "<owner>/<k>"` names the triage it escalates.
// `model` defaults to settings.generation's route for the task (a task routed
// to `code` needs one named). `extractorModel` is an API sweep's extractor
// (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's
@@ -77,6 +87,7 @@ export async function POST(request: Request) {
ok: true,
jobId: out.result.jobId,
iteration: out.iteration,
+ ...(out.triage ? { triage: out.triage } : {}),
...(out.warnings?.length ? { warnings: out.warnings } : {}),
});
});
diff --git a/editor/app/api/ops/report-schedule/route.ts b/editor/app/api/ops/report-schedule/route.ts
@@ -12,15 +12,18 @@ export const dynamic = "force-dynamic";
// "delete" | "tick-now", …}
//
// A recurring report (umtool R5): a LIVING report (one article kept current —
-// each tick re-fetches the scope and refreshes it) or a SERIES (a dated
-// edition each tick over the window since the last), on a cadence the editor
+// each tick re-fetches the scope and refreshes it), a SERIES (a dated
+// edition each tick over the window since the last) or a WATCH (umtool R6: no
+// article until a triage finds something), on a cadence the editor
// keeps (its report-schedule lane, held by `pnpm ops lane
// {"lane":"report-schedule","held":true}`).
// list {id?} -> {schedules | schedule, problems, lane: {held, armed}}
-// create {shape: living | series, topic, question?, channels, case?,
-// from?, terms?, regex?, cadence ({kind, at, dow?, days?} or
-// "weekly mon 06:00"), tz?, article? (living), autoMakeCurrent?
-// (living), model?, maxUsd?, dryRun?} -> {plan, schedule?}
+// create {shape: living | series | watch, topic, question?, channels,
+// case?, from?, terms?, regex?, cadence ({kind, at, dow?, days?}
+// or "weekly mon 06:00"), tz?, article? (living),
+// autoMakeCurrent? (living), model?, maxUsd?, triageFirst?
+// (living, series), topics?, threshold? {strong, weak},
+// dryRun?} -> {plan, schedule?}
// update {id, …} -> {schedule} a new cadence re-plans from now
// pause / resume {id} -> {schedule} a resume re-plans from now
// delete {id, confirm?} -> {plan} | {deleted} the plan unless confirm
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/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -441,8 +441,8 @@ edition reviewed with the operator before the schedule is left on.
| P4b benches + Media | `ux/p4b` → `main` `e66dd702` | LIVE 2026-10-14 (umtool ktVxkFBl…) |
| R4 refresh | `ux/r4` → `main` `08fee8e1` | LIVE 2026-10-14 (editor nFiNyOdI…, umtool -HUqAEPA…) |
| R5 recurring reports | `ux/r5` → `main` `0bf4aacd` | LIVE 2026-10-14 (editor 379S-Sk9…, umtool vWDhtigj…) |
-| R6 triage first | `ux/r6` | in progress |
-| Co-host pilot | — | after R6 (operator-approved) |
+| R6 triage first | `ux/r6` → `main` `326beacf` | LIVE 2026-10-14 (editor i-wNjJfg…) |
+| Co-host pilot | — | in progress (orchestrator, with the operator) |
| P6a cleanup, docs, audit | `ux/p6a` | shipped on the branch (before R6) |
| P6b 308s, screenshot audit | — | after R6 |
@@ -2946,3 +2946,207 @@ after R5's fix, 3/3 alone; taken as its own fix (below). `main` fast-forwarded t
decisions API 833 rows, notes' hrefs end `note=<id>`. P6b adds: **Prune…** on Settings · system wears the Reject colour
for a destructive action (outline it, as Delete schedule).
+
+### R6, as shipped
+
+**What.** Triage first: a cheap pass that flags what is worth researching, and only what it flags reaches the
+better model with tools. A `report-draft` STEP `triage` (tier 0 code, tier 1 the local window judge, the
+threshold), wired into R5's tick as `TickSteps.triage` — a schedule's `triageFirst` (living, series) and R5's
+reserved third shape, **watch** (no article until something is found) — with umtool's tiers, marks and the
+Worth researching card.
+
+- **The step** (`common/lib/report/draft/triage/`; the editor's side `controller/reportTriage.ts`):
+ - **A run** is `reports/.triage/<owner>/<k>/` — `triage.json` (`archilyzer-triage` v1: the question, scope,
+ terms, topics, threshold, `since`, tier 0, tier 1, the escalation, `cost {tier0, tier1}`, warnings) and
+ `trace.jsonl` — and `reports/.triage/<owner>/seen.json` is the ids the owner's last COMPLETED run saw. A
+ dot-directory of the article store (`idDirs` never lists it). The owner is the schedule's id. ONE writer:
+ the job (the run is created queued under the article store's lock, numbered 1, 2, …).
+ - **Tier 0** (`tier0.ts`, code, $0): the scope is scanned once with enumerate's "any recording" regex (the
+ set this run SAW); new = not in `seen.json` **by id** — an old recording whose transcript lands late is new
+ (R5's late-transcript gap, closed); with no last run, new = uploaded on or after `since` (the tick passes the
+ cadence's length back). Candidates: new recordings matching the terms (R4's `deltaCandidates` with `known` =
+ the ids seen; aliases as enumerate has them) OR carrying a digest topic tag that matches a topic (the build's
+ digest, read through `get_video_metadata`'s "Topic tags"); with neither terms nor topics, every new one.
+ `maxCandidates` (default 40) — the rest are cut and left OUT of the next `seen`, so they stay new.
+ - **Tier 1** (`judge.ts`): the sweep pipeline's window judge (`EXTRACT_SYSTEM`/`EXTRACT_SCHEMA`, its
+ `windowsOf`/`chunksOf`/`locate`) over the candidates' MATCHING windows only (get_transcripts around the
+ terms and topics; a caller's own `windows`; a recording put forward by a digest tag that no word matched is
+ read from its opening), at most 3 chunks and 3 flags a recording. A flag is a line `locate` finds verbatim
+ in the window AND R2's word check (`checkWordsInWindow`) finds in the transcript's cues near that second;
+ score 3 on topic = strong, 2 = weak. Dismissed, each with its reason: a window not relevant (`judge`), a
+ line not verbatim — the invented line kept beside it — or not in the cues (`verbatim`), off topic or a
+ mention only (`score`), nothing to read (`read`). The judge's model is `settings.generation.triage.model`:
+ `local` (`models.local`, on `draft:local` through the GPU arbiter — `gpuGatedFetch` — ollama unloaded at the
+ end, $0) or `extractor` (`models.extractor`, on `draft:api`, metered, its usage rows task `triage`).
+ - **The decision** (`escalationOf`): strong flags ≥ `strong` OR flags of any strength ≥ `weak` (0 turns a
+ rule off); default one strong or three. The step only SAYS it; the tick escalates.
+ - **The trace** gains `{t: "triage", owner, k, candidates, flagged, dismissed, escalated, why, cost, model}`,
+ `cost.tier`, and `check` stage `triage`; a triage run's own trace has its scope, tier 0's enumerations, one
+ `batch` per read batch with the judge's lines, a `check` per flag and dismissed line, the triage line and the
+ tier-1 cost. A sweep that escalates a triage names it (`report-draft {…, "triage": "<owner>/<k>"}`, kept as
+ `scope.triage`) and `runOnIteration` writes the triage line right after the run's start.
+ - **`report-draft {"task":"triage", "article": <owner>, question, channels, terms?, regex?, topics?,
+ threshold?, since?, ids?, windows?, maxCandidates?, model?}`**; the answer's `iteration` is the run's number
+ and `triage: {owner, k}`; the log ends `@@report-draft {…, triage: {k, status, candidates, flagged,
+ dismissed, escalate, why, usd}}`. A refresh takes `ids` (R6: the update reads exactly those, even when the
+ delta found nothing else). COMMANDS.md regenerated.
+ - **`settings.generation.triage`** `{model: local | extractor, strong: 1, weak: 3, maxEscalationsPerDay: 3,
+ maxCandidates: 40}` (SETTINGS.md, settings.json.example regenerated); umtool's Settings → Generation edits it.
+- **The tick** (`controller/reportTick.ts`; `triageStep(draft)` the real step, awaited, a cancelled tick cancels
+ it). Living or series with `triageFirst`, and every watch: fetch → triage → (escalate) → the shape's step on
+ the FLAGGED ids only:
+ - **watch** — stage 1 over the scope; below the threshold `no-change`, $0 API, the triage on the line; at or
+ above it an API sweep restricted to the flagged ids (`generateEdition` with `ids` and the triage ref — no
+ date bound, so a late transcript is in; no window check) as a new article `<watch>-<YYYY-MM-DD>` titled
+ "<topic> · <date>".
+ - **series** — the window, stage 1 over it, the triage over the SCOPE by id; below the threshold the edition
+ is quiet (its window covered, the triage's reason); above it the edition sweeps the flagged ids.
+ - **living** — stage 1, the triage, then R4's refresh with `ids` and `fetch: false` (no second fetch); below
+ the threshold `no-change`. Its first tick (no report yet) is its first sweep, as in R5 (triage applies from
+ the next tick).
+ - **The day's escalation cap** (`escalationCapRefusal`): escalations ticked on the UTC day across every
+ schedule (`tick.triage.escalated`) ≥ `maxEscalationsPerDay` → the tick is `held-by-cap` (R5's tick-held
+ card) with the flags kept (`triage.capped`). The tier-2 sweep is also held to the policy's caps as any sweep.
+ - The tick line gains `triage` (`TickTriage`: owner, k, status, candidates, flagged, dismissed, escalated,
+ why, the flagged ids, the top five flags, `usd {tier1, tier2}`); the tick's `usd` is tier 1 + tier 2.
+- **The schedule**: `OFFERED_SHAPES` gains `watch` (stored like a series, `.series/<id>/series.json`, no
+ editions); `triageFirst`; `scope.topics`; `triage.threshold` (a schedule's own); create's plan names the
+ triage (model, provider, threshold, the day's cap, terms, topics); a watch's delete plan keeps its articles and
+ its triage runs. `pnpm ops report-schedule` takes `triageFirst`, `topics`, `threshold`.
+- **umtool**:
+ - **Create → A recurring report** offers **Watch** ("No article until something is found: each tick triages
+ what is new, and only what it flags is researched.") with its terms, digest tags and threshold ("Escalate on
+ [1] strong or [3] any"), and **Triage first** on a living report or a series; the plan says "triage first on
+ <model> ($0): escalates on 1 strong or 3 weak · at most 3 escalations a day; no article until one does".
+ - **The triage page** `/series/<id>/triage/<k>` (`components/series/TriageView.tsx`; a living report's runs
+ too, under its id): the question and the run's facts in the head, the run picker, **Open as a board** (`b`,
+ the one filled action); ONE lit list — the flags (strong first) then the dismissals — each flag's line in the
+ reader serif with its recording, second and reason, strength and mark badges; beside it the three tiers
+ (Tier 0 · code, Tier 1 · local model or extractor, Tier 2 · sweep — each with its spend; tier 2 links the
+ escalated sweep's run page and its findings, or says "not escalated: $0 API" or the cap that held it), the
+ escalation line, the lit item's detail (the line on the reader with its cite and window, "why: …", **Right**
+ `y` / **Wrong** `x` / **Unmark** `u`), the candidates with why each was one, and the schedule's precision and
+ suggested threshold.
+ - **The series page**: a watch shows **Found** (each escalation's article, its top flag, its board and its
+ triage run, the spend) instead of editions; every schedule that triages shows the **Triage** table (each
+ run: when, candidates · flagged · dismissed, escalated or below and why, tier 1 and tier 2 spend), its
+ threshold, the precision of the marks and the suggested threshold; the tick log links each tick's triage.
+ - **The run page** (R3): an escalated sweep's first step is **triage first** (its tiers in the facts, the
+ flagged ids, a link to the triage run).
+ - **Marks** (`lib/research/triage-marks.mjs`): `REPORTS_ROOT/.umtool/triage/<schedule>.json`, umtool's own
+ (one writer, serialised, temp + rename, a file that does not parse never overwritten). Precision = right /
+ marked; the suggestion (`suggestThreshold`, common): weak flags right under 25% → let weak flags alone not
+ escalate, under 60% → one more weak, 80% and up → one fewer; strong flags under 50% → one more strong; fewer
+ than 3 marks of a kind → "mark N more". A suggestion only: nothing writes the schedule's threshold.
+ - **The board** (`lib/research/triage.ts` `openTriageBoard`): an R2 case of the run's flags, each `by:
+ "triage"` (the slip says **by triage**), in **Strong flags** / **Weak flags**, the judge's reason as the
+ claim line, the case's `triage {schedule, k}` (the side panel's **From triage**). Its id is the escalation's
+ article (so the board's article hand-off adds an iteration to it), else `<schedule>-t<k>`. A second open adds
+ what is new and never touches the operator's claims, notes, sections or order.
+ - **Inbox kind `worth-researching`** (Your call, add-only; `lib/inbox/schedules.mjs`): a watch's tick that
+ escalated and made its article — the flags (the first two, with their reasons) and how many findings the sweep
+ kept; **Open the board**. It goes once the board has a hand-off or every flag of the run is marked. The
+ watch's articles are its own: no iteration cards, not Work rows (`editionOf`).
+- **ONE WRITER OF THE CASE FILES: umtool.** The editor's tick never writes a case: it records the escalation on
+ its tick line and the triage run. umtool makes the board the first time it reads an escalated watch tick (the
+ Inbox's read, `ensureTriageBoards` — idempotent; a failure leaves the card on the triage page) or when the
+ operator presses **Open as a board**.
+- **Docs**: `umtool/docs/triage.md` (P6a's rewrite of `umtool/docs/` may link it from its recurring page).
+- **Not built (said so)**: a watch has no Work kind of its own (it is listed as a series); the run page shows the
+ tiers as one step with a link, the flags and dismissals in full are on the triage page; a living report's
+ first tick does not triage.
+
+**Commits** (`ux/r6`, from `main` `165a4ee2`):
+
+| sha | what |
+|---|---|
+| `077c36d1` | common, editor: the triage step (types, store, tier 0, judge, the run), `controller/reportTriage.ts`, report-draft's `triage` task and keys, a sweep's triage ref, a refresh's `ids`, `settings.generation.triage`, the watch shape and `triageFirst` on the tick, the day's escalation cap, the tick line's triage; `triage.test.ts` (8), `reportSchedule.test.ts` (+4), `_reportRefresh.test.ts`; COMMANDS.md, SETTINGS.md |
+| `a2b20f96` | umtool: Create's Watch and Triage first, the triage page and its API, the series page (Found, Triage, precision), the run page's triage step, marks, the board, Inbox `worth-researching`; the stub's triage and escalation; `triage-first.spec`, editor `report-draft.spec` (+1) and `ops-api.spec` (+1); `lib/research/triage.test.ts` (3), `triage-marks.test.mjs` (1), `inbox/schedules.test.mjs` (+1) |
+| `e0f072ca` | Settings → Generation edits triage first; `umtool/docs/triage.md` |
+| `73f2078c` | the digest tags field is not named for topics; the stub escalation's report claims carry ids |
+| `9d85ca8d` | the precision panel says "no flag marked yet" once; the run page's triage link; Digest tags on a watch's scope |
+| `9a18c171` | this record (first cut), `[Unreleased]` bullets |
+| `fc1695cf` | merge `main` `9330a309` (P6a live) — one conflict, this plan: P6a's record and rollout kept, R6's after them, one status row per phase |
+| `a94031d7` | after P6a: a paused schedule's chip is the `state` tag (the series page, the piece head); a dismissal an ink tag; Right / Wrong pressed outlines; `recurring.md` and the README name the watch and `triage.md` |
+| `a9765711` | docs: the Inbox's `worth-researching`, the run page's triage step |
+| `2501f9ee` | common: REPORT.md's generator says what P6a wrote into REPORT.md by hand (`docs.test` "REPORT.md is what the schema generates" failed on `main` after P6a) |
+| (this commit) | the record's final gates |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean at `a2b20f96` (repo-wide); common, editor, mcp at `077c36d1`; umtool and common at every later commit |
+| common `pnpm --filter yt-dlp-transcript-common test` (`SETTINGS_FILE` at the primary's, read only) | **4156/4156** (+12: `triage/triage.test.ts` 8 — tier 0 by id with a late transcript, by date with no last run, digest topics, the cap left new; the judge over given windows with a stubbed model — a strong and a weak flag, an invented line dismissed as not verbatim, a mention only, a window not relevant, a line the cues do not hold; the threshold; precision and the suggestion; a run end to end with its trace and `seen.json`, and the next run by id; a failed run keeps nothing seen — and `reportSchedule.test.ts` +4: a watch's plan and a tick below the threshold, an escalation as `<watch>-<date>` and the day's cap, triage first on a series and a living report, `triageStep` over stubbed calls) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | 365/365 |
+| editor unit `pnpm --filter editor test` | 304/304 (`_reportRefresh.test.ts`: a refresh's `ids`, a triage's keys and refusals, a sweep's triage ref) |
+| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 860 tests, 858 pass, 2 skipped, 0 fail (new: `triage-marks.test.mjs` 1, `inbox/schedules.test.mjs` +1) |
+| `pnpm --filter umtool test` | **31/31** (+3: `lib/research/triage.test.ts` — the run view with its tick and tier 2, marks and precision, the board by umtool, idempotent, the Inbox's ensure) |
+| `pnpm run test:scripts` (reads the capped build) | 1012 tests, 1010 pass, 2 skipped, 0 fail |
+| `archilyzer docs cli --check`, `settings example --check` | clean (COMMANDS.md, SETTINGS.md, settings.json.example regenerated) |
+| capped umtool `next build` (corpus linked inside the heavy slot, `MemoryMax=5G`) | exit 0; compiled 16.0 s, 47.7 s wall, 1.50 GB max RSS; the link removed |
+| capped editor `next build` (heavy slot, `MemoryMax=5G`) | exit 0; compiled 29.1 s, 1:06 wall, 2.52 GB max RSS |
+| editor e2e `report-draft.spec` + `ops-api.spec` (detached, queued; `export/public` linked) | **25 passed**, 0 failed, 1.8 min — the two new: a watch over the fake models (the fake ollama started in the spec for the judge, $0; below the threshold, then a late transcript flagged strong and escalated to a sweep of it on the fake Anthropic) and a watch over HTTP (its plan; a tick with no build fails in its triage, saying so) |
+| umtool `triage-first.spec` + neighbours | run 1 (`a2b20f96`, with recurring, run-trace, board, inbox): 33 passed, 1 failed, 5 skipped — Create's "digest tags" field was named "topics", which `getByRole({name: "topic"})` also matched (`73f2078c`); run 2 (with recurring, create): 19 passed, 1 failed — the stub's escalation report's claims had no ids (`73f2078c`); run 3: **6/6** |
+
+Gates after merging `main` `9330a309` (P6a), at `2501f9ee`: repo-wide tsc clean; common (`SETTINGS_FILE` at the
+primary's) 4156 tests, 4155 pass, 1 fail at `a9765711` — `lib/report/docs.test.ts` "REPORT.md is what the schema
+generates", P6a's hand edit of REPORT.md (fixed in `2501f9ee`; the file's tests 4/4 after); mcp 365/365; editor unit
+304/304; umtool unit 860 tests, 858 pass, 2 skipped, 0 fail; `pnpm --filter umtool test` 31/31; docs `cli` and
+`settings` checks clean; capped umtool build exit 0 (compiled 15.8 s, 44.2 s wall, 1.55 GB; the corpus linked inside
+the heavy slot, removed after; the triage routes' traces 1,008–1,012 files, none from `transcripts/`, `export/public`,
+`.e2e-song` or `.env*`); capped editor build exit 0 (compiled 24.4 s, 1:38 wall, 2.49 GB); test:scripts 1012 tests,
+1010 pass, 2 skipped, 0 fail; **full umtool e2e 476 tests: 470 passed, 0 failed, 6 skipped** (the song-data skips),
+11.6 min; **full editor e2e (`export/public` linked from the primary, 0 dangling; queued, detached) 714 tests: 702
+passed, 0 failed, 12 skipped**, 23.1 min.
+
+**Screenshots and keys.** Job scratch `r6-shots/` (32, from `triage-first.spec` with `R6_SHOTS`), each at 1366×768 and
+1440×900, dark and light, on the e2e fixture with the stub editor: Create's Watch (`create-watch`) and its plan
+(`create-watch-plan`), the triage run with its tiers and the lit strong flag (`triage-run`) and after the marks
+(`triage-marked`), the escalated sweep's run page with its **triage first** step (`triage-run-page`), the watch page
+with Found, the Triage table and the precision (`watch-page`), the Inbox's Worth researching card (`inbox-worth-researching`)
+and its board (`triage-board`). No canvas screen exists for triage; the triage page is the run page's two columns (the
+lit list, the detail) with the three tier lanes in Meter. **Keyboard only** (asserted in `triage-first.spec`'s keys test;
+production build): the flags and dismissals are ONE lit list (one Tab stop, the lit line's dashed 1 px focus), `j`/`k`,
+`Home`/`End` move it, `y`/`x`/`u` act on the lit flag only (on a dismissal they do nothing), `b` opens the board; the
+head's run picker and **Open as a board** are in the Tab order before the list, the mark buttons after it.
+
+**Found and left.**
+- **The judge's windows are what the terms match.** A recording put forward by a digest tag that no word matches is
+ judged on its opening (the first window, at most three chunks) — said in its dismissal when it is not relevant.
+ The digest's chapters could pick a better window; not built.
+- **Tier 0 scans the whole scope each tick** (enumerate's `.` regex over the build), and `seen.json` keeps every id it
+ saw — on Jeralyzer's scale a few hundred KB and a scan of a few seconds a channel. A scan that was partial says so
+ on the run; what it did not reach is not a candidate that time.
+- **A watch is listed as a series** (Work's Series kind, `s:<id>`); its found articles are its own (not Work rows, no
+ iteration cards — one Worth researching card on the watch).
+- **The run page shows the tiers as one step** (the facts, the flagged ids, the link); the flags and dismissals in full,
+ with their lines on the reader, are on the triage page.
+- **The board is made on the Inbox's read** when a watch has escalated and no board exists (idempotent, umtool's own
+ state), so a watch that escalates while nobody opens the Inbox has its board made later. The triage page's **Open as a
+ board** does the same by hand.
+- **A living report's first tick is its first sweep**, as in R5: triage applies from the second tick (its `seen` starts
+ then; the first triage counts new by upload date from the cadence's length back).
+- **The spec is `triage-first.spec.ts`**: `triage.spec.ts` is the song deck's clip triage. The brief's editor
+ `ops-api.spec` watch tick over the fake model is in `report-draft.spec` (where the fake Anthropic lives, with a fake
+ ollama started beside it); `ops-api.spec` has the watch over HTTP.
+- **`REPORT.md` was hand-edited by P6a** (`/articles/new` "is an address"); its generator (`lib/report/docs.ts`) now says
+ the same, so common's docs test passes on this branch (it failed on `main` `9330a309`).
+- **Docs**: `umtool/docs/triage.md`, linked from `recurring.md` (now three shapes), the README, `inbox.md` and
+ `research.md`.
+- **No live schedule was made**; the pilot is the orchestrator's, with the operator.
+
+### R6 rollout (orchestrator, 2026-10-14)
+
+Rulings: umtool is the one writer of case files (the board is made idempotently on the Inbox read or "Open as a
+board"; the editor tick never writes one); a living report's first tick stays its first sweep (triage from the second);
+the run page shows triage as one step linking the triage page. P6b adds: a watch is listed under Work's Series kind —
+give it its own. R6 also restored common's generated-REPORT.md test, which P6a's hand edit of `REPORT.md` had broken on
+`main` (`2501f9ee`, the generator's text). Gates on `326beacf` (main `9330a309` merged): full umtool e2e 470 passed,
+0 failed, 6 skipped; full editor e2e 702 passed, 0 failed, 12 skipped; common 4156/4156 in the primary after the
+fast-forward. Editor built (75 s) and restarted (`scripts/r6-editor-{build,restart}.sh`; no ZodError, no queued metas
+lost), then umtool (`scripts/r6-umtool.sh`). Live: a dry-run watch over `the-quartering`, `the-quartering-rumble`,
+`quartering-live` (weekly Mon 06:00) plans triage on `qwen3:8b` (local), threshold 1 strong or 3 weak, 3 escalations a
+day, the API model capped $5 a tick, and stores nothing; no schedules exist, the lane armed; decisions API 833 rows,
+notes' hrefs end `note=<id>`.
+
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -111,8 +111,10 @@
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'
// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait
// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'
+// pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait
// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait
// pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'
+// pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'
// pnpm ops report-schedule --json '{"action":"list"}'
// pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait
// pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'
@@ -409,7 +411,10 @@ const ACTIONS = [
// narration step over an article's iteration ({task, article, iteration?,
// model?, extractorModel?, feedback?, question?, channels?, copyOf?, maxUsd?,
// …}), as a report-draft job on draft:api or draft:local. `job cancel` stops
- // it.
+ // it. umtool R6: {task: "triage", article: <owner>, question, channels,
+ // terms?, topics?, threshold?, ids?, …} — the cheap pass of a recurring
+ // report (tier 0 by id, tier 1 the local window judge), its run in
+ // reports/.triage/<owner>/<k>/.
"report-draft",
// RESEARCH RUNS (release 27 S11): a research run's acquisitions, after its
// job — refreshed from their jobs, then approved (run through the editor) or
@@ -421,7 +426,8 @@ const ACTIONS = [
"bench-verdicts",
// RECURRING REPORTS (umtool R5): a living report or a dated series on a
// cadence the editor keeps ({action: list | create | update | pause |
- // resume | delete | tick-now, …}); tick-now is a report-tick job.
+ // resume | delete | tick-now, …}); tick-now is a report-tick job. R6: a
+ // watch (no article until a triage finds something), and triageFirst.
"report-schedule",
];
diff --git a/settings.json.example b/settings.json.example
@@ -295,6 +295,13 @@
"notFoundRecall": 0
},
"models": []
+ },
+ "triage": {
+ "model": "local",
+ "strong": 1,
+ "weak": 3,
+ "maxEscalationsPerDay": 3,
+ "maxCandidates": 40
}
}
}
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>
@@ -101,8 +121,8 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str
actions={<LifecycleChip piece={v.piece} title={v.topic} state={life} />}
below={
<div className="flex flex-wrap items-center gap-x-4 gap-y-2" data-series={v.id} data-series-paused={v.paused ? "yes" : "no"}>
- <span className={cn(badgeVariants({ variant: v.paused ? "open" : "meter", size: "md" }))} data-schedule-chip={v.chip}>
- <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", v.paused ? "bg-doubt-text" : "bg-meter")} />
+ <span className={cn(badgeVariants({ variant: v.paused ? "state" : "meter", size: "md" }))} data-schedule-chip={v.chip}>
+ <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", v.paused ? "bg-muted" : "bg-meter")} />
{v.chip}
</span>
<ScheduleControls schedule={{ id: v.id, shape: v.shape, paused: v.paused, cadence: v.cadence, running: !!v.running }} />
@@ -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">Digest tags</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/articles/PolicyPanel.tsx b/umtool/components/articles/PolicyPanel.tsx
@@ -31,6 +31,8 @@ export default function PolicyPanel({
const [policy, setPolicy] = useState(initial);
const [today] = useState(initialToday);
const [caps, setCaps] = useState(() => Object.fromEntries(CAP_KEYS.map((k) => [k, String(initial.generation.caps[k])])));
+ const triOf = (t: PolicyView["generation"]["triage"]) => ({ model: t.model, strong: String(t.strong), weak: String(t.weak), cap: String(t.maxEscalationsPerDay) });
+ const [tri, setTri] = useState(() => triOf(initial.generation.triage));
const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
const g = policy.generation;
@@ -46,6 +48,7 @@ export default function PolicyPanel({
if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`);
setPolicy(body.policy);
setCaps(Object.fromEntries(CAP_KEYS.map((k) => [k, String(body.policy.generation.caps[k])])));
+ setTri(triOf(body.policy.generation.triage));
setStatus({ ok: true, text: `saved ${what}` });
} catch (e) {
setStatus({ ok: false, text: (e as Error).message });
@@ -157,6 +160,38 @@ export default function PolicyPanel({
</Button>
</form>
+ <div className="micro pt-1">triage first</div>
+ <form
+ className="flex flex-wrap items-center gap-x-4 gap-y-1"
+ data-policy-triage=""
+ onSubmit={(e) => {
+ e.preventDefault();
+ save({ triage: { ...g.triage, model: tri.model, strong: Number(tri.strong), weak: Number(tri.weak), maxEscalationsPerDay: Number(tri.cap) } }, "triage");
+ }}
+ >
+ <label className="flex items-center gap-1.5">
+ <span className="text-[var(--color-dim)]">judge</span>
+ <select aria-label="triage model" className={`${field} font-mono`} value={tri.model} disabled={busy} onChange={(e) => setTri({ ...tri, model: e.target.value as "local" | "extractor" })}>
+ <option value="local">local ({g.models.local})</option>
+ <option value="extractor">extractor ({g.models.extractor})</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-1">
+ <span className="text-[var(--color-dim)]">escalate on</span>
+ <input aria-label="triage strong flags" className={`${field} num w-10`} inputMode="numeric" value={tri.strong} onChange={(e) => setTri({ ...tri, strong: e.target.value })} />
+ <span className="text-[var(--color-dim)]">strong or</span>
+ <input aria-label="triage flags of any strength" className={`${field} num w-10`} inputMode="numeric" value={tri.weak} onChange={(e) => setTri({ ...tri, weak: e.target.value })} />
+ <span className="text-[var(--color-dim)]">any</span>
+ </label>
+ <label className="flex items-center gap-1">
+ <span className="text-[var(--color-dim)]">escalations a day</span>
+ <input aria-label="triage escalations a day" className={`${field} num w-12`} inputMode="numeric" value={tri.cap} onChange={(e) => setTri({ ...tri, cap: e.target.value })} />
+ </label>
+ <Button size="sm" type="submit" disabled={busy}>
+ Save triage
+ </Button>
+ </form>
+
<div className="micro pt-1">API key</div>
<div className="flex items-center gap-2" data-key-file-exists={policy.keyFile.exists ? "yes" : "no"}>
<code className="font-mono text-[11px]">{policy.keyFile.path}</code>
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,17 @@ 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", "digest tags"
+// (never "topics": a name holding "topic" would match the topic field too),
+// "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 +57,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 +84,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 +110,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 +134,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 +195,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 +229,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 +244,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="Digest tags" 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="digest tags" 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 +284,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/piece/PieceFrame.tsx b/umtool/components/piece/PieceFrame.tsx
@@ -125,8 +125,8 @@ export default function PieceFrame({
{head}
{schedule && (
<span className="inline-flex flex-wrap items-center gap-2" data-piece-schedule={schedule.id}>
- <span className={cn(chipVariants({ variant: schedule.paused ? "open" : "meter", size: "md" }))} data-schedule-chip={schedule.chip}>
- <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", schedule.paused ? "bg-doubt-text" : "bg-meter")} />
+ <span className={cn(chipVariants({ variant: schedule.paused ? "state" : "meter", size: "md" }))} data-schedule-chip={schedule.chip}>
+ <i aria-hidden="true" className={cn("inline-block size-[7px] rounded-full", schedule.paused ? "bg-muted" : "bg-meter")} />
{schedule.chip}
</span>
<ScheduleControls part="head" schedule={schedule} />
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";
// ---------------------------------------------------------------------------
@@ -628,6 +629,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}
+ </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: "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} aria-pressed={view.marks[lit.flag.f]?.verdict === "right"} className={cn(buttonVariants({ variant: "outline", size: "sm" }), view.marks[lit.flag.f]?.verdict === "right" && "border-muted bg-panel-2")} onClick={() => void mark(lit.flag, "right")} data-mark-right="">
+ Right <kbd>y</kbd>
+ </button>
+ <button type="button" disabled={!hydrated || busy} aria-pressed={view.marks[lit.flag.f]?.verdict === "wrong"} className={cn(buttonVariants({ variant: "outline", size: "sm" }), view.marks[lit.flag.f]?.verdict === "wrong" && "border-muted bg-panel-2")} 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'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/docs/README.md b/umtool/docs/README.md
@@ -117,7 +117,8 @@ root. See [report-video.md](report-video.md#one-manifest-two-cuts).
| [work.md](work.md) | Work's facets, the projects grid, a site's page |
| [piece.md](piece.md) | The piece page: head, stepper, Next card, tabs per kind; iterations, the reader and notes, evidence; projects: kinds, ids, routing, delete |
| [refresh.md](refresh.md) | Refresh: fetch what is new, check it, update; the daily check |
-| [recurring.md](recurring.md) | Recurring reports: living reports and series, the schedule, the series page |
+| [recurring.md](recurring.md) | Recurring reports: living reports, series and watches, the schedule, the series page |
+| [triage.md](triage.md) | Triage first: the cheap pass, its tiers, flags and marks, Worth researching |
| [tools.md](tools.md) | The song piles, find, mix, faces, sources, trims, the verdict bench |
| [settings.md](settings.md) | The generation policy and spend; the system page; `umtool doctor` |
| [report-video.md](report-video.md) | The manifest as an EDL, the three-stage window model, `lock` |
diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md
@@ -85,6 +85,7 @@ Cover); a cut's opens the cut's page, at the song's full path.
|---|---|---|
| `research-proposal` — a research run's acquisition waiting (`proposals.json`, status `proposed`) | Your call | Approve acquisition |
| `iteration-failed` — a failed run not superseded by a later live one; spend from its `usage` | Your call | Retry run |
+| `worth-researching` — a watch's tick whose triage escalated ([triage.md](triage.md)); gone once its board has a hand-off or every flag is marked | Your call | Open the board |
| `tick-failed`, `tick-held` ([recurring.md](recurring.md)) | Your call | Tick now / Raise cap |
| `refresh-held` ([refresh.md](refresh.md)) | Your call | Refresh |
| `iteration-ready` — done, not current, newer than current | Review | Make i<n> current |
diff --git a/umtool/docs/recurring.md b/umtool/docs/recurring.md
@@ -1,6 +1,6 @@
# Recurring reports
-## Two shapes
+## Three shapes
The same topic, updated at an interval. The EDITOR keeps the schedule and runs the ticks (its `report-schedule` lane,
armed at boot unless `ARCHILYZER_IDLE_BOOT`); umtool shows and edits a schedule and never runs a timer.
@@ -9,6 +9,11 @@ armed at boot unless `ARCHILYZER_IDLE_BOOT`); umtool shows and edits a schedule
|---|---|
| **Living report** | One article kept current: a [refresh](refresh.md) (its own fetch, then what changed, then the update). The result is an iteration-ready card; "Make each update current without review" makes it current (default off). The first tick, with no report yet, is the article's first sweep. |
| **Series** | A new dated **edition** over whole days since the last: the day after the previous edition's end through the day before the tick (weekly on Mon 06:00 covers Mon … Sun before it). Fetch over the window's channels and dates, then a sweep with from/to. A window nothing matches is a quiet edition: recorded, no article, $0. A tick with nothing to cover yet makes no edition. |
+| **Watch** | No article until something is found: each tick fetches, then [triages](triage.md) what is new in scope. Only a triage at or above its threshold escalates to an API sweep of what it flagged, as a new article `<watch>-<date>` and an Inbox **Worth researching** card. |
+
+A living report or a series can also **triage first**: the cheap pass runs before its own step, and that step reads only
+the flagged recordings — or, below the threshold, the tick ends $0 (a series' edition is quiet). See
+[triage.md](triage.md).
## Make one
diff --git a/umtool/docs/research.md b/umtool/docs/research.md
@@ -93,6 +93,8 @@ step by step — live while it runs (re-read every 2.5 s), a replay when done:
- **Open as a board** makes the case `<article>-run<n>` from the report's quoted citations (`by: "agent"`, the
report's sections, the finding as the claim); a second press adds what is new and never touches your claims, notes,
sections or order. The board's side panel links **From run**.
+- A sweep a triage escalated ([triage.md](triage.md)) starts with a **triage first** step: the tiers, the flagged ids,
+ a link to the triage run.
- The Iterations tab's **Run** link and a sweep's Running row open it.
## The archive inventory, `/research/archive`
diff --git a/umtool/docs/triage.md b/umtool/docs/triage.md
@@ -0,0 +1,72 @@
+# Triage first
+
+A recurring report can run a cheap pass before its sweep. The pass flags what is
+worth researching. Only what it flags reaches the better model with tools.
+Release R6 of the umtool redesign; the plan is `plans/umtool-redesign.md`, "R6".
+
+## Where it runs
+
+| Shape | What a tick does |
+|---|---|
+| **Watch** | Fetch, then triage what is new in scope. At or above the threshold, an API sweep of the flagged recordings, as a new article `<watch>-<date>`. Below it, nothing: the tick ends with its triage log, $0 API. |
+| **Series** with *Triage first* | Fetch the window, triage, then sweep the flagged recordings as the edition (no date bound, so a late transcript is in). Below the threshold the edition is quiet. |
+| **Living report** with *Triage first* | Fetch, triage, then R4's refresh reads the flagged recordings (no second fetch). Below the threshold, no change. |
+
+Create one at **Create → A recurring report**: pick **Watch**, or tick
+**Triage first** on a series or a living report. Set the terms, the digest
+topics and the threshold there.
+
+## The tiers
+
+| Tier | What | Cost |
+|---|---|---|
+| 0 | Code. Recordings new since the last triage **by id** (an old recording whose transcript landed late is new), that match the terms (aliases too) or carry a matching digest topic tag. The first run counts new by upload date. | $0 |
+| 1 | The local model (or `models.extractor`) judges each candidate's matching windows: the sweep pipeline's window judge. A line is a flag only when the code finds it verbatim in the window and in the transcript's cues. Score 3 is a strong flag, 2 a weak one; 1, off topic, invented or not relevant is dismissed, with why. | $0 local |
+| 2 | Only at or above the threshold: an API sweep restricted to the flagged ids, within the caps and the day's escalation cap. | metered |
+
+The default threshold is one strong flag, or three flags of any strength.
+
+## What you see
+
+- **`/series/<id>`** — a watch's **Found** list (each escalation's article and
+ board), the **Triage** table (every run, escalated or not, the spend per
+ tier), the precision of your marks and a suggested threshold.
+- **`/series/<id>/triage/<k>`** — one run: the tiers, the candidates, each flag
+ with its line on the reader surface and the judge's reason, each dismissal
+ with why, what escalated. Keys: `j`/`k` move, `y` right, `x` wrong, `u`
+ unmark, `b` open the flags as a board.
+- **The run page** of an escalated sweep (`/research/runs/<article>/<n>`) — its
+ first step is **triage first**, linking the run.
+- **The Inbox** — a watch that escalated is a **Worth researching** card (Your
+ call). Its action opens the board: an R2 case of the flags, each quote **by
+ triage**, whose hand-offs make an article or a video. The card goes once the
+ board has a hand-off or every flag of the run is marked.
+
+A suggested threshold is only a suggestion. The schedule keeps its own until
+you change it.
+
+## Where things live
+
+| Path | Writer |
+|---|---|
+| `reports/.triage/<schedule>/<k>/triage.json`, `trace.jsonl` | the editor's `report-draft {"task":"triage"}` job |
+| `reports/.triage/<schedule>/seen.json` | the same job (only when a run completes) |
+| the schedule's tick line `triage` | the editor's tick |
+| `REPORTS_ROOT/.umtool/triage/<schedule>.json` (marks) | umtool |
+| `REPORTS_ROOT/.umtool/research/<case>/case.json` (the board) | umtool, never the editor |
+
+## Settings
+
+`settings.generation.triage` (SETTINGS.md): the judge (`local` or `extractor`),
+`strong` and `weak`, `maxEscalationsPerDay`, `maxCandidates`. Settings →
+Generation edits them. A schedule may carry its own threshold.
+
+## From the command line
+
+```sh
+pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'
+pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait
+```
+
+A flag on a co-host's line is a speaker check, not a finding: a board's quote
+says **Speaker not checked** until you check it.
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: "digest tags" })).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: "digest tags" }).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/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -230,7 +230,7 @@ export async function readPolicy(): Promise<PolicyView> {
// What umtool may write of `generation`. The key file's path is not here: the
// panel shows it, and the editor's own settings page sets it.
-const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl"] as const;
+const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl", "triage"] as const;
/** Write the policy through the editor's settings action. Answers the policy as read back. */
export async function writePolicy(patch: Record<string, unknown>): Promise<PolicyView> {
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;
+}