commit 51423478c4e53e0fb5545bb3e370320763e313a4
parent fcdfc744ed93d0ae40daefff152aa984c9aa4749
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 18:56:43 -0400
common: no silent zeros from a capped scan; fetch under a transcription hold (R6.1, R4.1)
- Tier 0 lists the scope from an uncapped source: the corpus tools'
listRecordings (each channel's transcripts manifest, dated by the summaries
index or the record's own page), never one capped enumerate("."). The terms
query is bounded: restricted to the new ids (enumerate's new `ids`: only
their pages are read) and, on a first run, dated from `since`.
- A cap or an unlisted channel makes tier 0 partial with what it did not
reach; a partial run keeps no seen set. A partial triage below the threshold
ends the tick `partial` (a new tick status, the operator's call), never
quiet; a series records no quiet edition for it.
- The refresh delta is bounded by `since` when there is no known set; a capped
search with nothing to update ends `partial`. The window check's 0 from a
capped scan is partial, not quiet. enumerateOf reads a name with
parentheses whole and the channel a cap stopped inside.
- R4.1: transcribe-bucket is skipped (and said) while transcription is paused
or no worker is enabled; a cancelled step is a warning; "nothing new to
transcribe" is a routine skip, not a warning.
- report-schedule reset-triage {id, k?, confirm?}: discards a schedule's
triage runs, seen.json and the quiet editions they covered (plan, then
confirm). COMMANDS.md regenerated.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
30 files changed, 1024 insertions(+), 90 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,10 +145,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` |
| `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` |
-| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
+| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and 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; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), 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 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
-| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"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}'` |
+| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. | `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}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'` |
### Usage, flags and environment
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -415,6 +415,10 @@ export type ReportDraftDeps = {
researchEditor?: ResearchEditor;
// An editor job's state (default: the registry and the .jobs sidecars).
jobOf?: JobOf;
+ // R4.1: why transcription would not run now, or null (default: the worker
+ // pool — paused, or no worker enabled). A refresh's fetch skips
+ // transcribe-bucket under a hold rather than wait on it.
+ transcriptionHeld?: () => Promise<string | null>;
};
// The editor's channels, as a research run lists them.
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -26,6 +26,7 @@ import path from "node:path";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import type { JobProgress } from "../jobs/registry";
import { heldPlatformRefusal, platformCooldownRemainingMs } from "../jobs/downloadBackoff";
+import { getWorkerPool } from "../jobs/workerPool";
import { DRAFT_REFRESH_QUEUE } from "../lib/queueKeys";
import { getSettings } from "../lib/settings";
import { capFor, type GenerationSettings } from "../lib/generationSettings";
@@ -278,6 +279,18 @@ export async function enqueueRefresh(body: ReportDraftBody, deps: ReportDraftDep
// ─── stage 1 on its own (R5's seam) ───
+/**
+ * R4.1: why transcription would not run now — the worker pool's own state
+ * (the live one, never the stored flag: lib/pauseGates.ts): paused, or no
+ * worker enabled. Null: it would run.
+ */
+export async function transcriptionHeldNow(): Promise<string | null> {
+ const pool = getWorkerPool();
+ if (pool.isPaused()) return "the transcription workers are paused";
+ if (!pool.enabledIds().length) return "no transcription worker is enabled";
+ return null;
+}
+
/** The editor's side of a refresh's stage 1: its actions (deps.refreshEditor), jobs, channels, holds, reports and builds. */
export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks {
const paths = deps.paths;
@@ -297,6 +310,7 @@ export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks {
const snap = await readChannelSnapshot(paths, slug).catch(() => null);
return snap ? [...(snap.buckets.downloadedNoTranscript ?? [])] : null;
},
+ transcriptionHeld: deps.transcriptionHeld ?? transcriptionHeldNow,
siteOf: async (channels, prefer) => {
const b = await refreshBuild(channels, prefer, paths);
if (!b) return { site: null, reason: `no composed build holds ${channels.join(", ")}` };
diff --git a/common/controller/reportSchedule.test.ts b/common/controller/reportSchedule.test.ts
@@ -647,3 +647,139 @@ test("triageStep: report-draft triage for the schedule (its terms, topics, thres
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" });
});
+
+// ─── R6.1: no silent zeros; recovering a bad run ───
+
+import { callOf } from "../lib/report/schedule/types";
+import { planResetTriage, resetTriage } from "./reportSchedule";
+import { createTriageRun, listTriageRuns, readTriageSeen, writeTriageSeen } from "../lib/report/draft/triage/store";
+import { TRIAGE_SEEN_FORMAT } from "../lib/report/draft/triage/types";
+
+const partialTier0 = (flags: TriageFlag[]) => ({
+ tier0: {
+ ...triageFile("x", 1, flags).tier0!,
+ partial: true,
+ unreached: ["Jeremy Hambly", "TheQuartering (Rumble)"],
+ },
+});
+
+test("R6.1: a partial triage below the threshold is never quiet — a series' tick is partial (the operator's call), no edition covers its window; above it escalates with a warning", async () => {
+ const paths = store();
+ await createSchedule(parseCreate({ shape: "series", topic: "Pilot", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths));
+ const t = await runTick("pilot", { trigger: "now", jobId: "p1" }, depsOf(paths, { triage: triageOf([], [], partialTier0([])), generateEdition: async () => assert.fail("below the threshold: no sweep") }), ctx());
+ assert.equal(t.status, "partial");
+ assert.equal(t.usd, 0);
+ assert.equal(t.edition, undefined);
+ assert.match(t.reason!, /^partial — not reached: Jeremy Hambly, TheQuartering \(Rumble\); nothing flagged in what was read \(no flag/);
+ assert.equal(t.triage!.partial, "not reached: Jeremy Hambly, TheQuartering (Rumble)");
+ const s = (await readSchedule("pilot", paths))!;
+ assert.deepEqual(s.editions, [], "the window is not covered: the next tick covers it");
+ assert.equal(callOf(s)?.status, "partial", "a Your call card");
+ // The next window still starts where the first would have.
+ assert.deepEqual(editionWindow(s, "2026-10-21"), { window: { from: "2026-10-14", to: "2026-10-20" } });
+ const later = new Date("2026-10-21T12:00:00.000Z");
+ assert.deepEqual(editionWindow(s, "2026-10-14"), { window: { from: "2026-10-07", to: "2026-10-13" } });
+
+ // A watch, partial and above the threshold: the escalation runs, the partial said.
+ await createSchedule(parseCreate({ shape: "watch", topic: "Pw", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths));
+ const w = await runTick("pw", { trigger: "now", jobId: "p2" }, depsOf(paths, { triage: triageOf([flag("v1", "strong")], [], partialTier0([flag("v1", "strong")])), generateEdition: async () => ({ status: "done", usd: 0.4, iteration: 1 }) }, later), ctx());
+ assert.equal(w.status, "done", w.reason);
+ assert.ok(w.warnings?.some((x) => /the triage was partial \(not reached: Jeremy Hambly/.test(x)), JSON.stringify(w.warnings));
+ // A living report, partial and below: partial, not no-change.
+ await createSchedule(parseCreate({ shape: "living", topic: "Pl", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), depsOf(paths));
+ await doneIteration(paths, "pl");
+ const l = await runTick("pl", { trigger: "now", jobId: "p3" }, depsOf(paths, { triage: triageOf([], [], partialTier0([])), refresh: async () => assert.fail("no refresh") }), ctx());
+ assert.equal(l.status, "partial");
+});
+
+test("R6.1: the window check — 0 from a capped scan is partial (not quiet), naming what it did not reach; a capped scan with matches still sweeps", async () => {
+ const paths = store();
+ await createSchedule(parseCreate({ shape: "series", topic: "Win", channels: ["chan-a"], cadence: weekly, tz: TZ, terms: "co-host" }), depsOf(paths));
+ const s = (await readSchedule("win", paths))!;
+ const draft = { paths, corpusTools: async () => assert.fail("no corpus read"), settings: () => ({ generation: gen() }), now: () => NOW };
+ const input = { schedule: s, article: "win-2026-10-14", title: "Win · week of 2026-10-07", window: { from: "2026-10-07", to: "2026-10-13" }, quietCheck: true };
+ const part = await editionGenerator({ draft, countWindow: async () => ({ recordings: 0, partial: true, unreached: ["Chan B"] }) })(input, ctx());
+ assert.equal(part.status, "partial");
+ assert.match(part.reason!, /^partial — the window check of 2026-10-07 … 2026-10-13 was capped \(not reached: Chan B\)/);
+ // Through the tick: partial, no quiet edition.
+ const t = await runTick("win", { trigger: "now", jobId: "w1" }, depsOf(paths, { generateEdition: async () => part }), ctx());
+ assert.equal(t.status, "partial");
+ assert.deepEqual((await readSchedule("win", paths))!.editions, []);
+ // With matches the capped check does not stop the edition (held here by the daily cap, past the check).
+ writeFileSync(paths.generationUsageFile, JSON.stringify({ at: NOW.toISOString(), day: "2026-10-14", jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }) + "\n");
+ const some = await editionGenerator({ draft, countWindow: async () => ({ recordings: 2000, partial: true, unreached: ["Chan B"] }) })(input, ctx());
+ assert.equal(some.status, "held-by-cap");
+ assert.equal(some.matched, 2000);
+});
+
+test("R6.1: r4Steps — a refresh that ended partial is a partial tick; a routine skip is not a warning, a cancelled step is", async () => {
+ const paths = store();
+ await doneIteration(paths, "shop");
+ const draft = { paths, corpusTools: async () => assert.fail("no corpus") };
+ const steps = r4Steps(draft as never, {
+ fetchScope: async () => ({
+ fetch: [
+ { channel: "chan-a", action: "sync", status: "done", jobId: "j1" },
+ { channel: "chan-a", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe", routine: true },
+ { channel: "chan-b", action: "transcribe-bucket", status: "skipped", reason: "transcription is paused (no transcription worker is enabled) — 7 recordings wait; a later run reads them once transcribed" },
+ ],
+ build: { site: "site-x", status: "done" },
+ warnings: ["chan-c: sync cancelled — the job ended cancelled"],
+ }),
+ enqueueReportDraft: (async () => ({ result: okJob("rj"), iteration: 2 })) as never,
+ readRefreshFile: (async () => ({ status: "partial", summary: "partial — not reached: Chan B; Nothing new since 2026-10-07 in what was read", warnings: [], fetch: [] })) as never,
+ });
+ const f = await steps.fetchAndBuild({ channels: ["chan-a", "chan-b"] }, ctx());
+ assert.deepEqual(f.warnings, [
+ "chan-c: sync cancelled — the job ended cancelled",
+ "chan-b transcribe-bucket: transcription is paused (no transcription worker is enabled) — 7 recordings wait; a later run reads them once transcribed",
+ ]);
+ const r = await steps.refresh("shop", {}, ctx());
+ assert.equal(r.status, "partial");
+ assert.match(r.reason!, /^partial — not reached: Chan B/);
+});
+
+test("R6.1: reset-triage — the plan names the runs, seen.json and the quiet editions they covered; refused while a tick runs; confirm discards them", async () => {
+ const paths = store();
+ const deps = depsOf(paths);
+ await createSchedule(parseCreate({ shape: "series", topic: "Bad run", channels: ["chan-a"], cadence: weekly, tz: TZ, triageFirst: true }), deps);
+ // Tick 1: a triage (run 1, its seen.json) and a quiet edition.
+ const quiet = await runTick("bad-run", { trigger: "now", jobId: "b1" }, depsOf(paths, { triage: triageOf([]) }), ctx());
+ assert.equal(quiet.status, "quiet");
+ const mk = (k: number) => triageFile("bad-run", k, []);
+ await createTriageRun(mk, paths, "bad-run");
+ await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "bad-run", k: 1, at: NOW.toISOString(), ids: ["a", "b", "c"] }, paths);
+ const plan = await reportScheduleAction({ action: "reset-triage", id: "bad-run" }, deps);
+ assert.equal(plan.ok, true, JSON.stringify(plan));
+ assert.equal(plan.confirmed, false);
+ assert.deepEqual(plan.plan.runs, [1]);
+ assert.deepEqual(plan.plan.seen, { k: 1, ids: 3 });
+ assert.equal(plan.plan.seenRemoved, true);
+ assert.deepEqual(plan.plan.editions.map((e: { n: number }) => e.n), [1]);
+ assert.match(plan.plan.removes.join(" | "), /1 triage run \(#1\) in \.triage\/bad-run\/ \| seen\.json — the 3 recording ids run #1 counted as known .* \| 1 quiet edition line those runs covered \(2026-10-07 … 2026-10-13\)/);
+ assert.equal(plan.plan.refused, null);
+ // Nothing was written by the plan.
+ assert.deepEqual(await listTriageRuns("bad-run", paths), [1]);
+ // Refused while a tick runs.
+ await claimTick("bad-run", { jobId: "busy", trigger: "now" }, deps);
+ assert.match((await planResetTriage("bad-run", null, deps)).refused!, /a tick is queued or running \(job busy\)/);
+ const refused = await reportScheduleAction({ action: "reset-triage", id: "bad-run", confirm: true }, deps);
+ assert.equal(refused.ok, false);
+ const { releaseClaim } = await import("./reportSchedule");
+ await releaseClaim("bad-run", "busy", deps);
+ const done = await reportScheduleAction({ action: "reset-triage", id: "bad-run", confirm: true }, deps);
+ assert.equal(done.ok, true, JSON.stringify(done));
+ assert.equal(done.confirmed, true);
+ assert.deepEqual(await listTriageRuns("bad-run", paths), []);
+ assert.equal(await readTriageSeen("bad-run", paths), null);
+ const s = (await readSchedule("bad-run", paths))!;
+ assert.deepEqual(s.editions, []);
+ assert.equal(s.ticks.length, 1, "the tick log keeps its lines");
+ // The next window is the one the discarded edition covered.
+ assert.deepEqual(editionWindow(s, "2026-10-14"), { window: { from: "2026-10-07", to: "2026-10-13" } });
+ // Nothing left: the plan refuses; a bad k is an input error.
+ assert.match(((await resetTriage("bad-run", null, deps).catch((e: Error) => e)) as Error).message, /has no triage state to discard/);
+ const badK = await reportScheduleAction({ action: "reset-triage", id: "bad-run", k: 0 }, deps);
+ assert.equal(badK.ok, false);
+ assert.match(badK.error, /"k" is a triage run's number/);
+});
diff --git a/common/controller/reportSchedule.ts b/common/controller/reportSchedule.ts
@@ -20,6 +20,7 @@ import { withArticleStoreLock, RESERVED_ARTICLE_IDS, ARTICLE_ITERATIONS_DIRNAME
import { isReportId } from "../lib/report/schema";
import { capFor, triageModelOf, type GenerationSettings } from "../lib/generationSettings";
import { thresholdWords } from "../lib/report/draft/triage/types";
+import { listTriageRuns, readTriageSeen, triageOwnerDir, triageRunDir, triageSeenPath } from "../lib/report/draft/triage/store";
import { providerOf } from "../lib/llm";
import {
CadenceError,
@@ -626,6 +627,88 @@ export async function deleteSchedule(id: string, deps: ScheduleDeps): Promise<De
}, deps.paths);
}
+// ─── reset a schedule's triage (R6.1: recovering a bad run) ───
+
+export type ResetTriagePlan = {
+ id: string;
+ // The runs discarded (reports/.triage/<id>/<k>/), from run `from` on.
+ dir: string;
+ from: number | null;
+ runs: number[];
+ // seen.json — what the next run counts as known — and whether it goes.
+ seen: { k: number; ids: number } | null;
+ seenRemoved: boolean;
+ // A series' quiet editions those runs covered: dropped, so the next tick
+ // covers their windows again.
+ editions: { n: number; title: string; window: { from: string; to: string } }[];
+ // Words for the plan's head and its confirm.
+ removes: string[];
+ keeps: string[];
+ refused: string | null;
+};
+
+const planResetOf = async (s: Schedule, k: number | null, deps: ScheduleDeps): Promise<ResetTriagePlan> => {
+ const id = s.id;
+ const all = await listTriageRuns(id, deps.paths);
+ const from = k ?? all[0] ?? null;
+ const runs = from === null ? [] : all.filter((n) => n >= from);
+ const seenFile = await readTriageSeen(id, deps.paths);
+ const seen = seenFile ? { k: seenFile.k, ids: seenFile.ids.length } : null;
+ // seen.json is cumulative: a run from `from` on fed it, so it goes.
+ const seenRemoved = !!seen && (from === null || seen.k >= from || k === null);
+ const discarded = new Set(runs);
+ const editionsOf = new Set(s.ticks.filter((t) => t.edition !== undefined && t.triage && discarded.has(t.triage.k)).map((t) => t.edition!));
+ const editions = (s.editions ?? []).filter((e) => e.status === "quiet" && editionsOf.has(e.n)).map((e) => ({ n: e.n, title: e.title, window: { from: e.window.from, to: e.window.to } }));
+ const dir = path.relative(deps.paths.articlesDir, triageOwnerDir(deps.paths, id));
+ const removes = [
+ ...(runs.length ? [`${runs.length} triage run${runs.length === 1 ? "" : "s"} (${runs.map((n) => `#${n}`).join(", ")}) in ${dir}/`] : []),
+ ...(seenRemoved && seen ? [`seen.json — the ${seen.ids} recording id${seen.ids === 1 ? "" : "s"} run #${seen.k} counted as known (the next run counts new from its since)`] : []),
+ ...(editions.length ? [`${editions.length} quiet edition line${editions.length === 1 ? "" : "s"} those runs covered (${editions.map((e) => `${e.window.from} … ${e.window.to}`).join(", ")}): the next tick covers ${editions.length === 1 ? "that window" : "those windows"} again`] : []),
+ ];
+ return {
+ id,
+ dir,
+ from,
+ runs,
+ seen,
+ seenRemoved,
+ editions,
+ removes,
+ keeps: [
+ "the schedule, its cadence and its tick log (a discarded run's line stays, its link gone)",
+ ...((s.editions ?? []).some((e) => e.article) ? ["every edition article"] : []),
+ ...(from !== null && all.some((n) => n < from) ? [`the runs before #${from}`] : []),
+ ],
+ refused: s.running ? `a tick is ${s.running.trigger === "now" ? "queued or running" : "running"} (job ${s.running.jobId}) — cancel it or let it end first` : !runs.length && !seenRemoved ? `"${id}" has no triage state${k !== null ? ` from run #${k}` : ""} to discard` : null,
+ };
+};
+
+/** What `reset-triage` would discard (nothing written). `k`: from that run on (default: every run). */
+export async function planResetTriage(id: string, k: number | null, deps: ScheduleDeps): Promise<ResetTriagePlan> {
+ const r = await readScheduleById(id, deps.paths);
+ if (!r) fail(`no schedule "${id}"`);
+ if (!r!.ok) fail(`the schedule "${id}" does not read (${r!.file}): ${(r as { problem: string }).problem}`);
+ return planResetOf((r as { schedule: Schedule }).schedule, k, deps);
+}
+
+/**
+ * Discard a schedule's triage state (the plan, re-made under the lock; a
+ * refusal stands): the runs from `k` on, seen.json when they fed it, and the
+ * quiet edition lines they covered — so the next tick triages afresh.
+ */
+export async function resetTriage(id: string, k: number | null, deps: ScheduleDeps): Promise<ResetTriagePlan> {
+ let plan: ResetTriagePlan | null = null;
+ await mutateSchedule(id, deps, async (s) => {
+ plan = await planResetOf(s, k, deps);
+ if (plan.refused) fail(plan.refused);
+ for (const n of plan.runs) await rm(triageRunDir(deps.paths, id, n), { recursive: true, force: true });
+ if (plan.seenRemoved) await rm(triageSeenPath(deps.paths, id), { force: true });
+ const drop = new Set(plan.editions.map((e) => e.n));
+ return drop.size ? { ...s, editions: (s.editions ?? []).filter((e) => !drop.has(e.n)) } : s;
+ });
+ return plan!;
+}
+
// ─── the tick's bookkeeping (controller/reportTick.ts, the runner) ───
/**
diff --git a/common/controller/reportScheduleOps.ts b/common/controller/reportScheduleOps.ts
@@ -19,6 +19,11 @@
// {"action": "delete", "id", "confirm"?} the plan, unless confirm: true
// {"action": "tick-now", "id"} one tick now (refused while one
// is queued or running)
+// {"action": "reset-triage", "id", "k"?, (R6.1) discard the schedule's
+// "confirm"?} triage state — its runs (from
+// run k on), seen.json, the quiet
+// editions they covered — the plan
+// unless confirm: true
import { getSettings } from "../lib/settings";
import { ArticleRegistryError } from "../lib/report/registry";
@@ -34,13 +39,15 @@ import {
parseUpdate,
planCreate,
planDelete,
+ planResetTriage,
+ resetTriage,
setPaused,
updateSchedule,
} from "./reportSchedule";
import { enqueueTick, type TickDeps } from "./reportTick";
import { isReportScheduleArmed } from "./reportScheduleRunner";
-export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now"] as const;
+export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage"] as const;
export type ReportScheduleActionName = (typeof REPORT_SCHEDULE_ACTIONS)[number];
export const REPORT_SCHEDULE_BODY_KEYS = [
@@ -66,6 +73,7 @@ export const REPORT_SCHEDULE_BODY_KEYS = [
"triageFirst",
"topics",
"threshold",
+ "k",
] as const;
export type ScheduleView = Schedule & {
@@ -152,6 +160,20 @@ export async function reportScheduleAction(
const plan = await deleteSchedule(id, deps);
return { ok: true, confirmed: true, deleted: plan };
}
+ case "reset-triage": {
+ const id = idOf(body);
+ let k: number | null = null;
+ if (body.k !== undefined) {
+ if (typeof body.k !== "number" || !Number.isInteger(body.k) || body.k < 1) throw new ScheduleInputError('"k" is a triage run\'s number (1, 2, …): discard from that run on');
+ k = body.k;
+ }
+ if (body.confirm !== true) {
+ const plan = await planResetTriage(id, k, deps);
+ return { ok: true, confirmed: false, plan };
+ }
+ const plan = await resetTriage(id, k, deps);
+ return { ok: true, confirmed: true, reset: plan };
+ }
case "tick-now": {
const id = idOf(body);
const r = await readScheduleById(id, deps.paths);
diff --git a/common/controller/reportTick.ts b/common/controller/reportTick.ts
@@ -75,7 +75,7 @@ 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 { partialWords, tickTriageOf, type TickTriage, type TriageFile } from "../lib/report/draft/triage/types";
import { enqueueReportDraft, type ReportDraftDeps } from "./reportDraft";
import { fetchScope, readRefreshFile } from "./reportRefresh";
import {
@@ -105,7 +105,7 @@ export type StepCtx = { log: (line: string) => void; signal: AbortSignal };
// channel no build holds) -- recorded on the tick, never its failure.
export type FetchOutcome = { ok: true; note?: string; warnings?: string[] } | { ok: false; status: "failed" | "held-by-cap"; reason: string; warnings?: string[] };
-export type StepStatus = "done" | "no-change" | "quiet" | "held-by-cap" | "failed" | "cancelled";
+export type StepStatus = "done" | "no-change" | "quiet" | "partial" | "held-by-cap" | "failed" | "cancelled";
export type StepOutcome = {
status: StepStatus;
// The iteration made (a refresh's, an edition's sweep).
@@ -165,8 +165,12 @@ export const notWiredRefresh: TickSteps["refresh"] = async () => ({ status: "fai
// ─── the real generateEdition ───
-/** A window's recordings for the quiet check: `{recordings}` or why it could not say. */
-export type CountWindow = (q: { channels: string[]; from: string; to: string; terms?: string; regex?: boolean }) => Promise<{ recordings: number } | { error: string }>;
+/**
+ * A window's recordings for the quiet check: `{recordings}` or why it could not
+ * say. `partial` (R6.1): the scan hit a cap, `unreached` what it did not read
+ * — 0 from a partial scan is NOT quiet.
+ */
+export type CountWindow = (q: { channels: string[]; from: string; to: string; terms?: string; regex?: boolean }) => Promise<{ recordings: number; partial?: boolean; unreached?: string[] } | { error: string }>;
export type EditionDeps = {
draft: ReportDraftDeps;
@@ -197,6 +201,12 @@ export function editionGenerator(deps: EditionDeps): TickSteps["generateEdition"
});
if ("error" in c) return { status: "failed", usd: 0, reason: `the window check failed: ${c.error}` };
matched = c.recordings;
+ if (c.partial && c.recordings === 0) {
+ // A capped scan that read nothing matching: not a quiet window.
+ const where = c.unreached?.length ? `not reached: ${c.unreached.join(", ")}` : "a cap was hit";
+ return { status: "partial", usd: 0, matched: 0, reason: `partial — the window check of ${window.from} … ${window.to} was capped (${where}): nothing matched in what it read, so the window is not called quiet` };
+ }
+ if (c.partial) ctx.log(`warning: the window check was capped${c.unreached?.length ? ` (not reached: ${c.unreached.join(", ")})` : ""}: at least ${c.recordings} match`);
if (c.recordings === 0) {
return {
status: "quiet",
@@ -333,7 +343,9 @@ export function r4Steps(draft: ReportDraftDeps, calls: Partial<R4Calls> = {}): P
}
const warnings = [
...r.warnings,
- ...r.fetch.filter((f) => f.status === "refused" || f.status === "skipped" || f.status === "failed").map(stepWords),
+ // A refused or skipped step (not a routine one) — failed, cancelled and
+ // still-going steps are in r.warnings already.
+ ...r.fetch.filter((f) => (f.status === "refused" || f.status === "skipped") && !f.routine).map(stepWords),
...(r.build && r.build.status !== "done" && r.build.status !== "failed" && r.build.reason ? [stepWords({ ...r.build, site: r.build.site })] : []),
];
if (r.build?.status === "failed") {
@@ -365,7 +377,7 @@ export function r4Steps(draft: ReportDraftDeps, calls: Partial<R4Calls> = {}): P
const it = await readIteration(article, n, draft.paths).catch(() => null);
const usd = it ? iterationUsd(it) : 0;
const f = await c.readRefreshFile(article, n, draft.paths).catch(() => null);
- const warnings = [...(out.warnings ?? []), ...(f?.warnings ?? []), ...(f?.fetch ?? []).filter((x) => x.status === "refused" || x.status === "skipped").map(stepWords)];
+ const warnings = [...(out.warnings ?? []), ...(f?.warnings ?? []), ...(f?.fetch ?? []).filter((x) => (x.status === "refused" || x.status === "skipped") && !x.routine).map(stepWords)];
const base = { iteration: n, usd, jobId: result.jobId, ...(warnings.length ? { warnings } : {}) };
ctx.log(`refresh ${article} i${n} ended ${f?.status ?? it?.status ?? "unread"}: ~$${usd.toFixed(2)}${f?.summary ? ` — ${f.summary}` : ""}`);
switch (f?.status) {
@@ -373,6 +385,8 @@ export function r4Steps(draft: ReportDraftDeps, calls: Partial<R4Calls> = {}): P
return { status: "done", ...base, ...(f.summary ? { reason: f.summary } : {}) };
case "no-change":
return { status: "no-change", ...base, reason: f.summary };
+ case "partial":
+ return { status: "partial", ...base, reason: f.summary };
case "held-by-cap":
return {
status: "held-by-cap",
@@ -547,7 +561,19 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
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;
+ // R6.1: a partial tier 0 never ends a tick quiet — what it did not reach
+ // is not "nothing new". Below the threshold it is the operator's call.
+ const part = partialWords(t.file.tier0);
+ if (!esc?.escalate && part) {
+ const reason = `partial — ${part}; nothing flagged in what was read (${esc?.why ?? t.file.summary})`;
+ ctx.log(`triage ${reason}`);
+ return { done: await finish({ status: "partial", usd: tier1Usd(), reason, ...triageLine(), ...warned() }) };
+ }
if (!esc?.escalate) return { done: await o.onBelow(`triage: ${esc?.why ?? t.file.summary} — below the threshold, nothing escalated`) };
+ if (part) {
+ warnings.push(`the triage was partial (${part}): the escalation reads what it reached`);
+ ctx.log(`warning: the triage was partial (${part})`);
+ }
const gen = (deps.settings ?? getSettings)().generation;
const capped = await escalationCapRefusal(deps.paths, now, gen.triage.maxEscalationsPerDay);
if (capped) {
@@ -659,7 +685,8 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
at: edition.at,
window,
title,
- status: out.status === "no-change" ? "done" : out.status,
+ // A made edition whose step said partial still made its article.
+ status: out.status === "no-change" || out.status === "partial" ? "done" : out.status,
...(out.status !== "quiet" ? { article, iteration: out.iteration } : {}),
usd,
...(out.jobId ? { jobId: out.jobId } : {}),
diff --git a/common/controller/reportTriage.ts b/common/controller/reportTriage.ts
@@ -32,7 +32,7 @@ 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 { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, cleanThreshold, partialWords, 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";
@@ -40,7 +40,7 @@ import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, resolve
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 type TriageMarker = { k: number; status: string; candidates: number; flagged: number; dismissed: number; escalate: boolean; why: string; usd: number; partial?: string };
export async function enqueueTriage(body: ReportDraftBody, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
const refuse = (error: string) => ({ result: { ok: false as const, error } });
@@ -213,6 +213,7 @@ async function runTriageJob(
escalate: !!f.escalation?.escalate,
why: f.escalation?.why ?? f.summary,
usd: f.cost.tier1,
+ ...(partialWords(f.tier0) ? { partial: partialWords(f.tier0)! } : {}),
};
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");
diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts
@@ -39,17 +39,30 @@ export type Candidates = {
// One enumeration's answer, as data: its rows, whether the scan was capped,
// the channels a capped scan never reached.
+// `unreached`: the channels a capped scan never reached, and the one it
+// stopped inside ("TheQuartering (stopped at page 12 of 29)").
export type EnumeratedAnswer = { rows: EnumeratedRow[]; partial: boolean; unreached: string[] };
// enumerate_matches as a function: the corpus tools' (enumerateViaTools), or
// a caller's own over the MCP's engine (umtool's daily check).
export type EnumerateFn = (args: Record<string, unknown>) => Promise<EnumeratedAnswer>;
+// R6.1 — EVERY RECORDING IN A SCOPE, from an UNCAPPED source: each channel's
+// transcripts manifest (every record the build ships, by id) dated by the
+// summaries index. Never one capped enumerate_matches(".") — a scan that
+// stops at its cap and calls what it read "the scope" is a silent zero.
+// `complete` false: some channel was not listed in full (`unreached`, with
+// why in `problems`), so what is missing is NOT "nothing new".
+export type ListedRecording = { id: string; channel: string | null; channelSlug: string | null; date: string | null; title: string | null };
+export type RecordingListing = { rows: ListedRecording[]; complete: boolean; unreached: string[]; problems: string[] };
+export type ListArgs = { channels?: string[]; date_from?: string; date_to?: string };
+export type ListFn = (args: ListArgs) => Promise<RecordingListing>;
+
/** enumerate_matches through the corpus tools, its answer read back as data. */
export const enumerateViaTools =
(corpus: Pick<CorpusToolsLike, "call">): EnumerateFn =>
async (args) => {
const e = enumerateOf(await corpus.call("enumerate_matches", args));
- return { rows: e.rows, partial: e.partial, unreached: e.unreached };
+ return { rows: e.rows, partial: e.partial, unreached: [...(e.stopped ? [e.stopped] : []), ...e.unreached] };
};
/** The enumerate_matches arguments of one query under a scope. */
@@ -82,7 +95,8 @@ const ymdOf = (d: string | null | undefined): string | null => {
export async function deltaCandidates(
basis: { queries: readonly RefreshQuery[]; scope: CandidateScope },
corpus: Pick<CorpusToolsLike, "call"> | EnumerateFn,
- o: { known?: Record<string, number | null>; since?: string | null; signal?: AbortSignal } = {},
+ // R6.1: `ids` restricts every query to those recordings (a bounded scan).
+ o: { known?: Record<string, number | null>; since?: string | null; ids?: readonly string[]; signal?: AbortSignal } = {},
): Promise<Candidates> {
const run = typeof corpus === "function" ? corpus : enumerateViaTools(corpus);
const seen = new Set<string>();
@@ -97,8 +111,17 @@ export async function deltaCandidates(
if (seen.has(key)) continue;
seen.add(key);
let e: EnumeratedAnswer;
+ const args = enumerateArgs(q, basis.scope);
+ // R6.1: with no known set, "new" is by upload date — the scan is bounded
+ // by it (a whole-scope scan would hit the cap and miss the newest).
+ const sinceDay = !o.known && o.since ? ymdOf(o.since) : null;
+ if (sinceDay) {
+ const had = ymdOf(args.date_from as string | undefined);
+ if (!had || had < sinceDay) args.date_from = sinceDay;
+ }
+ if (o.ids?.length) args.ids = [...o.ids];
try {
- e = await run(enumerateArgs(q, basis.scope));
+ e = await run(args);
} catch (err) {
// One query that cannot run is said, and makes the scan partial.
partial = true;
diff --git a/common/lib/report/draft/refresh/fetch.ts b/common/lib/report/draft/refresh/fetch.ts
@@ -35,6 +35,10 @@ export type RefreshHooks = {
platformRefusal?: (platform: string) => Promise<string | null>;
// A channel's "downloaded, not transcribed" recordings (its report's bucket), or null.
bucketOf?: (slug: string) => Promise<string[] | null>;
+ // R4.1: why transcription would not run now (the pool paused, no worker
+ // enabled), or null. Asked before transcribe-bucket is queued: a held
+ // transcription is skipped and said, never waited on for hours.
+ transcriptionHeld?: () => Promise<string | null>;
// The site to build so a build holds the channels (the parent's corpus
// first); null with why when there is none to build.
siteOf: (channels: string[], prefer: string | null) => Promise<{ site: string | null; reason?: string }>;
@@ -53,7 +57,7 @@ export type RefreshHooks = {
};
// Stage 1 needs only the editor's side.
-export type FetchHooks = Pick<RefreshHooks, "editor" | "jobOf" | "channelOf" | "platformRefusal" | "bucketOf" | "siteOf" | "builtAt" | "pollMs" | "waitMs" | "sleep">;
+export type FetchHooks = Pick<RefreshHooks, "editor" | "jobOf" | "channelOf" | "platformRefusal" | "bucketOf" | "transcriptionHeld" | "siteOf" | "builtAt" | "pollMs" | "waitMs" | "sleep">;
export type FetchAndBuild = { fetch: FetchStep[]; build: BuildStep | null; warnings: string[] };
@@ -155,8 +159,8 @@ export async function fetchAndBuild(
return step;
};
- const skip = (channel: string, action: string, reason: string): FetchStep => {
- const step: FetchStep = { channel, action, status: "skipped", reason };
+ const skip = (channel: string, action: string, reason: string, routine = false): FetchStep => {
+ const step: FetchStep = { channel, action, status: "skipped", reason, ...(routine ? { routine: true } : {}) };
trace({ t: "fetch", ...step });
log(`${channel}: ${action} skipped — ${reason}`);
return step;
@@ -186,7 +190,16 @@ export async function fetchAndBuild(
const had = new Set(before);
const landed = after.filter((id) => !had.has(id));
if (!landed.length) {
- steps.push(skip(slug, "transcribe-bucket", "nothing new to transcribe"));
+ steps.push(skip(slug, "transcribe-bucket", "nothing new to transcribe", true));
+ return steps;
+ }
+ // R4.1: a held transcription is not waited on (the step would sit for hours).
+ const held = hooks.transcriptionHeld ? await hooks.transcriptionHeld().catch(() => null) : null;
+ if (held) {
+ steps.push({
+ ...skip(slug, "transcribe-bucket", `transcription is paused (${held}) — ${landed.length} recording${landed.length === 1 ? "" : "s"} wait; a later run reads them once transcribed`),
+ ids: landed,
+ });
return steps;
}
steps.push(await runAndWait(slug, "transcribe-bucket", { slug, ids: landed }));
@@ -194,7 +207,9 @@ export async function fetchAndBuild(
};
const fetch = (await Promise.all(channels.map((c) => fetchChannel(c)))).flat();
- for (const s of fetch) if (s.status === "failed" || s.status === "waiting") warnings.push(`${s.channel}: ${s.action} ${s.status}${s.reason ? ` — ${s.reason}` : ""}`);
+ // A step that failed, was cancelled or is still going is a warning (a
+ // refused or skipped one is said by the caller; a routine skip never is).
+ for (const s of fetch) if (s.status === "failed" || s.status === "waiting" || s.status === "cancelled") warnings.push(`${s.channel}: ${s.action} ${s.status}${s.reason ? ` — ${s.reason}` : ""}`);
await o.onFetched?.(fetch);
if (o.build === false) return { fetch, build: null, warnings };
diff --git a/common/lib/report/draft/refresh/refresh.test.ts b/common/lib/report/draft/refresh/refresh.test.ts
@@ -432,3 +432,104 @@ test("a source deleted on its platform: the recheck carries the platform the sum
);
assert.deepEqual({ status: out[0]!.status, state: out[0]!.state, platform: out[0]!.platform }, { status: "ok", state: "deleted", platform: "youtube" });
});
+
+// ─── R6.1: no silent zeros; R4.1: fetch under a transcription hold ───
+
+import { enumerateOf } from "../tasks/trace";
+import { fetchAndBuild } from "./fetch";
+
+/** The stub corpus, its enumerations answered as a CAPPED scan (the MCP's head and coverage note). */
+function cappedCorpus(recs: Rec[]): ReturnType<typeof fakeCorpus> {
+ const c = fakeCorpus(recs);
+ const call = c.call.bind(c);
+ c.call = async (name, args = {}) => {
+ const text = await call(name, args);
+ if (name !== "enumerate_matches") return text;
+ return (
+ "⚠ COVERAGE PARTIAL — the scan hit its page/video cap before the corpus was exhausted. The 2 match(es) below are a SAMPLE, not the full set: …\n" +
+ "The sample is biased by CHANNEL ORDER, not random — fully scanned (1): Synth Kitchen; stopped inside Synth Other at page 3/9; NEVER REACHED (2): Synth Rumble (Mirror), Synth Live.\n\n" +
+ text.replace("(complete set: yes", "(complete set: NO — capped")
+ );
+ };
+ return c;
+}
+
+test("enumerateOf reads a capped scan's coverage: names with parentheses whole, the channel it stopped inside", () => {
+ const e = enumerateOf(
+ "⚠ COVERAGE PARTIAL — …\nThe sample is biased by CHANNEL ORDER, not random — fully scanned (1): A; stopped inside TheQuartering at page 29/29; NEVER REACHED (3): Jeremy Hambly, Melonie Mac, TheQuartering (Rumble).\n\n- x | video | A | 2026-10-01 | 1 match(es) | X\n\n(complete set: NO — capped; 1 match(es))",
+ );
+ assert.equal(e.partial, true);
+ assert.deepEqual(e.unreached, ["Jeremy Hambly", "Melonie Mac", "TheQuartering (Rumble)"]);
+ assert.equal(e.stopped, "TheQuartering (stopped at page 29 of 29)");
+});
+
+test("deltaCandidates with no known set: the scan is bounded by `since` (date_from), never the whole scope; `ids` restricts it", async () => {
+ const corpus = fakeCorpus(BASE);
+ await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"], from: "2020-01-01" } }, corpus, { since: "2026-10-07T00:00:00Z", ids: ["pie-02"] });
+ assert.deepEqual(corpus.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"], date_from: "2026-10-07", ids: ["pie-02"] });
+ // A known set keeps the whole scan (changed and unmatched need it).
+ const whole = fakeCorpus(BASE);
+ await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, whole, { known: { "pie-02": 2 }, since: "2026-10-07" });
+ assert.deepEqual(whole.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"] });
+ // A capped answer is partial, with what it did not reach (the stopped channel first).
+ const capped = await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, cappedCorpus(BASE), { known: {} });
+ assert.equal(capped.partial, true);
+ assert.deepEqual(capped.unreached, ["Synth Live", "Synth Other (stopped at page 3 of 9)", "Synth Rumble (Mirror)"]);
+ assert.deepEqual(capped.unmatched, [], "unmatched is never said of a partial scan");
+});
+
+test("refresh, a capped search again with nothing new: partial (naming what it did not reach), never no-change", async () => {
+ const paths = store();
+ await doneSweep(paths);
+ await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths);
+ const h = harness({ recs: BASE });
+ const deps = h.deps(paths);
+ const capped = cappedCorpus(BASE);
+ deps.refresh!.openCorpus = async () => {
+ Object.assign(deps.corpus, { source: capped.source, tools: capped.tools, call: capped.call.bind(capped) });
+ return { source: capped.source, origin: "https://synth.example", build: "synth" };
+ };
+ const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, deps);
+ assert.equal(out.status, "done", h.lines.join("\n"));
+ const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile;
+ assert.equal(f.status, "partial");
+ assert.match(f.summary, /^partial — not reached: Synth Live, Synth Other \(stopped at page 3 of 9\), Synth Rumble \(Mirror\); Nothing new since \d{4}-\d{2}-\d{2} in what was read$/);
+ assert.equal(f.delta?.partial, true);
+ assert.equal(outcomeOf(f).status, "partial");
+});
+
+test("R4.1 fetch: transcription held — transcribe-bucket is skipped and said (a warning to the caller), never waited on; nothing to transcribe is a routine skip; a cancelled job is a warning", async () => {
+ const calls: Call[] = [];
+ const buckets: Record<string, string[]> = { held: ["old"], quiet: ["old"], gone: [] };
+ const hooks = {
+ editor: {
+ async run(action: string, args: Record<string, unknown>) {
+ calls.push({ action, args });
+ if (action === "sync" && args.slug === "held") buckets.held = ["old", "n1", "n2"];
+ if (action === "sync" && args.slug === "gone") return { ok: true, jobId: "cancel-me" };
+ return { ok: true, jobId: `job-${calls.length}` };
+ },
+ },
+ jobOf: async (id: string) => ({ status: id === "cancel-me" ? "cancelled" : "done", endedAt: Date.now() }),
+ channelOf: async () => ({ kind: "video" as const, platform: "youtube" }),
+ bucketOf: async (slug: string) => buckets[slug] ?? null,
+ transcriptionHeld: async () => "no transcription worker is enabled",
+ siteOf: async () => ({ site: null, reason: "no build" }),
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ const r = await fetchAndBuild({ channels: ["held", "quiet", "gone"] }, hooks);
+ assert.ok(!calls.some((c) => c.action === "transcribe-bucket"), "nothing queued for a held transcription");
+ const tb = r.fetch.find((s) => s.channel === "held" && s.action === "transcribe-bucket")!;
+ assert.deepEqual(tb, {
+ channel: "held",
+ action: "transcribe-bucket",
+ status: "skipped",
+ reason: "transcription is paused (no transcription worker is enabled) — 2 recordings wait; a later run reads them once transcribed",
+ ids: ["n1", "n2"],
+ });
+ const routine = r.fetch.find((s) => s.channel === "quiet" && s.action === "transcribe-bucket")!;
+ assert.deepEqual(routine, { channel: "quiet", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe", routine: true });
+ assert.ok(r.warnings.some((w) => /^gone: sync cancelled — the job ended cancelled$/.test(w)), JSON.stringify(r.warnings));
+ assert.ok(!r.warnings.some((w) => /nothing new to transcribe/.test(w)));
+});
diff --git a/common/lib/report/draft/refresh/task.ts b/common/lib/report/draft/refresh/task.ts
@@ -263,8 +263,10 @@ async function refreshBody(h: TaskHandle, input: RefreshInput): Promise<TaskOutc
return { status: outcome, summary, patch: { refresh: outcomeOf(file) } };
};
+ // R6.1: nothing found by a capped search is not "no change".
+ const partialWhy = delta.partial ? `partial — ${delta.unreached.length ? `not reached: ${delta.unreached.join(", ")}` : "a cap was hit"}` : null;
const flagged = input.ids?.length ? [...new Set(input.ids)] : null;
- if (delta.status === "no-change" && !flagged) return finish("no-change", line);
+ if (delta.status === "no-change" && !flagged) return partialWhy ? finish("partial", `${partialWhy}; ${line} in what was read`) : 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(", ")}` });
@@ -317,7 +319,8 @@ async function refreshBody(h: TaskHandle, input: RefreshInput): Promise<TaskOutc
}
if (!findings && !delta.drifted.length && !delta.deleted.length) {
- return finish("no-change", `${line} — ${ids.length} recording(s) read; nothing in them for the question`);
+ const said = `${line} — ${ids.length} recording(s) read; nothing in them for the question`;
+ return partialWhy && !flagged ? finish("partial", `${partialWhy}; ${said}`) : finish("no-change", said);
}
// 3b. the revision of the parent's report.
diff --git a/common/lib/report/draft/refresh/types.ts b/common/lib/report/draft/refresh/types.ts
@@ -138,11 +138,15 @@ export type FetchStep = {
reason?: string;
// transcribe-bucket: the recordings that landed.
ids?: string[];
+ // R6.1: a skip that is routine ("nothing new to transcribe"): said, never a warning.
+ routine?: boolean;
};
export type BuildStep = { site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string; builtAt?: string };
-export type RefreshStatus = "running" | "no-change" | "updated" | "held-by-cap" | "failed" | "cancelled";
+// `partial` (R6.1): the search again hit a cap (or did not reach a channel)
+// and found nothing to update in what it read — never `no-change`.
+export type RefreshStatus = "running" | "no-change" | "partial" | "updated" | "held-by-cap" | "failed" | "cancelled";
export type RefreshUpdate = {
model: string;
diff --git a/common/lib/report/draft/tasks/restrict.ts b/common/lib/report/draft/tasks/restrict.ts
@@ -2,7 +2,8 @@
// a refresh's new recordings, R6's escalation). The agent keeps its corpus
// tools, narrowed:
//
-// enumerate_matches answers only the rows of the given ids (and says so)
+// enumerate_matches scans only the given ids (R6.1: their pages) and
+// answers only their rows (and says so)
// get_transcripts, the given ids only: the others are dropped from the
// extract_batch call (and the answer says which); none left refuses
// get_transcript, an id outside refuses
@@ -43,7 +44,10 @@ export function restrictedTool(t: AgentTool, only: ReadonlySet<string>): AgentTo
case "search_transcripts":
return null;
case "enumerate_matches":
- return { ...t, run: async (input: unknown, ctx) => restrictEnumerateText(await t.run(input, ctx), only) };
+ // R6.1: the scan itself is restricted (`ids`: only the pages holding
+ // them are read), so a cap on the scope never hides them; the rows are
+ // still filtered here for an engine that ignores `ids`.
+ return { ...t, run: async (input: unknown, ctx) => restrictEnumerateText(await t.run({ ...((input ?? {}) as Record<string, unknown>), ids: [...only] }, ctx), only) };
case "get_transcripts":
case "extract_batch":
return {
diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts
@@ -240,7 +240,7 @@ export type EnumeratedRow = { id: string; kind: "video" | "post" | "audio"; chan
// enumerate_matches' answer: its rows' ids, whether the scan was capped, and
// the channels a capped scan never reached; `rows` each row as it reads (its
// channel's name, date, matching lines and title).
-export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; total: number | null; rows: EnumeratedRow[] } {
+export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; stopped?: string; total: number | null; rows: EnumeratedRow[] } {
const ids: string[] = [];
const rows: EnumeratedRow[] = [];
let videos = 0;
@@ -264,11 +264,15 @@ export function enumerateOf(text: string): { ids: string[]; videos: number; post
}
const partial = /COVERAGE PARTIAL/.test(text);
const unreached: string[] = [];
- const nr = /NEVER REACHED \(\d+\): ([^;\n)]+)/.exec(text);
- // The list ends the sentence: its last name carries the full stop.
- if (nr) for (const c of nr[1]!.trim().replace(/\.$/, "").split(",")) if (c.trim()) unreached.push(c.trim());
+ // The list ends the sentence (its last name carries the full stop); a name
+ // may hold parentheses ("TheQuartering (Rumble)") — read to the line's end.
+ const nr = /NEVER REACHED \(\d+\): (.*?)\.?$/m.exec(text);
+ if (nr) for (const c of nr[1]!.split(", ")) if (c.trim()) unreached.push(c.trim());
+ // The channel the cap stopped inside (read in part).
+ const st = /stopped inside (.+?) at page (\d+)\/(\d+)/.exec(text);
+ const stopped = st ? `${st[1]!.trim()} (stopped at page ${st[2]} of ${st[3]})` : undefined;
const total = /^(\d+) match\(es\) for /m.exec(text) ?? /\(complete set: [^;]+; (\d+) match\(es\)/.exec(text);
- return { ids, videos, posts, partial, unreached, total: total ? Number(total[1]) : null, rows };
+ return { ids, videos, posts, partial, unreached, ...(stopped ? { stopped } : {}), total: total ? Number(total[1]) : null, rows };
}
// Each row's matching lines, by id (a row whose count does not read is left
diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts
@@ -16,6 +16,7 @@ import type { Report } from "../../schema";
import type { ResearchEditor } from "../research/tools";
import type { DeckChecks } from "./deckChecks";
import type { RefreshHooks } from "../refresh/fetch";
+import type { ListArgs, RecordingListing } from "../refresh/delta";
// The iterations store's paths (S4 takes them on every call).
export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>;
@@ -25,6 +26,10 @@ export type CorpusToolsLike = {
source: string;
tools: AgentTool[];
call(name: string, args?: Record<string, unknown>): Promise<string>;
+ // R6.1: every recording in a scope, uncapped (the build's manifests), when
+ // the corpus can say (mcp/src/callTool.ts). Absent: a triage lists the scope
+ // per channel through enumerate_matches, and says when that was capped.
+ listRecordings?(args: ListArgs): Promise<RecordingListing>;
};
// A quote problem an outside verifier found (the editor's verify-quotes over
diff --git a/common/lib/report/draft/triage/task.ts b/common/lib/report/draft/triage/task.ts
@@ -21,13 +21,13 @@
import { Meter, structuredAnswer, type LlmConfig, type ModelTally } from "../../../llm";
import type { WordCue } from "../../quoteWords";
-import { enumerateViaTools, type EnumerateFn } from "../refresh/delta";
+import { enumerateViaTools, type EnumerateFn, type ListFn } from "../refresh/delta";
import { openTrace, NO_TRACE, type RunTracer } from "../tasks/trace";
import type { CorpusToolsLike } from "../tasks/types";
import { judgeCandidates } from "./judge";
import { 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";
+import { TRIAGE_SEEN_FORMAT, escalationOf, partialWords, triageLine, type TriageFile, type TriageWindow } from "./types";
export const DEFAULT_MAX_CANDIDATES = 40;
@@ -51,6 +51,8 @@ export type TriageRunDeps = {
topicsOf?: (id: string, channel: string | null) => Promise<string[] | null>;
// enumerate_matches as data (default: through the corpus tools).
enumerate?: EnumerateFn;
+ // Every recording in scope, uncapped (default: the corpus tools' listRecordings, when they have it).
+ list?: ListFn;
// 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;
@@ -125,6 +127,14 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
trace({ t: "enumerate", query: String(args.query), n: e.rows.length, ids: e.rows.map((r) => r.id), partial: e.partial, unreached: e.unreached });
return e;
};
+ const listRaw: ListFn | undefined = deps.list ?? (deps.corpus.listRecordings ? (a) => deps.corpus.listRecordings!(a) : undefined);
+ const list: ListFn | undefined = listRaw
+ ? async (args) => {
+ const l = await listRaw(args);
+ trace({ t: "enumerate", query: "(every recording, listed)", n: l.rows.length, ids: l.rows.map((r) => r.id), partial: !l.complete, unreached: l.unreached });
+ return l;
+ }
+ : undefined;
const topicsOf =
deps.topicsOf ??
(async (id: string, channel: string | null) => {
@@ -153,11 +163,15 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
...(input.ids?.length ? { ids: input.ids } : {}),
max: input.maxCandidates ?? DEFAULT_MAX_CANDIDATES,
},
- { enumerate, topicsOf, ...(deps.signal ? { signal: deps.signal } : {}), log },
+ { enumerate, ...(list ? { list } : {}), 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.partial) {
+ file.warnings.push(
+ `partial — ${t0r.tier0.unreached.length ? `not reached: ${t0r.tier0.unreached.join(", ")}` : (t0r.tier0.problems ?? []).join("; ") || "a cap was hit"}: a recording it did not reach is not a candidate this time, and this run's seen set is not kept${seen ? " (the last complete run's stands)" : ` (the next run counts new from ${file.since ?? "its since"} again)`}`,
+ );
+ }
if (t0r.tier0.cut.length) file.warnings.push(`${t0r.tier0.cut.length} candidate(s) past the cap of ${input.maxCandidates ?? DEFAULT_MAX_CANDIDATES}: not judged, left new for the next run`);
if (!seen && !input.ids?.length) file.warnings.push(file.since ? `no earlier triage: "new" is uploaded on or after ${file.since}` : "no earlier triage: every recording in scope is new");
await save();
@@ -190,7 +204,8 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
// ─── 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}`;
+ const part = partialWords(file.tier0);
+ file.summary = `${part ? `partial (${part}) · ` : ""}${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",
diff --git a/common/lib/report/draft/triage/tier0.ts b/common/lib/report/draft/triage/tier0.ts
@@ -1,22 +1,30 @@
-// TRIAGE, TIER 0 — code, $0 (umtool R6): the candidates.
+// TRIAGE, TIER 0 — code, $0 (umtool R6; R6.1): 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
+// alias-aware), 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).
+// R6.1 — NO SILENT ZEROS. What exists in scope is LISTED, never scanned with
+// one capped enumerate_matches("."): the corpus's `listRecordings` (each
+// channel's transcripts manifest, dated by the summaries index — uncapped),
+// else enumerate_matches per channel (capped: said). The terms query is
+// BOUNDED: restricted to the new ids (`ids`: only the pages holding them are
+// read), and on a first run also by `date_from = since`. Any cap hit, or a
+// channel not listed in full, makes tier 0 `partial` with what was not
+// reached — and a partial run's seen set is never stored (`seen: null`), so
+// the next run does not count what this one missed as known.
//
-// Pure over the enumerate function and the topic reader it is handed.
+// The listing is 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 list and enumerate functions and the topic reader it is handed.
-import { deltaCandidates, type EnumerateFn } from "../refresh/delta";
+import { type EnumerateFn, type ListFn, type RecordingListing } from "../refresh/delta";
import type { TriageCandidate, TriageTier0 } from "./types";
export type Tier0Input = {
@@ -37,6 +45,9 @@ export type Tier0Input = {
export type Tier0Deps = {
enumerate: EnumerateFn;
+ // Every recording in scope, uncapped (the corpus's listRecordings). Absent:
+ // enumerate_matches per channel, its cap said.
+ list?: ListFn;
// A recording's digest topic tags (null: no digest). Absent: topics unread.
topicsOf?: (id: string, channel: string | null) => Promise<string[] | null>;
signal?: AbortSignal;
@@ -45,9 +56,10 @@ export type Tier0Deps = {
export type Tier0Result = {
tier0: TriageTier0;
- // What the next run counts as known (null: leave seen.json as it is).
+ // What the next run counts as known (null: leave seen.json as it is — a
+ // partial run, or ids named).
seen: string[] | null;
- // The scope scan's ids (for the trace).
+ // The scope listing's ids (for the trace).
scannedIds: string[];
};
@@ -82,37 +94,62 @@ export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tie
};
}
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);
+ // The scope, listed: what this run SAW (the whole scope — on a first run
+ // too, or the next run would count everything older as new).
+ const listing = await listScope(i.scope, d);
+ d.signal?.throwIfAborted();
+ const rows = listing.rows;
+ const perQuery: TriageTier0["perQuery"] = [{ query: listing.by === "manifests" ? "(every recording, listed)" : "(any recording)", n: rows.length, partial: !listing.complete }];
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);
+ log(
+ `tier 0: ${rows.length} recording(s) in scope (${listing.by === "manifests" ? "listed from the build's manifests" : "enumerated per channel"}), ${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)"}${listing.complete ? "" : ` — PARTIAL: ${listing.problems.join("; ")}`}`,
+ );
+ let partial = !listing.complete;
+ const unreached = new Set(listing.unreached);
+ const problems = [...listing.problems];
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"] });
+ if (terms && fresh.length) {
+ // Bounded: only the new recordings' pages are read (and, on a first run,
+ // from `since`) — never the whole scope, whose scan would hit the cap.
+ const args: Record<string, unknown> = {
+ query: terms,
+ ...(i.regex ? { regex: true } : {}),
+ ...(channels.length ? { channels } : {}),
+ ...(i.scope.to ? { date_to: i.scope.to } : {}),
+ ...(since ? { date_from: i.scope.from && i.scope.from > since ? i.scope.from : since } : i.scope.from ? { date_from: i.scope.from } : {}),
+ ids: [...byId.keys()],
+ content_types: ["video"],
+ };
+ let n = 0;
+ try {
+ const e = await d.enumerate(args);
+ if (e.partial) {
+ partial = true;
+ problems.push(`the terms query hit its cap`);
+ }
+ for (const u of e.unreached) unreached.add(u);
+ for (const row of e.rows) {
+ if (row.kind === "post" || !byId.has(row.id)) continue;
+ n++;
+ const r = byId.get(row.id)!;
+ found.set(row.id, { id: row.id, channel: row.channel ?? r.channel ?? null, title: row.title ?? r.title ?? null, date: ymdOf(row.date) ?? ymdOf(r.date), matches: row.matches ?? null, by: ["terms"] });
+ }
+ perQuery.push({ query: terms, n, partial: e.partial });
+ } catch (err) {
+ partial = true;
+ problems.push(`the terms query could not run: ${(err as Error).message}`);
+ perQuery.push({ query: terms, n: 0, partial: true, error: (err as Error).message });
}
- log(`tier 0: terms ${JSON.stringify(terms)}: ${c.newIds.length} new recording(s) match`);
+ log(`tier 0: terms ${JSON.stringify(terms)}: ${n} new recording(s) match (of ${fresh.length} new, read by id)`);
+ } else if (terms) {
+ perQuery.push({ query: terms, n: 0, partial: false });
+ log(`tier 0: terms ${JSON.stringify(terms)}: no new recording to read`);
}
if (topics.length && d.topicsOf) {
let reads = 0;
@@ -122,7 +159,7 @@ export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tie
if (reads >= max) break;
d.signal?.throwIfAborted();
reads++;
- const tags = await d.topicsOf(r.id, r.channel).catch(() => null);
+ const tags = await d.topicsOf(r.id, r.channelSlug ?? r.channel).catch(() => null);
const matched = (tags ?? []).filter((t) => topics.some((p) => tagMatches(t, p)));
if (!matched.length) continue;
hits++;
@@ -148,11 +185,56 @@ export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tie
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));
+ // Seen: everything known, everything listed, less what was cut (it stays
+ // new). A PARTIAL run stores nothing: what it did not reach must not become
+ // known, so the next run falls back to the last complete run's set (or to
+ // its `since`).
+ const seen = partial ? null : [...new Set([...(i.known ?? []), ...scannedIds])].filter((id) => !cutSet.has(id));
+ if (partial) log(`tier 0: PARTIAL${unreached.size ? ` — not reached: ${[...unreached].join(", ")}` : ""}: this run's seen set is not kept`);
return {
- tier0: { candidates, scanned: rows.length, newCount: fresh.length, cut, partial, unreached: [...unreached].sort(), perQuery, newBy: i.known ? "id" : "date" },
+ tier0: {
+ candidates,
+ scanned: rows.length,
+ newCount: fresh.length,
+ cut,
+ partial,
+ unreached: [...unreached].sort(),
+ perQuery,
+ newBy: i.known ? "id" : "date",
+ listedBy: listing.by,
+ ...(problems.length ? { problems } : {}),
+ },
seen,
scannedIds,
};
}
+
+type ScopeRow = { id: string; channel: string | null; channelSlug?: string | null; date: string | null; title: string | null };
+
+/**
+ * Every recording in scope: the corpus's uncapped listing when it has one,
+ * else enumerate_matches(".") per channel — each capped, and a capped one
+ * said (the channel named), never taken for the whole channel.
+ */
+async function listScope(scope: Tier0Input["scope"], d: Tier0Deps): Promise<{ rows: ScopeRow[]; complete: boolean; unreached: string[]; problems: string[]; by: "manifests" | "enumerate" }> {
+ const dates = { ...(scope.from ? { date_from: scope.from } : {}), ...(scope.to ? { date_to: scope.to } : {}) };
+ if (d.list) {
+ const l: RecordingListing = await d.list({ ...(scope.channels.length ? { channels: scope.channels } : {}), ...dates });
+ return { rows: l.rows, complete: l.complete, unreached: l.unreached, problems: l.problems, by: "manifests" };
+ }
+ const rows: ScopeRow[] = [];
+ const unreached: string[] = [];
+ const problems: string[] = [];
+ const groups = scope.channels.length ? scope.channels.map((c) => [c]) : [[]];
+ for (const chs of groups) {
+ d.signal?.throwIfAborted();
+ const e = await d.enumerate({ query: ".", regex: true, ...(chs.length ? { channels: chs } : {}), ...dates, content_types: ["video"] });
+ for (const r of e.rows) if (r.kind !== "post") rows.push({ id: r.id, channel: r.channel, date: r.date, title: r.title });
+ if (e.partial) {
+ const where = e.unreached.length ? e.unreached : chs.length ? chs : ["the scope"];
+ unreached.push(...where);
+ problems.push(`${chs.length ? chs.join(", ") : "the scope"}: the listing hit enumerate's cap after ${e.rows.length} recording(s) (not reached: ${where.join(", ")})`);
+ }
+ }
+ return { rows, complete: problems.length === 0, unreached, problems, by: "enumerate" };
+}
diff --git a/common/lib/report/draft/triage/triage.test.ts b/common/lib/report/draft/triage/triage.test.ts
@@ -331,3 +331,104 @@ test("a run that fails keeps nothing seen: the next sees the same recordings as
assert.match(file.error!, /the build is gone/);
assert.equal(await readTriageSeen("watch-b", paths), null);
});
+
+// ─── R6.1: a complete scope listing; bounded term queries; no silent zeros ───
+
+import type { ListFn, RecordingListing } from "../refresh/delta";
+
+// A scope LARGER THAN THE CAP: 60 old recordings, then the new ones, which
+// sort last — the order a channel's shards are read in.
+const BIG: Rec[] = [
+ ...Array.from({ length: 60 }, (_, i) => ({ id: `old-${String(i).padStart(2, "0")}`, date: `2024${String((i % 12) + 1).padStart(2, "0")}15`, title: `Old ${i}`, lines: ["the contest again", "flour"] })),
+ ...RECS,
+];
+const CAP = 50;
+
+/** enumerate_matches with a cap of CAP rows, as the MCP answers a capped scan: the rows read first, partial, what it did not reach. `ids` restricts (bounds) the scan. */
+function cappedEnumerate(recs: Rec[]): EnumerateFn & { calls: Record<string, unknown>[] } {
+ const inner = enumerateOver(recs);
+ const fn = (async (args: Record<string, unknown>): Promise<EnumeratedAnswer> => {
+ const only = Array.isArray(args.ids) ? new Set(args.ids as string[]) : null;
+ const from = typeof args.date_from === "string" ? args.date_from : null;
+ const e = await inner(args);
+ let rows = e.rows.filter((r) => (!only || only.has(r.id)) && (!from || (r.date ?? "") >= from));
+ const partial = rows.length > CAP;
+ rows = rows.slice(0, CAP);
+ return { rows, partial, unreached: partial ? [`${NAME} (stopped at page 3 of 4)`] : [] };
+ }) as EnumerateFn & { calls: Record<string, unknown>[] };
+ fn.calls = inner.calls;
+ return fn;
+}
+
+/** The corpus's listing: every recording, uncapped (the build's manifests). */
+const listOver = (recs: Rec[], o: Partial<RecordingListing> = {}): ListFn & { calls: unknown[] } => {
+ const calls: unknown[] = [];
+ const fn = (async (args) => {
+ calls.push(args);
+ return { rows: recs.map((r) => ({ id: r.id, channel: NAME, channelSlug: CHAN, date: ymd(r.date), title: r.title })), complete: true, unreached: [], problems: [], ...o };
+ }) as ListFn & { calls: unknown[] };
+ fn.calls = calls;
+ return fn;
+};
+
+test("R6.1 tier 0: a scope larger than the cap whose new recordings sort last — listed in full, the terms read by id: the new ones are found, nothing partial", async () => {
+ const enumerate = cappedEnumerate(BIG);
+ const list = listOver(BIG);
+ // First run: new by date from `since`.
+ const first = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate, list });
+ assert.equal(first.tier0.partial, false);
+ assert.equal(first.tier0.listedBy, "manifests");
+ assert.equal(first.tier0.scanned, BIG.length);
+ assert.deepEqual(first.tier0.candidates.map((c) => c.id), ["new-04"]);
+ // The terms query: restricted to the new ids, and dated from `since` — never the whole scope.
+ const termCall = enumerate.calls.find((c) => c.query === "contest")!;
+ assert.deepEqual(termCall.ids, ["new-04", "tag-05"]);
+ assert.equal(termCall.date_from, "2026-10-01");
+ assert.ok(!enumerate.calls.some((c) => c.query === "."), "the scope is listed, not scanned with one capped '.'");
+ // Seen is the WHOLE scope (on a first run too), so the next run's "new" is by id.
+ assert.equal(first.seen?.length, BIG.length);
+ // By id: the late transcript (an old upload date) is new too.
+ const byId = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: new Set(BIG.map((r) => r.id).filter((id) => id !== "late-03" && id !== "new-04")), since: null, max: 40 }, { enumerate: cappedEnumerate(BIG), list });
+ assert.deepEqual(byId.tier0.candidates.map((c) => c.id).sort(), ["late-03", "new-04"]);
+ assert.equal(byId.tier0.partial, false);
+});
+
+test("R6.1 tier 0: a capped scan is partial — the channels named, seen not kept; through a run the earlier seen.json stands and the warning says so", async () => {
+ // No listing (a corpus that cannot list): one capped "." per channel.
+ const capped = await triageCandidates({ scope: { channels: [CHAN] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG) });
+ assert.equal(capped.tier0.partial, true);
+ assert.equal(capped.tier0.listedBy, "enumerate");
+ assert.deepEqual(capped.tier0.unreached, [`${NAME} (stopped at page 3 of 4)`]);
+ assert.equal(capped.seen, null, "a partial run's seen set is not kept");
+ assert.deepEqual(capped.tier0.candidates, [], "the newest were never reached — and that is said, not 0");
+ // A listing that is not complete (a channel's manifest does not read) is partial too.
+ const holes = await triageCandidates({ scope: { channels: [CHAN, "gone"] }, terms: "contest", topics: [], known: null, since: "2026-10-01", max: 40 }, { enumerate: cappedEnumerate(BIG), list: listOver(BIG, { complete: false, unreached: ["gone"], problems: ["gone: its transcripts manifest does not read (404)"] }) });
+ assert.equal(holes.tier0.partial, true);
+ assert.deepEqual(holes.tier0.unreached, ["gone"]);
+ assert.deepEqual(holes.tier0.candidates.map((c) => c.id), ["new-04"], "what was listed is still judged");
+ assert.equal(holes.seen, null);
+
+ // Through a run: the earlier complete run's seen.json stands.
+ const paths = store();
+ await writeTriageSeen({ format: TRIAGE_SEEN_FORMAT, owner: "watch-p", k: 0, at: "2026-10-07T00:00:00Z", ids: ["bread-01"] }, paths);
+ await createTriageRun(queued("watch-p"), paths, "watch-p");
+ const { file } = await runTriage({ owner: "watch-p", k: 1 }, { llm: {} as never, corpus: corpusOver(BIG), enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask: async <T,>() => ({ relevant: false, items: [] }) as T });
+ assert.equal(file.status, "done", file.error);
+ assert.equal(file.tier0!.partial, true);
+ assert.match(file.summary, /^partial \(not reached: Synth Kitchen \(stopped at page 3 of 4\)\) · /);
+ assert.ok(file.warnings.some((w) => /^partial — not reached: Synth Kitchen \(stopped at page 3 of 4\): .*this run's seen set is not kept \(the last complete run's stands\)$/.test(w)), JSON.stringify(file.warnings));
+ assert.deepEqual((await readTriageSeen("watch-p", paths))?.ids, ["bread-01"]);
+ assert.equal(tickTriageOf(file).partial, "not reached: Synth Kitchen (stopped at page 3 of 4)");
+});
+
+test("R6.1 tier 0: the corpus tools' listRecordings is the default listing", async () => {
+ const paths = store();
+ await createTriageRun(queued("watch-l"), paths, "watch-l");
+ const listed: unknown[] = [];
+ const corpus = { ...corpusOver(BIG), listRecordings: async (a: unknown) => (listed.push(a), listOver(BIG)(a as never)) };
+ const { file } = await runTriage({ owner: "watch-l", k: 1 }, { llm: {} as never, corpus, enumerate: cappedEnumerate(BIG), paths, cuesOf: cuesOver(BIG), ask: async <T,>() => ({ relevant: false, items: [] }) as T });
+ assert.equal(file.tier0!.partial, false);
+ assert.equal(file.tier0!.listedBy, "manifests");
+ assert.deepEqual(listed, [{ channels: [CHAN] }]);
+ assert.equal((await readTriageSeen("watch-l", paths))?.ids.length, BIG.length);
+});
diff --git a/common/lib/report/draft/triage/types.ts b/common/lib/report/draft/triage/types.ts
@@ -125,6 +125,11 @@ export type TriageTier0 = {
// 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";
+ // R6.1: how the scope was listed — the build's manifests (uncapped), or
+ // enumerate_matches per channel (a corpus that cannot list; capped, said).
+ listedBy?: "manifests" | "enumerate";
+ // Why the listing or a query is partial, in words.
+ problems?: string[];
};
export type TriageTier1 = {
@@ -206,6 +211,13 @@ export function escalationOf(flags: readonly Pick<TriageFlag, "strength">[], thr
}
/** "8 candidates · 2 flagged · 6 dismissed". */
+/** R6.1: why a tier 0 is partial, in words ("not reached: A, B (stopped at page 3 of 29)"); null: complete. */
+export function partialWords(t: Pick<TriageTier0, "partial" | "unreached" | "problems"> | null | undefined): string | null {
+ if (!t?.partial) return null;
+ if (t.unreached.length) return `not reached: ${t.unreached.join(", ")}`;
+ return (t.problems ?? []).join("; ") || "a cap was hit";
+}
+
export function triageLine(f: Pick<TriageFile, "tier0" | "tier1">): string {
const c = f.tier0?.candidates.length ?? 0;
const flagged = f.tier1?.flags.length ?? 0;
@@ -231,6 +243,8 @@ export type TickTriage = {
usd: { tier1: number; tier2: number };
// An escalation the day's cap refused.
capped?: string;
+ // R6.1: tier 0 was partial — what it did not reach ("not reached: …").
+ partial?: string;
};
/** A run's slice for its tick line. */
@@ -250,6 +264,7 @@ export function tickTriageOf(f: TriageFile, o: { tier2Usd?: number; capped?: str
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 } : {}),
+ ...(partialWords(f.tier0) ? { partial: partialWords(f.tier0)! } : {}),
};
}
diff --git a/common/lib/report/schedule/types.ts b/common/lib/report/schedule/types.ts
@@ -43,10 +43,13 @@ export type ScheduleShape = (typeof SCHEDULE_SHAPES)[number];
// 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;
+// `partial` (R6.1): a scan the tick decided on hit a cap or did not reach a
+// channel, and found nothing in what it read — never `quiet`/`no-change`,
+// which would be a silent zero. The reason names what was not reached.
+export const TICK_STATUSES = ["done", "no-change", "quiet", "partial", "held-by-cap", "failed", "cancelled", "interrupted"] as const;
export type TickStatus = (typeof TICK_STATUSES)[number];
// The outcomes that are the operator's call (a Your call card).
-export const CALL_STATUSES: readonly TickStatus[] = ["failed", "held-by-cap", "interrupted"];
+export const CALL_STATUSES: readonly TickStatus[] = ["failed", "held-by-cap", "interrupted", "partial"];
export const EDITION_STATUSES = ["running", "done", "quiet", "failed", "cancelled", "held-by-cap"] as const;
export type EditionStatus = (typeof EDITION_STATUSES)[number];
@@ -101,6 +104,7 @@ export const tickTriageSchema = z.looseObject({
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(),
+ partial: z.string().optional(),
});
export const tickSchema = z.looseObject({
diff --git a/editor/app/api/ops/_reportSchedule.ts b/editor/app/api/ops/_reportSchedule.ts
@@ -23,7 +23,8 @@ import { refreshEditor, researchEditor } from "./_researchEditor";
// countWindow enumerate_matches' own scan (the MCP's, in process) over
// the build a sweep would read (the newest holding the
// channels): the schedule's terms, or any recording, in
-// the window. 0 is a quiet edition.
+// the window. 0 is a quiet edition — unless the scan
+// was capped (R6.1: partial, the channels it did not read).
// fetchAndBuild R4's stage 1 (controller/reportRefresh.ts fetchScope):
// this editor's own paced fetches for the scope, then the
// local build of the site holding it — through
@@ -53,7 +54,10 @@ const countWindow: CountWindow = async (q) => {
date_to: q.to,
});
if ("error" in e) return { error: e.error };
- return { recordings: e.result.total };
+ // R6.1: a capped scan says so — 0 from it is not a quiet window.
+ const c = e.result.coverage;
+ const unreached = [...(c.channelStopped ? [`${c.channelStopped.channel} (stopped at page ${c.channelStopped.page} of ${c.channelStopped.pages})`] : []), ...c.channelsNotReached];
+ return { recordings: e.result.total, ...(e.result.truncated ? { partial: true, unreached } : {}) };
};
export function reportScheduleDeps(): TickDeps {
diff --git a/editor/app/api/ops/report-schedule/route.ts b/editor/app/api/ops/report-schedule/route.ts
@@ -9,7 +9,7 @@ import { reportScheduleDeps } from "../_reportSchedule";
export const dynamic = "force-dynamic";
// POST {"action": "list" | "create" | "update" | "pause" | "resume" |
-// "delete" | "tick-now", …}
+// "delete" | "tick-now" | "reset-triage", …}
//
// A recurring report (umtool R5): a LIVING report (one article kept current —
// each tick re-fetches the scope and refreshes it), a SERIES (a dated
@@ -29,6 +29,9 @@ export const dynamic = "force-dynamic";
// delete {id, confirm?} -> {plan} | {deleted} the plan unless confirm
// tick-now {id} -> {jobId} one `report-tick` job now (409 while
// one is queued or running)
+// reset-triage {id, k?, confirm?} -> {plan} | {reset} (R6.1) discard the
+// triage runs (from k on), seen.json and the quiet editions they
+// covered; the plan unless confirm
// AN ADAPTER: every refusal and write is the controller's
// (common/controller/reportScheduleOps.ts).
export async function POST(request: Request) {
diff --git a/mcp/src/callTool.ts b/mcp/src/callTool.ts
@@ -23,6 +23,8 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { FetchClipDeps } from "./fetchClip";
+import type { ListArgs, RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta";
+import { listRecordings } from "./enumerate";
import { createServer, TOOLS } from "./server";
import { SourceRegistry } from "./sourceRegistry";
import type { ShardSource } from "./source";
@@ -69,6 +71,9 @@ export type CorpusTools = {
// Call one allowed tool; its text. A tool error is thrown as a
// CorpusToolError carrying the tool's own words.
call(name: string, args?: Record<string, unknown>): Promise<string>;
+ // R6.1: every recording in a scope, uncapped (the build's manifests), as
+ // data — what a triage's tier 0 lists the scope with. Not an agent tool.
+ listRecordings(args: ListArgs): Promise<RecordingListing>;
close(): Promise<void>;
};
@@ -179,6 +184,7 @@ export async function createCorpusTools(opts: CorpusToolsOptions): Promise<Corpu
source,
tools,
call: (name, args) => call(name, args),
+ listRecordings: async (args) => listRecordings((await registry.resolve()).source, args),
close: async () => {
await client.close();
await server.close();
diff --git a/mcp/src/enumerate.ts b/mcp/src/enumerate.ts
@@ -20,9 +20,11 @@ import {
} from "yt-dlp-transcript-common/lib/availability";
import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts";
+import type { ListArgs, ListedRecording, RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta";
import type { ChannelRef, ShardSource } from "./source";
import {
parseContentTypes,
+ resolveSelectedChannels,
searchTranscripts,
type SearchFilters,
type SearchResult,
@@ -238,6 +240,8 @@ export async function enumerate(
includeSnippets: opts.includeSnippets === true,
...(opts.snippetsPerVideo !== undefined ? { snippetsPerVideo: opts.snippetsPerVideo } : {}),
...(opts.onRecord ? { onRecord: opts.onRecord } : {}),
+ // R6.1: only these recordings — the pages holding them, nothing else.
+ ...(strArray(args.ids) ? { ids: strArray(args.ids) } : {}),
offset: 0,
// The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then
// slices, so asking for every collected match costs nothing extra.
@@ -245,3 +249,92 @@ export async function enumerate(
});
return { query, parsed, result, batchSize };
}
+
+// ─── R6.1: every recording in a scope, uncapped ───
+
+const ymd = (d: unknown): string | null => {
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim());
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+};
+
+/**
+ * Every transcript record in a scope, by id: each channel's transcripts
+ * manifest (`slugToPage` lists every record the build ships — no cap) dated
+ * and titled from the summaries index (`videoIndex`). A record the index does
+ * not know is dated from its own page (only those pages are read). With
+ * `date_from`/`date_to`, only the records in the range. Never a capped scan:
+ * a channel whose manifest does not read, a scope token no channel matches,
+ * or a record no page dates is said in `problems` and makes the listing
+ * incomplete — never "nothing there".
+ */
+export async function listRecordings(source: ShardSource, args: ListArgs): Promise<RecordingListing> {
+ const from = args.date_from ? ymd(args.date_from) : null;
+ const to = args.date_to ? ymd(args.date_to) : null;
+ const sel = await resolveSelectedChannels(source, { channels: args.channels?.length ? args.channels : undefined });
+ const problems: string[] = [];
+ const unreached = new Set<string>();
+ for (const t of sel.unknownChannels) {
+ problems.push(`no channel "${t}" in this corpus`);
+ unreached.add(t);
+ }
+ let index: Awaited<ReturnType<NonNullable<ShardSource["videoIndex"]>>> | null = null;
+ if (typeof source.videoIndex === "function") {
+ try {
+ index = await source.videoIndex();
+ } catch {
+ index = null;
+ }
+ }
+ const rows: ListedRecording[] = [];
+ const inRange = (d: string | null) => (!from || (d !== null && d >= from)) && (!to || (d !== null && d <= to));
+ for (const ch of sel.channels) {
+ let manifest;
+ try {
+ manifest = await source.transcriptsManifest(ch);
+ } catch (e) {
+ // A posts channel ships no transcripts: nothing to list, nothing missed.
+ const posts = await source.postsManifest(ch).catch(() => null);
+ if (posts) continue;
+ problems.push(`${ch.slug}: its transcripts manifest does not read (${(e as Error).message})`);
+ unreached.add(ch.name);
+ continue;
+ }
+ // The ids the index cannot date, by page: read those pages only.
+ const undated = new Map<number, string[]>();
+ for (const [id, page] of Object.entries(manifest.slugToPage)) {
+ const rec = index?.get(`${ch.slug}/${id}`);
+ if (!rec) {
+ const list = undated.get(page) ?? [];
+ list.push(id);
+ undated.set(page, list);
+ continue;
+ }
+ const date = ymd(rec.uploadDate);
+ if (inRange(date)) rows.push({ id, channel: ch.name, channelSlug: ch.slug, date, title: rec.title ?? null });
+ }
+ let lost = 0;
+ for (const [page, ids] of undated) {
+ let recs: TranscriptDetail[] | null = null;
+ try {
+ recs = await source.transcriptPage(ch, page);
+ } catch {
+ recs = null;
+ }
+ const byId = new Map((recs ?? []).map((r) => [r.id, r]));
+ for (const id of ids) {
+ const r = byId.get(id);
+ if (!r) {
+ lost++;
+ continue;
+ }
+ const date = ymd(r.uploadDate);
+ if (inRange(date)) rows.push({ id, channel: ch.name, channelSlug: ch.slug, date, title: r.title ?? null });
+ }
+ }
+ if (lost) {
+ problems.push(`${ch.slug}: ${lost} recording(s) its manifest lists could not be read or dated`);
+ unreached.add(ch.name);
+ }
+ }
+ return { rows, complete: problems.length === 0, unreached: [...unreached], problems };
+}
diff --git a/mcp/src/listRecordings.test.ts b/mcp/src/listRecordings.test.ts
@@ -0,0 +1,105 @@
+// R6.1: what a triage's tier 0 lists the scope with, and how its term query
+// is bounded. A channel of three shard pages, oldest first and the newest on
+// the last page (the order a scan reads them in): a capped scan never reaches
+// the newest — said, and parsed back as partial with what it did not reach —
+// while `listRecordings` (the manifests, dated by the summaries index or, for
+// a record the index lacks, its own page) lists every recording, and an
+// enumeration restricted to `ids` reads only the pages holding them.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { enumerateOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/trace";
+import { createCorpusTools, type CorpusTools } from "./callTool";
+import { enumerate, listRecordings, type Enumerated } from "./enumerate";
+import { LocalSource } from "./source";
+
+let dir: string;
+let corpus: CorpusTools;
+
+const rec = (id: string, date: string, lines: string[]) => ({
+ slug: `big/${id}`,
+ id,
+ channelSlug: "big",
+ channel: "Big Channel (Mirror)",
+ title: `Title ${id}`,
+ uploadDate: date,
+ webpageUrl: `https://video.example/watch?v=${id}`,
+ cues: lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })),
+});
+
+const PAGES = [
+ [rec("old-1", "20240101", ["the contest"]), rec("old-2", "20240201", ["flour"]), rec("old-3", "20240301", ["the contest again"])],
+ [rec("old-4", "20250101", ["water"]), rec("old-5", "20250201", ["the contest once more"])],
+ [rec("new-1", "20261012", ["a co-host joined the show"]), rec("new-2", "20261013", ["the contest results"])],
+];
+
+before(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), "mcp-list-"));
+ await writeFile(path.join(dir, "corpus.json"), JSON.stringify({ channels: [{ slug: "big", name: "Big Channel (Mirror)", videoCount: 7 }] }));
+ const ch = path.join(dir, "transcripts", "big");
+ await mkdir(ch, { recursive: true });
+ const slugToPage: Record<string, number> = {};
+ PAGES.forEach((p, i) => p.forEach((r) => (slugToPage[r.id] = i)));
+ await writeFile(path.join(ch, "manifest.json"), JSON.stringify({ version: 1, channelSlug: "big", pageCount: PAGES.length, maxPageBytes: 1e6, generatedAt: "2026-10-14", slugToPage }));
+ for (const [i, p] of PAGES.entries()) await writeFile(path.join(ch, `page-${String(i).padStart(4, "0")}.json`), JSON.stringify(p));
+ // The summaries index dates all but new-2 (a record it lacks is dated from its page).
+ const sum = path.join(dir, "summaries");
+ await mkdir(sum, { recursive: true });
+ const rows = PAGES.flat().filter((r) => r.id !== "new-2").map((r) => ({ slug: r.slug, id: r.id, channelSlug: "big", title: r.title, uploadDate: r.uploadDate }));
+ await writeFile(path.join(sum, "manifest.json"), JSON.stringify({ version: 3, totalCount: rows.length, pageSize: 1000, pageCount: 1, generatedAt: "2026-10-14", channels: [{ slug: "big", name: "Big Channel (Mirror)", count: 7 }] }));
+ await writeFile(path.join(sum, "page-0000.json"), JSON.stringify(rows));
+ corpus = await createCorpusTools({ source: `local:${dir}` });
+});
+
+after(async () => {
+ await corpus.close();
+ await rm(dir, { recursive: true, force: true });
+});
+
+const ok = (e: Enumerated | { error: string }): Enumerated => {
+ if ("error" in e) throw new Error(e.error);
+ return e;
+};
+
+test("a capped scan never reaches the newest: the tool says so, and its coverage parses back whole (a name with parentheses, the channel it stopped inside)", async () => {
+ const e = ok(await enumerate(new LocalSource(dir), { query: ".", regex: true, max_pages: 2 }));
+ assert.equal(e.result.truncated, true);
+ assert.deepEqual(e.result.hits.map((h) => h.videoId), ["old-1", "old-2", "old-3", "old-4", "old-5"]);
+ const text = await corpus.call("enumerate_matches", { query: ".", regex: true, max_pages: 2 });
+ const parsed = enumerateOf(text);
+ assert.equal(parsed.partial, true);
+ assert.equal(parsed.stopped, "Big Channel (Mirror) (stopped at page 2 of 3)");
+});
+
+test("listRecordings lists every recording, uncapped, dated (the index, else the record's own page); a date range; an unknown channel is said, never 'nothing'", async () => {
+ const src = new LocalSource(dir);
+ const all = await listRecordings(src, { channels: ["big"] });
+ assert.equal(all.complete, true, all.problems.join("; "));
+ assert.deepEqual(all.rows.map((r) => r.id).sort(), PAGES.flat().map((r) => r.id).sort());
+ assert.deepEqual(all.rows.find((r) => r.id === "new-2"), { id: "new-2", channel: "Big Channel (Mirror)", channelSlug: "big", date: "2026-10-13", title: "Title new-2" });
+ const recent = await listRecordings(src, { channels: ["big"], date_from: "2026-10-07" });
+ assert.deepEqual(recent.rows.map((r) => r.id).sort(), ["new-1", "new-2"]);
+ const unknown = await listRecordings(src, { channels: ["big", "nowhere"] });
+ assert.equal(unknown.complete, false);
+ assert.deepEqual(unknown.unreached, ["nowhere"]);
+ assert.match(unknown.problems[0]!, /no channel "nowhere" in this corpus/);
+ // Through the corpus tools (what the editor's triage gets).
+ const viaTools = await corpus.listRecordings({ channels: ["big"] });
+ assert.equal(viaTools.rows.length, 7);
+});
+
+test("enumerate with `ids` reads only the pages holding them — bounded, so a scan the scope would cap is complete", async () => {
+ const read: string[] = [];
+ const e = ok(await enumerate(new LocalSource(dir), { query: "contest", ids: ["new-2", "old-1", "gone-9"], max_pages: 2 }, { onRecord: (r) => read.push(r.id) }));
+ assert.equal(e.result.truncated, false);
+ assert.deepEqual(e.result.hits.map((h) => h.videoId), ["old-1", "new-2"]);
+ assert.deepEqual(read.sort(), ["new-2", "old-1"], "only the ids' records are matched");
+ assert.deepEqual(e.result.coverage.onlyIds, { asked: 3, found: 2 });
+ assert.equal(e.result.coverage.pagesPlanned, 2, "pages 0 and 2, never page 1");
+ const text = await corpus.call("enumerate_matches", { query: "contest", ids: ["new-2"] });
+ assert.match(text, /restricted to 1 recording id\(s\): 1 held by a channel in scope/);
+ assert.deepEqual(enumerateOf(text).ids, ["new-2"]);
+});
diff --git a/mcp/src/research.ts b/mcp/src/research.ts
@@ -13,6 +13,7 @@
// its fetch-window route.
export {
enumerate,
+ listRecordings,
parseSearchArgs,
strArray,
DEFAULT_BATCH_SIZE,
diff --git a/mcp/src/search.ts b/mcp/src/search.ts
@@ -273,6 +273,10 @@ export type SearchResult = {
channelsCompleted: string[];
channelsNotReached: string[];
channelStopped?: { channel: string; page: number; pages: number };
+ // R6.1: a scan restricted to given recording ids (`ids`): how many were
+ // asked for and how many a channel in scope holds. Only those ids' pages
+ // are read, so the scan is bounded by them, not by the scope.
+ onlyIds?: { asked: number; found: number };
};
// How the scope selector resolved (for the tool's scope note): whether it was
// whole-corpus, the channels/groups it matched, and any tokens that matched
@@ -347,6 +351,8 @@ export type ScanPlan = {
// included unconditionally; a non-zero count here is why a "pruned" scan may
// still read more than the filter suggests.
unknownVideos: number;
+ // With `onlyIds`: how many of them a manifest in scope holds.
+ idsFound?: number;
};
// Build the page plan for a scan. Falls back to "every page of every channel"
@@ -357,11 +363,14 @@ export async function buildScanPlan(
source: ShardSource,
channels: readonly ChannelRef[],
filters: SearchFilters | null | undefined,
+ // R6.1: only these recording ids — the pages that hold them, nothing else.
+ onlyIds?: ReadonlySet<string> | null,
): Promise<ScanPlan> {
const perChannel = new Map<string, { ch: ChannelRef; pages: number[] }>();
let pagesTotal = 0;
let pagesPlanned = 0;
let unknownVideos = 0;
+ let idsFound = 0;
const wantPrune = filterIsSelective(filters) && typeof source.videoIndex === "function";
const index = wantPrune ? await source.videoIndex!() : null;
@@ -376,6 +385,21 @@ export async function buildScanPlan(
const pageCount = manifest.pageCount;
pagesTotal += pageCount;
+ if (onlyIds) {
+ // The pages holding the ids asked for: the record predicate still decides.
+ const keep = new Set<number>();
+ for (const id of onlyIds) {
+ const page = manifest.slugToPage[id];
+ if (page === undefined) continue;
+ idsFound++;
+ keep.add(page);
+ }
+ const pages = [...keep].sort((a, b) => a - b);
+ perChannel.set(ch.key, { ch, pages });
+ pagesPlanned += pages.length;
+ continue;
+ }
+
if (!index || !filters) {
const pages = Array.from({ length: pageCount }, (_, i) => i);
perChannel.set(ch.key, { ch, pages });
@@ -403,10 +427,11 @@ export async function buildScanPlan(
return {
perChannel,
- pruned: Boolean(index),
+ pruned: Boolean(index) || Boolean(onlyIds),
pagesPlanned,
pagesTotal,
unknownVideos,
+ ...(onlyIds ? { idsFound } : {}),
};
}
@@ -491,6 +516,9 @@ export async function searchTranscripts(
// about it for free (umtool counts transcripts vs captions per channel).
// Changes nothing about what matches.
onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void;
+ // R6.1: only these recordings (their ids). The scan reads the pages that
+ // hold them and nothing else, so it is bounded by the ids, not the scope.
+ ids?: readonly string[];
},
): Promise<SearchResult> {
const policy = opts.policy ?? MCP_POLICY;
@@ -580,8 +608,9 @@ export async function searchTranscripts(
const filters = opts.filters ?? null;
const availability =
wantVideos && needsAvailability(filters) ? await source.availabilityMap() : null;
+ const onlyIds = opts.ids?.length ? new Set(opts.ids) : null;
const plan = wantVideos
- ? await buildScanPlan(source, channels, filters)
+ ? await buildScanPlan(source, channels, filters, onlyIds)
: null;
const concurrency = concurrencyOf(source);
const channelsCompleted: string[] = [];
@@ -608,6 +637,7 @@ export async function searchTranscripts(
if (records === null) continue; // failed page — skipped, as before
pagesScanned++;
for (const rec of records) {
+ if (onlyIds && !onlyIds.has(rec.id)) continue;
opts.onRecord?.(rec, ch);
if (
filters &&
@@ -732,7 +762,11 @@ export async function searchTranscripts(
}
if (!pm) continue; // not a social channel
postChannelsScanned++;
- for (let page = 0; page < pm.pageCount; page++) {
+ // With ids: only the pages that hold them.
+ const postPages = onlyIds
+ ? [...new Set([...onlyIds].map((id) => pm.slugToPage?.[id]).filter((p): p is number => typeof p === "number"))].sort((a, b) => a - b)
+ : Array.from({ length: pm.pageCount }, (_, i) => i);
+ for (const page of postPages) {
if (pagesScanned >= maxPages) {
truncated = true;
break postsOuter;
@@ -746,6 +780,7 @@ export async function searchTranscripts(
pagesScanned++;
postPagesScanned++;
for (const post of posts) {
+ if (onlyIds && !onlyIds.has(post.id)) continue;
if (!match(post.text)) continue;
if (isExcluded("", [{ text: post.text }])) continue;
all.push({
@@ -820,6 +855,7 @@ export async function searchTranscripts(
channelsCompleted,
channelsNotReached: planned.filter((n) => !reached.has(n)),
...(channelStopped ? { channelStopped } : {}),
+ ...(onlyIds ? { onlyIds: { asked: onlyIds.size, found: plan?.idsFound ?? 0 } } : {}),
},
selection: {
all: selection.all,
diff --git a/mcp/src/server.ts b/mcp/src/server.ts
@@ -579,6 +579,14 @@ export const TOOLS: Tool[] = [
"Max shard pages to scan before stopping (default 400). Reaching " +
"it makes coverage partial, which is reported loudly.",
},
+ ids: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Optional recording ids to restrict the scan to: only the pages " +
+ "holding them are read, so the scan is bounded by the ids rather " +
+ "than the scope. The footer says how many of them the scope holds.",
+ },
},
required: ["query"],
additionalProperties: false,
@@ -1806,6 +1814,9 @@ async function handleEnumerateMatches(
const tagNote = await describeTagCoverage(source, parsed);
const prunedNote = describeCoverage(result);
const dupNote = describeDuplicates(result);
+ const idsNote = result.coverage.onlyIds
+ ? `restricted to ${result.coverage.onlyIds.asked} recording id(s): ${result.coverage.onlyIds.found} held by a channel in scope`
+ : "";
const footer =
`\n\n(complete set: ${partial ? "NO — capped" : "yes"}; ` +
@@ -1814,6 +1825,7 @@ async function handleEnumerateMatches(
`${result.scanned.channels} channel(s)` +
(prunedNote ? `; ${prunedNote}` : "") +
(dupNote ? `; ${dupNote}` : "") +
+ (idsNote ? `; ${idsNote}` : "") +
(scopeNote ? `; ${scopeNote}` : "") +
(filterNote ? `; ${filterNote}` : "") +
(postsNote ? `; ${postsNote}` : "") +
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -118,6 +118,7 @@
// 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}'
+// pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -426,8 +427,9 @@ 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. R6: a
- // watch (no article until a triage finds something), and triageFirst.
+ // resume | delete | tick-now | reset-triage, …}); tick-now is a
+ // report-tick job. R6: a watch (no article until a triage finds something),
+ // and triageFirst. R6.1: reset-triage discards a schedule's triage state.
"report-schedule",
];
@@ -1269,17 +1271,20 @@ export function usage() {
" 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.",
+ " recordings: an enumeration reads only their pages and 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",
+ " platform held or cooling down is skipped; transcribe-bucket is skipped,",
+ " and said, while transcription is paused or no worker is enabled), 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 — or partial, naming what a capped search did not reach.",
+ " 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,",
@@ -1317,7 +1322,7 @@ export function usage() {
"",
'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",',
+ ' "tick-now" | "reset-triage", …}. 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"?',
@@ -1337,6 +1342,12 @@ export function usage() {
' is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued',
' or running); --wait prints the tick\'s @@report-tick {json}. list {"id"?}',
' answers the schedules with their chip, call and spend, and the lane.',
+ ' A tick whose scan hit a cap (or did not reach a channel) and found',
+ ' nothing ends partial, naming what it did not reach — never quiet.',
+ ' reset-triage {"id", "k"?, "confirm"?} discards a schedule\'s triage state',
+ ' (its runs from run k on, default all; seen.json, so the next run counts',
+ ' new from its since; the quiet editions they covered): the plan unless',
+ ' confirm is true; refused while a tick runs.',
"",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",