Archilyzer · Source

archilyzer

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

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

common, editor: triage first — report-draft's triage step (tier 0 by id, tier 1 the local window judge, the threshold), the watch shape and triageFirst on R5's tick, the day's escalation cap (R6)

- lib/report/draft/triage/: the run (reports/.triage/<owner>/<k>/triage.json,
  trace.jsonl; seen.json), tier 0 (new by id — a late transcript is new —
  matching the terms or digest topics), tier 1 (the sweep pipeline's window
  judge over the matching windows; a line verbatim in its window and the
  cues, else dismissed with why), escalationOf, precision and the suggested
  threshold; settings.generation.triage
- controller/reportTriage.ts: report-draft {task: triage} on draft:local (or
  the extractor on draft:api); a sweep's triage ref (scope.triage, its trace's
  triage line); a refresh's ids
- reportTick: TickSteps.triage (triageStep), the watch shape, triageFirst on
  living and series, escalationCapRefusal; the tick line's triage
- unit: triage.test.ts (8), reportSchedule.test.ts (+4); editor
  _reportRefresh.test.ts; COMMANDS.md, SETTINGS.md

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

Diffstat:
MCOMMANDS.md | 4++--
MSETTINGS.md | 18++++++++++++++++++
Mcommon/controller/reportDraft.ts | 102++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/controller/reportRefresh.ts | 2+-
Mcommon/controller/reportSchedule.test.ts | 181++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/reportSchedule.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/reportScheduleOps.ts | 12++++++++++--
Mcommon/controller/reportTick.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Acommon/controller/reportTriage.ts | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/refresh/task.ts | 13+++++++++++--
Mcommon/lib/report/draft/tasks/run.ts | 21+++++++++++++++++++++
Mcommon/lib/report/draft/tasks/trace.ts | 33++++++++++++++++++++++++++++-----
Acommon/lib/report/draft/triage/index.ts | 6++++++
Acommon/lib/report/draft/triage/judge.ts | 265+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/triage/store.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/triage/task.ts | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/triage/tier0.ts | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/triage/triage.test.ts | 333+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/triage/types.ts | 327+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/iterations.ts | 2++
Mcommon/lib/report/schedule/types.ts | 48++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/settingsDocs.ts | 2++
Mcommon/lib/settingsSchema.ts | 1+
Meditor/app/api/ops/_reportRefresh.test.ts | 16++++++++++++++--
Meditor/app/api/ops/_reportSchedule.ts | 5+++++
Meditor/app/api/ops/report-draft/route.ts | 13++++++++++++-
Meditor/app/api/ops/report-schedule/route.ts | 15+++++++++------
Mscripts/archilyzer-ops.mjs | 10++++++++--
Msettings.json.example | 7+++++++
30 files changed, 2438 insertions(+), 56 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)} -&gt; {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"} -&gt; {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/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, 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", ...} -&gt; {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", ...} -&gt; {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"?} -&gt; {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"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -&gt; {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/&lt;run&gt;/ (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"?} -&gt; {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 &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); 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"} -&gt; {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"?} -&gt; {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 &lt;series&gt;-&lt;date&gt; over the window since the last edition ("&lt;topic&gt; · week of &lt;date&gt;"); 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"} -&gt; {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/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 ? `no flag marked yet: 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/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/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 } } }