commit c143aa6f85f72b206f41e60aeb8f8cc1506a6fc2
parent 1ba3a0dbe960b8796ea07a330dfd0e850734ef21
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 14:17:43 -0400
Merge main (R4 live, 27f2c61e) into ux/r5
Conflicts: the Inbox's kinds and ranks (R4's refresh-held/refresh-available
beside R5's tick-failed/tick-held/edition-ready), lib/inbox.ts's disk
decisions (both), umtool.mjs's tsx commands (one helper for inbox, schedule
and refresh), the CHANGELOG (both), the plan (main's, R5's records after
R4's, one status row per phase: R4 LIVE, R5 shipped on the branch).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
55 files changed, 5149 insertions(+), 117 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,7 +145,7 @@ 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. | `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}'` |
+| `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}'` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'` |
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -31,6 +31,14 @@
// autonomy a research run's: propose | limits | auto (default:
// settings.generation.research.autonomy; the limits are the
// settings')
+// ids a sweep restricted to these recordings (umtool R4; kept in its
+// scope): an enumeration shows only them, a read of another is
+// refused
+//
+// task "refresh" (umtool R4, ./reportRefresh.ts): re-fetch, see what changed,
+// update — `iteration` (default: the current report's), `model`,
+// `extractorModel`, `maxUsd`; `fetch: false` skips the fetch and the build;
+// `dryRun: true` answers the plan and writes nothing.
//
// The iteration is created `queued` before the job, and the job's id set on it;
// the job runs the S5 task in process. Its queue is the model's provider's:
@@ -103,6 +111,9 @@ export const REPORT_DRAFT_BODY_KEYS = [
"force",
"autonomy",
"seed",
+ "ids",
+ "fetch",
+ "dryRun",
] as const;
// A seed's size: a board of a few hundred quotes, with room.
@@ -110,8 +121,13 @@ export const SEED_MAX_CHARS = 200_000;
export class ReportDraftInputError extends Error {}
+// A refresh (umtool R4) is a report-draft task with no route of its own: its
+// update runs on the sweep route's model.
+export const REFRESH_TASK = "refresh" as const;
+export type ReportDraftTask = GenerationTask | typeof REFRESH_TASK;
+
export type ReportDraftBody = {
- task: GenerationTask;
+ task: ReportDraftTask;
article: string;
iteration?: number;
model?: string;
@@ -130,6 +146,9 @@ export type ReportDraftBody = {
force?: boolean;
autonomy?: Autonomy;
seed?: string;
+ ids?: string[];
+ fetch?: boolean;
+ dryRun?: boolean;
};
// A Claude model the price table knows: one of its ids, or a dated id of one
@@ -138,7 +157,7 @@ export function isKnownApiModel(model: string): boolean {
return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`));
}
-const TASKS: readonly GenerationTask[] = GENERATION_TASKS;
+const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -148,7 +167,7 @@ function fail(msg: string): never {
// The body, judged without touching the disk.
export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBody {
const task = b.task;
- if (typeof task !== "string" || !TASKS.includes(task as GenerationTask)) fail(`"task" is one of ${TASKS.join(", ")}`);
+ if (typeof task !== "string" || !TASKS.includes(task as ReportDraftTask)) fail(`"task" is one of ${TASKS.join(", ")}`);
const article = b.article;
if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)');
const int = (k: string) => {
@@ -170,7 +189,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`);
return (arr as string[]).map((x) => x.trim());
};
- const out: ReportDraftBody = { task: task as GenerationTask, article: article as string };
+ const out: ReportDraftBody = { task: task as ReportDraftTask, article: article as string };
const set = <K extends keyof ReportDraftBody>(k: K, v: ReportDraftBody[K] | undefined) => {
if (v !== undefined) out[k] = v;
};
@@ -182,7 +201,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (!isKnownApiModel(extractor)) {
fail(`"extractorModel" is a Claude model id (${Object.keys(PRICES).filter((m) => m.startsWith("claude-")).join(", ")}): an API sweep's extractor runs on the API`);
}
- if (task !== "sweep") fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)');
+ if (task !== "sweep" && task !== REFRESH_TASK) fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)');
out.extractorModel = extractor;
}
set("feedback", text("feedback"));
@@ -216,6 +235,23 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (out.task !== "sweep" || out.iteration !== undefined || out.copyOf !== undefined) fail('"seed" starts a new sweep: no "iteration", no "copyOf"');
out.seed = b.seed;
}
+ for (const k of ["fetch", "dryRun"] as const) {
+ if (b[k] === undefined || b[k] === null) continue;
+ if (typeof b[k] !== "boolean") fail(`"${k}" is true or false`);
+ if (out.task !== REFRESH_TASK) fail(`"${k}" is a refresh's`);
+ out[k] = b[k] as boolean;
+ }
+ const ids = list("ids");
+ if (ids !== undefined) {
+ if (out.task !== "sweep") fail('"ids" is a sweep\'s: the recordings it is restricted to');
+ if (!ids.length) fail('"ids" names at least one recording');
+ if (ids.length > 2000) fail('"ids" is at most 2,000 recordings');
+ out.ids = [...new Set(ids)];
+ }
+ if (out.task === REFRESH_TASK) {
+ const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined);
+ if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`);
+ }
if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>');
if (out.source && out.build) fail('give "source" or "build", not both');
// What each task needs.
@@ -288,6 +324,12 @@ export function llmConfigOf(gen: GenerationSettings, paths: Pick<Paths, "ollamaU
export type ReportDraftDeps = {
paths: Paths;
+ // A refresh's editor (umtool R4): its ops actions in process — sync,
+ // fetch-posts, refresh-report, transcribe-bucket, publish (the editor's
+ // route passes itself). Without it a refresh is refused.
+ refreshEditor?: ResearchEditor;
+ // A refresh's polling and waits (the tests shorten them).
+ refreshTiming?: { pollMs?: number; waitMs?: number; sleep?: (ms: number, signal?: AbortSignal) => Promise<void> };
// The MCP's corpus tools over a source handle (mcp/src/callTool.ts).
corpusTools: (source: string) => Promise<CorpusToolsLike & { close(): Promise<void> }>;
settings?: () => { generation: GenerationSettings };
@@ -343,6 +385,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return { result: { ok: false, error: (e as Error).message } };
}
const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ if (body.task === REFRESH_TASK) {
+ if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)');
+ try {
+ const { enqueueRefresh } = await import("./reportRefresh");
+ return await enqueueRefresh(body, deps);
+ } catch (e) {
+ return refuse((e as Error).message);
+ }
+ }
try {
// The model, and from it the lane; the copy's source tells a copy's kind.
const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null;
@@ -409,7 +460,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
model,
parent: cont.research.n,
question: cont.question,
- scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}) },
+ scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) },
},
paths,
)
@@ -422,7 +473,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
kind: kindOf(body.task),
model,
...(body.task === "sweep" || body.task === "research"
- ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }
+ ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}) } }
: { parent: body.iteration!, feedback: body.feedback }),
},
paths,
@@ -534,6 +585,9 @@ async function runReportDraft(
const extractor = body.extractorModel ?? gen.models.extractor;
let input: TaskInput;
switch (body.task) {
+ case "refresh":
+ // A refresh is its own job (./reportRefresh.ts), never this one.
+ throw new Error("a refresh runs as its own job");
case "sweep":
input =
provider === "api"
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -0,0 +1,527 @@
+// `report-draft {"task": "refresh", "article", "iteration"?}` — re-fetch, see
+// what changed, update (umtool R4; plans/umtool-redesign.md "R4 — Refresh").
+// The task is draft/refresh/task.ts; this is the editor's side of it:
+//
+// planRefresh what a refresh would do, nothing written (the ops route's
+// `dryRun: true`; umtool's plan-then-confirm): the iteration
+// refreshed and what it was built from, each channel's
+// actions (or why one is skipped), the site built, the
+// model and the cap
+// enqueueRefresh the `refresh` iteration (queued, its parent the one
+// refreshed), then ONE `report-draft` job on its own lane
+// (`draft:refresh`: it waits on fetches and a build before
+// any model runs, so it never holds `draft:api`)
+// the job the task over the editor's own hooks: its ops actions in
+// process (the research run's door), its job registry, its
+// channels, the platform holds, the builds, the disk's
+// records, and the caps. The log ends `@@report-draft {…,
+// refresh: {status, newIds, changed, drifted, deleted,
+// summary}}`.
+//
+// The iteration refreshed: `iteration` when given, else the current report's
+// (current.json), else the newest done iteration that carries a report.
+
+import { access, readdir, readFile } from "node:fs/promises";
+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 { DRAFT_REFRESH_QUEUE } from "../lib/queueKeys";
+import { getSettings } from "../lib/settings";
+import { capFor, type GenerationSettings } from "../lib/generationSettings";
+import { PROJECT_URL } from "../lib/project";
+import { providerOf, unloadOllama } from "../lib/llm";
+import { webTools } from "../lib/web/tools";
+import { stateFromAvailability } from "../lib/availability";
+import { resolveEffectiveAvailability } from "../lib/availability-server";
+import { resolveVideoDir } from "../lib/videoDir-server.mjs";
+import { detectPlatform } from "../lib/detectPlatform.mjs";
+import { WHISPER_FILENAME, englishVttsByPreference } from "../lib/videoStatus";
+import { parseVtt } from "../lib/vtt";
+import { parseTranscriptJson } from "../lib/whisper";
+import { isCuesJsonFresh, readNormalizedTranscript } from "./normalizeTranscript";
+import { diskPostChannelOf } from "../lib/report/convert-server";
+import { readAllPosts } from "../lib/posts-server";
+import {
+ createIteration,
+ currentIteration,
+ listIterations,
+ readIteration,
+ readIterationFile,
+ updateIteration,
+} from "../lib/report/iterations";
+import { listCorpusBuilds, pickCorpusBuild, siteOriginOf, type CorpusBuild } from "../lib/report/draft/tasks/corpusSource";
+import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
+import type { CorpusToolsLike, TaskDeps } from "../lib/report/draft/tasks/types";
+import { refresh as refreshTask, type RefreshHooks } from "../lib/report/draft/refresh/task";
+import { fetchAndBuild, type FetchAndBuild, type FetchHooks } from "../lib/report/draft/refresh/fetch";
+import { NothingToRefreshError, refreshBasis } from "../lib/report/draft/refresh/basis";
+import type { RecordRead } from "../lib/report/draft/refresh/delta";
+import { DEFAULT_REVISION_USD, DEFAULT_USD_PER_RECORDING } from "../lib/report/draft/refresh/task";
+import { REFRESH_FORMAT, outcomeOf, type RefreshFile, type RefreshPlan, type RefreshPlanChannel } from "../lib/report/draft/refresh/types";
+import type { ResearchEditor } from "../lib/report/draft/research/tools";
+import { verifyReportQuotes } from "../bin/reports-check";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { listChannelConfigs, readChannelSnapshot } from "./channels";
+import { jobOfPaths } from "./researchRuns";
+import {
+ REPORT_DRAFT_JOB_KIND,
+ REPORT_DRAFT_RESULT_MARKER,
+ llmConfigOf,
+ type ReportDraftBody,
+ type ReportDraftDeps,
+ type ReportDraftEnqueued,
+} from "./reportDraft";
+
+// The editor actions a refresh runs (its in-process door must offer them).
+export const REFRESH_EDITOR_ACTIONS = ["sync", "fetch-posts", "refresh-report", "transcribe-bucket", "publish"] as const;
+
+export class RefreshInputError extends Error {}
+
+// ─── which iteration ───
+
+/** The iteration a refresh of `article` refreshes: the one asked, else the current report's, else the newest done one with a report. */
+export async function refreshTarget(article: string, asked: number | undefined, paths: ReportDraftDeps["paths"]): Promise<number> {
+ if (asked !== undefined) {
+ const it = await readIteration(article, asked, paths);
+ if (!it) throw new RefreshInputError(`"${article}" has no iteration i${asked}`);
+ if (it.status !== "done") throw new RefreshInputError(`"${article}" i${asked} is ${it.status}: only a done iteration is refreshed`);
+ return asked;
+ }
+ const cur = await currentIteration(article, paths).catch(() => null);
+ if (cur?.report != null) return cur.report;
+ const its = (await listIterations(article, paths).catch(() => [])).filter((i) => i.status === "done").sort((a, b) => b.n - a.n);
+ for (const it of its) {
+ if ((await readIterationFile(article, it.n, "report.json", paths)) !== null) return it.n;
+ }
+ throw new RefreshInputError(`"${article}" has no report to refresh: no iteration is current and none that is done carries a report`);
+}
+
+// The model and cap an update runs on: the asked model, else the sweep
+// route's (a sweep routed to Claude Code runs the API model here — said so).
+export function refreshModel(gen: GenerationSettings, body: Pick<ReportDraftBody, "model" | "maxUsd" | "extractorModel">): { model: string; provider: "api" | "local"; capUsd: number | null; extractor: string; note?: string } {
+ const route = gen.routes.sweep;
+ const model = body.model ?? (route === "local" ? gen.models.local : gen.models.api);
+ const provider = providerOf(model) === "local" ? "local" : "api";
+ return {
+ model,
+ provider,
+ capUsd: provider === "api" ? capFor(gen.caps, "sweep", body.maxUsd) : null,
+ extractor: body.extractorModel ?? gen.models.extractor,
+ ...(!body.model && route === "code" ? { note: "sweeps are routed to Claude Code: the update runs the API model here" } : {}),
+ };
+}
+
+// ─── the builds and the corpus ───
+
+// The composed build a handle names (`local:<exportBuildsDir>/<id>/out`), or null.
+function buildOfSource(source: string | null, builds: CorpusBuild[]): CorpusBuild | null {
+ if (!source?.startsWith("local:")) return null;
+ const dir = path.resolve(source.slice("local:".length));
+ return builds.find((b) => path.resolve(b.dir) === dir) ?? null;
+}
+
+/** The build a refresh reads and rebuilds: the parent's own when it still holds the channels, else the newest that holds them all. */
+export async function refreshBuild(channels: string[], prefer: string | null, paths: Pick<ReportDraftDeps["paths"], "exportBuildsDir">): Promise<CorpusBuild | null> {
+ const builds = await listCorpusBuilds(paths.exportBuildsDir);
+ const mine = buildOfSource(prefer, builds);
+ if (mine && channels.every((c) => mine.channels.includes(c))) return mine;
+ return pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir }).catch(() => mine);
+}
+
+const exists = (p: string) => access(p).then(() => true, () => false);
+
+// ─── the plan ───
+
+export async function planRefresh(body: ReportDraftBody, deps: ReportDraftDeps): Promise<RefreshPlan> {
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const n = await refreshTarget(body.article, body.iteration, paths);
+ const it = (await readIteration(body.article, n, paths))!;
+ const basis = await refreshBasis(body.article, n, paths).catch((e: Error) => {
+ throw new RefreshInputError(e.message);
+ });
+ const refusals: string[] = [];
+ const warnings: string[] = [];
+ const fetch = body.fetch !== false;
+ const configs = new Map((await listChannelConfigs(paths).catch(() => [])).map((c) => [c.slug, c.config as Record<string, unknown>]));
+ const channels: RefreshPlanChannel[] = [];
+ for (const slug of basis.scope.channels) {
+ const c = configs.get(slug);
+ if (!c) {
+ channels.push({ slug, kind: null, platform: null, actions: [], skip: "not a channel of this editor" });
+ continue;
+ }
+ const kind = isPostsChannel(c) ? "posts" : "video";
+ const platform = platformOfConfig(c);
+ const skip = fetch && platform ? await platformRefusalOf(platform, paths) : null;
+ channels.push({
+ slug,
+ kind,
+ platform,
+ actions: !fetch ? [] : kind === "posts" ? ["fetch-posts"] : ["sync", "refresh-report", "transcribe-bucket (what lands)"],
+ ...(skip ? { skip } : {}),
+ });
+ }
+ const build = await refreshBuild(basis.scope.channels, basis.source, paths);
+ let site: RefreshPlan["build"] = { site: null, reason: "no composed build holds these channels" };
+ if (build) {
+ site = (await exists(path.join(paths.sitesDir, build.build, "site.json")))
+ ? { site: build.build, builtAt: new Date(build.mtimeMs).toISOString() }
+ : { site: null, reason: `the build ${build.build} is not a site's: it is read as it stands`, builtAt: new Date(build.mtimeMs).toISOString() };
+ } else {
+ refusals.push(`no composed build holds ${basis.scope.channels.join(", ")} — publish build the site that carries them first`);
+ }
+ if (!fetch) site = { site: null, reason: "no fetch: the corpus is read as it stands", ...(build ? { builtAt: new Date(build.mtimeMs).toISOString() } : {}) };
+ const m = refreshModel(gen, body);
+ if (m.note) warnings.push(m.note);
+ if (basis.from === "question") warnings.push(`i${n} recorded no enumeration: its question is searched again as one query`);
+ if (!basis.countsKnown) warnings.push(`changed recordings are not tracked before ${basis.at.slice(0, 10)}: i${n} recorded no matching-line counts (new ones are still found)`);
+ if (!basis.knownComplete) warnings.push(`i${n} kept no whole match set: a recording counts as new only when it was uploaded on or after ${basis.at.slice(0, 10)}`);
+ const parentIt = basis.queriesOf === n ? it : await readIteration(body.article, basis.queriesOf, paths).catch(() => null);
+ const parentUsd = parentIt ? Object.values(parentIt.usage).reduce((s, u) => s + u.usd, 0) : 0;
+ const read = parentIt?.coverage?.read ?? 0;
+ const day = m.provider === "api" ? await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())).catch(() => null) : null;
+ return {
+ article: body.article,
+ parent: {
+ n,
+ kind: it.kind,
+ model: it.model,
+ question: basis.question,
+ at: basis.at,
+ from: basis.from,
+ queries: basis.queries.map((q) => q.query),
+ knownCount: Object.keys(basis.known).length,
+ knownComplete: basis.knownComplete,
+ citedCount: basis.cited.length,
+ },
+ scope: basis.scope,
+ fetch,
+ channels,
+ build: site,
+ corpus: { source: build ? `local:${build.dir}` : null, build: build?.build ?? null },
+ model: m.model,
+ provider: m.provider,
+ extractor: m.provider === "api" ? m.extractor : null,
+ capUsd: m.capUsd,
+ daily: day ? { usd: day.usd, cap: gen.caps.daily } : null,
+ estimate: parentUsd > 0 && read > 0 ? { perRecordingUsd: Math.round((parentUsd / read) * 1000) / 1000, revisionUsd: DEFAULT_REVISION_USD, from: "parent" } : { perRecordingUsd: DEFAULT_USD_PER_RECORDING, revisionUsd: DEFAULT_REVISION_USD, from: "default" },
+ refusals,
+ warnings,
+ };
+}
+
+// A social channel's posts are fetched (fetch-posts); a video channel is synced.
+const isPostsChannel = (c: Record<string, unknown>) => c.sourceKind === "social" || (typeof c.postFetcher === "string" && !!c.postFetcher);
+// The platform a channel's fetches are paced (and held) under: its config's, else its URL's.
+const platformOfConfig = (c: Record<string, unknown>): string | null =>
+ typeof c.platform === "string" && c.platform ? c.platform : detectPlatform(typeof c.url === "string" ? c.url : null);
+
+// Why a fetch on `platform` is refused now: held (its probe still ahead), or cooling down.
+async function platformRefusalOf(platform: string, paths: ReportDraftDeps["paths"]): Promise<string | null> {
+ const held = await heldPlatformRefusal(platform, "A refresh's fetch", paths).catch(() => null);
+ if (held) return held;
+ const ms = await platformCooldownRemainingMs(platform, paths).catch(() => 0);
+ return ms > 0 ? `${platform} is cooling down after a rate limit (${Math.max(1, Math.ceil(ms / 60_000))} min left): skipped, as polite scraping asks` : null;
+}
+
+// ─── enqueue ───
+
+export async function enqueueRefresh(body: ReportDraftBody, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
+ const refuse = (error: string) => ({ result: { ok: false as const, error } });
+ const paths = deps.paths;
+ if (!deps.refreshEditor) return refuse("a refresh runs in the editor (its fetches and build are the editor's own actions)");
+ const gen = (deps.settings ?? getSettings)().generation;
+ let n: number;
+ let plan: RefreshPlan;
+ try {
+ n = await refreshTarget(body.article, body.iteration, paths);
+ plan = await planRefresh({ ...body, iteration: n }, deps);
+ } catch (e) {
+ if (e instanceof RefreshInputError || e instanceof NothingToRefreshError) return refuse(e.message);
+ throw e;
+ }
+ if (plan.refusals.length) return refuse(plan.refusals.join("; "));
+ const m = refreshModel(gen, body);
+ const parent = (await readIteration(body.article, n, paths))!;
+ const it = await createIteration(
+ body.article,
+ {
+ kind: "refresh",
+ model: m.model,
+ parent: n,
+ ...(plan.parent.question ? { question: plan.parent.question } : parent.question ? { question: parent.question } : {}),
+ scope: plan.scope,
+ },
+ paths,
+ );
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: DRAFT_REFRESH_QUEUE,
+ paths,
+ fn: (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps),
+ });
+ if (!result.ok) {
+ await updateIteration(body.article, it.n, { status: "failed", error: result.error }, paths).catch(() => {});
+ return { result };
+ }
+ await updateIteration(body.article, it.n, { jobId: result.jobId }, paths).catch(() => {});
+ void result.done.then(async (d) => {
+ const cur = await readIteration(body.article, it.n, paths).catch(() => null);
+ if (cur?.status === "queued") {
+ await updateIteration(body.article, it.n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {});
+ }
+ });
+ return { result, iteration: it.n, ...(plan.warnings.length ? { warnings: plan.warnings } : {}) };
+}
+
+// ─── stage 1 on its own (R5's seam) ───
+
+/** 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;
+ if (!deps.refreshEditor) throw new RefreshInputError("a refresh's fetch runs in the editor (its own actions): no refreshEditor");
+ const configs = async () => new Map((await listChannelConfigs(paths).catch(() => [])).map((c) => [c.slug, c.config as Record<string, unknown>]));
+ return {
+ editor: deps.refreshEditor,
+ jobOf: deps.jobOf ?? jobOfPaths(paths),
+ channelOf: async (slug) => {
+ const c = (await configs()).get(slug);
+ if (!c) return null;
+ const platform = platformOfConfig(c);
+ return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}) };
+ },
+ platformRefusal: (platform) => platformRefusalOf(platform, paths),
+ bucketOf: async (slug) => {
+ const snap = await readChannelSnapshot(paths, slug).catch(() => null);
+ return snap ? [...(snap.buckets.downloadedNoTranscript ?? [])] : null;
+ },
+ siteOf: async (channels, prefer) => {
+ const b = await refreshBuild(channels, prefer, paths);
+ if (!b) return { site: null, reason: `no composed build holds ${channels.join(", ")}` };
+ if (!(await exists(path.join(paths.sitesDir, b.build, "site.json")))) return { site: null, reason: `the build ${b.build} is not a site's: it is read as it stands` };
+ return { site: b.build };
+ },
+ builtAt: async (channels, prefer) => {
+ const b = await refreshBuild(channels, prefer, paths);
+ return b ? b.mtimeMs : null;
+ },
+ ...(deps.refreshTiming ?? {}),
+ };
+}
+
+/**
+ * R5's SEAM — a refresh's stage 1 for any scope, awaited: each channel's
+ * fetches (sync → refresh-report → transcribe-bucket for what landed; or
+ * fetch-posts), a held or cooling platform skipped and said, then the local
+ * build of the site whose build holds the channels (never a deploy). Answers
+ * what was fetched, built or refused. `deps.refreshEditor` is the editor's
+ * in-process door (editor/app/api/ops/_researchEditor.ts refreshEditor).
+ */
+export function fetchScope(
+ scope: { channels: string[]; from?: string; to?: string },
+ deps: ReportDraftDeps,
+ o: { prefer?: string | null; signal?: AbortSignal; log?: (line: string) => void; build?: boolean } = {},
+): Promise<FetchAndBuild> {
+ return fetchAndBuild(scope, fetchHooksOf(deps), o);
+}
+
+// ─── the job ───
+
+// The corpus a refresh reads: opened after its build (deps.corpus is this
+// holder; a call before it is open is refused).
+class CorpusHolder implements CorpusToolsLike {
+ current: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
+ get source() {
+ return this.current?.source ?? "";
+ }
+ get tools() {
+ return this.current?.tools ?? [];
+ }
+ call(name: string, args?: Record<string, unknown>): Promise<string> {
+ if (!this.current) return Promise.reject(new Error("the corpus is not open yet"));
+ return this.current.call(name, args);
+ }
+ async swap(next: CorpusToolsLike & { close(): Promise<void> }) {
+ const was = this.current;
+ this.current = next;
+ await was?.close().catch(() => {});
+ }
+}
+
+async function runRefreshJob(
+ o: {
+ body: ReportDraftBody;
+ n: number;
+ model: string;
+ capUsd: number | null;
+ extractor: string;
+ jobId: string;
+ onLog: (l: string) => void;
+ signal: AbortSignal;
+ setProgress?: (snap: JobProgress) => void;
+ },
+ deps: ReportDraftDeps,
+): Promise<void> {
+ const { body, n, model, onLog, signal } = o;
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const provider = providerOf(model);
+ onLog(`refresh of ${body.article} (i${n}) — the update on ${model} (${provider === "api" ? `the Claude API, cap $${o.capUsd}` : "the local model"})`);
+ const holder = new CorpusHolder();
+ const fallback = gen.citationOrigin || PROJECT_URL;
+ const disk = paths.channelsDir;
+ const posts = new Map<string, Promise<Map<string, string>>>();
+ const postText = (ch: string, id: string) => {
+ let p = posts.get(ch);
+ if (!p) {
+ p = readAllPosts(path.join(disk, ch)).then((all) => new Map(all.map((x) => [x.id, x.text])), () => new Map());
+ posts.set(ch, p);
+ }
+ return p.then((m) => m.get(id) ?? null);
+ };
+ const cuesOf = corpusCuesOf(holder);
+ const hooks: RefreshHooks = {
+ ...fetchHooksOf(deps),
+ openCorpus: async (channels, prefer) => {
+ const b = body.source ? null : body.build ? (await listCorpusBuilds(paths.exportBuildsDir)).find((x) => x.build === body.build) ?? null : await refreshBuild(channels, prefer, paths);
+ const source = body.source ?? (b ? `local:${b.dir}` : null);
+ if (!source) throw new Error(`no composed build holds ${channels.join(", ")} — publish build the site that carries them`);
+ const missing = b ? channels.filter((c) => !b.channels.includes(c)) : [];
+ if (missing.length) onLog(`the build ${b!.build} does not hold ${missing.join(", ")}: those are not searched`);
+ await holder.swap(await deps.corpusTools(source));
+ const origin = b ? ((await siteOriginOf(b.build, paths.sitesDir)) ?? fallback) : fallback;
+ return { source, origin, ...(b ? { build: b.build } : {}) };
+ },
+ recordOf: async (channel, id) => {
+ const rec = await diskRecordOf(disk, channel, id).catch(() => null);
+ if (rec) return rec;
+ const cues = await cuesOf(channel, id);
+ return cues ? { cues } : null;
+ },
+ capRefusal: async (usd) => {
+ if (provider !== "api") return null;
+ if (o.capUsd !== null && usd > o.capUsd) {
+ return `the update would cost about $${usd.toFixed(2)}, over this job's $${o.capUsd.toFixed(2)} cap (settings.generation.caps.sweep; maxUsd raises it, up to caps.max)`;
+ }
+ const day = await dayUsage(paths.generationUsageFile, utcDay(deps.now?.()));
+ const refused = dailyCapRefusal(day, gen.caps.daily);
+ if (refused) return refused;
+ if (gen.caps.daily > 0 && day.usd + usd > gen.caps.daily) {
+ return `the day's Claude API spend is $${day.usd.toFixed(2)} (${day.day}, UTC): about $${usd.toFixed(2)} more would pass the $${gen.caps.daily.toFixed(2)} daily cap (settings.generation.caps.daily)`;
+ }
+ return null;
+ },
+ };
+ const taskDeps: TaskDeps = {
+ llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined),
+ corpus: holder,
+ web: webTools({ ...(gen.web.searchUrl ? { searchUrl: gen.web.searchUrl } : {}) }),
+ cuesOf,
+ postTextOf: postText,
+ postChannelOf: diskPostChannelOf(disk),
+ verifyReport: async (report) =>
+ (await verifyReportQuotes(report, { paths }).catch(() => []))
+ .filter((r) => r.status === "drift" || r.status === "en-orig-drift")
+ .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })),
+ paths,
+ log: onLog,
+ progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }),
+ signal,
+ refresh: hooks,
+ ...(deps.now ? { now: deps.now } : {}),
+ };
+ let result: Awaited<ReturnType<typeof refreshTask>> | null = null;
+ try {
+ result = await refreshTask(
+ { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, ...(body.fetch === false ? { fetch: false } : {}) },
+ taskDeps,
+ );
+ } catch (e) {
+ const cur = await readIteration(body.article, n, paths).catch(() => null);
+ if (cur && (cur.status === "queued" || cur.status === "running")) {
+ await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {});
+ }
+ throw e;
+ } finally {
+ await holder.current?.close().catch(() => {});
+ if (provider === "local") {
+ await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ if (provider === "api" && result) await recordUsage(body.article, n, o.jobId, paths, deps.now?.() ?? new Date()).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ const file = await readRefreshFile(body.article, n, paths);
+ const refresh = file ? outcomeOf(file) : null;
+ onLog(
+ `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: n, task: "refresh", status: result.status, summary: result.summary, usd: result.usd, minutes: result.minutes, ...(refresh ? { refresh } : {}) })}`,
+ );
+ if (result.status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (result.status === "failed") throw new Error(result.summary);
+}
+
+// A cited recording on disk, as a refresh reads it: every transcript track it
+// has (the normalized cues, our transcription, each English caption track,
+// en-orig first) and its platform state when it is not available; null when the
+// archive holds no directory for it. (publish/composeReports' readCitedRecord
+// reads the same files; a controller may not import publish.)
+export async function diskRecordOf(channelsDir: string, slug: string, id: string): Promise<RecordRead | null> {
+ const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null);
+ if (!dir) return null;
+ const entries = await readdir(dir).catch(() => [] as string[]);
+ if (!entries.length) return null;
+ const tracks: { name: string; cues: { start: number; end: number; text: string }[] }[] = [];
+ const fresh = await isCuesJsonFresh(dir).catch(() => ({ fresh: false as const }));
+ if (fresh.fresh && "cuesPath" in fresh) {
+ const n = await readNormalizedTranscript(fresh.cuesPath).catch(() => null);
+ if (n?.cues?.length) tracks.push({ name: path.basename(fresh.cuesPath), cues: n.cues });
+ }
+ if (entries.includes(WHISPER_FILENAME)) {
+ const w = await readFile(path.join(dir, WHISPER_FILENAME), "utf8").then((t) => parseTranscriptJson(t), () => []);
+ if (w.length) tracks.push({ name: WHISPER_FILENAME, cues: w });
+ }
+ for (const name of englishVttsByPreference(entries)) {
+ const v = await readFile(path.join(dir, name), "utf8").then((t) => parseVtt(t), () => []);
+ if (v.length) tracks.push({ name, cues: v });
+ }
+ const state = stateFromAvailability(await resolveEffectiveAvailability(dir).catch(() => null));
+ // The platform a deletion is said on: its metadata's page.
+ const meta = entries.includes("metadata.info.json")
+ ? await readFile(path.join(dir, "metadata.info.json"), "utf8").then((t) => JSON.parse(t) as { webpage_url?: unknown }, () => null)
+ : null;
+ const platform = detectPlatform(typeof meta?.webpage_url === "string" ? meta.webpage_url : null);
+ return { cues: tracks[0]?.cues ?? [], tracks, ...(state !== "available" ? { state, ...(platform ? { platform } : {}) } : {}) };
+}
+
+/** A refresh iteration's refresh.json, or null. */
+export async function readRefreshFile(article: string, n: number, paths: ReportDraftDeps["paths"]): Promise<RefreshFile | null> {
+ const text = await readIterationFile(article, n, "refresh.json", paths).catch(() => null);
+ if (!text) return null;
+ try {
+ const f = JSON.parse(text) as RefreshFile;
+ return f?.format === REFRESH_FORMAT ? f : null;
+ } catch {
+ return null;
+ }
+}
+
+async function recordUsage(article: string, n: number, jobId: string, paths: ReportDraftDeps["paths"], now: Date) {
+ const it = await readIteration(article, n, paths);
+ if (!it) return;
+ const base = { at: now.toISOString(), day: utcDay(now), jobId, article, iteration: n, task: "refresh" };
+ const rows: GenerationUsageRow[] = Object.entries(it.usage)
+ .filter(([m, u]) => providerOf(m) === "api" && (u.usd > 0 || (u.calls ?? 0) > 0))
+ .map(([m, u]) => ({
+ ...base,
+ model: m,
+ inputTokens: u.inputTokens,
+ outputTokens: u.outputTokens,
+ cacheReadTokens: u.cacheReadTokens ?? 0,
+ cacheWriteTokens: u.cacheWriteTokens ?? 0,
+ usd: Math.round(u.usd * 10_000) / 10_000,
+ }));
+ await appendGenerationUsage(paths.generationUsageFile, rows);
+}
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -24,6 +24,10 @@ export const DIGEST_REMOTE_QUEUE = "digest:remote";
// that must not wait behind it. Each runs one job at a time.
export const DRAFT_LOCAL_QUEUE = "draft:local";
export const DRAFT_API_QUEUE = "draft:api";
+// A refresh (umtool R4) waits on the editor's own fetches and a site build —
+// hours, sometimes — before any model runs: its own lane, so it never holds
+// `draft:api` or `draft:local` while it waits. One refresh at a time.
+export const DRAFT_REFRESH_QUEUE = "draft:refresh";
// The backfill lane (controller/operationBatch.ts). Its own key for exactly the
// reason the two digest keys have theirs: registry.ts submits every non-empty
diff --git a/common/lib/report/draft/refresh/basis.ts b/common/lib/report/draft/refresh/basis.ts
@@ -0,0 +1,242 @@
+// WHAT AN ITERATION WAS BUILT FROM (umtool R4): the enumerations to run again,
+// the scope, the recordings it matched, and the quotes its report cites —
+// read from the iteration and, for a revision, from the sweep it descends
+// from. In order of preference:
+//
+// refresh.json a refresh's own record: its basis's queries, and the match
+// set it saw (which includes what it found new)
+// trace.jsonl a sweep's trace (R3): each `enumerate` (query, ids, counts)
+// under the `scope`
+// turns.jsonl a run before the trace: the agent's enumerate_matches calls
+// (their arguments; their answers' rows when an import kept
+// them) or the pipeline's `enumerate` terms
+// the question nothing recorded: the question as the one query (said so)
+//
+// The report's own cited recordings are always in the known set.
+//
+// SERVER-ONLY (the iterations store).
+
+import { lineage, readIteration, readIterationFile, reportSourceOf, type Iteration } from "../../iterations";
+import { enumerateOf } from "../tasks/trace";
+import type { StorePaths } from "../tasks/types";
+import { REFRESH_FORMAT, type BasisFrom, type CitedQuote, type RefreshBasis, type RefreshFile, type RefreshQuery } from "./types";
+
+type Json = Record<string, unknown>;
+
+const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
+const strs = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && !!x.trim()) : typeof v === "string" && v.trim() ? [v.trim()] : []);
+
+function jsonLines(text: string | null): Json[] {
+ if (!text) return [];
+ const out: Json[] = [];
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const v = JSON.parse(line) as unknown;
+ if (v && typeof v === "object" && !Array.isArray(v)) out.push(v as Json);
+ } catch {
+ // a torn line is skipped
+ }
+ }
+ return out;
+}
+
+/** One query's identity: the same enumeration twice is run once. */
+export const queryKey = (q: RefreshQuery) => JSON.stringify([q.query, !!q.regex, [...(q.channels ?? [])].sort(), q.from ?? "", q.to ?? ""]);
+
+// What one iteration's records say (null: nothing recorded there).
+type Found = { from: BasisFrom; queries: RefreshQuery[]; perQuery: Map<string, Record<string, number | null>>; scope?: RefreshBasis["scope"]; source: string | null; known?: Record<string, number | null> };
+
+function addRows(perQuery: Found["perQuery"], key: string, rows: Record<string, number | null>) {
+ const had = perQuery.get(key);
+ // The same query run twice: the later answer stands (it is what was read).
+ perQuery.set(key, had ? { ...had, ...rows } : rows);
+}
+
+/** A refresh.json, as a basis. */
+export function fromRefreshFile(f: RefreshFile): Found {
+ const known: Record<string, number | null> = { ...(f.basis.known ?? {}) };
+ for (const [id, c] of Object.entries(f.delta?.matchedSet ?? {})) known[id] = c;
+ return { from: "refresh", queries: f.basis.queries, perQuery: new Map(), scope: f.basis.scope, source: f.corpus?.source ?? f.basis.source ?? null, known };
+}
+
+/** A trace.jsonl's text, as a basis (null: it holds no enumeration). Its LAST run is the one read. */
+export function fromTrace(text: string | null): Found | null {
+ const events = jsonLines(text);
+ if (!events.length) return null;
+ const last = Math.max(...events.map((e) => (typeof e.run === "number" ? e.run : 1)));
+ const mine = events.filter((e) => (typeof e.run === "number" ? e.run : 1) === last);
+ const scope = mine.find((e) => e.t === "scope");
+ const enums = mine.filter((e) => e.t === "enumerate" && str(e.query));
+ if (!enums.length) return null;
+ const sc: RefreshBasis["scope"] = {
+ channels: strs(scope?.channels),
+ ...(str(scope?.from) ? { from: str(scope?.from)! } : {}),
+ ...(str(scope?.to) ? { to: str(scope?.to)! } : {}),
+ };
+ const queries: RefreshQuery[] = [];
+ const perQuery: Found["perQuery"] = new Map();
+ for (const e of enums) {
+ const q: RefreshQuery = { query: str(e.query)! };
+ const key = queryKey(q);
+ if (!perQuery.has(key)) queries.push(q);
+ const ids = strs(e.ids);
+ const counts = (e.counts && typeof e.counts === "object" ? e.counts : {}) as Record<string, unknown>;
+ addRows(perQuery, key, Object.fromEntries(ids.map((id) => [id, typeof counts[id] === "number" ? (counts[id] as number) : null])));
+ }
+ return { from: "trace", queries, perQuery, scope: sc, source: str(scope?.source) ?? null };
+}
+
+/** A turns.jsonl's text, as a basis (null: it holds no enumeration). */
+export function fromTurns(text: string | null): Found | null {
+ const entries = jsonLines(text);
+ const queries: RefreshQuery[] = [];
+ const perQuery: Found["perQuery"] = new Map();
+ const add = (q: RefreshQuery, rows: Record<string, number | null>) => {
+ const key = queryKey(q);
+ if (!perQuery.has(key)) {
+ queries.push(q);
+ perQuery.set(key, {});
+ }
+ addRows(perQuery, key, rows);
+ };
+ for (const e of entries) {
+ if (e.kind === "tool" && e.name === "enumerate_matches") {
+ const i = (e.input ?? {}) as Json;
+ const query = str(i.query);
+ if (!query) continue;
+ const channels = strs(i.channels ?? i.channel);
+ const q: RefreshQuery = {
+ query,
+ ...(i.regex === true ? { regex: true } : {}),
+ ...(channels.length ? { channels } : {}),
+ ...(str(i.date_from) ? { from: str(i.date_from)! } : {}),
+ ...(str(i.date_to) ? { to: str(i.date_to)! } : {}),
+ };
+ const result = str(e.result);
+ const rows: Record<string, number | null> = {};
+ if (result) for (const r of enumerateOf(result).rows) rows[r.id] = r.matches;
+ add(q, rows);
+ } else if (e.kind === "enumerate" && str(e.term)) {
+ add({ query: str(e.term)! }, {});
+ }
+ }
+ return queries.length ? { from: "turns", queries, perQuery, source: null } : null;
+}
+
+// Every recording matched, summed over the distinct queries; a recording a
+// query matched without its count reads null.
+export function knownOf(perQuery: Found["perQuery"]): Record<string, number | null> {
+ const out: Record<string, number | null> = {};
+ for (const rows of perQuery.values()) {
+ for (const [id, c] of Object.entries(rows)) {
+ if (!(id in out)) out[id] = c;
+ else out[id] = out[id] === null || c === null ? null : out[id]! + c;
+ }
+ }
+ return out;
+}
+
+/** The quoted citations of a report. */
+export function citedQuotes(report: unknown): CitedQuote[] {
+ const cites = ((report ?? {}) as { citations?: Record<string, Json> }).citations ?? {};
+ const out: CitedQuote[] = [];
+ for (const [citation, c] of Object.entries(cites)) {
+ const kind = c.kind;
+ if (kind !== "video" && kind !== "audio" && kind !== "post") continue;
+ const channel = str(c.channel);
+ const id = str(c.id);
+ const quote = str(c.quote);
+ if (!channel || !id || !quote) continue;
+ out.push({
+ citation,
+ kind,
+ channel,
+ id,
+ ...(typeof c.start === "number" ? { start: c.start } : {}),
+ ...(typeof c.end === "number" ? { end: c.end } : {}),
+ quote,
+ });
+ }
+ return out;
+}
+
+async function foundAt(article: string, n: number, it: Iteration, paths: StorePaths | undefined): Promise<Found | null> {
+ if (it.kind === "refresh") {
+ const text = await readIterationFile(article, n, "refresh.json", paths);
+ if (text) {
+ try {
+ const f = JSON.parse(text) as RefreshFile;
+ if (f?.format === REFRESH_FORMAT && Array.isArray(f.basis?.queries)) return fromRefreshFile(f);
+ } catch {
+ // not a refresh record: read on
+ }
+ }
+ }
+ return fromTrace(await readIterationFile(article, n, "trace.jsonl", paths)) ?? fromTurns(await readIterationFile(article, n, "turns.jsonl", paths));
+}
+
+export class NothingToRefreshError extends Error {}
+
+/**
+ * The basis of iteration `n` of `article`: its own records, else those of the
+ * nearest ancestor that has them (a revision's sweep), else its question.
+ */
+export async function refreshBasis(article: string, n: number, paths?: StorePaths): Promise<RefreshBasis> {
+ const it = await readIteration(article, n, paths);
+ if (!it) throw new NothingToRefreshError(`"${article}" has no iteration i${n}`);
+ const from = await reportSourceOf(article, n, paths).catch(() => null);
+ const reportText = from === null ? null : await readIterationFile(article, from, "report.json", paths);
+ if (!reportText) throw new NothingToRefreshError(`"${article}" i${n} carries no report to refresh`);
+ const cited = citedQuotes(JSON.parse(reportText) as unknown);
+
+ // The records: this iteration's, else up its lineage.
+ const line = await lineage(article, n, paths).catch(() => [n]);
+ let found: Found | null = null;
+ let queriesOf = n;
+ let base: Iteration = it;
+ for (let i = line.length - 1; i >= 0 && !found; i--) {
+ const at = i === line.length - 1 ? it : await readIteration(article, line[i]!, paths);
+ if (!at) continue;
+ found = await foundAt(article, line[i]!, at, paths);
+ if (found) {
+ queriesOf = line[i]!;
+ base = at;
+ }
+ }
+ // The question and scope: the iteration's, else the one the records are of.
+ const question = it.question ?? base.question ?? null;
+ const scopeIt = it.scope?.channels?.length ? it.scope : base.scope;
+ const citedChannels = [...new Set(cited.map((c) => c.channel))];
+ const channels = [...new Set([...(found?.scope?.channels ?? []), ...(scopeIt?.channels ?? []), ...citedChannels])];
+ const from_ = found?.scope?.from ?? scopeIt?.from;
+ const to = found?.scope?.to ?? scopeIt?.to;
+ const scope: RefreshBasis["scope"] = { channels, ...(from_ ? { from: from_ } : {}), ...(to ? { to } : {}) };
+
+ let queries = found?.queries ?? [];
+ let fromKind: BasisFrom = found?.from ?? "question";
+ if (!queries.length) {
+ if (!question) throw new NothingToRefreshError(`"${article}" i${n} records no enumeration and names no question: nothing to search again`);
+ queries = [{ query: question }];
+ fromKind = "question";
+ }
+ const known: Record<string, number | null> = found?.known ? { ...found.known } : found ? knownOf(found.perQuery) : {};
+ const countsKnown = !!found && (found.from === "refresh" ? Object.values(known).some((c) => c !== null) : [...found.perQuery.values()].some((rows) => Object.values(rows).some((c) => c !== null)));
+ const knownComplete = !!found && (found.from === "refresh" || found.from === "trace" || [...found.perQuery.values()].some((rows) => Object.keys(rows).length > 0));
+ for (const c of cited) if (c.kind !== "post" && !(c.id in known)) known[c.id] = null;
+ return {
+ article,
+ n,
+ queriesOf,
+ question,
+ scope,
+ queries,
+ from: fromKind,
+ known,
+ knownComplete,
+ countsKnown,
+ cited,
+ source: found?.source ?? null,
+ at: it.endedAt ?? it.updatedAt,
+ };
+}
diff --git a/common/lib/report/draft/refresh/delta.ts b/common/lib/report/draft/refresh/delta.ts
@@ -0,0 +1,266 @@
+// WHAT CHANGED (umtool R4, stage 2 — deterministic, no model): the basis's
+// enumerations run again over the corpus as it is now, and every quote the
+// report cites read again at its cite.
+//
+// candidates deltaCandidates(basis-like, corpus, {known?, since?}):
+// the match set now, the recordings new against `known`
+// (or, without one, uploaded on or after `since`), the ones
+// whose matching lines changed, the ones no longer matched.
+// Callable on its own with a scope and a "since" point —
+// umtool's daily suggestion and R6's tier 0 are exactly it.
+// quotes recheckQuotes(cited, readers): R2's word check
+// (lib/report/quoteWords.ts) at each cite, on every track the
+// record has; a source gone from the archive or from its
+// platform; en vs en-orig.
+// computeDelta both, as one RefreshDelta.
+//
+// Pure over the corpus tools and readers it is handed.
+
+import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, type WordCue } from "../../quoteWords";
+import { enumerateOf, type EnumeratedRow } from "../tasks/trace";
+import type { CorpusToolsLike } from "../tasks/types";
+import { queryKey } from "./basis";
+import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types";
+
+export type CandidateScope = { channels: string[]; from?: string; to?: string };
+
+export type Candidates = {
+ // The match set now: each recording with its matching lines, summed over the queries.
+ matchedSet: Record<string, number | null>;
+ rows: Map<string, MatchedRow>;
+ newIds: string[];
+ changed: string[];
+ unmatched: string[];
+ partial: boolean;
+ unreached: string[];
+ // Each query's own answer (its matched count), for the log.
+ perQuery: { query: string; n: number; partial: boolean; error?: string }[];
+};
+
+// One enumeration's answer, as data: its rows, whether the scan was capped,
+// the channels a capped scan never reached.
+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>;
+
+/** 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 };
+ };
+
+/** The enumerate_matches arguments of one query under a scope. */
+export function enumerateArgs(q: RefreshQuery, scope: CandidateScope): Record<string, unknown> {
+ const channels = q.channels?.length ? q.channels : scope.channels;
+ const from = q.from ?? scope.from;
+ const to = q.to ?? scope.to;
+ return {
+ query: q.query,
+ ...(channels.length ? { channels } : {}),
+ ...(from ? { date_from: from } : {}),
+ ...(to ? { date_to: to } : {}),
+ ...(q.regex ? { regex: true } : {}),
+ };
+}
+
+// An upload date as YYYY-MM-DD ("20260105", "2026-01-05", …), or null.
+const ymdOf = (d: string | null | undefined): string | null => {
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim());
+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;
+};
+
+/**
+ * The candidates: every query run once over `scope`; new = matched now and
+ * not in `known` (and, when `since` is given, uploaded on or after it — with
+ * no `known`, `since` alone decides); changed = in both, their counts known
+ * and different; unmatched = known, not matched now (only said of a complete
+ * scan).
+ */
+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 } = {},
+): Promise<Candidates> {
+ const run = typeof corpus === "function" ? corpus : enumerateViaTools(corpus);
+ const seen = new Set<string>();
+ const perId = new Map<string, number | null>();
+ const rows = new Map<string, MatchedRow>();
+ const perQuery: Candidates["perQuery"] = [];
+ let partial = false;
+ const unreached = new Set<string>();
+ for (const q of basis.queries) {
+ o.signal?.throwIfAborted();
+ const key = queryKey(q);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ let e: EnumeratedAnswer;
+ try {
+ e = await run(enumerateArgs(q, basis.scope));
+ } catch (err) {
+ // One query that cannot run is said, and makes the scan partial.
+ partial = true;
+ perQuery.push({ query: q.query, n: 0, partial: true, error: (err as Error).message });
+ continue;
+ }
+ if (e.partial) partial = true;
+ for (const c of e.unreached) unreached.add(c);
+ perQuery.push({ query: q.query, n: e.rows.length, partial: e.partial });
+ for (const r of e.rows) {
+ if (r.kind === "post") continue;
+ const had = perId.get(r.id);
+ perId.set(r.id, had === undefined ? r.matches : had === null || r.matches === null ? null : had + r.matches);
+ if (!rows.has(r.id)) rows.set(r.id, { id: r.id, channel: r.channel, date: ymdOf(r.date), title: r.title, matches: null });
+ }
+ }
+ const matchedSet = Object.fromEntries(perId);
+ for (const [id, row] of rows) row.matches = perId.get(id) ?? null;
+ const known = o.known;
+ const since = o.since ? ymdOf(o.since) : null;
+ const isNew = (id: string) => {
+ if (known && id in known) return false;
+ if (since) {
+ const d = rows.get(id)?.date;
+ return !!d && d >= since;
+ }
+ return !!known;
+ };
+ const newIds = [...perId.keys()].filter(isNew);
+ const changed = known
+ ? [...perId.keys()].filter((id) => {
+ if (!(id in known)) return false;
+ const was = known[id];
+ const now = perId.get(id);
+ return was !== null && was !== undefined && now !== null && now !== undefined && was !== now;
+ })
+ : [];
+ const unmatched = known && !partial ? Object.keys(known).filter((id) => !perId.has(id)) : [];
+ return { matchedSet, rows, newIds, changed, unmatched, partial, unreached: [...unreached].sort(), perQuery };
+}
+
+// ─── the quotes ───
+
+// A recording as a refresh reads it: its cues (the primary track) and every
+// track it has (named: `transcript.en.vtt`, `transcript.en-orig.vtt`,
+// `transcript.json` …), and its platform state when it is not available.
+export type RecordRead = { cues: readonly WordCue[]; tracks?: { name: string; cues: readonly WordCue[] }[]; state?: string | null; platform?: string | null };
+
+export type QuoteReaders = {
+ // The recording (the disk, the build); null: not in the archive.
+ recordOf: (channel: string, id: string) => Promise<RecordRead | null>;
+ // A post's text; null: not in the archive. Absent: posts are not read.
+ postTextOf?: (channel: string, id: string) => Promise<string | null>;
+};
+
+// The states a recording is "gone" in, for the delta's `deleted`.
+const GONE_STATES = new Set(["deleted", "private"]);
+
+const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name);
+const isEnOrig = (name: string) => /en-orig/.test(name);
+
+/** Every quoted citation, read again at its cite. */
+export async function recheckQuotes(cited: readonly CitedQuote[], readers: QuoteReaders, o: { span?: number; signal?: AbortSignal } = {}): Promise<QuoteRecheck[]> {
+ const span = o.span ?? 30;
+ const out: QuoteRecheck[] = [];
+ const records = new Map<string, Promise<RecordRead | null>>();
+ for (const c of cited) {
+ o.signal?.throwIfAborted();
+ const base = { citation: c.citation, kind: c.kind, channel: c.channel, id: c.id, ...(c.start !== undefined ? { start: c.start } : {}), quote: c.quote };
+ try {
+ if (c.kind === "post") {
+ if (!readers.postTextOf) {
+ out.push({ ...base, status: "unreadable", message: "posts are not read here" });
+ continue;
+ }
+ const text = await readers.postTextOf(c.channel, c.id);
+ if (text === null) out.push({ ...base, status: "missing", message: `no post ${c.id} in ${c.channel} now` });
+ else out.push(holdsWords(text, c.quote) ? { ...base, status: "ok" } : { ...base, status: "drifted", now: text.slice(0, 3000) });
+ continue;
+ }
+ const key = `${c.channel}/${c.id}`;
+ let p = records.get(key);
+ if (!p) {
+ p = readers.recordOf(c.channel, c.id);
+ records.set(key, p);
+ }
+ const rec = await p;
+ if (!rec || (!rec.cues.length && !(rec.tracks ?? []).some((t) => t.cues.length))) {
+ out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` });
+ continue;
+ }
+ const state = rec.state && GONE_STATES.has(rec.state) ? rec.state : undefined;
+ const t = c.start ?? 0;
+ const cite = { t, end: c.end ?? t };
+ // The primary first, then every other track: the words on any of them stand.
+ const tracks = [rec.cues, ...(rec.tracks ?? []).map((x) => x.cues)].filter((x) => x.length);
+ let verdict = checkWordsInWindow(c.quote, cite, windowAround(tracks[0]!, t, span));
+ for (let i = 1; i < tracks.length && verdict.status !== "ok"; i++) {
+ const v = checkWordsInWindow(c.quote, cite, windowAround(tracks[i]!, t, span));
+ if (v.status === "ok") verdict = v;
+ }
+ const en = (rec.tracks ?? []).find((x) => isEn(x.name) && !isEnOrig(x.name));
+ const orig = (rec.tracks ?? []).find((x) => isEnOrig(x.name));
+ const enOrig = en && orig ? enOrigDifference(en.cues, orig.cues, cite) : null;
+ const extra = { ...(state ? { state, ...(rec.platform ? { platform: rec.platform } : {}) } : {}), ...(enOrig ? { enOrig } : {}) };
+ if (verdict.status === "ok") {
+ out.push(verdict.nowAt !== undefined ? { ...base, status: "moved", nowAt: verdict.nowAt, ...extra } : { ...base, status: "ok", ...extra });
+ } else {
+ out.push({ ...base, status: "drifted", now: verdict.now, ...(verdict.nowAt !== undefined ? { nowAt: verdict.nowAt } : {}), ...(verdict.empty ? { message: `no cues within ${span} s of the cite now` } : {}), ...extra });
+ }
+ } catch (e) {
+ if (o.signal?.aborted) throw e;
+ out.push({ ...base, status: "unreadable", message: (e as Error).message });
+ }
+ }
+ return out;
+}
+
+/** Stage 2: the candidates and the quotes, as one delta. */
+export async function computeDelta(
+ basis: RefreshBasis,
+ corpus: Pick<CorpusToolsLike, "call">,
+ readers: QuoteReaders,
+ o: { now?: Date; signal?: AbortSignal } = {},
+): Promise<RefreshDelta> {
+ const cand = await deltaCandidates(basis, corpus, {
+ known: basis.knownComplete ? basis.known : undefined,
+ since: basis.knownComplete ? null : basis.at,
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ // Without the whole old set, "new" is by upload date; the cited are never new.
+ const newIds = cand.newIds.filter((id) => !(id in basis.known));
+ const quotes = await recheckQuotes(basis.cited, readers, o.signal ? { signal: o.signal } : {});
+ const drifted = quotes.filter((q) => q.status === "drifted").map((q) => q.citation);
+ const deleted = [...new Set(quotes.filter((q) => q.status === "missing" || q.state).map((q) => `${q.channel}/${q.id}`))];
+ const goneFromArchive = [...new Set(quotes.filter((q) => q.status === "missing").map((q) => `${q.channel}/${q.id}`))];
+ const removed = new Map<string, { source: string; state: string; platform: string | null }>();
+ for (const q of quotes) {
+ const source = `${q.channel}/${q.id}`;
+ if (q.status !== "missing" && q.state && !removed.has(source)) removed.set(source, { source, state: q.state, platform: q.platform ?? null });
+ }
+ const enOrig = quotes.filter((q) => q.enOrig).map((q) => q.citation);
+ const changed = basis.countsKnown ? cand.changed : [];
+ const status = newIds.length || changed.length || drifted.length || deleted.length ? "changed" : "no-change";
+ return {
+ at: (o.now ?? new Date()).toISOString(),
+ status,
+ matched: Object.keys(cand.matchedSet).length,
+ newIds,
+ new: newIds.map((id) => cand.rows.get(id)!).filter(Boolean),
+ changed: basis.countsKnown ? cand.changed : [],
+ changedTracked: basis.countsKnown,
+ ...(basis.countsKnown ? {} : { changedSince: basis.at }),
+ unmatched: cand.unmatched,
+ drifted,
+ deleted,
+ goneFromArchive,
+ removedOnPlatform: [...removed.values()],
+ enOrig,
+ quotes,
+ partial: cand.partial,
+ unreached: cand.unreached,
+ matchedSet: cand.matchedSet,
+ };
+}
diff --git a/common/lib/report/draft/refresh/fetch.ts b/common/lib/report/draft/refresh/fetch.ts
@@ -0,0 +1,244 @@
+// A REFRESH'S STAGE 1 — fetch what is new, then build (umtool R4), on its own:
+// a refresh runs it first (./task.ts), and R5's recurring reports run it on a
+// tick before a series' edition. No model, nothing written but what the
+// editor's own actions write.
+//
+// per channel a video channel: `sync`, then `refresh-report` (its report,
+// so the bucket is current) and `transcribe-bucket` for the
+// recordings that LANDED (the bucket against the one before —
+// never the channel's whole backlog); a posts channel:
+// `fetch-posts`. A platform held or cooling down is skipped,
+// and says so (polite scraping). Channels run side by side;
+// the editor's platform queues pace them.
+// the build the site whose build holds the channels, `publish build`
+// (never forced: a fresh build is not rebuilt; through the
+// publish lock; never a deploy), waited for.
+//
+// Every action's job is waited for (polled; a step still going after
+// `waitMs` is left running and said). Each step is logged and traced.
+
+import type { JobOf } from "../research/state";
+import type { ResearchEditor } from "../research/tools";
+import type { TraceInput, TraceStepStatus } from "../tasks/trace";
+import type { QuoteReaders } from "./delta";
+import type { BuildStep, FetchStep } from "./types";
+
+// What a refresh asks of the editor (the controller passes the editor's own,
+// in process — controller/reportRefresh.ts refreshHooksOf; the tests stub them).
+export type RefreshHooks = {
+ // One ops action (the research run's door: the same refusals, same words).
+ editor: ResearchEditor;
+ jobOf: JobOf;
+ // A channel of this editor: what it is and on which platform; null: none.
+ channelOf: (slug: string) => Promise<{ kind: "video" | "posts"; platform?: string } | null>;
+ // Why a fetch on this platform would be refused now (held, cooling down), or null.
+ 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>;
+ // 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 }>;
+ // When the build that holds the channels was made (ms), to say whether it moved.
+ builtAt?: (channels: string[], prefer: string | null) => Promise<number | null>;
+ // Open the corpus the delta and the update read (deps.corpus becomes it).
+ openCorpus: (channels: string[], prefer: string | null) => Promise<{ source: string; origin: string; build?: string }>;
+ // A recording on disk (every track, its platform state), else the build's cues.
+ recordOf?: QuoteReaders["recordOf"];
+ // Why an update of about `usd` would be refused by a cap now, or null.
+ capRefusal: (usd: number) => Promise<string | null>;
+ // Polling (default 5 s) and how long one step is waited for (default 6 h).
+ pollMs?: number;
+ waitMs?: number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+};
+
+// 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 FetchAndBuild = { fetch: FetchStep[]; build: BuildStep | null; warnings: string[] };
+
+const sleeper = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason ?? new Error("cancelled"));
+ const t = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(t);
+ reject(signal?.reason ?? new Error("cancelled"));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+
+const ENDED = new Set(["done", "failed", "cancelled", "archived"]);
+
+/** Stage 1 over `scope.channels`: each channel's fetches, then the build (see the head of this file). */
+export async function fetchAndBuild(
+ scope: { channels: readonly string[] },
+ hooks: FetchHooks,
+ o: {
+ // The corpus the work was read from (its build is preferred).
+ prefer?: string | null;
+ signal?: AbortSignal;
+ log?: (line: string) => void;
+ trace?: (e: TraceInput) => void;
+ // After the fetches, before the build (a refresh keeps them on disk).
+ onFetched?: (steps: FetchStep[]) => void | Promise<void>;
+ // false: fetch, no build.
+ build?: boolean;
+ } = {},
+): Promise<FetchAndBuild> {
+ const channels = [...scope.channels];
+ const prefer = o.prefer ?? null;
+ const log = (l: string) => o.log?.(l);
+ const trace = (e: TraceInput) => o.trace?.(e);
+ const sleep = hooks.sleep ?? sleeper;
+ const poll = hooks.pollMs ?? 5000;
+ const waitMs = hooks.waitMs ?? 6 * 3600_000;
+ const warnings: string[] = [];
+
+ // Every job ended (or the wait's limit): each job's status, "waiting" for one still going.
+ const waitJobs = async (ids: string[]): Promise<Record<string, string>> => {
+ const out: Record<string, string> = {};
+ const t0 = Date.now();
+ for (;;) {
+ o.signal?.throwIfAborted();
+ let pending = 0;
+ for (const id of ids) {
+ if (out[id] && out[id] !== "waiting") continue;
+ const j = await hooks.jobOf(id).catch(() => null);
+ if (!j) out[id] = "unknown";
+ else if (ENDED.has(j.status)) out[id] = j.status;
+ else {
+ out[id] = "waiting";
+ pending++;
+ }
+ }
+ if (!pending || Date.now() - t0 >= waitMs) return out;
+ await sleep(poll, o.signal);
+ }
+ };
+
+ // One action, then its job waited for.
+ const runAndWait = async (channel: string, action: string, args: Record<string, unknown>): Promise<FetchStep> => {
+ let answer: Record<string, unknown>;
+ try {
+ answer = await hooks.editor.run(action, args);
+ } catch (e) {
+ const step: FetchStep = { channel, action, status: "refused", reason: (e as Error).message };
+ trace({ t: "fetch", ...step });
+ log(`${channel}: ${action} refused — ${step.reason}`);
+ return step;
+ }
+ const jobId = typeof answer.jobId === "string" ? answer.jobId : undefined;
+ const ids = Array.isArray(args.ids) ? (args.ids as string[]) : undefined;
+ if (!jobId) {
+ const step: FetchStep = { channel, action, status: "done", reason: "nothing queued" };
+ trace({ t: "fetch", ...step });
+ return step;
+ }
+ trace({ t: "fetch", channel, action, status: "queued", jobId, ...(ids ? { ids } : {}) });
+ log(`${channel}: ${action} queued (job ${jobId})`);
+ const st = (await waitJobs([jobId]))[jobId] ?? "unknown";
+ const status: TraceStepStatus = st === "done" ? "done" : st === "cancelled" ? "cancelled" : st === "waiting" ? "waiting" : "failed";
+ const step: FetchStep = {
+ channel,
+ action,
+ status,
+ jobId,
+ ...(ids ? { ids } : {}),
+ ...(status === "done" ? {} : { reason: st === "waiting" ? `still running after ${Math.round(waitMs / 60_000)} min: read what is there` : `the job ended ${st}` }),
+ };
+ trace({ t: "fetch", ...step });
+ log(`${channel}: ${action} ${status}${step.reason ? ` (${step.reason})` : ""}`);
+ return step;
+ };
+
+ const skip = (channel: string, action: string, reason: string): FetchStep => {
+ const step: FetchStep = { channel, action, status: "skipped", reason };
+ trace({ t: "fetch", ...step });
+ log(`${channel}: ${action} skipped — ${reason}`);
+ return step;
+ };
+
+ const fetchChannel = async (slug: string): Promise<FetchStep[]> => {
+ const ch = await hooks.channelOf(slug).catch(() => null);
+ if (!ch) return [skip(slug, "sync", "not a channel of this editor")];
+ const first = ch.kind === "posts" ? "fetch-posts" : "sync";
+ if (ch.platform && hooks.platformRefusal) {
+ const no = await hooks.platformRefusal(ch.platform).catch(() => null);
+ if (no) return [skip(slug, first, no)];
+ }
+ if (ch.kind === "posts") return [await runAndWait(slug, "fetch-posts", { slug })];
+ const steps: FetchStep[] = [];
+ const before = hooks.bucketOf ? await hooks.bucketOf(slug).catch(() => null) : null;
+ const sync = await runAndWait(slug, "sync", { slug });
+ steps.push(sync);
+ if (sync.status !== "done" || !hooks.bucketOf) return steps;
+ // What landed: the channel's report again, its bucket against the one before.
+ steps.push(await runAndWait(slug, "refresh-report", { slug }));
+ const after = await hooks.bucketOf(slug).catch(() => null);
+ if (before === null || after === null) {
+ steps.push(skip(slug, "transcribe-bucket", before === null ? "no channel report before the sync: what landed is not known" : "the channel's report does not read"));
+ return steps;
+ }
+ 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"));
+ return steps;
+ }
+ steps.push(await runAndWait(slug, "transcribe-bucket", { slug, ids: landed }));
+ return steps;
+ };
+
+ 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}` : ""}`);
+ await o.onFetched?.(fetch);
+ if (o.build === false) return { fetch, build: null, warnings };
+
+ // The build: the site whose build holds the channels, built if stale.
+ const target = await hooks.siteOf(channels, prefer).catch((e: Error) => ({ site: null, reason: e.message }));
+ let build: BuildStep;
+ if (!target.site) {
+ build = { site: null, status: "skipped", reason: target.reason ?? "no site's build holds these channels" };
+ } else {
+ const was = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null;
+ let answer: Record<string, unknown> | null = null;
+ build = { site: target.site, status: "refused" };
+ try {
+ answer = await hooks.editor.run("publish", { verb: "build", siteId: target.site, force: false });
+ } catch (e) {
+ build = { site: target.site, status: "refused", reason: (e as Error).message };
+ }
+ if (answer) {
+ const jobs = Array.isArray(answer.jobs) ? (answer.jobs as { jobId?: unknown }[]).map((j) => j.jobId).filter((x): x is string => typeof x === "string") : [];
+ if (!jobs.length) {
+ const skipped = Array.isArray(answer.skipped) ? (answer.skipped as { reason?: unknown }[]).map((s) => String(s.reason ?? "")).filter(Boolean) : [];
+ build = { site: target.site, status: "skipped", reason: skipped[0] ?? "nothing to build" };
+ } else {
+ trace({ t: "build", site: target.site, status: "queued", jobIds: jobs });
+ log(`build ${target.site}: queued (${jobs.join(", ")})`);
+ const st = await waitJobs(jobs);
+ const bad = jobs.filter((j) => st[j] !== "done");
+ const worst = bad.length ? st[bad[0]!]! : "done";
+ build = bad.length
+ ? {
+ site: target.site,
+ status: worst === "waiting" ? "waiting" : worst === "cancelled" ? "cancelled" : "failed",
+ jobIds: jobs,
+ reason: `job ${bad[0]} ${worst === "waiting" ? "still running" : `ended ${worst}`}: the corpus is read as it stands`,
+ }
+ : { site: target.site, status: "done", jobIds: jobs };
+ }
+ }
+ const is = hooks.builtAt ? await hooks.builtAt(channels, prefer).catch(() => null) : null;
+ if (is) build.builtAt = new Date(is).toISOString();
+ if (build.status === "done" && was !== null && is !== null && is <= was) build.reason = "the build was current: nothing to rebuild";
+ }
+ trace({ t: "build", ...build });
+ log(`build: ${build.site ?? "none"} ${build.status}${build.reason ? ` — ${build.reason}` : ""}`);
+ if (build.status !== "done" && build.status !== "skipped") warnings.push(`the build ${build.site ?? ""} ${build.status}: ${build.reason ?? ""}`.trim());
+ return { fetch, build, warnings };
+}
diff --git a/common/lib/report/draft/refresh/index.ts b/common/lib/report/draft/refresh/index.ts
@@ -0,0 +1,26 @@
+// A refresh (umtool R4): re-fetch, see what changed, update. See ./task.ts.
+export * from "./types";
+export { NothingToRefreshError, citedQuotes, fromRefreshFile, fromTrace, fromTurns, knownOf, queryKey, refreshBasis } from "./basis";
+export {
+ computeDelta,
+ deltaCandidates,
+ enumerateArgs,
+ enumerateViaTools,
+ recheckQuotes,
+ type CandidateScope,
+ type Candidates,
+ type EnumerateFn,
+ type EnumeratedAnswer,
+ type QuoteReaders,
+ type RecordRead,
+} from "./delta";
+export { fetchAndBuild, type FetchAndBuild, type FetchHooks, type RefreshHooks } from "./fetch";
+export {
+ DEFAULT_REVISION_USD,
+ DEFAULT_USD_PER_RECORDING,
+ estimateUpdateUsd,
+ findingsOf,
+ refresh,
+ refreshFeedback,
+ type RefreshInput,
+} from "./task";
diff --git a/common/lib/report/draft/refresh/refresh.test.ts b/common/lib/report/draft/refresh/refresh.test.ts
@@ -0,0 +1,434 @@
+// A refresh (umtool R4): the basis read from an iteration's records, the
+// candidates against a stubbed corpus, the quotes read again, and the task's
+// stages over stubbed editor actions — no change ($0), a cap's hold, and the
+// fetch steps (a held platform skipped, a posts channel, what landed sent to
+// transcription, the build waited for). The update over the MCP's own corpus
+// tools and the fake Anthropic is mcp/src/refreshTask.test.ts. Temp stores
+// only.
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createIteration, iterationFile, readIteration, updateIteration, writeIterationFile } from "../../iterations";
+import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, wordsOf } from "../../quoteWords";
+import { restrictEnumerateText, restrictTools } from "../tasks/restrict";
+import type { AgentTool } from "../agentTool";
+import type { CorpusToolsLike, TaskDeps } from "../tasks/types";
+import { fromTrace, fromTurns, knownOf, refreshBasis } from "./basis";
+import { deltaCandidates, recheckQuotes, type RecordRead } from "./delta";
+import { estimateUpdateUsd, refresh, refreshFeedback, type RefreshHooks } from "./task";
+import { deltaLine, goneParts, outcomeOf, type RefreshDelta, type RefreshFile } from "./types";
+
+const tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-"));
+after(() => rm(tmp, { recursive: true, force: true }));
+let k = 0;
+const store = () => {
+ k++;
+ return { articlesDir: path.join(tmp, `reports-${k}`), exportIndexDir: path.join(tmp, `idx-${k}`) };
+};
+
+// ─── a corpus, stubbed: enumerate_matches and get_transcript as the MCP answers them ───
+
+type Rec = { channel: string; name: string; id: string; date: string; title: string; lines: string[] };
+
+const BASE: Rec[] = [
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "pie-02", date: "20260210", title: "Pie stream", lines: ["a lot of you asked about the contest", "I did not enter the contest this year", "the judges were friends of mine"] },
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "bread-01", date: "20260105", title: "Bread day", lines: ["welcome back", "the contest rumor again", "I paid for the new mixer myself"] },
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "qa-03", date: "20260301", title: "Q and A", lines: ["no mention here", "only flour and water"] },
+];
+
+function fakeCorpus(recs: Rec[]): CorpusToolsLike & { calls: { name: string; args: Record<string, unknown> }[] } {
+ const calls: { name: string; args: Record<string, unknown> }[] = [];
+ return {
+ source: "local:/fake/build/out",
+ tools: [],
+ calls,
+ async call(name, args = {}) {
+ calls.push({ name, args });
+ if (name === "enumerate_matches") {
+ const q = String(args.query).toLowerCase();
+ const chans = Array.isArray(args.channels) ? (args.channels as string[]) : null;
+ const rows = recs
+ .filter((r) => !chans || chans.includes(r.channel))
+ .map((r) => ({ r, n: r.lines.filter((l) => l.toLowerCase().includes(q)).length }))
+ .filter((x) => x.n > 0);
+ if (!rows.length) return `No matches for "${args.query}".\n\n(complete set: yes; 0 match(es))`;
+ const date = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`;
+ return (
+ `${rows.length} match(es) for "${args.query}" — the complete worklist:\n\n` +
+ rows.map(({ r, n }) => `- ${r.id} | video | ${r.name} | ${date(r.date)} | ${n} match(es) | ${r.title}`).join("\n") +
+ `\n\n(complete set: yes; ${rows.length} match(es); 1 batch(es) of 8)`
+ );
+ }
+ throw new Error(`the stub has no ${name}`);
+ },
+ };
+}
+
+const cuesOfRec = (r: Rec) => r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text }));
+const recordReader = (recs: Rec[], extra: Partial<Record<string, Partial<RecordRead>>> = {}) => async (channel: string, id: string): Promise<RecordRead | null> => {
+ const r = recs.find((x) => x.channel === channel && x.id === id);
+ if (!r) return null;
+ return { cues: cuesOfRec(r), ...(extra[id] ?? {}) };
+};
+
+// ─── a done sweep with its trace and report ───
+
+const REPORT = {
+ format: "archilyzer-report",
+ version: 1,
+ id: "synth",
+ kind: "sweep",
+ title: "The contest",
+ summary: "What she says.",
+ citations: {
+ c1: { kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" },
+ c2: { kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" },
+ c3: { kind: "post", channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." },
+ },
+ sections: [{ id: "s1", title: "The contest", body: "She [did not enter](cite:c1). [Mixer](cite:c2). [Post](cite:c3)." }],
+};
+
+const TRACE = [
+ { t: "run", at: "2026-10-01T10:00:00.000Z", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" },
+ { t: "scope", at: "2026-10-01T10:00:01.000Z", run: 1, source: "local:/fake/build/out", channels: ["synth-kitchen", "synth-other"], question: "What does she say about the contest?", model: "claude-sonnet-5-5" },
+ { t: "enumerate", at: "2026-10-01T10:00:02.000Z", run: 1, query: "contest", n: 2, ids: ["pie-02", "bread-01"], partial: false, unreached: [], counts: { "pie-02": 2, "bread-01": 1 } },
+ { t: "run", at: "2026-10-01T10:05:00.000Z", run: 1, phase: "end", status: "done", summary: "ok", usd: 0.8, minutes: 5, coverage: { matched: 2, read: 2, partial: false, unreached: [] } },
+];
+
+async function doneSweep(paths: ReturnType<typeof store>, article = "synth") {
+ await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does she say about the contest?", scope: { channels: ["synth-kitchen", "synth-other"] } }, paths);
+ await writeIterationFile(article, 1, "report.json", REPORT, paths);
+ await writeIterationFile(article, 1, "trace.jsonl", TRACE.map((e) => JSON.stringify(e)).join("\n") + "\n", paths);
+ await updateIteration(article, 1, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.8, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 2, read: 2, partial: false, unreached: [] } }, paths);
+}
+
+// ─── the words ───
+
+test("quoteWords: R2's check — words, the window, ok / moved / drifted, en vs en-orig", () => {
+ assert.equal(wordsOf("I’d NEVER, ever!"), "i'd never ever");
+ assert.ok(holdsWords("so I did not enter the contest this year, ok", "I did not enter the contest"));
+ assert.ok(!holdsWords("I did not enter", "I did not enter the contest"));
+ const cues = [
+ { start: 0, end: 4, text: "a lot of you asked" },
+ { start: 5, end: 9, text: "I did not enter" },
+ { start: 10, end: 14, text: "the contest this year" },
+ ];
+ assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 5, end: 14 }, windowAround(cues, 5)), { status: "ok" });
+ assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 0, end: 9 }, windowAround(cues, 0)), { status: "ok", nowAt: 5 });
+ const drift = checkWordsInWindow("I never entered", { t: 5, end: 9 }, windowAround(cues, 5));
+ assert.equal(drift.status, "drifted");
+ assert.equal(drift.status === "drifted" && drift.now, "I did not enter");
+ assert.deepEqual(checkWordsInWindow("x", { t: 500, end: 501 }, windowAround(cues, 500)), { status: "drifted", now: "", empty: true });
+ assert.equal(enOrigDifference(cues, cues, { t: 5, end: 9 }), null);
+ assert.deepEqual(enOrigDifference(cues, [{ start: 5, end: 9, text: "I did enter" }], { t: 5, end: 9 }), { en: "I did not enter", orig: "I did enter" });
+});
+
+// ─── the sweep's ids restriction ───
+
+test("restrict: an enumeration answers only the given rows; reads outside are refused; search is not offered", async () => {
+ const text = '3 match(es) for "contest" — the complete worklist:\n\n- a | video | C | 2026-01-01 | 1 match(es) | A\n- b | video | C | 2026-01-02 | 2 match(es) | B\n- c | video | C | 2026-01-03 | 1 match(es) | C\n\n(complete set: yes)';
+ const out = restrictEnumerateText(text, new Set(["b"]));
+ assert.ok(out.includes("- b | video"));
+ assert.ok(!out.includes("- a | video") && !out.includes("- c | video"));
+ assert.match(out, /restricted to 1 recording\(s\): 1 of the 3 row\(s\) above are kept/);
+ const seen: unknown[] = [];
+ const tool = (name: string): AgentTool => ({ name, description: name, inputSchema: { type: "object" }, run: async (i: unknown) => (seen.push(i), name === "enumerate_matches" ? text : "ok") });
+ const tools = restrictTools([tool("enumerate_matches"), tool("search_transcripts"), tool("get_transcripts"), tool("get_transcript"), tool("list_channels")], ["b"]);
+ assert.deepEqual(tools.map((t) => t.name), ["enumerate_matches", "get_transcripts", "get_transcript", "list_channels"]);
+ const byName = Object.fromEntries(tools.map((t) => [t.name, t]));
+ assert.ok(!(await byName.enumerate_matches!.run({ query: "contest" }, {})).includes("- a |"));
+ assert.match(await byName.get_transcripts!.run({ video_ids: ["a", "b"] }, {}), /not read — outside this sweep's recordings: a/);
+ assert.deepEqual(seen.at(-1), { video_ids: ["b"] });
+ await assert.rejects(byName.get_transcripts!.run({ video_ids: ["a"] }, {}), /restricted: a is not one of/);
+ await assert.rejects(byName.get_transcript!.run({ video_id: "c" }, {}), /restricted: c/);
+ assert.equal(await byName.get_transcript!.run({ video_id: "b" }, {}), "ok");
+ assert.equal(restrictTools([tool("search_transcripts")], undefined).length, 1, "no ids: the tools as they are");
+});
+
+// ─── the basis ───
+
+test("basis: a trace's last run (its queries, counts and scope); turns' calls; known summed over queries", () => {
+ const two = [...TRACE, { t: "run", run: 2, phase: "start" }, { t: "scope", run: 2, channels: ["synth-other"], question: "q", source: "local:/b2" }, { t: "enumerate", run: 2, query: "oven", ids: ["x9"], counts: { x9: 3 } }];
+ const f = fromTrace(two.map((e) => JSON.stringify(e)).join("\n") + "\n{torn");
+ assert.equal(f?.from, "trace");
+ assert.deepEqual(f?.queries, [{ query: "oven" }]);
+ assert.deepEqual(f?.scope?.channels, ["synth-other"]);
+ assert.equal(f?.source, "local:/b2");
+ assert.deepEqual(knownOf(f!.perQuery), { x9: 3 });
+ assert.equal(fromTrace('{"t":"run","phase":"start"}'), null, "no enumeration: nothing to read");
+
+ const turns = [
+ { kind: "response", turn: 0, content: [] },
+ { kind: "tool", name: "enumerate_matches", input: { query: "contest", channels: ["synth-kitchen"], date_from: "2026-01-01" }, result: "- pie-02 | video | Synth Kitchen | 2026-02-10 | 2 match(es) | Pie stream" },
+ { kind: "tool", name: "enumerate_matches", input: { query: "mixer" } },
+ { kind: "enumerate", term: "oven", videos: 3 },
+ ];
+ const t = fromTurns(turns.map((e) => JSON.stringify(e)).join("\n"));
+ assert.deepEqual(t?.queries, [{ query: "contest", channels: ["synth-kitchen"], from: "2026-01-01" }, { query: "mixer" }, { query: "oven" }]);
+ assert.deepEqual(knownOf(t!.perQuery), { "pie-02": 2 });
+});
+
+test("refreshBasis: the iteration's trace, the report's quotes; a revision reads its sweep's; no records → the question", async () => {
+ const paths = store();
+ await doneSweep(paths);
+ const b = await refreshBasis("synth", 1, paths);
+ assert.equal(b.from, "trace");
+ assert.equal(b.queriesOf, 1);
+ assert.deepEqual(b.queries, [{ query: "contest" }]);
+ assert.deepEqual(b.scope.channels, ["synth-kitchen", "synth-other", "synth-social"], "the trace's scope, plus every channel cited");
+ assert.deepEqual(b.known, { "pie-02": 2, "bread-01": 1 });
+ assert.equal(b.knownComplete, true);
+ assert.equal(b.countsKnown, true);
+ assert.deepEqual(b.cited.map((c) => c.citation), ["c1", "c2", "c3"]);
+ assert.equal(b.source, "local:/fake/build/out");
+
+ // A revision: its own report, its sweep's records.
+ await createIteration("synth", { kind: "revise-report", model: "claude-sonnet-5-5", parent: 1, feedback: "tighten" }, paths);
+ await writeIterationFile("synth", 2, "report.json", { ...REPORT, citations: { c1: REPORT.citations.c1 } }, paths);
+ await updateIteration("synth", 2, { status: "done" }, paths);
+ const r = await refreshBasis("synth", 2, paths);
+ assert.equal(r.queriesOf, 1);
+ assert.deepEqual(r.cited.map((c) => c.citation), ["c1"]);
+ assert.equal(r.question, "What does she say about the contest?");
+
+ // Nothing recorded: the question, and new only by upload date.
+ const p2 = store();
+ await createIteration("bare", { kind: "sweep", model: "qwen3:8b", question: "contest", scope: { channels: ["synth-kitchen"] } }, p2);
+ await writeIterationFile("bare", 1, "report.json", { ...REPORT, id: "bare" }, p2);
+ await updateIteration("bare", 1, { status: "done" }, p2);
+ const q = await refreshBasis("bare", 1, p2);
+ assert.equal(q.from, "question");
+ assert.deepEqual(q.queries, [{ query: "contest" }]);
+ assert.equal(q.knownComplete, false);
+ assert.equal(q.countsKnown, false);
+ assert.deepEqual(Object.keys(q.known).sort(), ["bread-01", "pie-02"], "the cited are known");
+});
+
+// ─── the candidates ───
+
+test("deltaCandidates: new against known, changed by matching lines, unmatched; `since` without known (R6's tier 0)", async () => {
+ const recs = [
+ ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: [...r.lines, "the contest came up twice"] } : r)),
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "late-04", date: "20250101", title: "An old one, transcribed late", lines: ["the contest was rigged"] },
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["the contest again"] },
+ ];
+ const corpus = fakeCorpus(recs);
+ const c = await deltaCandidates({ queries: [{ query: "contest" }, { query: "contest" }], scope: { channels: ["synth-kitchen"], from: "2020-01-01" } }, corpus, { known: { "pie-02": 2, "bread-01": 1, "gone-09": 1 } });
+ assert.equal(corpus.calls.length, 1, "the same query twice runs once");
+ assert.deepEqual(corpus.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"], date_from: "2020-01-01" });
+ assert.deepEqual(c.newIds.sort(), ["late-04", "new-05"]);
+ assert.deepEqual(c.changed, ["bread-01"]);
+ assert.deepEqual(c.unmatched, ["gone-09"]);
+ assert.equal(c.rows.get("new-05")?.date, "2026-10-12");
+ const since = await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, fakeCorpus(recs), { since: "2026-10-01T00:00:00Z" });
+ assert.deepEqual(since.newIds, ["new-05"], "uploaded on or after the day");
+});
+
+test("recheckQuotes: ok, moved, drifted, missing, gone from its platform, en-orig, a post", async () => {
+ const recs = BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r));
+ const cited = [
+ { citation: "c1", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" },
+ { citation: "c2", kind: "video" as const, channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" },
+ { citation: "c4", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 0, end: 4, quote: "the judges were friends of mine" },
+ { citation: "c5", kind: "video" as const, channel: "synth-kitchen", id: "nope", start: 0, end: 1, quote: "x" },
+ { citation: "c3", kind: "post" as const, channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." },
+ ];
+ const out = await recheckQuotes(cited, {
+ recordOf: recordReader(recs, { "pie-02": { state: "deleted", tracks: [{ name: "transcript.en.vtt", cues: cuesOfRec(recs[0]!) }, { name: "transcript.en-orig.vtt", cues: [{ start: 5, end: 9.8, text: "I did enter the contest this year" }] }] } }),
+ postTextOf: async () => "No, I did not enter the pie contest. The judges are my friends.",
+ });
+ const by = Object.fromEntries(out.map((q) => [q.citation, q]));
+ assert.equal(by.c1!.status, "ok");
+ assert.equal(by.c1!.state, "deleted");
+ assert.deepEqual(by.c1!.enOrig, { en: "I did not enter the contest this year", orig: "I did enter the contest this year" });
+ assert.equal(by.c2!.status, "drifted");
+ assert.equal(by.c2!.now, "I bought the mixer with sponsor money");
+ assert.equal(by.c4!.status, "moved");
+ assert.equal(by.c4!.nowAt, 10);
+ assert.equal(by.c5!.status, "missing");
+ assert.equal(by.c3!.status, "ok");
+});
+
+// ─── the task ───
+
+type Call = { action: string; args: Record<string, unknown> };
+
+function harness(o: { recs: Rec[]; refusal?: string | null; held?: string[] }) {
+ const calls: Call[] = [];
+ const polls = new Map<string, number>();
+ let n = 0;
+ const holder = { source: "", tools: [] as AgentTool[], call: (_: string, __?: Record<string, unknown>) => Promise.reject(new Error("not open")) } as CorpusToolsLike;
+ const corpus = fakeCorpus(o.recs);
+ const buckets: Record<string, string[]> = { "synth-kitchen": ["old-1"] };
+ const hooks: RefreshHooks = {
+ editor: {
+ async run(action, args) {
+ calls.push({ action, args });
+ if (action === "sync") buckets["synth-kitchen"] = ["old-1", "landed-7"];
+ if (action === "publish") return { ok: true, jobs: [{ target: "synth", kind: "build-site", jobId: `job-${++n}` }] };
+ return { ok: true, jobId: `job-${++n}` };
+ },
+ },
+ // A job runs for one poll, then is done.
+ jobOf: async (id) => {
+ const k = (polls.get(id) ?? 0) + 1;
+ polls.set(id, k);
+ return { status: k < 2 ? "running" : "done", endedAt: Date.now() };
+ },
+ channelOf: async (slug) => (slug === "synth-kitchen" ? { kind: "video", platform: "youtube" } : slug === "synth-social" ? { kind: "posts", platform: "x" } : slug === "synth-other" ? { kind: "video", platform: "rumble" } : null),
+ platformRefusal: async (p) => ((o.held ?? []).includes(p) ? `${p} is held` : null),
+ bucketOf: async (slug) => buckets[slug] ?? null,
+ siteOf: async () => ({ site: "synth" }),
+ openCorpus: async () => {
+ Object.assign(holder, { source: corpus.source, tools: corpus.tools, call: corpus.call.bind(corpus) });
+ return { source: corpus.source, origin: "https://synth.example", build: "synth" };
+ },
+ recordOf: recordReader(o.recs),
+ capRefusal: async () => o.refusal ?? null,
+ pollMs: 1,
+ sleep: async () => {},
+ };
+ const lines: string[] = [];
+ const deps = (paths: ReturnType<typeof store>): TaskDeps => ({
+ llm: { anthropic: { baseUrl: "http://127.0.0.1:9", env: {} }, ollama: { baseUrl: "http://127.0.0.1:9" } },
+ corpus: holder,
+ cuesOf: async () => null,
+ postTextOf: async () => "No, I did not enter the pie contest.",
+ paths,
+ log: (l) => lines.push(l),
+ refresh: hooks,
+ });
+ return { calls, deps, lines, corpus };
+}
+
+const readJson = async (file: string) => JSON.parse(await readFile(file, "utf8"));
+const traceOf = async (paths: ReturnType<typeof store>, n: number) =>
+ (await readFile(iterationFile(paths, "synth", n, "trace.jsonl"), "utf8"))
+ .trim()
+ .split("\n")
+ .map((l) => JSON.parse(l) as Record<string, unknown>);
+
+test("refresh, nothing changed: the fetches and the build waited for, the delta $0, the iteration done with no report", 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, held: ["rumble"] });
+ const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3 }, h.deps(paths));
+ assert.equal(out.status, "done", h.lines.join("\n"));
+ assert.equal(out.usd, 0);
+ assert.match(out.summary, /^Nothing new since 2026-/);
+ // The actions, in order per channel: a sync, its report, what landed to transcription; the posts; the build.
+ // (The channels run side by side: the posts channel's one action lands between.)
+ assert.deepEqual(
+ h.calls.map((c) => c.action).filter((a) => a !== "fetch-posts"),
+ ["sync", "refresh-report", "transcribe-bucket", "publish"],
+ );
+ assert.equal(h.calls.filter((c) => c.action === "fetch-posts").length, 1);
+ assert.deepEqual(h.calls.find((c) => c.action === "transcribe-bucket")!.args, { slug: "synth-kitchen", ids: ["landed-7"] });
+ assert.deepEqual(h.calls.find((c) => c.action === "publish")!.args, { verb: "build", siteId: "synth", force: false });
+ const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile;
+ assert.equal(f.status, "no-change");
+ assert.equal(f.parent, 1);
+ assert.deepEqual(f.fetch.find((s) => s.channel === "synth-other"), { channel: "synth-other", action: "sync", status: "skipped", reason: "rumble is held" });
+ assert.equal(f.build?.status, "done");
+ assert.equal(f.delta?.status, "no-change");
+ assert.deepEqual(f.delta?.matchedSet, { "pie-02": 2, "bread-01": 1 });
+ assert.equal(f.update, undefined);
+ const it = await readIteration("synth", 2, paths);
+ assert.equal(it?.status, "done");
+ assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "no-change", newIds: 0, changed: 0, drifted: 0, deleted: 0, summary: f.summary });
+ await assert.rejects(readFile(iterationFile(paths, "synth", 2, "report.json")), /ENOENT/);
+ const trace = await traceOf(paths, 2);
+ assert.deepEqual(trace.map((e) => e.t).filter((t) => t !== "note"), ["run", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "build", "build", "delta", "run"]);
+ assert.equal(trace.at(-1)!.status, "done");
+});
+
+test("refresh, something new but the cap refuses: held-by-cap with the delta and the estimate, no model called", async () => {
+ const paths = store();
+ await doneSweep(paths);
+ await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths);
+ const recs = [
+ ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r)),
+ { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["about the contest", "it was rigged"] },
+ ];
+ const h = harness({ recs, refusal: "the day's Claude API spend is $20.00, at the daily cap" });
+ const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, h.deps(paths));
+ assert.equal(out.status, "done");
+ assert.equal(out.usd, 0);
+ assert.deepEqual(h.calls, [], "fetch: false runs no editor action");
+ const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile;
+ assert.equal(f.status, "held-by-cap");
+ assert.deepEqual(f.delta?.newIds, ["new-05"]);
+ assert.deepEqual(f.delta?.drifted, ["c2"]);
+ assert.equal(f.update?.refusal, "the day's Claude API spend is $20.00, at the daily cap");
+ // The parent spent $0.80 reading 2 recordings: one more is $0.40, and a revision.
+ assert.equal(f.update?.estimateUsd, 0.7);
+ assert.equal(f.summary, "1 new recording matches · 1 quote changed — held by the cap (about $0.70 to update): the day's Claude API spend is $20.00, at the daily cap");
+ assert.equal(deltaLine(f.delta!), "1 new recording matches · 1 quote changed");
+});
+
+test("the estimate and the revision's feedback", () => {
+ assert.equal(estimateUpdateUsd({ recordings: 4, model: "claude-sonnet-5-5" }), 0.62);
+ assert.equal(estimateUpdateUsd({ recordings: 4, model: "qwen3:8b" }), 0);
+ assert.equal(estimateUpdateUsd({ recordings: 0, model: "claude-sonnet-5-5" }), 0.3);
+ const fb = refreshFeedback({
+ parent: 3,
+ since: "2026-10-01T10:05:00.000Z",
+ findings: "## New\n\n- She says it was rigged: \"it was rigged\" — [New stream @ 0:05](https://synth.example/?v=synth-kitchen%2Fnew-05&t=5)",
+ delta: {
+ quotes: [
+ { citation: "c2", kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, status: "drifted", quote: "I paid for the new mixer myself", now: "I bought the mixer" },
+ { citation: "c1", kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, status: "ok", quote: "q", state: "deleted" },
+ ],
+ } as never,
+ });
+ assert.match(fb, /^A REFRESH of i3 \(made 2026-10-01\)/);
+ assert.match(fb, /NEW FINDINGS[\s\S]*it was rigged/);
+ assert.match(fb, /QUOTES THAT CHANGED[\s\S]*"I paid for the new mixer myself" \(synth-kitchen\/bread-01 @ 0:10\) — now: "I bought the mixer"/);
+ assert.match(fb, /SOURCES GONE FROM THEIR PLATFORM[\s\S]*synth-kitchen\/pie-02 \(deleted on its platform\)/);
+});
+
+test("a refresh iteration names its parent; refresh.json is an iteration file", async () => {
+ const paths = store();
+ await doneSweep(paths);
+ await assert.rejects(createIteration("synth", { kind: "refresh", model: "m" }, paths), /needs the iteration it refreshes/);
+ await createIteration("synth", { kind: "refresh", model: "m", parent: 1 }, paths);
+ await writeIterationFile("synth", 2, "refresh.json", { ok: 1 }, paths);
+});
+
+test("the sources gone, said by where; changes not tracked before an older parent, never a silent 0", async () => {
+ const d = { newIds: [], changed: [], drifted: [], deleted: ["a/1", "a/2", "b/3", "c/4"], goneFromArchive: ["c/4"], removedOnPlatform: [{ source: "a/1", state: "deleted", platform: "youtube" }, { source: "a/2", state: "deleted", platform: "youtube" }, { source: "b/3", state: "private", platform: "rumble" }] };
+ assert.deepEqual(goneParts(d), ["2 sources deleted on YouTube", "1 source made private on Rumble", "1 source gone from the archive"]);
+ assert.equal(deltaLine({ ...d, deleted: ["c/4"], goneFromArchive: ["c/4"], removedOnPlatform: [] }), "1 source gone from the archive");
+ assert.equal(deltaLine({ newIds: [], changed: [], drifted: [], deleted: ["x/1"] }), "1 source deleted", "a record from before the split");
+
+ // A trace with no counts: the refresh says changes were not tracked, and the outcome's `changed` is null.
+ const paths = store();
+ await doneSweep(paths);
+ const noCounts = TRACE.map((e) => (e.t === "enumerate" ? { ...e, counts: undefined } : e));
+ await writeIterationFile("synth", 1, "trace.jsonl", noCounts.map((e) => JSON.stringify(e)).join("\n") + "\n", paths);
+ const b = await refreshBasis("synth", 1, paths);
+ assert.equal(b.countsKnown, false);
+ await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths);
+ const h = harness({ recs: BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: [...r.lines, "the contest came up twice"] } : r)) });
+ const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, h.deps(paths));
+ assert.equal(out.status, "done");
+ const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile;
+ assert.equal(f.delta?.changedTracked, false);
+ assert.deepEqual(f.delta?.changed, [], "bread-01's lines changed, but nothing recorded them before");
+ assert.equal(f.delta?.changedSince, f.basis.at);
+ assert.ok(f.warnings.some((w) => w.startsWith(`changed recordings are not tracked before ${f.basis.at.slice(0, 10)}`)), f.warnings.join("; "));
+ assert.equal(outcomeOf(f).changed, null);
+ assert.equal(outcomeOf({ ...f, delta: { ...(f.delta as RefreshDelta), changedTracked: true } }).changed, 0);
+});
+
+test("a source deleted on its platform: the recheck carries the platform the summary names", async () => {
+ const out = await recheckQuotes(
+ [{ citation: "c1", kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }],
+ { recordOf: recordReader(BASE, { "pie-02": { state: "deleted", platform: "youtube" } }) },
+ );
+ assert.deepEqual({ status: out[0]!.status, state: out[0]!.state, platform: out[0]!.platform }, { status: "ok", state: "deleted", platform: "youtube" });
+});
diff --git a/common/lib/report/draft/refresh/task.ts b/common/lib/report/draft/refresh/task.ts
@@ -0,0 +1,325 @@
+// TASK refresh — re-fetch, see what changed, update (umtool R4; plans/
+// umtool-redesign.md "R4 — Refresh"). ONE editor job over a `refresh`
+// iteration whose parent is the iteration refreshed, in three stages, each
+// logged, traced (trace.jsonl: `fetch`, `build`, `delta`, and the sweep's own
+// events) and kept in the iteration's refresh.json:
+//
+// 1 fetch (Archilyzer, no model) the parent's scope plus every channel its
+// citations touch: the editor's own paced actions — `sync`, then
+// `refresh-report` and `transcribe-bucket` for what landed, per
+// video channel; `fetch-posts` per posts channel — each refused
+// for a platform held or cooling down (skipped, said); waited
+// for. Then a LOCAL BUILD of the site whose build holds the
+// channels (`publish build`, never forced, through the publish
+// lock; never a deploy), waited for — a sweep reads a composed
+// build (corpusSource.ts), and what was fetched is invisible to
+// it until a build holds it.
+// 2 delta (deterministic, no model) the parent's enumerations again over
+// the build (./basis.ts, ./delta.ts): new recordings, changed
+// ones, and every cited quote read again. Nothing changed: the
+// iteration ends `no-change`, $0.
+// 3 update (the model, on its own) within the policy's caps — a cap's
+// refusal ends it `held-by-cap` with the delta and the estimate —
+// a sweep RESTRICTED to the new and changed recordings over the
+// parent's question, then a revision of the parent's report with
+// its findings and the drift fixes. The result is the iteration's
+// report: made current only by the operator.
+//
+// The iteration ENDS `done` whatever the refresh's own status (no-change,
+// held-by-cap, updated); only an update that fails, or a cancel, ends it
+// failed or cancelled. A done refresh without a report is never offered as
+// current (it has nothing to offer).
+
+import { providerOf } from "../../../llm";
+import { iterationLabel, readIteration, readIterationFile, writeIterationFile } from "../../iterations";
+import { reviseReportBody } from "../tasks/revise-report";
+import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "../tasks/run";
+import { sweepAgentBody } from "../tasks/sweep-agent";
+import { sweepPipelineBody } from "../tasks/sweep-pipeline";
+import type { TaskDeps, TaskResult } from "../tasks/types";
+import { refreshBasis } from "./basis";
+import { fetchAndBuild } from "./fetch";
+import { computeDelta, type QuoteReaders, type RecordRead } from "./delta";
+import {
+ REFRESH_FORMAT,
+ REFRESH_VERSION,
+ deltaLine,
+ outcomeOf,
+ platformName,
+ type BuildStep,
+ type FetchStep,
+ type RefreshBasis,
+ type RefreshDelta,
+ type RefreshFile,
+ type RefreshStatus,
+} from "./types";
+
+// The editor's side (./fetch.ts): its actions, jobs, channels, builds, corpus and caps.
+export type { RefreshHooks } from "./fetch";
+
+export type RefreshInput = {
+ article: string;
+ n: number;
+ // The update's model, its extractor (an API sweep's) and the job's cap
+ // (Infinity on a local model).
+ model: string;
+ extractorModel: string;
+ maxUsd: number;
+ // false: no stage 1 (read the corpus as it stands).
+ fetch?: boolean;
+};
+
+// ─── the estimate ───
+
+// A recording read in an API sweep, and a revision, when nothing better is
+// known (the parent's own spend per recording read is preferred).
+export const DEFAULT_USD_PER_RECORDING = 0.08;
+export const DEFAULT_REVISION_USD = 0.3;
+
+/** About what the update costs: the recordings to read at the parent's rate, and a revision. */
+export function estimateUpdateUsd(o: { recordings: number; model: string; parentUsd?: number | null; parentRead?: number | null; revisionUsd?: number }): number {
+ if (providerOf(o.model) !== "api") return 0;
+ const rate = o.parentUsd && o.parentRead ? o.parentUsd / o.parentRead : DEFAULT_USD_PER_RECORDING;
+ const usd = (o.recordings ? Math.max(0.05, rate * o.recordings) : 0) + (o.revisionUsd ?? DEFAULT_REVISION_USD);
+ return Math.round(usd * 100) / 100;
+}
+
+// ─── the feedback the revision is given ───
+
+const clock = (s: number | undefined) => {
+ const t = Math.max(0, Math.floor(s ?? 0));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const sec = t % 60;
+ return h ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+};
+
+// The findings of the restricted sweep's markdown: everything after its title
+// and summary (its sections, with their findings and links).
+export function findingsOf(md: string): string {
+ const i = md.indexOf("\n## ");
+ return (i >= 0 ? md.slice(i + 1) : md).trim();
+}
+
+export function refreshFeedback(o: { parent: number; since: string; delta: RefreshDelta; findings: string | null }): string {
+ const parts: string[] = [
+ `A REFRESH of i${o.parent} (made ${o.since.slice(0, 10)}): the corpus was fetched and searched again. Fold in what changed; keep everything else as it is.`,
+ ];
+ if (o.findings) {
+ parts.push(
+ [
+ "NEW FINDINGS — a sweep of the new and changed recordings found these. Add each that bears on the question with an `add` op, its quote and link EXACTLY as given, in the section it fits (or a new one). Do not duplicate a finding the report already has.",
+ o.findings,
+ ].join("\n"),
+ );
+ }
+ const drifted = o.delta.quotes.filter((q) => q.status === "drifted");
+ if (drifted.length) {
+ parts.push(
+ [
+ "QUOTES THAT CHANGED — the transcript no longer holds these words at their cite. Drop each finding quoting them; if its claim still stands on what the transcript says now, add it again with those words (verbatim) and the same link.",
+ ...drifted.map((q) => `- "${q.quote}" (${q.channel}/${q.id} @ ${clock(q.start)}) — now: "${(q.now ?? "").slice(0, 400)}"`),
+ ].join("\n"),
+ );
+ }
+ const gone = o.delta.quotes.filter((q) => q.status === "missing");
+ const deleted = o.delta.quotes.filter((q) => q.status !== "missing" && q.state);
+ if (gone.length) {
+ parts.push(["SOURCES NOT IN THE ARCHIVE NOW — drop the findings that quote them:", ...gone.map((q) => `- "${q.quote}" (${q.channel}/${q.id})`)].join("\n"));
+ }
+ if (deleted.length) {
+ parts.push(
+ [
+ "SOURCES GONE FROM THEIR PLATFORM (the archive keeps them; their quotes still verify) — keep their findings, and say in the summary that these were since removed:",
+ ...[...new Map(deleted.map((q) => [`${q.channel}/${q.id}`, q])).values()].map((q) => `- ${q.channel}/${q.id} (${q.state} on ${platformName(q.platform)})`),
+ ].join("\n"),
+ );
+ }
+ return parts.join("\n\n");
+}
+
+// ─── the job ───
+
+export async function refresh(input: RefreshInput, deps: TaskDeps): Promise<TaskResult> {
+ return runOnIteration(
+ { article: input.article, n: input.n, deps, maxUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : undefined, kinds: ["refresh"], trace: { task: "refresh", model: input.model } },
+ (h) => refreshBody(h, input),
+ );
+}
+
+async function refreshBody(h: TaskHandle, input: RefreshInput): Promise<TaskOutcome> {
+ const { deps, iteration } = h;
+ const hooks = deps.refresh;
+ if (!hooks) throw new TaskInputError("a refresh runs in the editor (its fetches and build are the editor's actions)");
+ const parent = iteration.parent;
+ if (parent === null) throw new TaskInputError(`"${h.article}" ${iterationLabel(h.n)} names no iteration to refresh`);
+ const now = () => (deps.now ?? (() => new Date()))();
+ const basis: RefreshBasis = await refreshBasis(h.article, parent, h.paths).catch((e: Error) => {
+ throw new TaskInputError(e.message);
+ });
+ const channels = basis.scope.channels;
+ const warnings: string[] = [];
+
+ const file: RefreshFile = {
+ format: REFRESH_FORMAT,
+ version: REFRESH_VERSION,
+ article: h.article,
+ n: h.n,
+ parent,
+ status: "running",
+ summary: "",
+ startedAt: now().toISOString(),
+ basis: {
+ article: basis.article,
+ n: basis.n,
+ queriesOf: basis.queriesOf,
+ question: basis.question,
+ scope: basis.scope,
+ queries: basis.queries,
+ from: basis.from,
+ knownComplete: basis.knownComplete,
+ countsKnown: basis.countsKnown,
+ source: basis.source,
+ at: basis.at,
+ knownCount: Object.keys(basis.known).length,
+ citedCount: basis.cited.length,
+ known: basis.known,
+ },
+ fetch: [],
+ build: null,
+ warnings,
+ };
+ const save = () => writeIterationFile(h.article, h.n, "refresh.json", file, h.paths).catch((e: Error) => h.log(`refresh.json not kept: ${e.message}`));
+ await save();
+ h.log(`refresh of ${h.article} ${iterationLabel(parent)}: ${basis.queries.length} quer${basis.queries.length === 1 ? "y" : "ies"} (from its ${basis.from}), ${channels.length} channel(s), ${basis.cited.length} cited quote(s)`);
+ if (basis.from === "question") warnings.push(`i${parent} recorded no enumeration: its question is searched again as one query`);
+ if (!basis.countsKnown) warnings.push(`changed recordings are not tracked before ${basis.at.slice(0, 10)}: i${parent} recorded no matching-line counts (new ones are still found)`);
+ if (!basis.knownComplete) warnings.push(`i${parent} kept no whole match set: a recording counts as new only when it was uploaded on or after ${basis.at.slice(0, 10)}`);
+ h.trace({ t: "note", text: `refresh of ${iterationLabel(parent)}: ${basis.queries.map((q) => q.query).join(", ")} over ${channels.join(", ")}` });
+ const stages = input.fetch === false ? 2 : 4;
+ let stage = 0;
+ const progress = () => h.progress({ metric: "entries", current: Math.min(stage, stages), total: stages });
+ progress();
+
+ // ─── stage 1: fetch, then build (./fetch.ts) ───
+
+ if (input.fetch !== false) {
+ h.log(`stage 1: fetch ${channels.join(", ")}`);
+ const got = await fetchAndBuild({ channels }, hooks, {
+ prefer: basis.source,
+ ...(deps.signal ? { signal: deps.signal } : {}),
+ log: h.log,
+ trace: h.trace,
+ onFetched: async (steps) => {
+ file.fetch = steps;
+ stage = 1;
+ progress();
+ await save();
+ },
+ });
+ file.fetch = got.fetch;
+ file.build = got.build;
+ warnings.push(...got.warnings);
+ stage = 2;
+ progress();
+ await save();
+ }
+
+ // ─── stage 2: what changed ───
+
+ const opened = await hooks.openCorpus(channels, basis.source);
+ file.corpus = opened;
+ h.log(`stage 2: corpus ${opened.source}${opened.build ? ` (build ${opened.build})` : ""}; links on ${opened.origin}`);
+ const readers: QuoteReaders = {
+ recordOf:
+ hooks.recordOf ??
+ (async (channel, id): Promise<RecordRead | null> => {
+ const cues = await deps.cuesOf(channel, id);
+ return cues ? { cues } : null;
+ }),
+ ...(deps.postTextOf ? { postTextOf: deps.postTextOf } : {}),
+ };
+ const delta = await computeDelta(basis, deps.corpus, readers, { now: now(), ...(deps.signal ? { signal: deps.signal } : {}) });
+ file.delta = delta;
+ if (delta.partial) warnings.push(`the search again was partial${delta.unreached.length ? ` (not reached: ${delta.unreached.join(", ")})` : ""}`);
+ h.trace({ t: "delta", status: delta.status, matched: delta.matched, newIds: delta.newIds, changed: delta.changed, drifted: delta.drifted, deleted: delta.deleted, partial: delta.partial, unreached: delta.unreached });
+ const line = deltaLine(delta, basis.at);
+ h.log(`delta: ${line} (${delta.matched} recording(s) matched)`);
+ stage = input.fetch === false ? 1 : 3;
+ progress();
+
+ const finish = async (status: RefreshStatus, summary: string, outcome: TaskOutcome["status"] = "done"): Promise<TaskOutcome> => {
+ file.status = status;
+ file.summary = summary;
+ file.endedAt = now().toISOString();
+ if (file.update) file.update.usd = Math.round(h.meter.usd * 10_000) / 10_000;
+ await save();
+ stage = stages;
+ progress();
+ return { status: outcome, summary, patch: { refresh: outcomeOf(file) } };
+ };
+
+ if (delta.status === "no-change") return finish("no-change", line);
+
+ // ─── stage 3: the update ───
+
+ const ids = [...new Set([...delta.newIds, ...delta.changed])];
+ const parentIt = await readIteration(h.article, basis.queriesOf, h.paths).catch(() => null);
+ const parentUsd = parentIt ? Object.values(parentIt.usage).reduce((s, u) => s + u.usd, 0) : null;
+ const estimate = estimateUpdateUsd({ recordings: ids.length, model: input.model, parentUsd, parentRead: parentIt?.coverage?.read ?? null });
+ file.update = { model: input.model, estimateUsd: estimate, capUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : null };
+ const refusal = await hooks.capRefusal(estimate);
+ if (refusal) {
+ file.update.refusal = refusal;
+ h.log(`update held by the cap: ${refusal}`);
+ h.trace({ t: "note", text: `update held by the cap: ${refusal}` });
+ return finish("held-by-cap", `${line} — held by the cap (about $${estimate.toFixed(2)} to update): ${refusal}`);
+ }
+ h.log(`stage 3: update on ${input.model} (about $${estimate.toFixed(2)}${Number.isFinite(input.maxUsd) ? `, cap $${input.maxUsd.toFixed(2)}` : ""})`);
+
+ // 3a. a sweep restricted to the new and changed recordings.
+ let findings: string | null = null;
+ if (ids.length) {
+ const sweepIn = {
+ article: h.article,
+ n: h.n,
+ question: basis.question ?? basis.queries.map((q) => q.query).join(", "),
+ channels,
+ ...(basis.scope.from ? { from: basis.scope.from } : {}),
+ ...(basis.scope.to ? { to: basis.scope.to } : {}),
+ model: input.model,
+ origin: opened.origin,
+ ids,
+ terms: basis.queries.map((q) => q.query),
+ };
+ const isApi = providerOf(input.model) === "api";
+ const capped = Number.isFinite(input.maxUsd) ? input.maxUsd * 0.7 : Number.POSITIVE_INFINITY;
+ const out = isApi
+ ? await sweepAgentBody(h, { ...sweepIn, extractorModel: input.extractorModel, maxUsd: capped })
+ : await sweepPipelineBody(h, { ...sweepIn, ...(Number.isFinite(capped) ? { maxUsd: capped } : {}) });
+ if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" };
+ const md = out.status === "done" ? await readIterationFile(h.article, h.n, "sweep.md", h.paths) : null;
+ findings = md ? findingsOf(md) : null;
+ const n = findings ? (findings.match(/^\s*-\s/gm) ?? []).length : 0;
+ file.update.sweep = { ids, status: out.status, summary: out.summary, findings: n };
+ h.log(`the sweep of ${ids.length} recording(s): ${out.status} — ${out.summary}`);
+ if (!n) findings = null;
+ await save();
+ }
+
+ if (!findings && !delta.drifted.length && !delta.deleted.length) {
+ return finish("no-change", `${line} — ${ids.length} recording(s) read; nothing in them for the question`);
+ }
+
+ // 3b. the revision of the parent's report.
+ const feedback = refreshFeedback({ parent, since: basis.at, delta, findings });
+ const rev = await reviseReportBody(h, { article: h.article, n: h.n, model: input.model, feedback, origin: opened.origin, maxUsd: Number.isFinite(input.maxUsd) ? input.maxUsd : Number.POSITIVE_INFINITY, channels });
+ file.update.revision = { status: rev.status, summary: rev.summary };
+ if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" };
+ if (rev.status !== "done") {
+ const r = await finish("failed", `${line} — the revision failed: ${rev.summary}`, "failed");
+ return { ...r, patch: { ...(rev.patch ?? {}), ...(r.patch ?? {}) } };
+ }
+ const r = await finish("updated", `${line} — updated: ${rev.summary}`);
+ return { ...r, patch: { ...(rev.patch ?? {}), ...(r.patch ?? {}) } };
+}
diff --git a/common/lib/report/draft/refresh/types.ts b/common/lib/report/draft/refresh/types.ts
@@ -0,0 +1,298 @@
+// A REFRESH, as data (umtool R4, plans/umtool-redesign.md "R4 — Refresh"):
+// what an iteration was built from (its BASIS), what is different now (the
+// DELTA), and the record the refresh keeps — `refresh.json` beside the new
+// iteration — which the next refresh reads as its basis, the umtool page shows,
+// and R5's scheduler and R6's triage log read. Plain JSON, versioned.
+
+import type { TraceStepStatus } from "../tasks/trace";
+
+export const REFRESH_FORMAT = "archilyzer-refresh" as const;
+export const REFRESH_VERSION = 1 as const;
+
+// One enumeration to run again: the query and the arguments it was run with
+// (absent: the basis scope's).
+export type RefreshQuery = { query: string; regex?: boolean; channels?: string[]; from?: string; to?: string };
+
+// A quoted citation of the report refreshed.
+export type CitedQuote = {
+ citation: string;
+ kind: "video" | "audio" | "post";
+ channel: string;
+ id: string;
+ start?: number;
+ end?: number;
+ quote: string;
+};
+
+// Where the queries came from: a refresh's own record, a sweep's trace, its
+// turns.jsonl (a run before the trace), or — nothing recorded — the question.
+export type BasisFrom = "refresh" | "trace" | "turns" | "question";
+
+// What an iteration was built from.
+export type RefreshBasis = {
+ article: string;
+ // The iteration refreshed, and the one whose enumerations the queries are
+ // (itself, or the sweep it descends from).
+ n: number;
+ queriesOf: number;
+ question: string | null;
+ scope: { channels: string[]; from?: string; to?: string };
+ queries: RefreshQuery[];
+ from: BasisFrom;
+ // Every recording matched then, with its matching lines when they were
+ // recorded (null: not recorded), summed over the queries. The report's own
+ // cited recordings are in it.
+ known: Record<string, number | null>;
+ // Whether `known` carries matching-line counts (a trace from umtool R4 on, a
+ // refresh's record): without them a changed recording cannot be told.
+ countsKnown: boolean;
+ // Whether `known` is the whole match set then. When it is not (a run whose
+ // answers were not kept, or the question alone), a recording counts as new
+ // only when it was uploaded on or after `at`'s day.
+ knownComplete: boolean;
+ cited: CitedQuote[];
+ // The corpus it read (a handle), when recorded.
+ source: string | null;
+ // When it was made (its end).
+ at: string;
+};
+
+// One recording an enumeration matched now.
+export type MatchedRow = { id: string; channel: string | null; date: string | null; title: string | null; matches: number | null };
+
+// A quote against the transcript as it is now.
+export type QuoteRecheckStatus =
+ | "ok"
+ // the words are there, starting a second or more from the cited one
+ | "moved"
+ // the words are not there now
+ | "drifted"
+ // the recording or post is not in the archive now
+ | "missing"
+ // it could not be read (a channel's text not readable, a corpus error)
+ | "unreadable";
+
+export type QuoteRecheck = {
+ citation: string;
+ kind: CitedQuote["kind"];
+ channel: string;
+ id: string;
+ start?: number;
+ status: QuoteRecheckStatus;
+ quote: string;
+ // drifted: the words over the quote's seconds now; moved: where they start now
+ now?: string;
+ nowAt?: number;
+ // The recording's platform state when it is gone from the platform (deleted,
+ // private), and the platform.
+ state?: string;
+ platform?: string;
+ // The en track and the en-orig track's words over the cite, when they differ.
+ enOrig?: { en: string; orig: string };
+ message?: string;
+};
+
+export type DeltaStatus = "no-change" | "changed";
+
+// Stage 2's answer.
+export type RefreshDelta = {
+ at: string;
+ status: DeltaStatus;
+ // Distinct recordings matched now.
+ matched: number;
+ // Matched now and not before (old videos that only now have a transcript among them).
+ newIds: string[];
+ new: MatchedRow[];
+ // Matched before and now, their matching lines changed (a transcript replaced or re-cut).
+ changed: string[];
+ // Whether changes could be told (the basis recorded matching lines); when not,
+ // `changed` is empty because nothing was tracked before `changedSince`.
+ changedTracked: boolean;
+ changedSince?: string;
+ // Matched before, not now (with a complete scan).
+ unmatched: string[];
+ // Citations whose words are not at their cite now.
+ drifted: string[];
+ // The cited sources (`<channel>/<id>`) that are gone: not in the archive,
+ // or deleted / private on their platform.
+ deleted: string[];
+ // The same, split: gone from the archive, and deleted or private on their
+ // platform (the archive keeps those).
+ goneFromArchive: string[];
+ removedOnPlatform: { source: string; state: string; platform: string | null }[];
+ // Citations whose en and en-orig tracks differ over the cite.
+ enOrig: string[];
+ quotes: QuoteRecheck[];
+ partial: boolean;
+ unreached: string[];
+ // The full match set now, with matching lines: the next refresh's `known`.
+ matchedSet: Record<string, number | null>;
+};
+
+// One editor action of stage 1.
+export type FetchStep = {
+ channel: string;
+ action: string;
+ status: TraceStepStatus;
+ jobId?: string;
+ reason?: string;
+ // transcribe-bucket: the recordings that landed.
+ ids?: string[];
+};
+
+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";
+
+export type RefreshUpdate = {
+ model: string;
+ estimateUsd: number;
+ capUsd: number | null;
+ // The cap's refusal, when it held the update.
+ refusal?: string;
+ // The restricted sweep over the new and changed recordings.
+ sweep?: { ids: string[]; status: string; summary: string; findings: number };
+ // The revision of the parent's report.
+ revision?: { status: string; summary: string };
+ usd?: number;
+};
+
+// refresh.json.
+export type RefreshFile = {
+ format: typeof REFRESH_FORMAT;
+ version: typeof REFRESH_VERSION;
+ article: string;
+ n: number;
+ parent: number;
+ status: RefreshStatus;
+ // One line: "4 new recordings match · 2 quotes changed · 1 source deleted",
+ // or "Nothing new since <date>".
+ summary: string;
+ startedAt: string;
+ endedAt?: string;
+ basis: Omit<RefreshBasis, "known" | "cited"> & { knownCount: number; citedCount: number; known: Record<string, number | null> };
+ fetch: FetchStep[];
+ build: BuildStep | null;
+ corpus?: { source: string; build?: string; origin: string };
+ delta?: RefreshDelta;
+ update?: RefreshUpdate;
+ warnings: string[];
+};
+
+// What the job's last log line carries (`@@report-draft {…, refresh}`), and
+// what iteration.json keeps as `refresh`.
+export type RefreshOutcome = {
+ status: RefreshStatus;
+ newIds: number;
+ // null: changes were not tracked (the parent recorded no matching-line counts).
+ changed: number | null;
+ drifted: number;
+ deleted: number;
+ summary: string;
+};
+
+export function outcomeOf(f: Pick<RefreshFile, "status" | "summary" | "delta">): RefreshOutcome {
+ return {
+ status: f.status,
+ newIds: f.delta?.newIds.length ?? 0,
+ changed: f.delta && f.delta.changedTracked === false ? null : (f.delta?.changed.length ?? 0),
+ drifted: f.delta?.drifted.length ?? 0,
+ deleted: f.delta?.deleted.length ?? 0,
+ summary: f.summary,
+ };
+}
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+const PLATFORM_NAMES: Record<string, string> = {
+ youtube: "YouTube",
+ rumble: "Rumble",
+ odysee: "Odysee",
+ twitch: "Twitch",
+ kick: "Kick",
+ archiveorg: "archive.org",
+ bitchute: "BitChute",
+ twitter: "X",
+ bluesky: "Bluesky",
+};
+/** A platform's name as a person writes it ("YouTube"); unknown: "its platform". */
+export const platformName = (p: string | null | undefined) => (p ? (PLATFORM_NAMES[p] ?? p) : "its platform");
+
+/** The sources gone, said by where: "1 source deleted on YouTube", "1 gone from the archive". */
+export function goneParts(d: Pick<RefreshDelta, "deleted"> & Partial<Pick<RefreshDelta, "goneFromArchive" | "removedOnPlatform">>): string[] {
+ // A record from before the split: its count, unsplit.
+ if (!d.goneFromArchive && !d.removedOnPlatform) return d.deleted.length ? [`${plural(d.deleted.length, "source")} deleted`] : [];
+ const out: string[] = [];
+ const by = new Map<string, number>();
+ for (const r of d.removedOnPlatform ?? []) {
+ const k = `${r.state === "private" ? "made private" : "deleted"} on ${platformName(r.platform)}`;
+ by.set(k, (by.get(k) ?? 0) + 1);
+ }
+ for (const [k, n] of by) out.push(`${plural(n, "source")} ${k}`);
+ const gone = d.goneFromArchive?.length ?? 0;
+ if (gone) out.push(`${plural(gone, "source")} gone from the archive`);
+ return out;
+}
+
+/** The delta in one line, as the umtool page shows it. */
+export function deltaLine(
+ d: Pick<RefreshDelta, "newIds" | "changed" | "drifted" | "deleted"> & Partial<Pick<RefreshDelta, "goneFromArchive" | "removedOnPlatform">>,
+ since?: string | null,
+): string {
+ const parts = [
+ d.newIds.length ? `${plural(d.newIds.length, "new recording")} ${d.newIds.length === 1 ? "matches" : "match"}` : null,
+ d.changed.length ? `${plural(d.changed.length, "recording")} changed` : null,
+ d.drifted.length ? `${plural(d.drifted.length, "quote")} changed` : null,
+ ...goneParts(d),
+ ].filter(Boolean);
+ return parts.length ? parts.join(" · ") : `Nothing new${since ? ` since ${since.slice(0, 10)}` : ""}`;
+}
+
+// ─── the plan (what a Refresh would do; nothing written) ───
+
+export type RefreshPlanChannel = {
+ slug: string;
+ // video | posts; null: not a channel of this editor (skipped)
+ kind: "video" | "posts" | null;
+ platform: string | null;
+ // The editor actions it would run, in order ("sync", "refresh-report",
+ // "transcribe-bucket (what lands)"; "fetch-posts").
+ actions: string[];
+ // Why it is skipped (held, cooling down, not a channel here).
+ skip?: string;
+ localOnly?: boolean;
+};
+
+export type RefreshPlan = {
+ article: string;
+ // The iteration refreshed.
+ parent: {
+ n: number;
+ kind: string;
+ model: string;
+ question: string | null;
+ at: string;
+ from: BasisFrom;
+ queries: string[];
+ knownCount: number;
+ knownComplete: boolean;
+ citedCount: number;
+ };
+ scope: { channels: string[]; from?: string; to?: string };
+ fetch: boolean;
+ channels: RefreshPlanChannel[];
+ // The site built (never deployed), or null with why.
+ build: { site: string | null; reason?: string; builtAt?: string | null };
+ // The corpus the delta reads now.
+ corpus: { source: string | null; build?: string | null };
+ model: string;
+ provider: "api" | "local";
+ extractor: string | null;
+ // The update's cap (null: a local model), the day's spend against the daily cap.
+ capUsd: number | null;
+ daily: { usd: number; cap: number } | null;
+ // What an update costs per recording read (the parent's rate, else the default) and the revision.
+ estimate: { perRecordingUsd: number; revisionUsd: number; from: "parent" | "default" };
+ refusals: string[];
+ warnings: string[];
+};
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -17,6 +17,7 @@ import { TaskInputError, runOnIteration } from "./run";
import { threads } from "./threads";
import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types";
import { youtube } from "./youtube";
+import { refresh, type RefreshInput } from "../refresh/task";
export * from "./types";
export { TaskInputError, runOnIteration, usageOf } from "./run";
@@ -60,6 +61,8 @@ export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, ty
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes";
export { projectDirOf } from "./project";
+// umtool R4: the sweep's `ids` restriction (a general sweep option).
+export { restrictEnumerateText, restrictTools } from "./restrict";
// umtool R3: a sweep's trace (trace.jsonl).
export { TRACE_FILE, enumerateOf, openTrace, runStartsOf, type TraceCite, type TraceEvent, type TraceInput } from "./trace";
@@ -70,6 +73,7 @@ export type TaskInput =
| ({ task: "revise-video" } & ReviseVideoInput)
| ({ task: "narrate" } & NarrateInput)
| ({ task: "research" } & ResearchInput)
+ | ({ task: "refresh" } & RefreshInput)
| ({ task: "cut" } & CutInput)
| ({ task: "onscreen" } & OnscreenInput)
| ({ task: "teaser" } & TeaserInput)
@@ -89,6 +93,8 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> {
return narrate(input, deps);
case "research":
return research(input, deps);
+ case "refresh":
+ return refresh(input, deps);
case "flips":
return flips(input, deps);
case "threads":
diff --git a/common/lib/report/draft/tasks/restrict.ts b/common/lib/report/draft/tasks/restrict.ts
@@ -0,0 +1,85 @@
+// A SWEEP RESTRICTED TO GIVEN RECORDINGS (umtool R4; a general sweep option —
+// 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)
+// 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
+// get_post, get_thread
+// search_transcripts not offered (its hits are the whole corpus's)
+//
+// Pure over the tools it is handed.
+
+import type { AgentTool } from "../agentTool";
+
+const ROW = /^- (\S+) \| (?:video|post|audio) \| /;
+
+/** enumerate_matches' answer with only the rows of `only` kept, and a line saying so. */
+export function restrictEnumerateText(text: string, only: ReadonlySet<string>): string {
+ let kept = 0;
+ let dropped = 0;
+ const lines: string[] = [];
+ for (const raw of text.split("\n")) {
+ const m = ROW.exec(raw.trim());
+ if (m) {
+ if (only.has(m[1]!)) {
+ kept++;
+ lines.push(raw);
+ } else dropped++;
+ continue;
+ }
+ lines.push(raw);
+ }
+ return `${lines.join("\n")}\n\n(this sweep is restricted to ${only.size} recording(s): ${kept} of the ${kept + dropped} row(s) above are kept)`;
+}
+
+const idsOf = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);
+
+/** A tool narrowed to `only` (see the head of this file); null: not offered. */
+export function restrictedTool(t: AgentTool, only: ReadonlySet<string>): AgentTool | null {
+ const outside = (id: string) => `restricted: ${id} is not one of this sweep's ${only.size} recording(s) (${[...only].slice(0, 20).join(", ")})`;
+ switch (t.name) {
+ case "search_transcripts":
+ return null;
+ case "enumerate_matches":
+ return { ...t, run: async (input: unknown, ctx) => restrictEnumerateText(await t.run(input, ctx), only) };
+ case "get_transcripts":
+ case "extract_batch":
+ return {
+ ...t,
+ run: async (input: unknown, ctx) => {
+ const i = (input ?? {}) as Record<string, unknown>;
+ const ids = idsOf(i.video_ids);
+ const keep = ids.filter((id) => only.has(id));
+ const drop = ids.filter((id) => !only.has(id));
+ if (!keep.length) throw new Error(ids.length ? outside(ids[0]!) : `${t.name} needs video_ids`);
+ const out = await t.run({ ...i, video_ids: keep }, ctx);
+ return drop.length ? `${out}\n\n(not read — outside this sweep's recordings: ${drop.join(", ")})` : out;
+ },
+ };
+ case "get_transcript":
+ case "get_post":
+ case "get_thread": {
+ const key = t.name === "get_transcript" ? "video_id" : "post_id";
+ return {
+ ...t,
+ run: async (input: unknown, ctx) => {
+ const i = (input ?? {}) as Record<string, unknown>;
+ const id = typeof i[key] === "string" ? (i[key] as string) : typeof i.thread_id === "string" ? (i.thread_id as string) : "";
+ if (id && !only.has(id)) throw new Error(outside(id));
+ return t.run(input, ctx);
+ },
+ };
+ }
+ default:
+ return t;
+ }
+}
+
+/** Every tool narrowed to `only` (none given: the tools as they are). */
+export function restrictTools(tools: readonly AgentTool[], only: readonly string[] | undefined): AgentTool[] {
+ if (!only?.length) return [...tools];
+ const set = new Set(only);
+ return tools.map((t) => restrictedTool(t, set)).filter((t): t is AgentTool => t !== null);
+}
diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts
@@ -167,7 +167,9 @@ export async function reviseReport(input: ReviseReportInput, deps: TaskDeps): Pr
);
}
-async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promise<TaskOutcome> {
+// The revision's body over a handle (exported: a refresh runs it on its own
+// iteration with the feedback it composes — draft/refresh/task.ts).
+export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promise<TaskOutcome> {
const { deps, iteration } = h;
const model = input.model ?? iteration.model;
const feedback = (input.feedback ?? iteration.feedback ?? "").trim();
diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts
@@ -35,8 +35,9 @@ import { plainAnswer, userCharsFor } from "./llmText";
import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep, type QuoteProblem } from "./quotes";
import { reportFile } from "./reportFile";
+import { restrictTools } from "./restrict";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
-import { CoverageTally, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace";
+import { CoverageTally, countsOf, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace";
import type { TaskDeps, TaskResult } from "./types";
// The corpus reads the agent may make (no fetch_clip, enqueue, notes or jobs:
@@ -74,14 +75,21 @@ export type SweepAgentInput = {
batchSize?: number;
maxTurns?: number;
terms?: string[];
+ // Only these recordings (umtool R4: a refresh's new ones; R6's escalation):
+ // an enumeration shows only them, a read of any other is refused, and the
+ // free-text search is not offered. Default: the iteration's scope.ids.
+ ids?: string[];
// The web: Claude's server search (max uses) plus the deps' web_fetch; a
// local model gets the deps' web tools. Default on.
web?: boolean;
webSearchMaxUses?: number;
};
-function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from?: string; to?: string }): string {
+function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from?: string; to?: string; ids?: string[] }): string {
const terms = o.terms?.length ? ` The operator chose these terms: ${o.terms.join(", ")} — use them.` : "";
+ const only = o.ids?.length
+ ? `\n- THIS SWEEP IS RESTRICTED to ${o.ids.length} recording(s): ${o.ids.join(", ")}. Read only these — enumerate_matches shows only them, and a read of any other is refused. Report what they say; nothing else is in scope.`
+ : "";
const dates =
o.from || o.to
? `\n- The scope is dated${o.from ? ` from ${o.from}` : ""}${o.to ? ` to ${o.to}` : ""}: pass date_from / date_to on every enumerate and search.`
@@ -94,7 +102,7 @@ function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from
"- `extract_batch` IS the plan's extractor subagent: give it the batch's video ids, the sweep's queries and the directive; it returns the verbatim lines. You may call it for several batches in one turn.",
"- `write_report` / `edit_report` / `read_report` are your Write/Edit tools, for the report file only.",
"- You cannot fetch clips, enqueue jobs or write notes here: skip those steps (the clips for every citation are fetched after you finish).",
- `- The plan's \`query\` is the request's own wording. Search with real terms instead — a few words or phrases the question is about (and their obvious variants), not the sentence.${terms}${dates}`,
+ `- The plan's \`query\` is the request's own wording. Search with real terms instead — a few words or phrases the question is about (and their obvious variants), not the sentence.${terms}${dates}${only}`,
"- Your context is trimmed as you go: a tool result older than the last few is dropped once you have merged it. Merge each fragment into the report BEFORE asking for many more, and use read_report rather than memory.",
"",
"The report must convert as a sweep:",
@@ -207,13 +215,16 @@ export async function sweepAgent(input: SweepAgentInput, deps: TaskDeps): Promis
);
}
-async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<TaskOutcome> {
+// The sweep's body over a handle (exported: a refresh runs it on its own
+// iteration, restricted to its new recordings — draft/refresh/task.ts).
+export async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<TaskOutcome> {
const { deps, iteration } = h;
const question = (input.question ?? iteration.question ?? "").trim();
const channels = input.channels ?? iteration.scope?.channels ?? [];
const model = input.model ?? iteration.model;
const from = input.from ?? iteration.scope?.from;
const to = input.to ?? iteration.scope?.to;
+ const only = input.ids ?? iteration.scope?.ids;
if (!question) throw new TaskInputError("a sweep needs its question");
if (!channels.length) throw new TaskInputError("a sweep needs its channels");
const origin = input.origin.replace(/\/+$/, "");
@@ -241,23 +252,28 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
maxUsd: input.maxUsd,
batchSize: batch,
...(seed ? { seed: { chars: seed.length } } : {}),
+ ...(only?.length ? { ids: only } : {}),
});
- h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}`);
+ h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}${only?.length ? `, restricted to ${only.length} recording(s)` : ""}`);
const request =
`${question} channels=${channels.join(",")} batch_size=${batch} parse_model=${input.extractorModel} report=sweep.md`;
const plan = await deps.corpus.call("sweep_plan", { request });
- const corpusTools = deps.corpus.tools
- .filter((t) => (SWEEP_READ_TOOLS as readonly string[]).includes(t.name))
- .map((t) =>
- t.name === "get_transcripts"
- ? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) }
- : t,
- )
- .map((t) => watched(h, t, watch));
+ // A restricted sweep's tools are narrowed BEFORE they are watched: the trace
+ // records what the agent was answered.
+ const corpusTools = restrictTools(
+ deps.corpus.tools
+ .filter((t) => (SWEEP_READ_TOOLS as readonly string[]).includes(t.name))
+ .map((t) =>
+ t.name === "get_transcripts"
+ ? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) }
+ : t,
+ ),
+ only,
+ ).map((t) => watched(h, t, watch));
const web = input.web === false ? [] : (deps.web ?? []);
- const tools = [...corpusTools, extractTool(h, input, rewrite, extracts, watch), ...file.tools, ...web];
+ const tools = [...corpusTools, ...restrictTools([extractTool(h, input, rewrite, extracts, watch)], only), ...file.tools, ...web];
const isApi = providerOf(model) === "api";
const maxTurns = input.maxTurns ?? 150;
// The job's progress: every model turn, the repair round's included.
@@ -291,7 +307,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
const run = await runAgent({
llm: deps.llm,
model,
- system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to }),
+ system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to, ...(only?.length ? { ids: only } : {}) }),
user: seed ? `${plan}\n\n${SEED_NOTE}` : plan,
tools,
meter: h.meter,
@@ -430,6 +446,7 @@ function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool {
const e = enumerateOf(out);
w.cov.enumerated(e.ids, e.partial, e.unreached);
const q = (input as { query?: unknown } | null)?.query;
+ const counts = countsOf(e.rows);
h.trace({
t: "enumerate",
query: typeof q === "string" ? q : "",
@@ -439,6 +456,7 @@ function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool {
unreached: e.unreached,
...(e.total !== null ? { total: e.total } : {}),
...(e.posts ? { posts: e.posts } : {}),
+ ...(counts ? { counts } : {}),
turn,
phase,
});
diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts
@@ -127,6 +127,10 @@ export type SweepPipelineInput = {
terms?: string[];
maxVideos?: number;
maxClaims?: number;
+ // Only these recordings (umtool R4; a general sweep option): the worklist is
+ // the enumeration's rows of these ids, and any of them the terms did not
+ // find is read too. Default: the iteration's scope.ids.
+ ids?: string[];
};
// ─── Pure helpers (exported for the tests) ───
@@ -290,6 +294,12 @@ async function ask<T>(h: TaskHandle, model: string, system: string, user: string
return out;
}
+// The pipeline's body over a handle (exported: a refresh runs it on its own
+// iteration, restricted to its new recordings — draft/refresh/task.ts).
+export async function sweepPipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> {
+ return pipelineBody(h, input);
+}
+
async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> {
const { deps, iteration } = h;
const question = (input.question ?? iteration.question ?? "").trim();
@@ -300,13 +310,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
const origin = input.origin.replace(/\/+$/, "");
const maxVideos = input.maxVideos ?? 40;
const maxClaims = input.maxClaims ?? 40;
+ const only = input.ids ?? iteration.scope?.ids;
if (!question) throw new TaskInputError("a sweep needs its question");
if (!channels.length) throw new TaskInputError("a sweep needs its channels");
const event = (e: Record<string, unknown>) => h.turns([e]);
h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}`);
const cov = new CoverageTally();
h.setCoverage(() => cov.value());
- h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin });
+ h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin, ...(only?.length ? { ids: only } : {}) });
// 1. terms (the model, unless given)
let terms: string[] = [];
@@ -352,6 +363,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
unreached: e.unreached,
...(e.total !== null ? { total: e.total } : {}),
...(e.posts ? { posts: e.posts } : {}),
+ counts: Object.fromEntries(vids.map((v) => [v.id, v.hits[term] ?? 0])),
});
for (const v of vids) {
const had = found.get(v.id);
@@ -379,6 +391,15 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8);
}
}
+ if (only?.length) {
+ // A restricted sweep: only these recordings, each read even when the
+ // terms did not find it (its windows are what the terms match in it).
+ const set = new Set(only);
+ for (const id of [...found.keys()]) if (!set.has(id)) found.delete(id);
+ for (const id of only) if (!found.has(id)) found.set(id, { id, channel: channels.length === 1 ? channels[0]! : "", date: "", title: id, hits: {} });
+ h.log(`restricted to ${only.length} recording(s)`);
+ h.trace({ t: "note", text: `restricted to ${only.length} recording(s): ${only.slice(0, 20).join(", ")}` });
+ }
const nEnum = found.size;
const weight = new Map(terms.map((t, i) => [t, 1 / (i + 1)]));
const order = [...found.values()].sort((a, b) => {
diff --git a/common/lib/report/draft/tasks/trace.test.ts b/common/lib/report/draft/tasks/trace.test.ts
@@ -17,6 +17,7 @@ import {
TRACE_MAX_LINES,
boundEvent,
citeOfCitation,
+ countsOf,
enumerateOf,
idsReadBy,
linesOf,
@@ -58,7 +59,17 @@ test("enumerateOf: the rows' ids, partial, the channels never reached, the total
assert.deepEqual(e.unreached, ["synth-other", "synth-third"]);
assert.equal(e.total, 3);
const whole = enumerateOf('1 match(es) for "x" — the complete worklist:\n\n- a1 | video | C | 2024-01-01 | 1 match(es) | T\n\n(complete set: yes; 1 match(es); …)');
- assert.deepEqual(whole, { ids: ["a1"], videos: 1, posts: 0, partial: false, unreached: [], total: 1 });
+ assert.deepEqual(whole, {
+ ids: ["a1"],
+ videos: 1,
+ posts: 0,
+ partial: false,
+ unreached: [],
+ total: 1,
+ // umtool R4: each row as it reads (a refresh compares the matching lines).
+ rows: [{ id: "a1", kind: "video", channel: "C", date: "2024-01-01", matches: 1, title: "T" }],
+ });
+ assert.deepEqual(countsOf(enumerateOf(PARTIAL).rows), { "pie-stream-02": 2, "bread-day-01": 1, "17": 1 });
assert.deepEqual(enumerateOf('No matches for "x".(complete set: yes; 0 match(es); 0 batch(es) of 10)').ids, []);
});
diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts
@@ -16,6 +16,15 @@
// {t: "note", text}
// {t: "run", phase: "end", status, summary, usd, minutes, coverage?}
//
+// A REFRESH (umtool R4, draft/refresh) adds its stages' own:
+// {t: "fetch", channel, action, status, jobId?, reason?, ids?}
+// one editor action of stage 1
+// {t: "build", site, status, jobIds?, reason?} the local build it waited on
+// {t: "delta", status, matched, newIds, changed, drifted, deleted, partial,
+// unreached} stage 2's answer
+// and an enumeration may carry `counts` (each id's matching lines), so the
+// next refresh can tell a recording whose transcript changed.
+//
// Every line also carries `at` (ISO time) and `run` (1 for the file's first
// run; a resumed job's run is 2, …). An agent's events carry `turn` and
// `phase` ("agent" or "repair") so a step can be put on the turn that made it.
@@ -72,15 +81,34 @@ export type TraceInput =
maxUsd?: number;
batchSize?: number;
seed?: { chars: number };
+ // A sweep restricted to these recordings (umtool R4).
+ ids?: string[];
}
| { t: "terms"; terms: string[]; extra?: boolean }
- | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; turn?: number; phase?: string; error?: string }
+ | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record<string, number>; turn?: number; phase?: string; error?: string }
| { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string }
| { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string }
| { t: "cost"; step: string; usd: number; model: string; total: number; turn?: number; phase?: string; calls?: string[]; text?: string }
| { t: "check"; quote: string; cite: TraceCite; ok: boolean; reason?: string; stage: CheckStage; dropped?: boolean; claim?: string; round?: number }
| { t: "finding"; section: string; claim: string; cites: TraceCite[] }
- | { t: "note"; text: string; turn?: number; phase?: string };
+ | { t: "note"; text: string; turn?: number; phase?: string }
+ // A refresh's stages (umtool R4).
+ | { t: "fetch"; channel: string; action: string; status: TraceStepStatus; jobId?: string; reason?: string; ids?: string[] }
+ | { t: "build"; site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string }
+ | {
+ t: "delta";
+ status: string;
+ matched: number;
+ newIds: string[];
+ changed: string[];
+ drifted: string[];
+ deleted: string[];
+ partial: boolean;
+ unreached: string[];
+ };
+
+// How one of a refresh's editor steps went.
+export type TraceStepStatus = "queued" | "running" | "done" | "failed" | "cancelled" | "skipped" | "refused" | "waiting";
export type TraceEvent = TraceInput & { at: string; run: number };
@@ -101,6 +129,11 @@ const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}…
export function boundEvent(e: TraceInput): TraceInput {
const o = { ...e } as Record<string, unknown>;
if (Array.isArray(o.ids)) o.ids = (o.ids as string[]).slice(0, TRACE_MAX_IDS);
+ for (const k of ["newIds", "changed", "drifted", "deleted"]) if (Array.isArray(o[k])) o[k] = (o[k] as string[]).slice(0, TRACE_MAX_IDS);
+ if (o.counts && typeof o.counts === "object") {
+ const entries = Object.entries(o.counts as Record<string, number>);
+ if (entries.length > TRACE_MAX_IDS) o.counts = Object.fromEntries(entries.slice(0, TRACE_MAX_IDS));
+ }
if (Array.isArray(o.lines)) {
const lines = (o.lines as string[]).map((l) => cut(l, TRACE_LINE_CHARS));
o.lines = lines.length > TRACE_MAX_LINES ? [...lines.slice(0, TRACE_MAX_LINES), `(+${lines.length - TRACE_MAX_LINES} more lines)`] : lines;
@@ -175,19 +208,36 @@ export async function openTrace(o: {
// ─── Reading what the corpus tools answered (pure; the tests use them) ───
const ENUM_ROW = /^- (\S+) \| (video|post|audio) \| /;
+// The whole row: id | kind | channel | date | N match(es) | title[ | mirrors].
+const ENUM_FULL = /^- (\S+) \| (video|post|audio) \| (.*?) \| ([^|]*?) \| (\d+) match\(es\) \| (.*)$/;
+
+// One row of enumerate_matches' answer, as far as it reads.
+export type EnumeratedRow = { id: string; kind: "video" | "post" | "audio"; channel: string | null; date: string | null; matches: number | null; title: string | null };
// enumerate_matches' answer: its rows' ids, whether the scan was capped, and
-// the channels a capped scan never reached.
-export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; total: number | null } {
+// 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[] } {
const ids: string[] = [];
+ const rows: EnumeratedRow[] = [];
let videos = 0;
let posts = 0;
for (const raw of text.split("\n")) {
- const m = ENUM_ROW.exec(raw.trim());
+ const line = raw.trim();
+ const m = ENUM_ROW.exec(line);
if (!m) continue;
ids.push(m[1]!);
if (m[2] === "post") posts++;
else videos++;
+ const f = ENUM_FULL.exec(line);
+ rows.push({
+ id: m[1]!,
+ kind: m[2] as EnumeratedRow["kind"],
+ channel: f ? f[3]!.trim() : null,
+ date: f ? f[4]!.trim() || null : null,
+ matches: f ? Number(f[5]) : null,
+ title: f ? f[6]!.replace(/ \| ⧉ .*$/, "").trim() : null,
+ });
}
const partial = /COVERAGE PARTIAL/.test(text);
const unreached: string[] = [];
@@ -195,7 +245,20 @@ export function enumerateOf(text: string): { ids: string[]; videos: number; post
// 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());
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 };
+ return { ids, videos, posts, partial, unreached, total: total ? Number(total[1]) : null, rows };
+}
+
+// Each row's matching lines, by id (a row whose count does not read is left
+// out); undefined when none reads.
+export function countsOf(rows: readonly EnumeratedRow[]): Record<string, number> | undefined {
+ const out: Record<string, number> = {};
+ let any = false;
+ for (const r of rows) {
+ if (r.matches === null) continue;
+ out[r.id] = r.matches;
+ any = true;
+ }
+ return any ? out : undefined;
}
// The ids a corpus read names (get_transcripts' video_ids, get_transcript's
diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts
@@ -15,6 +15,7 @@ import type { readIteration } from "../../iterations";
import type { Report } from "../../schema";
import type { ResearchEditor } from "../research/tools";
import type { DeckChecks } from "./deckChecks";
+import type { RefreshHooks } from "../refresh/fetch";
// The iterations store's paths (S4 takes them on every call).
export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>;
@@ -57,6 +58,9 @@ export type TaskDeps = {
editor?: ResearchEditor;
// The editor's channels (a research run imports into these first).
editorChannels?: () => Promise<EditorChannel[]>;
+ // A refresh's editor (umtool R4): its fetches, build, corpus and caps
+ // (draft/refresh/task.ts). Without it a refresh is refused.
+ refresh?: RefreshHooks;
// The iterations store (default: getPaths()).
paths?: StorePaths;
now?: () => Date;
@@ -88,5 +92,5 @@ export type TaskResult = {
// The media tasks (narrate first; release 28's cut, onscreen, teaser, flips,
// threads and youtube) are generationSettings' MEDIA_STEP_TASKS: each a step
// on a done iteration (./media.ts).
-export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", ...MEDIA_STEP_TASKS] as const;
+export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", "refresh", ...MEDIA_STEP_TASKS] as const;
export type TaskName = (typeof TASK_NAMES)[number];
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -59,7 +59,10 @@ export const ITERATION_FILENAME = "iteration.json";
export const ITERATIONS_CURRENT_FILENAME = "current.json";
export const ITERATIONS_CURRENT_FORMAT = "archilyzer-iterations-current";
-export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research"] as const;
+// `refresh` (umtool R4, draft/refresh): fetch what is new, say what changed
+// against its parent, and fold it in — a revision of its parent that names no
+// feedback of its own.
+export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research", "refresh"] as const;
export type IterationKind = (typeof ITERATION_KINDS)[number];
// `queued`: created for a job that has not started; the rest as a job ends.
export const ITERATION_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const;
@@ -72,11 +75,15 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number];
// `seed.md`: a seeded sweep's starting report (a research board, umtool R2).
// `trace.jsonl`: a sweep's structured trace, appended as it runs (umtool R3,
// draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl.
-export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl"] as const;
+// `refresh.json`: a refresh's fetches, build and delta (umtool R4,
+// draft/refresh/types.ts RefreshFile).
+export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json"] as const;
export type IterationFile = (typeof ITERATION_FILES)[number];
-// A revision needs something to revise.
+// A revision needs something to revise (and feedback saying how); a refresh
+// needs the iteration it refreshes (its feedback is what it finds).
const NEEDS_PARENT: readonly IterationKind[] = ["revise-report", "revise-video"];
+const NEEDS_PARENT_ONLY: readonly IterationKind[] = ["refresh"];
// ─── The schema ───
@@ -124,6 +131,8 @@ export const iterationScopeSchema = z.looseObject({
channels: z.array(channelSlug).optional(),
from: ymd.optional(),
to: ymd.optional(),
+ // A sweep restricted to these recordings (umtool R4: a refresh's new ones).
+ ids: z.array(z.string().min(1)).optional(),
});
export type IterationScope = z.infer<typeof iterationScopeSchema>;
@@ -215,6 +224,7 @@ export function parseIteration(
if (it.parent !== null && it.parent >= it.n) problems.push(`parent: i${it.parent} is not an earlier iteration`);
if (it.copyOf !== null && it.copyOf >= it.n) problems.push(`copyOf: i${it.copyOf} is not an earlier iteration`);
if (NEEDS_PARENT.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} revises an iteration`);
+ if (NEEDS_PARENT_ONLY.includes(it.kind) && it.parent === null) problems.push(`parent: a ${it.kind} names the iteration it refreshes`);
return problems.length ? { ok: false, problems } : { ok: true, value: it };
}
@@ -427,6 +437,9 @@ async function createLocked(id: string, input: NewIteration, paths: StorePaths,
if (parent === null) throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it revises (parent)`);
if (!input.feedback?.trim()) throw new ArticleRegistryError(`a ${input.kind} iteration needs feedback: say what to change`);
}
+ if (NEEDS_PARENT_ONLY.includes(input.kind) && parent === null) {
+ throw new ArticleRegistryError(`a ${input.kind} iteration needs the iteration it refreshes (parent)`);
+ }
if ((input.kind === "sweep" || input.kind === "research") && parent === null && !input.question?.trim() && copyOf === null) {
throw new ArticleRegistryError(`a ${input.kind} iteration needs its question`);
}
@@ -625,7 +638,7 @@ export async function addIterationUsage(
}
function fileText(name: IterationFile, data: string | Uint8Array | object, id: string): string | Buffer {
- if (name === "report.json" || name === "proposals.json") {
+ if (name === "report.json" || name === "proposals.json" || name === "refresh.json") {
let value: unknown;
if (typeof data === "string" || data instanceof Uint8Array) {
try {
@@ -645,7 +658,7 @@ function fileText(name: IterationFile, data: string | Uint8Array | object, id: s
throw new ArticleRegistryError(`the iteration's report.json is "${String((value as { id?: unknown }).id)}", not "${id}"`);
}
} else if (!value || typeof value !== "object") {
- throw new ArticleRegistryError("proposals.json is a JSON object or list");
+ throw new ArticleRegistryError(`${name} is a JSON object or list`);
}
return `${JSON.stringify(value, null, 2)}\n`;
}
diff --git a/common/lib/report/quoteWords.ts b/common/lib/report/quoteWords.ts
@@ -0,0 +1,108 @@
+// A QUOTE AGAINST THE TRANSCRIPT AS IT IS NOW — the word-level re-verify a
+// research board runs on a pinned quote (umtool R2, lib/research/boards.ts
+// verifyQuote) and a refresh runs on every quote its parent report cites
+// (umtool R4, draft/refresh). Pure: the caller reads the cues (a board through
+// the MCP engine, a refresh through the editor's corpus); this says what they
+// hold.
+//
+// wordsOf / holdsWords the comparison: case, punctuation and spacing
+// aside, whole words, in order
+// windowAround the cues within ±span s of the cite, the one
+// starting nearest the cite lit (R1's windowOf)
+// checkWordsInWindow ok (and where the words start now, when they
+// moved a second or more) or drifted (with the
+// words over the quote's own seconds now)
+// enOrigDifference the words of the `en` and the `en-orig` tracks
+// over the cite, when they differ — the served `en`
+// track can rewrite what was said
+
+export type WordCue = { start: number; end?: number; text: string };
+export type WindowCue = { t: number; end?: number; text: string };
+
+/** The words of a text, for comparing: lowercase, apostrophes kept, everything else a space. */
+export function wordsOf(text: string | null | undefined): string {
+ return String(text ?? "")
+ .toLowerCase()
+ .replace(/[‘’ʼ`]/g, "'")
+ .replace(/[^\p{L}\p{N}' ]+/gu, " ")
+ .replace(/'+/g, "'")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+/** Do `inside`'s words hold `quote`'s, in order and whole? */
+export function holdsWords(inside: string, quote: string): boolean {
+ const q = wordsOf(quote);
+ if (!q) return false;
+ return ` ${wordsOf(inside)} `.includes(` ${q} `);
+}
+
+/** Cue texts joined as one line. */
+export const joinedCues = (cs: readonly { text: string }[]): string => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" ");
+
+/** The cues starting within ±span s of `t`, and which of them is the one starting nearest `t` (-1: none in the window). */
+export function windowAround(all: readonly WordCue[], t: number, span = 30): { cues: WindowCue[]; lit: number } {
+ let litAll = -1;
+ let best = Infinity;
+ for (let i = 0; i < all.length; i++) {
+ const d = Math.abs(all[i]!.start - t);
+ if (d < best) {
+ best = d;
+ litAll = i;
+ }
+ }
+ const cues: WindowCue[] = [];
+ let lit = -1;
+ for (let i = 0; i < all.length; i++) {
+ const c = all[i]!;
+ if (c.start < t - span || c.start > t + span) continue;
+ if (i === litAll) lit = cues.length;
+ cues.push({ t: c.start, ...(c.end !== undefined ? { end: c.end } : {}), text: c.text });
+ }
+ return { cues, lit };
+}
+
+export type WordsVerdict =
+ | { status: "ok"; nowAt?: number }
+ // `now`: the words over the quote's own seconds now ("" when the window is empty).
+ | { status: "drifted"; now: string; nowAt?: number; empty?: boolean };
+
+/** The longest run of cues a quote is looked for in (a pin spans at most this many). */
+export const MAX_QUOTE_CUES = 12;
+
+/**
+ * The quote against the window around its cite: its words found → ok, with
+ * where they start now when that is a second or more from `t`; else drifted,
+ * with what the transcript says over the quote's seconds now.
+ */
+export function checkWordsInWindow(quote: string, cite: { t: number; end: number }, win: { cues: readonly WindowCue[]; lit: number }): WordsVerdict {
+ const cues = win.cues;
+ if (!cues.length) return { status: "drifted", now: "", empty: true };
+ if (holdsWords(joinedCues(cues), quote)) {
+ // Where the words start now: the cue the shortest run holding them starts
+ // with -- a run that still holds them without its first cue started too early.
+ let nowAt: number | null = null;
+ for (let i = 0; i < cues.length && nowAt === null; i++) {
+ for (let k = i; k < Math.min(cues.length, i + MAX_QUOTE_CUES); k++) {
+ if (!holdsWords(joinedCues(cues.slice(i, k + 1)), quote)) continue;
+ if (k === i || !holdsWords(joinedCues(cues.slice(i + 1, k + 1)), quote)) nowAt = cues[i]!.t;
+ break;
+ }
+ }
+ return nowAt !== null && Math.abs(nowAt - cite.t) >= 1 ? { status: "ok", nowAt } : { status: "ok" };
+ }
+ const lit = win.lit >= 0 ? win.lit : 0;
+ const length = Math.max(0, cite.end - cite.t);
+ const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit]!.t + length - 0.25);
+ return { status: "drifted", now: joinedCues(over).slice(0, 3000), nowAt: cues[lit]!.t };
+}
+
+/** The `en` and `en-orig` words over a cite, when they differ (else null). */
+export function enOrigDifference(en: readonly WordCue[], orig: readonly WordCue[], cite: { t: number; end: number }): { en: string; orig: string } | null {
+ const over = (cues: readonly WordCue[]) =>
+ joinedCues(cues.filter((x) => (x.end ?? x.start + 1) > cite.t + 0.25 && x.start < Math.max(cite.end, cite.t + 1) - 0.25));
+ const a = over(en);
+ const b = over(orig);
+ if (wordsOf(a) === wordsOf(b)) return null;
+ return { en: a, orig: b };
+}
diff --git a/common/testing/draft/corpus.d.mts b/common/testing/draft/corpus.d.mts
@@ -29,4 +29,6 @@ export function momentHref(channel: string, id: string, seconds: number, encode?
export function postHref(channel: string, id: string): string;
export function recordOf(channel: string, id: string): FixtureRecord | null;
export function cuesOf(channel: string, id: string): Promise<FixtureCue[] | null>;
-export function writeDraftCorpus(dir: string): Promise<string>;
+export const LATE_RECORD: FixtureRecord;
+export function withRecords(extra: FixtureRecord[]): FixtureChannel[];
+export function writeDraftCorpus(dir: string, opts?: { channels?: FixtureChannel[] }): Promise<string>;
diff --git a/common/testing/draft/corpus.mjs b/common/testing/draft/corpus.mjs
@@ -154,16 +154,31 @@ export async function cuesOf(channel, id) {
// The shard file name the index build writes (common/lib/manifest.ts pageFileName).
const pageFile = (n) => `page-${String(n).padStart(4, "0")}.json`;
+// A recording that is not in the corpus until a test adds it: a refresh's
+// "new recording" (umtool R4).
+export const LATE_RECORD = video("synth-kitchen", "Synth Kitchen", "contest-stream-04", "Contest results", "20261012", [
+ "the contest results came out today", // 0
+ "I was not a judge at the contest this year either", // 5
+ "congratulations to the winner", // 10
+]);
+
+// CHANNELS with `extra` records added to their channels (a later build).
+export function withRecords(extra) {
+ return CHANNELS.map((c) => ({ ...c, records: [...c.records, ...extra.filter((r) => r.channelSlug === c.slug)] }));
+}
+
// A composed public dir: corpus.json, and per channel a manifest and one shard.
-export async function writeDraftCorpus(dir) {
+// `channels`: another set than CHANNELS (withRecords: a later build).
+export async function writeDraftCorpus(dir, opts = {}) {
+ const CHANNELS_ = opts.channels ?? CHANNELS;
await mkdir(dir, { recursive: true });
await writeFile(
path.join(dir, "corpus.json"),
JSON.stringify({
- channels: CHANNELS.map((c) => ({ slug: c.slug, name: c.name, videoCount: c.records.length })),
+ channels: CHANNELS_.map((c) => ({ slug: c.slug, name: c.name, videoCount: c.records.length })),
}),
);
- for (const c of CHANNELS) {
+ for (const c of CHANNELS_) {
const chDir = path.join(dir, "transcripts", c.slug);
await mkdir(chDir, { recursive: true });
await writeFile(
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,12 @@
# Changelog
## [Unreleased]
+- **Refresh an article: fetch what is new, see what changed, update.** `pnpm ops report-draft --json '{"task": "refresh", "article": "<id>"}' --wait` (or umtool's **Refresh…**) takes the article's current report — or the iteration named by `"iteration"` — and runs ONE job on its own lane, `draft:refresh`: it fetches the report's scope and every channel its citations touch through the editor's own actions (`sync`, the channel's report, `transcribe-bucket` for only what landed; `fetch-posts` for a posts channel; a platform held or cooling down is skipped and said), builds the site whose build holds them locally (never a deploy), searches again with the report's own recorded enumerations (its trace; an older run's turns; else its question) and reads every cited quote again (words changed, `en` against `en-orig`, a source gone). Nothing changed: the new `refresh` iteration ends **no change**, $0. Something changed: a sweep of only the new and changed recordings, then a revision of the report with its findings and the quote fixes, within the caps — past one it ends **held by the cap** with the delta and the estimate. What it found is the iteration's `refresh.json`; the log ends `@@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}`. `"fetch": false` reads the corpus as it stands; `"dryRun": true` answers the plan and writes nothing. Needs a restart of the editor and umtool.
+- **umtool's Refresh: plan, then confirm.** The article piece's **⋯ → Refresh…**, the Iterations tab's **Refresh…** and the Next card (when one is suggested) open the plan — the iteration refreshed and what it searches again, each channel's fetches or why one is skipped, the site built, the model, the cap and the day's spend — and **Refresh** starts the job (the Running list follows it). The Overview then says what it found: "1 new recording matches · 1 quote changed" (or "Nothing new since <date>"), the new recordings, the quotes that changed and what they say now, the fetches and the build, the spend or the cap that held it; the sources gone are said by where ("1 source deleted on YouTube", "1 source gone from the archive"), and for an iteration made before match counts were kept, changed recordings are "not tracked before <date>" rather than none; a refresh's card on the Iterations tab carries the same line. A refresh with a report is an **iteration ready** card like any other; making it current stays yours.
+- **The Inbox suggests a refresh.** Once a day per active article with a current report (parked, done and muted pieces are skipped), umtool runs the report's enumerations again over the corpus it read — no fetch, no model — and an article with new matches gets a **Review** card, "3 new recordings mention this since 2026-10-01: …", whose action is **Refresh**. The check reads the build the report read, else the research corpus — and only when that corpus holds every channel of the report's scope: otherwise the article is **unchecked**, with why ("the build holding harbor-radio is not on this machine; channels not in the research corpus: …"), and gets no card. A refresh the cap held is a **Your call** card until something newer runs. The check is kept in `REPORTS_ROOT/.umtool/refresh-check.json`; `umtool refresh --check` runs it now and prints the unchecked ones with their reason.
+- **`umtool refresh <article>`** prints the plan; `--yes` starts it; `--no-fetch` skips the fetch and the build; `--check [<article>]` runs the daily check.
+- **A sweep can be restricted to given recordings: `"ids"`.** `report-draft {"task": "sweep", …, "ids": ["…"]}` keeps them in the iteration's scope: an enumeration answers only their rows, a read of another recording is refused, and the free-text search is not offered (the pipeline reads exactly those). A refresh's update uses it.
+- **A sweep's trace keeps each enumeration's matching lines** (`counts`), so a later refresh can tell a recording whose transcript changed; a refresh adds `fetch`, `build` and `delta` lines to its own trace.
- **Recurring reports.** umtool's Create has **A recurring report**: a topic, its scope (channels, or a research board's), a cadence (daily, weekly on a day, or every N days, at a time) and a shape — a **Living report** (one article kept current: each tick fetches what is new and updates it, the new iteration left for review unless "Make each update current without review" is on) or a **Series** (a new dated article each tick, "Co-host updates · week of 2026-10-12", over whole days — from the day after the last edition through the day before the tick, so weekly on Monday covers the Monday to Sunday before it and no day is read twice; a window nothing matches is a *quiet* edition — recorded, no article, $0; a Tick now with nothing new to cover makes no edition and says when the next one starts). **Plan the schedule** says the first tick, the model and the cap before anything is made. A series has its own page (the cadence chip "weekly · next Mon 06:00", Pause/Resume, **Tick now**, Edit cadence, Delete, the editions newest first, the tick log with each tick's spend); a living report wears the same chip in its article's head. Work has a **Recurring** facet; the Inbox puts a finished edition under Review and a failed or cap-held tick under Your call (**Tick now** / **Raise cap**). `umtool schedule list | show <id>` prints them. Needs a restart of umtool and of the editor.
- **The research board's `e`, `n` and `m` no longer lose the field.** Pressed while a move was still saving, the field took the focus and then lost it when the board redrew, and what was typed next landed on the board as commands (`s` toggled the speaker check, `x` asked to remove the quote). The field now takes the focus once the board has redrawn, and no key acts until it does.
- **The editor keeps the schedules.** A new `report-schedule` lane ticks each recurring report when its window comes — one `report-tick` job at a time, never two of one schedule, never on an idle boot; a window missed while the editor was down is caught up by ONE tick. Hold it with `pnpm ops lane '{"lane":"report-schedule","held":true}'` (`settings.reportSchedule.held`); a tick in flight finishes, and Tick now still runs. Drive it with `pnpm ops report-schedule` (`list`, `create` — with `dryRun` the plan —, `update`, `pause`, `resume`, `delete` — the plan unless `confirm: true` —, `tick-now`). A tick is held, not run, past the day's API cap. Until umtool's Refresh (R4) is in the editor, a tick's fetch-and-build step is not wired and every tick ends failed saying so.
diff --git a/editor/app/api/ops/_reportRefresh.test.ts b/editor/app/api/ops/_reportRefresh.test.ts
@@ -0,0 +1,203 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { LATE_RECORD, ORIGIN, withRecords, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
+import { fetchScope, planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh";
+import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { createIteration, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
+import type { Paths } from "yt-dlp-transcript-common/lib/paths";
+import type { RefreshFile } from "yt-dlp-transcript-common/lib/report/draft/refresh/types";
+import { refreshEditor } from "./_researchEditor";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_reportRefresh.test.ts"
+//
+// `report-draft {"task": "refresh"}` (umtool R4) in this process: the body,
+// the plan, and the job end to end over a stubbed editor door (the actions a
+// refresh asks for, answered with job ids the stubbed registry calls done),
+// the MCP's corpus tools over the synthetic draft corpus as a composed site
+// build, and a temp store. No model is called: the paths here end no-change
+// or held by the cap (the update itself is mcp/src/refreshTask.test.ts).
+
+const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft");
+let tmp: string;
+let paths: Paths;
+let gen: GenerationSettings;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "report-refresh-"));
+ paths = {
+ jobsDir: path.join(tmp, ".jobs"),
+ articlesDir: path.join(tmp, "reports"),
+ exportIndexDir: path.join(tmp, ".export-index"),
+ exportBuildsDir: path.join(tmp, ".export-builds"),
+ sitesDir: path.join(tmp, "sites"),
+ channelsDir: path.join(tmp, "channels"),
+ generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"),
+ ollamaUrl: "http://127.0.0.1:9",
+ } as Paths;
+ // The site whose composed build holds the channel, and the channel.
+ await writeDraftCorpus(path.join(paths.exportBuildsDir, "synth", "out"));
+ await mkdir(path.join(paths.sitesDir, "synth"), { recursive: true });
+ await writeFile(path.join(paths.sitesDir, "synth", "site.json"), JSON.stringify({ title: "Synth", siteUrl: ORIGIN }));
+ await mkdir(path.join(paths.channelsDir, "synth-kitchen"), { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "synth-kitchen", "config.json"), JSON.stringify({ name: "Synth Kitchen", handling: "youtube", url: "https://www.youtube.com/@synth/videos" }));
+ gen = sanitizeGeneration({ citationOrigin: ORIGIN, routes: { sweep: "api" }, models: { api: "claude-sonnet-5-5" }, caps: { sweep: 2, daily: 20, max: 5 } });
+});
+
+after(() => rm(tmp, { recursive: true, force: true }));
+
+// The door, stubbed: what was asked, and a job id the registry stub calls done.
+const asked: { action: string; args: Record<string, unknown> }[] = [];
+const door = {
+ async run(action: string, args: Record<string, unknown>) {
+ asked.push({ action, args });
+ if (action === "publish") return { ok: true, runId: "r1", jobs: [{ target: "synth", kind: "build-site", jobId: `job-${asked.length}` }] };
+ return { ok: true, jobId: `job-${asked.length}` };
+ },
+};
+
+const deps = (g: Partial<GenerationSettings> = {}): ReportDraftDeps => ({
+ paths,
+ corpusTools: (s: string) => createCorpusTools({ source: s }),
+ settings: () => ({ generation: { ...gen, ...g } }),
+ refreshEditor: door,
+ jobOf: async () => ({ status: "done", endedAt: Date.now() }),
+ refreshTiming: { pollMs: 1, sleep: async () => {} },
+});
+
+async function doneSweep(article: string) {
+ await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does the baker say about the contest?", scope: { channels: ["synth-kitchen"] } }, paths);
+ await writeIterationFile(article, 1, "sweep.md", await readFile(path.join(DRAFT, "sweeps", "basic.md"), "utf8"), paths);
+ await writeIterationFile(article, 1, "report.json", { ...JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")), id: article }, paths);
+ const trace = [
+ { t: "run", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" },
+ { t: "scope", run: 1, source: `local:${path.join(paths.exportBuildsDir, "synth", "out")}`, channels: ["synth-kitchen"], question: "What does the baker say about the contest?" },
+ { t: "enumerate", run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } },
+ ];
+ await writeIterationFile(article, 1, "trace.jsonl", trace.map((e) => JSON.stringify(e)).join("\n") + "\n", paths);
+ await updateIteration(article, 1, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 1, read: 2, partial: false, unreached: [] } }, paths);
+}
+
+test("the body: a refresh takes its iteration, model, caps, fetch and dryRun — never a question or a scope; ids are a sweep's", () => {
+ assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a" }), { task: "refresh", article: "a" });
+ assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a", iteration: 3, fetch: false, dryRun: true, maxUsd: 1, extractorModel: "claude-haiku-4-5" }), {
+ task: "refresh",
+ article: "a",
+ iteration: 3,
+ extractorModel: "claude-haiku-4-5",
+ maxUsd: 1,
+ fetch: false,
+ dryRun: true,
+ });
+ assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", question: "q", channels: ["x"] }), /a refresh takes its question and scope from the iteration it refreshes — not question, channels/);
+ assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", ids: ["x"] }), /"ids" is a sweep's/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], fetch: false }), /"fetch" is a refresh's/);
+ assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", dryRun: "yes" }), /"dryRun" is true or false/);
+ assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], ids: "v1, v2, v1" }).ids, ["v1", "v2"]);
+});
+
+test("the plan: the iteration refreshed (the current report's, else the newest with a report), its queries, the channel's actions, the site built, the cap", async () => {
+ await doneSweep("synth-plan");
+ const plan = await planRefresh({ task: "refresh", article: "synth-plan" }, deps());
+ assert.equal(plan.parent.n, 1);
+ assert.equal(plan.parent.from, "trace");
+ assert.deepEqual(plan.parent.queries, ["contest"]);
+ assert.equal(plan.parent.citedCount, 6);
+ assert.deepEqual(plan.channels, [{ slug: "synth-kitchen", kind: "video", platform: "youtube", actions: ["sync", "refresh-report", "transcribe-bucket (what lands)"] }]);
+ assert.equal(plan.build.site, "synth");
+ assert.equal(plan.corpus.build, "synth");
+ assert.equal(plan.model, "claude-sonnet-5-5");
+ assert.equal(plan.capUsd, 2);
+ assert.deepEqual(plan.estimate, { perRecordingUsd: 0.2, revisionUsd: 0.3, from: "parent" });
+ assert.deepEqual(plan.refusals, []);
+ const none = await planRefresh({ task: "refresh", article: "synth-plan", fetch: false }, deps());
+ assert.deepEqual(none.channels[0]!.actions, []);
+ assert.equal(none.build.site, null);
+ await assert.rejects(planRefresh({ task: "refresh", article: "synth-none" }, deps()), /has no report to refresh/);
+});
+
+test("refused: no editor door; the iteration named is not done", async () => {
+ await doneSweep("synth-refuse");
+ const noDoor = await enqueueReportDraft({ task: "refresh", article: "synth-refuse" }, { ...deps(), refreshEditor: undefined });
+ assert.match((noDoor.result as { error: string }).error, /a refresh runs in the editor/);
+ const missing = await enqueueReportDraft({ task: "refresh", article: "synth-refuse", iteration: 7 }, deps());
+ assert.match((missing.result as { error: string }).error, /has no iteration i7/);
+ assert.equal(await readIteration("synth-refuse", 2, paths), null);
+});
+
+test("a refresh with nothing new: one job on draft:refresh — the sync, its report, the build — no change, $0, the marker", async () => {
+ await doneSweep("synth-same");
+ asked.length = 0;
+ const out = await enqueueReportDraft({ task: "refresh", article: "synth-same" }, deps());
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ assert.equal(out.iteration, 2);
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.kind, "report-draft");
+ assert.equal(job.queueKey, "draft:refresh");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.deepEqual(asked.map((a) => a.action), ["sync", "refresh-report", "publish"]);
+ assert.deepEqual(asked.at(-1)!.args, { verb: "build", siteId: "synth", force: false });
+ assert.match(log, /@@report-draft \{"article":"synth-same","iteration":2,"task":"refresh","status":"done",.*"refresh":\{"status":"no-change","newIds":0,"changed":0,"drifted":0,"deleted":0,"summary":"Nothing new since 20\d\d-/);
+ const it = (await readIteration("synth-same", 2, paths))!;
+ assert.equal(it.kind, "refresh");
+ assert.equal(it.parent, 1);
+ assert.equal(it.status, "done");
+ assert.equal(it.jobId, out.result.jobId);
+ assert.deepEqual(it.usage, {});
+ const f = JSON.parse((await readIterationFile("synth-same", 2, "refresh.json", paths))!) as RefreshFile;
+ assert.equal(f.status, "no-change");
+ assert.equal(f.corpus?.build, "synth");
+ assert.equal(f.fetch.find((s) => s.action === "transcribe-bucket")?.reason, "no channel report before the sync: what landed is not known");
+ assert.equal(f.delta?.quotes.length, 6);
+ assert.ok(f.delta?.quotes.every((q) => q.status === "ok"), JSON.stringify(f.delta?.quotes));
+});
+
+test("a refresh with a new recording past the daily cap: held by the cap, the delta and the estimate kept, no model called", async () => {
+ // A later build holds one recording more.
+ await writeDraftCorpus(path.join(paths.exportBuildsDir, "synth", "out"), { channels: withRecords([LATE_RECORD]) });
+ await mkdir(path.dirname(paths.generationUsageFile), { recursive: true });
+ const day = new Date().toISOString().slice(0, 10);
+ await writeFile(paths.generationUsageFile, `${JSON.stringify({ at: new Date().toISOString(), day, jobId: "earlier", article: "x", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0.9 })}\n`);
+ await doneSweep("synth-held");
+ const out = await enqueueReportDraft({ task: "refresh", article: "synth-held", fetch: false }, deps({ caps: { ...gen.caps, daily: 1 } }));
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const job = getRegistry().get(out.result.jobId)!;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ const f = JSON.parse((await readIterationFile("synth-held", 2, "refresh.json", paths))!) as RefreshFile;
+ assert.equal(f.status, "held-by-cap");
+ assert.deepEqual(f.delta?.newIds, ["contest-stream-04"]);
+ assert.equal(f.update?.estimateUsd, 0.5);
+ assert.match(f.update?.refusal ?? "", /about \$0\.50 more would pass the \$1\.00 daily cap/);
+ assert.match(log, /"refresh":\{"status":"held-by-cap","newIds":1,/);
+ assert.deepEqual(f.fetch, []);
+ assert.equal(f.build, null);
+});
+
+test("R5's seam: stage 1 on its own for a scope — the fetches and the build, awaited", async () => {
+ asked.length = 0;
+ const got = await fetchScope({ channels: ["synth-kitchen", "nobody-here"] }, deps());
+ assert.deepEqual(asked.map((a) => a.action), ["sync", "refresh-report"]);
+ assert.deepEqual(got.fetch.find((s) => s.channel === "nobody-here"), { channel: "nobody-here", action: "sync", status: "skipped", reason: "not a channel of this editor" });
+ assert.equal(got.build?.status, "skipped", "no composed build holds a channel no site carries: nothing is built");
+ assert.match(got.build?.reason ?? "", /no composed build holds synth-kitchen, nobody-here/);
+ const one = await fetchScope({ channels: ["synth-kitchen"] }, deps());
+ assert.equal(one.build?.site, "synth");
+ assert.equal(one.build?.status, "done");
+});
+
+test("the editor's refresh door never deploys", async () => {
+ await assert.rejects(refreshEditor.run("publish", { verb: "deploy", siteId: "x" }), /a refresh only builds/);
+ await assert.rejects(refreshEditor.run("delete-channel", { slug: "x" }), /"delete-channel" is not an action a refresh may ask the editor for/);
+});
diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts
@@ -29,30 +29,60 @@ const ROUTES: Record<string, () => Promise<{ POST: Post }>> = {
export const RESEARCH_EDITOR_ACTIONS = Object.keys(ROUTES);
-export const researchEditor: ResearchEditor = {
+// An in-process door over `routes`: each action is its route's POST with a
+// Request carrying the editor's own worker token. `who` names the caller in
+// the refusal of an action it may not ask for.
+export function inProcessEditor(routes: Record<string, () => Promise<{ POST: Post }>>, who: string): ResearchEditor {
+ return {
+ async run(action, args) {
+ const load = routes[action];
+ if (!load) throw new Error(`"${action}" is not an action ${who} may ask the editor for`);
+ const token = getWorkerToken();
+ if (!token) throw new Error("the editor's ops actions are off (WORKER_TOKEN is unset)");
+ const { POST } = await load();
+ const res = await POST(
+ new Request(`http://localhost/api/ops/${action}`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify(args),
+ }),
+ );
+ let body: Record<string, unknown> = {};
+ try {
+ const j = await res.json();
+ if (j && typeof j === "object" && !Array.isArray(j)) body = j as Record<string, unknown>;
+ } catch {
+ // not JSON: refused below with the status
+ }
+ if (res.status < 200 || res.status >= 300 || body.ok === false) {
+ throw new Error(typeof body.error === "string" && body.error ? body.error : `HTTP ${res.status}`);
+ }
+ return body;
+ },
+ };
+}
+
+export const researchEditor: ResearchEditor = inProcessEditor(ROUTES, "a research run");
+
+// A REFRESH'S EDITOR (umtool R4, controller/reportRefresh.ts): the fetches it
+// runs — sync, fetch-posts, refresh-report, transcribe-bucket — and the build
+// (`publish {verb: "build"}`; a refresh never deploys), through the same door.
+const REFRESH_ROUTES: Record<string, () => Promise<{ POST: Post }>> = {
+ sync: () => import("./sync/route"),
+ "fetch-posts": () => import("./fetch-posts/route"),
+ "refresh-report": () => import("./refresh-report/route"),
+ "transcribe-bucket": () => import("./transcribe-bucket/route"),
+ publish: () => import("./publish/route"),
+};
+
+export const REFRESH_EDITOR_ACTIONS = Object.keys(REFRESH_ROUTES);
+
+const refreshDoor = inProcessEditor(REFRESH_ROUTES, "a refresh");
+
+export const refreshEditor: ResearchEditor = {
async run(action, args) {
- const load = ROUTES[action];
- if (!load) throw new Error(`"${action}" is not an action a research run may ask the editor for`);
- const token = getWorkerToken();
- if (!token) throw new Error("the editor's ops actions are off (WORKER_TOKEN is unset)");
- const { POST } = await load();
- const res = await POST(
- new Request(`http://localhost/api/ops/${action}`, {
- method: "POST",
- headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
- body: JSON.stringify(args),
- }),
- );
- let body: Record<string, unknown> = {};
- try {
- const j = await res.json();
- if (j && typeof j === "object" && !Array.isArray(j)) body = j as Record<string, unknown>;
- } catch {
- // not JSON: refused below with the status
- }
- if (res.status < 200 || res.status >= 300 || body.ok === false) {
- throw new Error(typeof body.error === "string" && body.error ? body.error : `HTTP ${res.status}`);
- }
- return body;
+ // A refresh builds; it never deploys (nor runs Publish now).
+ if (action === "publish" && (args as { verb?: unknown }).verb !== "build") throw new Error("a refresh only builds: publish {verb: \"build\"}");
+ return refreshDoor.run(action, args);
},
};
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -1,9 +1,10 @@
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft } from "yt-dlp-transcript-common/controller/reportDraft";
+import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft";
+import { planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh";
import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
-import { jobResponse, ops } from "../_lib";
-import { researchEditor } from "../_researchEditor";
+import { jobResponse, ops, opsFail } from "../_lib";
+import { refreshEditor, researchEditor } from "../_researchEditor";
export const dynamic = "force-dynamic";
@@ -30,7 +31,17 @@ export const dynamic = "force-dynamic";
// - "sweep" with `iteration` N: CONTINUES research run N — its question and
// its channels widened by what it acquired, the sweep's parent N (refused
// while N still waits, unless `force`);
-// - `copyOf` N: iteration N again on `model` (same kind and inputs).
+// - `copyOf` N: iteration N again on `model` (same kind and inputs);
+// - "refresh" (umtool R4): re-fetch the iteration's scope (`iteration`,
+// default the current report's) through this editor's own sync /
+// fetch-posts / refresh-report / transcribe-bucket, build its site
+// locally (never a deploy), search again for what changed, and — when
+// something did, within the caps — sweep the new recordings and revise
+// the report: a new `refresh` iteration, one job on `draft:refresh`.
+// `fetch: false` skips the fetch and the build; `dryRun: true` answers
+// `{ ok, plan }` and writes nothing. The log ends `@@report-draft {…,
+// refresh: {status, newIds, changed, drifted, deleted, summary}}`;
+// - `ids` on a sweep: only those recordings (kept in its scope).
// `model` defaults to settings.generation's route for the task (a task routed
// to `code` needs one named). `extractorModel` is an API sweep's extractor
// (a Claude model id; default settings.generation.models.extractor). An API job's cap is `maxUsd`, else the task's
@@ -44,11 +55,22 @@ export const dynamic = "force-dynamic";
// the corpus tools are the MCP's own, in process (mcp/src/callTool.ts).
export async function POST(request: Request) {
return ops(request, REPORT_DRAFT_BODY_KEYS, async (body) => {
- const out = await enqueueReportDraft(body, {
+ const deps = {
paths: getPaths(),
- corpusTools: (source) => createCorpusTools({ source }),
+ corpusTools: (source: string) => createCorpusTools({ source }),
researchEditor,
- });
+ refreshEditor,
+ };
+ if (body.task === "refresh" && body.dryRun === true) {
+ // The plan: what a refresh would do, nothing written.
+ try {
+ const plan = await planRefresh(parseReportDraftBody(body), deps);
+ return NextResponse.json({ ok: true, plan });
+ } catch (e) {
+ return opsFail((e as Error).message);
+ }
+ }
+ const out = await enqueueReportDraft(body, deps);
if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result);
void out.result.stream.cancel();
return NextResponse.json({
diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts
@@ -6,9 +6,9 @@ import { fileURLToPath } from "node:url";
// By relative path, as digest.spec.ts imports common: the test kit's fakes and
// the synthetic corpus are plain .mjs.
import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs";
-import { ORIGIN, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs";
+import { LATE_RECORD, ORIGIN, withRecords, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs";
import { baseUrl } from "./baseUrl";
-import { resetData, testPaths, writeSettings } from "./helpers";
+import { resetData, testPaths, writeChannelConfig, writeSettings } from "./helpers";
// `pnpm ops report-draft` end to end (release 27 S6): the editor against the
// fake Anthropic (started here, on loopback; settings point at it with a
@@ -34,8 +34,8 @@ test.afterAll(async () => {
await rm(keyDir, { recursive: true, force: true });
});
-async function setup(caps: Record<string, number> = {}) {
- await resetData(null);
+async function setup(caps: Record<string, number> = {}, fixture: string | null = null) {
+ await resetData(fixture);
const keyFile = join(keyDir, "anthropic.env");
await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
await chmod(keyFile, 0o600);
@@ -198,3 +198,124 @@ test("a media draft (release 28 M3): a teaser on the API, a step on the done ite
expect(api.remaining()).toBe(0);
});
+
+// ─── a refresh (umtool R4) ───
+
+const KIT = join(RUNS, "..");
+
+// i1 of `article`: the kit's basic sweep, done, with the trace of the one
+// enumeration it ran (over `channel`, read from `build`).
+async function doneBasicSweep(article: string, o: { channel?: string; report?: unknown; build?: string } = {}) {
+ const channel = o.channel ?? "synth-kitchen";
+ const itDir = join(testPaths().transcriptsDir, "reports", article, "iterations", "1");
+ await mkdir(itDir, { recursive: true });
+ const at = new Date().toISOString();
+ await writeFile(
+ join(itDir, "iteration.json"),
+ JSON.stringify({
+ format: "archilyzer-iteration", version: 1, article, n: 1, kind: "sweep", parent: null, copyOf: null, model: "claude-sonnet-5-5",
+ question: "What does the baker say about the contest?", scope: { channels: [channel] }, status: "done",
+ usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 1, read: 2, partial: false, unreached: [] },
+ steps: [], createdAt: at, updatedAt: at, endedAt: at,
+ }),
+ );
+ const report = o.report ?? { ...JSON.parse(await readFile(join(KIT, "reports", "basic.report.json"), "utf8")), id: article };
+ await writeFile(join(itDir, "report.json"), JSON.stringify(report));
+ await writeFile(join(itDir, "sweep.md"), await readFile(join(KIT, "sweeps", "basic.md"), "utf8"));
+ const build = o.build ?? join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out");
+ const trace = [
+ { t: "run", at, run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" },
+ { t: "scope", at, run: 1, source: `local:${build}`, channels: [channel], question: "What does the baker say about the contest?" },
+ { t: "enumerate", at, run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } },
+ ];
+ await writeFile(join(itDir, "trace.jsonl"), trace.map((e) => JSON.stringify(e)).join("\n") + "\n");
+}
+
+test("a refresh over ops: the plan (dryRun, nothing written), then the job — the fetch skipped where it cannot run, no change, $0", async ({ request }) => {
+ test.setTimeout(120_000);
+ await setup();
+ await doneBasicSweep("synth-refresh");
+ const planned = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data: { task: "refresh", article: "synth-refresh", dryRun: true } });
+ expect(planned.status()).toBe(200);
+ const { plan } = (await planned.json()) as { plan: { parent: { n: number; queries: string[] }; channels: { slug: string; skip?: string }[]; build: { site: string | null; reason?: string }; capUsd: number } };
+ expect(plan.parent).toMatchObject({ n: 1, queries: ["contest"] });
+ expect(plan.channels).toEqual([{ slug: "synth-kitchen", kind: null, platform: null, actions: [], skip: "not a channel of this editor" }]);
+ expect(plan.build).toMatchObject({ site: null, reason: "the build draft-e2e is not a site's: it is read as it stands" });
+ expect(plan.capUsd).toBe(3);
+ await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-refresh", "iterations", "2", "iteration.json"))).rejects.toThrow(/ENOENT/);
+
+ const before = api.requests.length;
+ const { status, body } = await draft(request, { task: "refresh", article: "synth-refresh" });
+ expect(status, body.error).toBe(200);
+ expect(body.iteration).toBe(2);
+ const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s));
+ const tail = (job.tail ?? []).join("\n");
+ expect(job.job?.status ?? job.status, tail).toBe("done");
+ expect(tail).toContain('"task":"refresh"');
+ expect(tail).toMatch(/"refresh":\{"status":"no-change","newIds":0,"changed":0,"drifted":0,"deleted":0,"summary":"Nothing new since 20\d\d-/);
+ expect(api.requests.length, "no model was asked").toBe(before);
+ const it = await iterationJson("synth-refresh", 2);
+ expect(it).toMatchObject({ kind: "refresh", parent: 1, status: "done", jobId: body.jobId, refresh: { status: "no-change" } });
+ const f = JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", "synth-refresh", "iterations", "2", "refresh.json"), "utf8"));
+ expect(f.fetch).toEqual([{ channel: "synth-kitchen", action: "sync", status: "skipped", reason: "not a channel of this editor" }]);
+ expect(f.build).toMatchObject({ site: null, status: "skipped" });
+ expect(f.delta.quotes).toHaveLength(6);
+});
+
+test("a refresh that finds a new recording: a sweep restricted to it, then the report revised — a new iteration with its finding", async ({ request }) => {
+ test.setTimeout(120_000);
+ await setup();
+ await doneBasicSweep("synth-refreshed");
+ // A later build holds one recording more.
+ await writeDraftCorpus(join(testPaths().transcriptsDir, ".export-builds", "draft-e2e", "out"), { channels: withRecords([LATE_RECORD]) });
+ const link = `${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5`;
+ api.push(
+ toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }),
+ toolTurn("write_report", { markdown: `# New on the contest\n\nOne new stream mentions it.\n\n## The contest\n\n- She says she was not a judge: "I was not a judge at the contest this year either" [Contest results @ 0:05](${link})\n` }),
+ textTurn("sweep.md: 1 finding."),
+ toolTurn("apply_ops", { ops: [{ op: "add", section: "The contest", text: "She says she was not a judge", quote: "I was not a judge at the contest this year either", link }] }),
+ textTurn("Added the new finding."),
+ );
+ const { status, body } = await draft(request, { task: "refresh", article: "synth-refreshed", model: "claude-sonnet-5-5", fetch: false });
+ expect(status, body.error).toBe(200);
+ const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s));
+ const tail = (job.tail ?? []).join("\n");
+ expect(job.job?.status ?? job.status, tail).toBe("done");
+ expect(tail).toMatch(/"refresh":\{"status":"updated","newIds":1,"changed":0,"drifted":0,"deleted":0/);
+ expect(api.remaining()).toBe(0);
+ const dir = join(testPaths().transcriptsDir, "reports", "synth-refreshed", "iterations", "2");
+ const f = JSON.parse(await readFile(join(dir, "refresh.json"), "utf8"));
+ expect(f).toMatchObject({ status: "updated", delta: { newIds: ["contest-stream-04"] }, update: { sweep: { ids: ["contest-stream-04"], findings: 1 }, revision: { status: "done" } } });
+ const report = JSON.parse(await readFile(join(dir, "report.json"), "utf8"));
+ expect(Object.values(report.citations).some((c) => (c as { id?: string }).id === "contest-stream-04")).toBe(true);
+ const ledger = await readFile(join(testPaths().transcriptsDir, ".generation-usage.jsonl"), "utf8");
+ expect(ledger).toContain('"task":"refresh"');
+});
+
+test("a refresh through the editor's own door: the channel's sync and its report run as jobs, then the delta", async ({ request }) => {
+ test.setTimeout(150_000);
+ await setup({}, "two-slow-channels");
+ // slow-b without its --test-slow flag: a sync that finishes in seconds.
+ await writeChannelConfig("slow-b", { name: "Slow B", url: "https://www.youtube.com/@slow-b/videos" });
+ // A composed build holding slow-b, and an article citing it.
+ const rec = { ...LATE_RECORD, channelSlug: "slow-b", channel: "Slow B", slug: "slow-b/contest-stream-04" };
+ const build = join(testPaths().transcriptsDir, ".export-builds", "slowb", "out");
+ await writeDraftCorpus(build, { channels: [{ slug: "slow-b", name: "Slow B", platform: "youtube", records: [rec] }] });
+ const report = {
+ format: "archilyzer-report", version: 1, id: "slowb-refresh", kind: "sweep", title: "Slow B on the contest", summary: "One finding.",
+ citations: { c1: { kind: "video", channel: "slow-b", id: "contest-stream-04", start: 5, end: 9.8, quote: "I was not a judge at the contest this year either" } },
+ sections: [{ id: "s1", title: "The contest", body: "She [was not a judge](cite:c1)." }],
+ };
+ await doneBasicSweep("slowb-refresh", { channel: "slow-b", report, build });
+ const { status, body } = await draft(request, { task: "refresh", article: "slowb-refresh" });
+ expect(status, body.error).toBe(200);
+ const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s), 120_000);
+ const tail = (job.tail ?? []).join("\n");
+ expect(job.job?.status ?? job.status, tail).toBe("done");
+ const f = JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", "slowb-refresh", "iterations", "2", "refresh.json"), "utf8"));
+ const sync = f.fetch.find((s: { action: string }) => s.action === "sync");
+ expect(sync, JSON.stringify(f.fetch)).toMatchObject({ channel: "slow-b", status: "done" });
+ expect(sync.jobId).toBeTruthy();
+ expect(f.fetch.find((s: { action: string }) => s.action === "refresh-report")).toMatchObject({ status: "done" });
+ expect(f.status).toBe("no-change");
+});
diff --git a/mcp/src/refreshTask.test.ts b/mcp/src/refreshTask.test.ts
@@ -0,0 +1,117 @@
+// A refresh's update end to end (umtool R4): the task over the MCP's own corpus
+// tools (a later build of the synthetic draft corpus holding one recording
+// more), the fake Anthropic, a temp iterations store. The parent is a done
+// sweep with its trace; the refresh finds the new recording, sweeps ONLY it
+// (the sweep's `ids` restriction: the enumeration answers its row alone), and
+// revises the parent's report with the finding. Stage 1's fetches and build
+// are common's tests (lib/report/draft/refresh/refresh.test.ts); here they
+// are skipped (`fetch: false`).
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { LATE_RECORD, ORIGIN, POSTS, withRecords, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { createIteration, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
+import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index";
+import { corpusCuesOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/corpusCues";
+import type { RefreshFile } from "yt-dlp-transcript-common/lib/report/draft/refresh/types";
+import { createCorpusTools, type CorpusTools } from "./callTool";
+
+const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft");
+
+let tmp: string;
+let later: CorpusTools;
+let api: FakeAnthropic;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-task-"));
+ const dir = await writeDraftCorpus(path.join(tmp, "later"), { channels: withRecords([LATE_RECORD]) });
+ later = await createCorpusTools({ source: `local:${dir}` });
+ api = await startFakeAnthropic();
+});
+
+after(async () => {
+ await later.close();
+ await api.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const article = "synth-basic";
+
+test("refresh: the new recording found, a sweep restricted to it, the report revised with its finding — updated", async () => {
+ const paths = { articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, "idx") };
+ // i1: the basic sweep, done, with the trace of the enumeration it ran.
+ await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does the baker say about the contest?", scope: { channels: ["synth-kitchen"] } }, paths);
+ await writeIterationFile(article, 1, "sweep.md", await readFile(path.join(DRAFT, "sweeps", "basic.md"), "utf8"), paths);
+ await writeIterationFile(article, 1, "report.json", JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")), paths);
+ const trace = [
+ { t: "run", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" },
+ { t: "scope", run: 1, source: "local:/the/first/build", channels: ["synth-kitchen"], question: "What does the baker say about the contest?" },
+ { t: "enumerate", run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } },
+ ];
+ await writeIterationFile(article, 1, "trace.jsonl", trace.map((e) => JSON.stringify(e)).join("\n") + "\n", paths);
+ await updateIteration(article, 1, { status: "done" }, paths);
+ await createIteration(article, { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths);
+
+ const finding = `- She says she was not a judge: "I was not a judge at the contest this year either" [Contest results @ 0:05](${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5)`;
+ api.push(
+ // The restricted sweep: one enumeration (its answer the new row only), the report, done.
+ toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }),
+ toolTurn("write_report", { markdown: `# New on the contest\n\nOne new stream mentions it.\n\n## The contest\n\n${finding}\n` }),
+ textTurn("sweep.md: 1 finding."),
+ // The revision: the finding added, as given.
+ toolTurn("apply_ops", {
+ ops: [{ op: "add", section: "The contest", text: "She says she was not a judge", quote: "I was not a judge at the contest this year either", link: `${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5` }],
+ }),
+ textTurn("Added the new finding."),
+ );
+ const lines: string[] = [];
+ const deps: TaskDeps = {
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, ollama: { baseUrl: "http://127.0.0.1:9" } },
+ corpus: later,
+ cuesOf: corpusCuesOf(later),
+ postTextOf: async (channel, id) => POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null,
+ paths,
+ log: (l) => lines.push(l),
+ refresh: {
+ editor: { run: async () => assert.fail("fetch: false runs no editor action") },
+ jobOf: async () => null,
+ channelOf: async () => null,
+ siteOf: async () => ({ site: null }),
+ openCorpus: async () => ({ source: later.source, origin: ORIGIN, build: "later" }),
+ capRefusal: async () => null,
+ },
+ };
+ const out = await runTask({ task: "refresh", article, n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, deps);
+ assert.equal(out.status, "done", `${out.summary}\n${lines.join("\n")}`);
+ assert.equal(api.remaining(), 0, "every scripted turn was used");
+ assert.ok(out.usd > 0);
+
+ const f = JSON.parse((await readIterationFile(article, 2, "refresh.json", paths))!) as RefreshFile;
+ assert.equal(f.status, "updated");
+ assert.deepEqual(f.delta?.newIds, ["contest-stream-04"]);
+ assert.equal(f.delta?.drifted.length, 0);
+ assert.deepEqual(f.update?.sweep, { ids: ["contest-stream-04"], status: "done", summary: f.update!.sweep!.summary, findings: 1 });
+ assert.equal(f.update?.revision?.status, "done");
+ assert.match(f.summary, /^1 new recording matches — updated: 1 op\(s\) applied/);
+
+ // The sweep was restricted: its scope says so, and its enumeration answered the new row alone.
+ const events = (await readIterationFile(article, 2, "trace.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(events.find((e) => e.t === "scope")?.ids, ["contest-stream-04"]);
+ assert.deepEqual(events.find((e) => e.t === "enumerate")?.ids, ["contest-stream-04"]);
+ assert.equal(events.find((e) => e.t === "delta")?.status, "changed");
+ assert.equal(events.at(-1).t, "run");
+ assert.equal(events.at(-1).status, "done");
+
+ // The report: the parent's findings, and the new one.
+ const report = JSON.parse((await readIterationFile(article, 2, "report.json", paths))!);
+ const quotes = Object.values(report.citations as Record<string, { quote?: string; id?: string }>);
+ assert.ok(quotes.some((c) => c.id === "contest-stream-04" && c.quote === "I was not a judge at the contest this year either"));
+ assert.ok(quotes.some((c) => c.quote === "I did not enter the contest this year"), "the parent's findings stay");
+ const it = await readIteration(article, 2, paths);
+ assert.equal(it?.status, "done");
+ assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "updated", newIds: 1, changed: 0, drifted: 0, deleted: 0, summary: f.summary });
+});
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -439,8 +439,8 @@ edition reviewed with the operator before the schedule is left on.
| P4a-3 song pieces | `ux/p4a3` → `main` `3d69d6c6` | LIVE 2026-10-14 (umtool oN73I6F3…) |
| R3 transparent runs | `ux/r3` → `main` `6362cf40` | LIVE 2026-10-14 (editor HqcZW4aJ…, umtool 85Ultdj2…) |
| P4b benches + Media | `ux/p4b` → `main` `e66dd702` | LIVE 2026-10-14 (umtool ktVxkFBl…) |
-| R4 refresh | `ux/r4` | in progress |
-| R5 recurring reports | `ux/r5` | shipped on the branch (R4's two steps behind the seam until R4 merges) |
+| R4 refresh | `ux/r4` → `main` `08fee8e1` | LIVE 2026-10-14 (editor nFiNyOdI…, umtool -HUqAEPA…) |
+| R5 recurring reports | `ux/r5` | shipped on the branch |
| R6 triage first | — | after R5 |
| Co-host pilot | — | after R6 (operator-approved) |
| P6 cleanup, docs, audit | — | after P4a-3, P4b, R4–R6 |
@@ -2359,6 +2359,240 @@ narration benches and clip benches c01/c03 200 with the bench head; `/drafts` 30
`drafts-unreviewed` rows are new), notes' hrefs end `note=<id>`. P6 audit: "Draft with is off here" reads clipped — name
the action whole.
+### R4, as shipped
+
+**What.** Refresh: a report iteration that is "fetch what is new, check it, update" — cheap and deterministic until
+something changed. ONE editor job (`report-draft {"task": "refresh"}`) over a new `refresh` iteration whose parent is
+the iteration refreshed; umtool plans it, confirms it, shows what it found, and suggests it.
+
+- **The engine** (`common/lib/report/draft/refresh/`; the task beside the others, `runTask`'s `refresh`):
+ - `types.ts` — `refresh.json` (`archilyzer-refresh` v1: the basis it searched again with, each fetch step, the build,
+ the corpus, the delta, the update, warnings, the one-line summary, `status` running · no-change · updated ·
+ held-by-cap · failed · cancelled), `RefreshPlan`, `RefreshOutcome` (what iteration.json keeps as `refresh` and the
+ log's marker carries), `deltaLine` ("1 new recording matches · 1 quote changed", "Nothing new since <date>").
+ - `basis.ts` `refreshBasis(article, n)` — what an iteration was built from: its own `refresh.json` (a refresh of a
+ refresh: its queries and the match set it saw), else its trace's last run (`scope`, each `enumerate` with its ids
+ and, new, `counts`), else its `turns.jsonl` (the agent's `enumerate_matches` calls with their arguments and, when
+ an import kept them, their rows; the pipeline's terms), walking up the lineage for a revision; else its question
+ as the one query (said). The report's quoted citations, and every cited recording counted as known.
+ `knownComplete` false (a run whose answers were not kept, or the question) makes "new" mean "uploaded on or after
+ the iteration's day".
+ - `delta.ts` — `deltaCandidates({queries, scope}, corpus | enumerateFn, {known?, since?})`, the candidates on their
+ own (R6's tier 0 and umtool's daily check call it): each distinct query once; new against `known` (or by upload
+ date from `since`); changed = matched before and now with different matching lines; unmatched (a complete scan
+ only). `recheckQuotes(cited, {recordOf, postTextOf})` — R2's word check at each cite on every track the record has
+ (ok, moved, drifted with the words there now, missing), the platform state (deleted, private), `en` vs `en-orig`.
+ `computeDelta` both; `deleted` counts sources (`channel/id`), `drifted` citations.
+ - `fetch.ts` `fetchAndBuild(scope, hooks)` — stage 1 on its own: per video channel `sync`, then `refresh-report` and
+ `transcribe-bucket` for ONLY the recordings that landed (the channel report's "downloaded, not transcribed" bucket
+ after the sync against the one before — never a channel's backlog); per posts channel `fetch-posts`; a platform held
+ or cooling down skipped with the editor's sentence; channels side by side (the platform queues pace them); then
+ `publish {"verb": "build", "siteId", "force": false}` for the site whose build holds the channels (the parent's build
+ first) — through the publish lock, never a deploy — every job waited for (polled; a step past `waitMs`, default 6 h,
+ is left running and said).
+ - `task.ts` `refresh` — `runOnIteration` (kind `refresh`, traced as task `refresh`): stage 1; the corpus opened after
+ the build; stage 2 (`delta` in the trace) — nothing changed ends `no-change`, $0; stage 3 within the caps
+ (`capRefusal(estimate)`: the job's cap, the daily cap, and "about $X more would pass the daily cap"; a refusal ends
+ `held-by-cap` with the estimate) — the sweep restricted to the new and changed recordings over the parent's
+ question and recorded queries (the API agent with its extractor, or the local pipeline; 70% of the cap), its
+ findings then handed to `reviseReportBody` as feedback with the drifted quotes ("drop it; add it again with the
+ words there now if the claim stands"), the sources gone, and those deleted from their platform; the revision's
+ report is the iteration's. A sweep that finds nothing and no drift ends `no-change` (with what it read). The
+ estimate is the parent's spend per recording read (else $0.08) × recordings + $0.30. The iteration ends `done`
+ whatever the refresh's status; only a failed revision or a cancel fails it. `sweepAgentBody`, `sweepPipelineBody`
+ and `reviseReportBody` are exported for it (additive).
+ - The sweep's **`ids` restriction** (`tasks/restrict.ts`; a general sweep option — R6's escalation path):
+ `report-draft {"task": "sweep", …, "ids"}` keeps the ids in the iteration's scope; the agent's `enumerate_matches`
+ answers only their rows (and says so), `get_transcripts`/`extract_batch` drop other ids (none left refuses),
+ `get_transcript`/`get_post`/`get_thread` refuse another id, `search_transcripts` is not offered, the preamble says
+ so; the pipeline's worklist is those ids, each read even when its terms did not find it.
+ - `lib/report/quoteWords.ts` — R2's check moved to common (`wordsOf`, `holdsWords`, `windowAround`,
+ `checkWordsInWindow`, `enOrigDifference`); umtool's `verifyQuote` calls it, its API and answers unchanged.
+ - `iterations.ts`: kind `refresh` (a parent, no feedback), `refresh.json` an iteration file (JSON), scope `ids`.
+ `trace.ts`: `fetch`, `build`, `delta` events; `enumerate.counts`; `enumerateOf` answers each row
+ (`rows`: channel, date, matches, title) and `countsOf`. Both sweeps record `counts`.
+- **The editor's side** (`common/controller/reportRefresh.ts`): `refreshTarget` (the iteration named, else
+ current.json's report, else the newest done one with a report), `refreshModel` (the sweep route's model; a sweep
+ routed to Claude Code runs the API model here, said), `planRefresh` (the dry run: each channel's actions or why
+ skipped, the site, the corpus, model, cap, the day's spend, the estimate's rate), `enqueueRefresh` (the iteration,
+ then one `report-draft` job on **`draft:refresh`** — a new queue, so a refresh waiting on fetches never holds
+ `draft:api`; no daily-cap refusal at the ask, stage 3 asks), the job's hooks over the editor (its jobs, channel
+ configs, `heldPlatformRefusal`/`platformCooldownRemainingMs`, channel snapshots, the builds, a disk reader of a cited
+ recording's tracks and platform state — `diskRecordOf`, not publish's `readCitedRecord`: a controller may not import
+ publish/), the usage rows (task `refresh`) and the marker. `reportDraft.ts`: task `refresh` (no route of its own),
+ keys `ids`, `fetch`, `dryRun`, a refresh refused a question or a scope.
+- **R5's seam** (named for the coordinator): `fetchScope(scope, deps, {prefer?, signal?, log?, build?})` in
+ `controller/reportRefresh.ts` — stage 1 for any `{channels, from?, to?}`, awaited, answering `{fetch, build,
+ warnings}` (each step done, skipped with why, refused, failed or still running); and the refresh itself:
+ `enqueueReportDraft({task: "refresh", article, iteration?}, deps)` (or `enqueueRefresh`) — its job's `done` ends
+ with the iteration's `refresh.json` (`readRefreshFile(article, n, paths)`) whose `status` is `no-change`, `updated` or
+ `held-by-cap`. Both need `deps.refreshEditor`, the editor's in-process door
+ (`editor/app/api/ops/_researchEditor.ts` `refreshEditor`).
+- **The ops route** (`editor/app/api/ops/report-draft`): `task: "refresh"`; `dryRun: true` answers `{ok, plan}`. The
+ in-process door (`refreshEditor`: sync, fetch-posts, refresh-report, transcribe-bucket, publish — build only; a
+ deploy is refused) is `_researchEditor.ts`'s factored `inProcessEditor`. `pnpm ops report-draft --json
+ '{"task":"refresh","article":"x"}' --wait` prints the marker. COMMANDS.md regenerated.
+- **umtool**:
+ - `lib/articles/refresh.ts` — `planArticleRefresh`, `startArticleRefresh` (through `enqueueDraft`, `fetch` now one of
+ its keys), `readRefreshes` (each refresh iteration with what its refresh.json kept). `GET/POST
+ /api/articles/refresh` (`{article, iteration?, fetch?, confirm?}` → plan, or `{jobId, iteration, href}`).
+ - `components/articles/RefreshDialog.tsx` — the plan then **Refresh**: Refreshes (i<n>, kind, made, the question),
+ Searched again (the queries, the match set then, the quotes read again), Fetch (each channel's actions, or
+ "skipped — <why>"), Build (the site, "locally, if anything changed — never deployed"), Update (model, extractor,
+ "spends up to $X", the rate, today's spend); refusals and warnings; one dialog per page (`RefreshHost`), opened by
+ the ⋯ menu's **Refresh…** (`RefreshMenuItem`), the Iterations tab's **Refresh…** (`RefreshButton`) or `?refresh=1`
+ (the Next card's and the Inbox card's action); after **Refresh** "Refresh i<n> is running (job …)" and the page
+ reads again.
+ - `components/articles/RefreshSummary.tsx` (the Overview, under Iterations): "Refresh · i<n>" with its state
+ (running, no change, updated, held by the cap, failed), the line, the new recordings, the quotes that changed and
+ what they say now, the sources gone, the fetches and the build, the spend or the estimate; "Review in Iterations →"
+ when it has a report; `RefreshWatch` reads the page again every 4 s while it runs. The Iterations tab: the
+ refresh's line on its card (`IterationRow.refresh`, additive), and **Refresh…** in the tab's head (P4b had freed
+ the tab).
+ - `lib/inbox/refresh.ts` (add-only; two kinds): **refresh-available** (Review) — the daily check per active store
+ article with a current report (parked, done and muted skipped): the newest done refresh of it, else the report
+ itself, as the basis, `deltaCandidates` over the build it read when it is on this machine (the MCP's
+ `SourceRegistry`), else Research's local corpus — the MCP engine's `enumerate`, no fetch, no model, at most 12
+ queries; kept a UTC day per article and iteration in `REPORTS_ROOT/.umtool/refresh-check.json` (one writer, temp +
+ rename). The Inbox only reads it; a stale one is checked in the background, one at a time, in the app's server only
+ (`NEXT_RUNTIME`; a CLI never waits on it), off with `UMTOOL_REFRESH_CHECK=0` (the e2e server). The card goes when a
+ refresh made after the check exists or one is running. **refresh-held** (Your call) — the newest refresh of an
+ article `held-by-cap`, until a later iteration runs. Both act **Refresh** → `?refresh=1`. `groups.mjs`/`what.mjs`
+ gain the two kinds only. `POST /api/articles/refresh/check {article?, force?}` runs it now.
+ - `umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` and `umtool refresh --check [<article>]
+ [--force]` (`bin/refresh.ts`, through tsx like `inbox`).
+ - The e2e stub answers `report-draft` refresh (a plan; an iteration running then done with its refresh.json —
+ updated, or no-change for an id ending `-quiet`).
+
+| sha | what |
+|---|---|
+| `f1982eef` | common: the refresh (`draft/refresh/`: types, basis, delta, task), the sweep's `ids` restriction (`tasks/restrict.ts`), `quoteWords.ts` (R2's check, umtool's `verifyQuote` on it), iteration kind `refresh` + `refresh.json` + scope `ids`, trace `fetch`/`build`/`delta` and `enumerate.counts`, `controller/reportRefresh.ts`, `reportDraft`'s task and keys, `draft:refresh`; the editor route's `refresh`/`dryRun` and the in-process refresh door; `refresh.test.ts` (10), `mcp/src/refreshTask.test.ts` (1) |
+| `3f33efe6` | editor: `_reportRefresh.test.ts` (7), `fetch.ts` `fetchAndBuild` and R5's `fetchScope` seam, `fetchHooksOf`; the ops help and COMMANDS.md |
+| `5f444574` | editor e2e: `report-draft.spec` +3 (the plan then no change, an update with the restricted sweep, the editor's own door: a real sync and channel report) |
+| `92fab5e7` | umtool: `lib/articles/refresh.ts`, `/api/articles/refresh` (+ `/check`), `RefreshDialog`/`RefreshSummary`/`RefreshWatch`, the ⋯ item, the Overview's summary, `lib/inbox/refresh.ts` (the daily check, refresh-available, refresh-held), `bin/refresh.ts`, the stub's refresh, `refresh-fixture.mjs`, `refresh.spec` (5), `lib/inbox/refresh.test.ts` (3), `UMTOOL_REFRESH_CHECK=0` on the e2e server |
+| `57c7eb7a` | merge `main` `d49737da` (P4a-3, P4b) — no conflict |
+| `e78e2ae8` | the Iterations tab's **Refresh…** and a refresh's line on its card (`IterationRow.refresh`); `diskRecordOf` (architecture test: a controller may not import publish/) |
+| `fed5716a` | the plan opens on a client navigation to `?refresh=1` (the Next card on its own page); `[Unreleased]` bullets |
+| `bed1e9d2` | the card reads "new recordings match"; a skipped step names its action |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean at `f1982eef`, `3f33efe6`, `92fab5e7`, `e78e2ae8` (repo-wide); umtool's at `fed5716a`, `bed1e9d2` |
+| common `pnpm --filter yt-dlp-transcript-common test` (`SETTINGS_FILE` at the primary's, read only) | **4114/4114** (+10: `refresh/refresh.test.ts`; `trace.test.ts`'s `enumerateOf` assertion has `rows`). A first run was 4113: `architecture.test.ts` refused `controller/reportRefresh.ts -> publish/composeReports` (fixed in `e78e2ae8`: `diskRecordOf`) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | **365/365** (+1: `refreshTask.test.ts`, the update end to end — the restricted sweep's enumeration answered the new row only, the revision added its finding) |
+| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 854 tests, 852 pass, 2 skipped, 0 fail |
+| `pnpm --filter umtool test` (now `lib/research/*.test.ts lib/inbox/*.test.ts`) | **27/27** (+3: `lib/inbox/refresh.test.ts` — the daily check over the refresh fixture and Research's local corpus, the two kinds, parked skipped, the plan and the start against a stand-in editor) |
+| editor unit `pnpm --filter editor test` | **304/304** (+7: `_reportRefresh.test.ts` — the body, the plan, refusals, the job on `draft:refresh` with no change and $0, held by the daily cap with no model, R5's `fetchScope`, the door never deploys) |
+| `pnpm run test:scripts` (reads the capped build) | 1005 tests, 1003 pass, 2 skipped, 0 fail |
+| `pnpm archilyzer docs cli --check` | clean (COMMANDS.md regenerated for the refresh and `ids`) |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`, heavy slot) | exit 0; compiled 13.9 s, 41 s wall, 1.53 GB max RSS; the link removed |
+| capped editor `next build` (common changed) | exit 0; compiled 41 s, 1:34 wall, 2.47 GB max RSS |
+| editor e2e `report-draft.spec` + `ops-api.spec` (`export/public` linked from the primary) | **20 passed, 0 failed** (57 s at `5f444574`; again at the tip, 35 s): the three refresh tests among them — the plan then no change, an update over the fake Anthropic, the editor's own door (a real sync of `slow-b` and its channel report as jobs) |
+| full umtool e2e, run 1 (`e78e2ae8`) | 458 tests: 451 passed, 1 failed, 6 skipped, 10.6 min. Red: `refresh.spec` — the Next card's action on its own page kept the dialog's host mounted, so `?refresh=1` did not open it; fixed in `fed5716a` |
+| `refresh` + `inbox` + `piece` + `article-iterations` (`fed5716a`) | 44/45: `inbox.spec`'s rail count 35 against the page's 34 (below); `article-iterations` + `inbox` + `refresh` again 22/22 |
+| `refresh` + `inbox` + `piece` + `inbox-engine` + `running` (`bed1e9d2`) | 49/49 |
+| full umtool e2e, run 2 (`bed1e9d2`) | 458 tests: 449 passed, 3 failed, 6 skipped, 9.4 min. Reds: `board.spec` 102 (a claim typed under load landed in the title) and the two after it that read that state; R2's spec, no file of it touched here |
+| `board.spec` × 3 (`bed1e9d2`) | 7/7, 7/7, 7/7 |
+
+**Screenshots** (job scratch `r4-shots/`, 1366×768, dark and light, on the e2e fixture with the refresh fixture written
+in and the stub editor): `suggestion-inbox` (the Inbox's Review card "1 new recording mentions this since 2026-10-14:
+Harbor Radio 52: storm season", action Refresh), `suggestion-next-card` (the article's Overview, the Next card the same
+call), `refresh-plan` (the plan dialog: the iteration and its query, harbor-radio's three actions, otherchan skipped as
+held, the build of priv, the cap and today's spend), `refreshed-summary` (the Overview after the run: "1 new recording
+matches · 1 quote changed", the new recording, the quote and what it says now, the fetches and the build, $0.31 spent),
+`refreshed-iterations` (the refresh's card with its line, **Refresh…** in the tab's head). No canvas screen exists for
+Refresh; the dialog is HandoffDialog's (the R2 plan-then-confirm) and the summary the Overview's own Card.
+**Keyboard only** (production build, reduced motion): Tab reaches **More**, Enter opens it, Tab reaches **Refresh…**
+(the 2 px Signal ring), Enter opens the plan with the focus inside the dialog, Escape closes it.
+
+**Found and left.**
+- **A refresh waits on the editor's own queues.** A sync on a busy platform queue, a transcription behind a long
+ backlog, a site build behind others: the job waits (up to 6 h a step, then reads what is there and says so). It holds
+ only `draft:refresh`, never `draft:api` or `draft:local`. The build is never forced, so a site that nothing changed
+ is not rebuilt — but one that did is a whole site build (Jeralyzer's is long), by design: a sweep reads only a
+ composed build.
+- **`transcribe-bucket` only for what landed** needs the channel's report from before the sync; a channel with no
+ report yet transcribes nothing (said: "what landed is not known"). Its auto-transcribe lane still does what its policy
+ says.
+- **"Changed" recordings need the counts** a sweep records from this release on; a parent from before has none (only new
+ ones are found). A parent whose answers were never kept (an import with its results cut, or a run with no
+ enumeration — the question searched as one phrase) finds new recordings only by upload date, so an old video
+ transcribed late is missed; the plan says which.
+- **"Deleted" counts sources gone from the archive AND those deleted or private on their platform** (the archive keeps
+ them, and their quotes still verify); the update keeps their findings and says so in the summary.
+- **The update runs on the sweep route's model**, not the parent's; a sweep routed to Claude Code runs the API model
+ (said in the plan). The estimate is the parent's own spend per recording read — rough by design.
+- **refresh-held's action reopens the plan**: there is no "run just the update". A second refresh fetches and searches
+ again (cheap when nothing moved: the build is skipped as fresh).
+- **The daily check reads the build the iteration read when it is on this machine, else Research's local corpus**
+ (`export/public`: whichever site was composed last). An article whose build is gone and whose channels the local
+ corpus lacks checks to 0 new, silently. It runs in umtool's server, one article at a time, at most 12 queries each
+ (a large build is ~10 s a query).
+- **The run page (R3) does not list refresh iterations** (`hasRunPage` is the sweeps'); a refresh's trace is there
+ (fetch, build, delta, then the restricted sweep's own events) for R5/R6 or a later run-page change to show.
+- **The editor e2e exercises the door with a real sync and channel report** (the fake yt-dlp); `transcribe-bucket` for
+ what landed and the held-platform skip are unit-tested (common `refresh.test.ts`). The umtool e2e's editor is the
+ stub (a canned refresh).
+- **`inbox.spec`'s first test went red once in a targeted run** (`article-iterations` + `inbox` + `piece` +
+ `refresh`): the rail's count 35 against the page's 34 — the rail's 10 s memo caught the count mid-change after
+ `article-iterations`' stub job finished. Green in the full runs and in a rerun of the same three specs (22/22); the
+ refresh kinds add no card there (no check file; `UMTOOL_REFRESH_CHECK=0`). Not this lane's to change.
+- **Not done:** a refresh's own run page; "make current automatically" (R5's living report decides that).
+
+**Follow-up (review, 2026-10-14).** Rulings accepted: no-change and held-by-cap end `done` with the outcome in
+`refresh.json` and iteration.json's `refresh`; "deleted" counts both kinds; changed recordings only from this release
+on; the update on the sweep route's model; not built — a refresh's run page, and "run just the update" from a held
+refresh (the held card's action stays **Refresh**). Three changes:
+- **The coverage rule in the daily check — no silent zeros** (`lib/inbox/refresh.ts` `pickCheckCorpus`). A check reads
+ the build the iteration read when it is on this machine AND holds every channel of the scope, else Research's local
+ corpus when THAT holds every channel; the entry says which (`corpus`: "its own build (local:…)" / "the research
+ corpus (local:…)"). When neither does, the entry is `status: "unchecked"` with the reason — "the build holding
+ harbor-radio, nowhere-chan is not on this machine; channels not in the research corpus: nowhere-chan" — never "0
+ new", and the article gets no `refresh-available` card. `umtool refresh --check` prints `UNCHECKED — <why>`, and a
+ checked one "over <corpus>". Unit-tested both ways (`lib/inbox/refresh.test.ts` +1): a build gone with the research
+ corpus holding the channel is a real check that finds the new recording; a channel no corpus here holds is unchecked
+ with that sentence and no card.
+- **The sources gone are said by where.** The delta keeps `deleted` and adds `goneFromArchive` and
+ `removedOnPlatform {source, state, platform}`; the summary line reads "2 sources deleted on YouTube · 1 source made
+ private on Rumble · 1 source gone from the archive" (`goneParts`; a record from before reads as it did). The editor's
+ disk reader takes the platform from the recording's metadata page; the revision's feedback names it.
+- **Changes not tracked before an older parent, never 0.** The basis says whether it carries matching-line counts
+ (`countsKnown`); when it does not, the delta's `changedTracked` is false with `changedSince`, the outcome's
+ `changed` is `null` (the log marker and iteration.json too), a warning reads "changed recordings are not tracked before
+ <date>: i<n> recorded no matching-line counts (new ones are still found)" (on the plan and the record), and the
+ Overview shows that line. Unit-tested (common `refresh.test.ts` +2).
+
+| sha | what |
+|---|---|
+| `9549f987` | the coverage rule (`unchecked`, with why), the sources gone by where, changes not tracked before an older parent; tests |
+
+Gates at `9549f987`: repo-wide tsc clean; common (`SETTINGS_FILE` at the primary's) **4116/4116**; mcp 365/365; umtool
+unit 854 tests, 852 pass, 2 skipped, 0 fail; `pnpm --filter umtool test` **28/28**; editor unit 304/304; test:scripts
+1005, 1003 pass, 2 skipped, 0 fail; docs cli `--check` clean; capped umtool build exit 0 (26.7 s compile, 1:35 wall,
+1.49 GB; the link removed); capped editor build exit 0 (42 s compile, 1:22 wall, 2.47 GB); **full umtool e2e 458 tests:
+452 passed, 0 failed, 6 skipped**, 9.1 min; **full editor e2e** (this worktree, `export/public` linked from the primary,
+0 dangling; queued, detached) **709 tests: 695 passed, 2 failed, 12 skipped**, 23.3 min. The reds,
+`operation-settings.spec:61` (the Saved status after a /settings save) and `publish-lane.spec:78` (the "pause
+publishing" button after Resume), touch no code of this lane (R4's editor reach is the report-draft route and the ops
+door); the two specs alone, three times: 9/9, 9/9, 9/9.
+
+### R4 rollout (orchestrator, 2026-10-14)
+
+Rulings: a no-change or held-by-cap refresh ends `done` with its outcome in `refresh.json`; gone sources say where
+(deleted or private on the platform, or gone from the archive); an older parent says "changed recordings are not tracked
+before <date>", never 0; the update runs on the sweep route's model; the daily check never reports a silent 0 — an
+article whose channels neither its build nor the research corpus holds is `unchecked`, with the reason, and gets no card.
+Not built: a refresh run page; "run just the update" from a held refresh (the held card's action is Refresh). Gates on
+`08fee8e1`: full umtool e2e 452 passed, 0 failed, 6 skipped; full editor e2e 695 passed, 2 failed, 12 skipped — the two
+(`operation-settings.spec:61`, `publish-lane.spec:78`) on pages R4 does not touch, 9/9 alone three times; common 4116/4116
+in the primary after the fast-forward; capped builds ok. `main` fast-forwarded to `08fee8e1`; editor built (55 s) and
+restarted (`scripts/r4-editor-{build,restart}.sh`: PATH, `UV_THREADPOOL_SIZE`, no ZodError, no queued metas lost), then
+umtool (`scripts/r4-umtool.sh`). Live: `pnpm ops report-draft {"task":"refresh","article":"piratesoftware-ai-friends",
+"dryRun":true}` plans sync/refresh-report/transcribe-bucket for `piratesoftware` and fetch-posts for its X and Bluesky
+channels, a local build of `jasolyzer-private` (never deployed), the $5 cap and today's spend, with the older parent's
+warnings; `umtool refresh --check` checked both articles with a current report.
### R5, as shipped
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -109,6 +109,8 @@
// pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
// pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'
+// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait
+// pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'
// pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait
// pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'
// pnpm ops report-schedule --json '{"action":"list"}'
@@ -1260,7 +1262,25 @@ export function usage() {
' 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.",
+ ' 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}}.",
"",
'research-approve settles a research run\'s acquisitions: {"article",',
' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->',
diff --git a/umtool/app/api/articles/refresh/check/route.ts b/umtool/app/api/articles/refresh/check/route.ts
@@ -0,0 +1,30 @@
+import { checkable, readRefreshChecks, runRefreshChecks } from "@/lib/inbox/refresh";
+import { readLifecycle } from "@/lib/lifecycle";
+import { readMutes } from "@/lib/mutes";
+import { readPieceGraph } from "@/lib/pieces";
+
+export const dynamic = "force-dynamic";
+
+// THE DAILY REFRESH CHECK (plans/umtool-redesign.md, R4; lib/inbox/refresh.ts):
+// each active article's current report's enumerations again over the corpus
+// it read -- no fetch, no model -- kept a day. The Inbox reads what it kept and
+// checks a stale one in the background; this runs it NOW.
+//
+// GET what is kept (refresh-check.json)
+// POST { article?, force? } check (only `article`; `force`: even
+// one checked today) -> { checked, skipped }
+const headers = { "cache-control": "no-store" };
+
+export async function GET() {
+ return Response.json(await readRefreshChecks(), { headers });
+}
+
+export async function POST(request: Request) {
+ const body = ((await request.json().catch(() => null)) ?? {}) as { article?: unknown; force?: unknown };
+ const [graph, life, mutes] = await Promise.all([readPieceGraph(), readLifecycle(), readMutes()]);
+ const out = await runRefreshChecks(checkable(graph, life, mutes), {
+ force: body.force === true,
+ ...(typeof body.article === "string" && body.article ? { only: body.article } : {}),
+ });
+ return Response.json(out, { headers });
+}
diff --git a/umtool/app/api/articles/refresh/route.ts b/umtool/app/api/articles/refresh/route.ts
@@ -0,0 +1,39 @@
+import { errorResponse } from "@/lib/articles/generation";
+import { planArticleRefresh, readRefreshes, startArticleRefresh } from "@/lib/articles/refresh";
+
+export const dynamic = "force-dynamic";
+
+// A REFRESH of an article (plans/umtool-redesign.md, R4): re-fetch its scope,
+// see what changed, update -- planned, then confirmed. The editor plans and
+// runs it (`report-draft {"task": "refresh"}`); umtool writes nothing here.
+//
+// GET ?article=<id> { refreshes }: each refresh
+// iteration, newest first, with
+// what its refresh.json kept
+// POST { article, iteration?, fetch? } { plan }: what it would do
+// POST { article, iteration?, fetch?, confirm: true }
+// { jobId, iteration, href }
+const ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const article = new URL(request.url).searchParams.get("article") ?? "";
+ if (!ID.test(article)) return Response.json({ error: "name the article (?article=<id>)" }, { status: 400, headers });
+ return Response.json({ refreshes: await readRefreshes(article) }, { headers });
+}
+
+export async function POST(request: Request) {
+ try {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "send { article }" }, { status: 400, headers });
+ const article = typeof body.article === "string" ? body.article : "";
+ if (!ID.test(article)) return Response.json({ error: '"article" is an article id' }, { status: 400, headers });
+ const iteration = body.iteration === undefined || body.iteration === null ? undefined : Number(body.iteration);
+ if (iteration !== undefined && !(Number.isInteger(iteration) && iteration > 0)) return Response.json({ error: '"iteration" is an iteration number' }, { status: 400, headers });
+ const o = { ...(iteration ? { iteration } : {}), ...(body.fetch === false ? { fetch: false } : {}) };
+ if (body.confirm === true) return Response.json({ ok: true, ...(await startArticleRefresh(article, o)) }, { headers });
+ return Response.json({ plan: await planArticleRefresh(article, o) }, { headers });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
diff --git a/umtool/bin/refresh.ts b/umtool/bin/refresh.ts
@@ -0,0 +1,85 @@
+// `umtool refresh` -- an article's Refresh from a terminal (plans/umtool-
+// redesign.md, R4; lib/articles/refresh.ts, lib/inbox/refresh.ts). Run by
+// bin/umtool.mjs through tsx, from umtool/ (the `@/` paths).
+//
+// umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]
+// the plan (the editor's dry run: the iteration refreshed, its queries,
+// each channel's fetches or why skipped, the site built, the model and
+// the cap); --yes starts it -- one editor job -- and prints where to
+// follow it
+// umtool refresh --check [<article>] [--force] [--json]
+// the daily suggestion check now: each active article's current report's
+// enumerations again (no fetch, no model), kept a day
+import { planArticleRefresh, startArticleRefresh } from "../lib/articles/refresh";
+import { checkable, runRefreshChecks } from "../lib/inbox/refresh";
+import { readLifecycle } from "../lib/lifecycle";
+import { readMutes } from "../lib/mutes";
+import { readPieceGraph } from "../lib/pieces";
+
+const args = process.argv.slice(2);
+const has = (f: string) => args.includes(f);
+const val = (f: string) => {
+ const i = args.indexOf(f);
+ return i >= 0 ? args[i + 1] : undefined;
+};
+const json = has("--json");
+const positional = args.filter((a, i) => !a.startsWith("--") && args[i - 1] !== "--iteration");
+const die = (msg: string): never => {
+ console.error(`umtool refresh: ${msg}`);
+ process.exit(1);
+};
+
+if (has("--check")) {
+ const [graph, life, mutes] = await Promise.all([readPieceGraph(), readLifecycle(), readMutes()]);
+ const out = await runRefreshChecks(checkable(graph, life, mutes), { force: has("--force"), ...(positional[0] ? { only: positional[0] } : {}) });
+ if (json) {
+ console.log(JSON.stringify(out, null, 2));
+ process.exit(0);
+ }
+ for (const c of out.checked) {
+ console.log(
+ c.status === "unchecked"
+ ? `${c.article} i${c.iteration}: UNCHECKED — ${c.reason ?? c.error ?? "no corpus here holds its scope"}`
+ : `${c.article} i${c.iteration}: ${c.newCount} new recording${c.newCount === 1 ? "" : "s"} since ${c.since.slice(0, 10)}${c.titles.length ? ` (${c.titles.join(", ")})` : ""}${c.partial ? " — partial" : ""} · over ${c.corpus ?? c.source}`,
+ );
+ }
+ for (const s of out.skipped) console.log(`${s.article}: ${s.why}`);
+ if (!out.checked.length && !out.skipped.length) console.log("no active article with a current report");
+ process.exit(0);
+}
+
+const article = positional[0];
+if (!article) die("usage: umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json] | umtool refresh --check [<article>] [--force]");
+const iteration = val("--iteration") ? Number(val("--iteration")) : undefined;
+if (iteration !== undefined && !(Number.isInteger(iteration) && iteration > 0)) die("--iteration is an iteration number");
+const o = { ...(iteration ? { iteration } : {}), ...(has("--no-fetch") ? { fetch: false } : {}) };
+
+try {
+ if (has("--yes")) {
+ const r = await startArticleRefresh(article!, o);
+ if (json) console.log(JSON.stringify(r, null, 2));
+ else console.log(`${article} i${r.iteration}: the refresh is running (job ${r.jobId}) — ${r.href}`);
+ process.exit(0);
+ }
+ const p = await planArticleRefresh(article!, o);
+ if (json) {
+ console.log(JSON.stringify(p, null, 2));
+ process.exit(0);
+ }
+ console.log(`# Refresh ${p.article} — i${p.parent.n} (${p.parent.kind}, made ${p.parent.at.slice(0, 10)})`);
+ if (p.parent.question) console.log(` question ${p.parent.question}`);
+ console.log(` searched ${p.parent.queries.map((q) => `"${q}"`).join(", ")} (from its ${p.parent.from}; ${p.parent.knownCount} matched then, ${p.parent.citedCount} cited quotes read again)`);
+ if (!p.fetch) console.log(" fetch none: the corpus is read as it stands");
+ for (const c of p.channels) console.log(` fetch ${c.slug}${c.platform ? ` (${c.platform})` : ""}: ${c.skip ? `skipped — ${c.skip}` : c.actions.join(" → ")}`);
+ console.log(` build ${p.build.site ? `${p.build.site}, locally (never deployed)` : (p.build.reason ?? "none")}`);
+ console.log(
+ ` update ${p.model}${p.capUsd !== null ? `, up to $${p.capUsd.toFixed(2)}` : " (local, no cap)"} — about $${p.estimate.perRecordingUsd.toFixed(2)} a new recording + $${p.estimate.revisionUsd.toFixed(2)}, only when something changed` +
+ (p.daily ? `; today $${p.daily.usd.toFixed(2)} of $${p.daily.cap.toFixed(2)}` : ""),
+ );
+ for (const w of p.warnings) console.log(` note ${w}`);
+ for (const r of p.refusals) console.log(` REFUSED ${r}`);
+ console.log(p.refusals.length ? "\nNothing was started." : `\nNothing was started. \`umtool refresh ${article}${iteration ? ` --iteration ${iteration}` : ""}${has("--no-fetch") ? " --no-fetch" : ""} --yes\` runs it.`);
+ process.exit(p.refusals.length ? 1 : 0);
+} catch (e) {
+ die((e as Error).message);
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -703,6 +703,10 @@ function usage() {
" umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
" umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
" umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
+ " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
+ " re-fetch an article's scope, see what changed, update: the plan (the editor's);",
+ " --yes starts it, one editor job (needs WORKER_TOKEN and the editor)",
+ " umtool refresh --check [<article>] [--force] [--json] the daily suggestion check, now",
"",
`reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`,
"",
@@ -734,12 +738,14 @@ const COMMANDS = {
notes: async () => process.exit(await notesCommand(argv.slice(argv.indexOf("notes") + 1))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
+ refresh: () => tsxScript("refresh"),
help: usage,
};
// `umtool inbox`: bin/inbox.ts, through tsx -- the inbox is the app's
// TypeScript (lib/inbox.ts), run from umtool/ so its `@/` paths resolve.
-// `umtool schedule` (R5) is bin/schedule.ts, the same way.
+// `umtool schedule` (R5) and `umtool refresh` (R4) are bin/schedule.ts and
+// bin/refresh.ts, the same way.
function cmdInbox() {
return tsxScript("inbox");
}
diff --git a/umtool/components/articles/ArticleOverview.tsx b/umtool/components/articles/ArticleOverview.tsx
@@ -4,6 +4,8 @@ import NextCard, { NextCardShell } from "@/components/piece/NextCard";
import { IterationsSummary, ProjectDecisions } from "@/components/projects/report/OverviewTab";
import { hms, type ClipDetail } from "@/components/projects/report/shared";
import { readArticleIterations } from "@/lib/articles/generation";
+import { readRefreshes } from "@/lib/articles/refresh";
+import RefreshSummary from "./RefreshSummary";
import { ARTICLES_KEY } from "@/lib/articles/key.mjs";
import { projectHref } from "@/lib/hrefs";
import { decisionsForProject } from "@/lib/projects";
@@ -40,9 +42,10 @@ export default async function ArticleOverview({
tabHref: Href;
}) {
const store = site === ARTICLES_KEY;
- const [iterations, decisions] = await Promise.all([
+ const [iterations, decisions, refreshes] = await Promise.all([
store ? readArticleIterations(frame.report).catch(() => null) : Promise.resolve(null),
videoRef ? decisionsForProject(videoRef).catch(() => []) : Promise.resolve([]),
+ store ? readRefreshes(frame.report).catch(() => []) : Promise.resolve([]),
]);
const rows = iterations?.iterations ?? [];
const asked = rows.find((r) => r.currentReport && r.question) ?? rows.find((r) => r.question) ?? null;
@@ -86,6 +89,7 @@ export default async function ArticleOverview({
)}
</section>
)}
+ {refreshes[0] && <RefreshSummary row={refreshes[0]} iterationsHref={tabHref("iterations")} />}
{videoRef && <ProjectDecisions project={videoRef.id} decisions={decisions} />}
</div>
diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx
@@ -7,6 +7,7 @@ import { readRevisionHead, REPORT_HISTORY_GIT_DIRNAME } from "yt-dlp-transcript-
import { hasSlides, slideLint } from "yt-dlp-transcript-common/lib/report/slides";
import type { Crumb } from "@/components/shell/AppHeader";
import DeleteArticle from "@/components/articles/DeleteArticle";
+import { RefreshHost, RefreshMenuItem } from "@/components/articles/RefreshDialog";
import ArticleOverview from "@/components/articles/ArticleOverview";
import ArticleReader from "@/components/articles/ArticleReader";
import WorkspacePanel from "@/components/articles/WorkspacePanel";
@@ -61,6 +62,8 @@ import type { NotesRead } from "@/lib/annotations/types";
// ?ws=&rel= a workspace file open on the source view
// ?project=<id> another video project the article owns
// ?all=1 the cut's every quote
+// ?refresh=1 the Refresh plan open (R4: the suggestion
+// card's action)
export type ArticleSearch = {
tab?: string;
@@ -71,6 +74,7 @@ export type ArticleSearch = {
rv?: string;
all?: string;
project?: string;
+ refresh?: string;
};
type TabHref = (t: string, q?: { all?: boolean; project?: string }) => string;
@@ -194,6 +198,7 @@ export default async function ArticlePage({
more={
<>
<span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{frame.pieceId}</span>
+ {store && hasIterations && r && <RefreshMenuItem article={reportId} />}
{store && <DeleteArticle article={reportId} published={published} />}
{schedule && <ScheduleControls part="menu" schedule={schedule} />}
{videoRef && (
@@ -207,6 +212,7 @@ export default async function ArticlePage({
</>
}
>
+ {store && hasIterations && r && <RefreshHost article={reportId} initialOpen={sp.refresh === "1"} href={tabHref(tab)} />}
{tab === "overview" && (
<ArticleOverview
site={site}
diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx
@@ -9,6 +9,7 @@ import { badgeVariants } from "@/components/ui/badge";
import ChainPanel from "@/components/articles/ChainPanel";
import { EditorJobProgress } from "@/components/ui/job-progress";
import ResearchSlot from "@/components/articles/ResearchSlot";
+import { RefreshButton } from "@/components/articles/RefreshDialog";
import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect";
import DeletePlan from "@/components/DeletePlan";
import { usd, type Today } from "@/components/articles/PolicyPanel";
@@ -197,6 +198,11 @@ function IterationCard({
</span>
</header>
+ {it.refresh && (
+ <p className="mt-1 text-[13px]" data-refresh-outcome={it.refresh.status}>
+ {it.refresh.summary}
+ </p>
+ )}
{(it.feedback ?? it.question) && <p className="mt-1 text-[13px]">{it.feedback ? `“${it.feedback}”` : it.question}</p>}
{it.scope?.channels && (
<p className="font-mono text-[11px] text-[var(--color-dim)]">
@@ -439,6 +445,11 @@ export default function IterationsTab({
{today.daily > 0 ? ` of ${usd(today.daily)}` : ""}
</span>
)}
+ {data.current.report !== null && !data.busy && (
+ <span className="ml-auto">
+ <RefreshButton article={article} />
+ </span>
+ )}
{compare.length === 2 && (
<Link
href={`/articles/${article}/compare?a=${Math.min(...compare)}&b=${Math.max(...compare)}`}
diff --git a/umtool/components/articles/RefreshDialog.tsx b/umtool/components/articles/RefreshDialog.tsx
@@ -0,0 +1,262 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { Dialog } from "@/components/ui/dialog";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import type { RefreshPlan } from "yt-dlp-transcript-common/lib/report/draft/refresh/types";
+
+// ---------------------------------------------------------------------------
+// REFRESH, plan then confirm (plans/umtool-redesign.md, R4). The plan is the
+// editor's dry run (`report-draft {"task": "refresh", "dryRun": true}`, through
+// /api/articles/refresh): the iteration refreshed and what it is searched
+// again with, each channel's fetches (or why one is skipped), the site built
+// locally, the model and the cap. Nothing is written until **Refresh** --
+// then it is one editor job (the Running list), and the Overview shows what
+// it found.
+//
+// The ⋯ menu's item (RefreshMenuItem) and the Next card's action (`?refresh=1`)
+// open the one dialog the page holds (RefreshHost): a menu item's own dialog
+// would close with the menu.
+// ---------------------------------------------------------------------------
+
+const OPEN_EVENT = "umtool:refresh";
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 10) : "");
+
+function Row({ k, children }: { k: string; children: React.ReactNode }) {
+ return (
+ <>
+ <dt className="text-muted">{k}</dt>
+ <dd className="m-0 min-w-0 break-words text-text-2">{children}</dd>
+ </>
+ );
+}
+
+function PlanBody({ p }: { p: RefreshPlan }) {
+ const fetched = p.channels.filter((c) => !c.skip);
+ return (
+ <dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 text-[12.5px]" data-refresh-plan={p.article}>
+ <Row k="Refreshes">
+ <span className="font-mono">i{p.parent.n}</span> ({p.parent.kind}, made {day(p.parent.at)})
+ {p.parent.question ? <span className="block text-muted">{p.parent.question}</span> : null}
+ </Row>
+ <Row k="Searched again">
+ <span data-refresh-queries="">{p.parent.queries.map((q) => `“${q}”`).join(", ")}</span>
+ <span className="block text-muted">
+ against {p.parent.knownCount.toLocaleString("en-US")} recording{p.parent.knownCount === 1 ? "" : "s"} matched then · {p.parent.citedCount} cited quote{p.parent.citedCount === 1 ? "" : "s"} read again
+ </span>
+ </Row>
+ <Row k="Fetch">
+ {!p.fetch ? (
+ "none: the corpus is read as it stands"
+ ) : (
+ <ul className="m-0 grid list-none gap-1 p-0" data-refresh-fetches={fetched.length}>
+ {p.channels.map((c) => (
+ <li key={c.slug} data-refresh-channel={c.slug} data-skip={c.skip ? "" : undefined}>
+ <span className="font-mono">{c.slug}</span>
+ {c.platform ? <span className="text-muted"> · {c.platform}</span> : null}
+ {c.skip ? <span className="block text-doubt-text">skipped — {c.skip}</span> : <span className="block text-muted">{c.actions.join(" → ")}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ </Row>
+ <Row k="Build">
+ <span data-refresh-build={p.build.site ?? ""}>
+ {p.build.site ? (
+ <>
+ <span className="font-mono">{p.build.site}</span>, locally, if anything changed — never deployed
+ </>
+ ) : (
+ (p.build.reason ?? "none")
+ )}
+ {p.build.builtAt ? <span className="block text-muted">built {day(p.build.builtAt)}</span> : null}
+ </span>
+ </Row>
+ <Row k="Update">
+ <span data-refresh-cap={p.capUsd ?? "local"}>
+ <span className="font-mono">{p.model}</span>
+ {p.extractor ? (
+ <>
+ {" "}
+ · extractor <span className="font-mono">{p.extractor}</span>
+ </>
+ ) : null}
+ {p.capUsd !== null ? (
+ <>
+ {" "}
+ · spends up to <span className="font-mono text-meter">{usd(p.capUsd)}</span>
+ </>
+ ) : (
+ " · the local model, no cap"
+ )}
+ <span className="block text-muted">
+ only when something changed: a sweep of the new recordings, then a revision · about {usd(p.estimate.perRecordingUsd)} a recording
+ {p.estimate.from === "parent" ? ` (i${p.parent.n}'s rate)` : ""} + {usd(p.estimate.revisionUsd)}
+ {p.daily ? ` · today ${usd(p.daily.usd)} of ${usd(p.daily.cap)}` : ""}
+ </span>
+ </span>
+ </Row>
+ </dl>
+ );
+}
+
+async function post<T>(body: unknown): Promise<T> {
+ const r = await fetch("/api/articles/refresh", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null;
+ if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`);
+ return j as T;
+}
+
+export function RefreshDialog({ article, open, onClose, onDone }: { article: string; open: boolean; onClose: () => void; onDone: (what: string) => void }) {
+ const [plan, setPlan] = useState<RefreshPlan | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [working, setWorking] = useState(false);
+ useEffect(() => {
+ setPlan(null);
+ setError(null);
+ if (!open) return;
+ let live = true;
+ post<{ plan: RefreshPlan }>({ article })
+ .then((r) => live && setPlan(r.plan))
+ .catch((e: Error) => live && setError(e.message));
+ return () => {
+ live = false;
+ };
+ }, [article, open]);
+
+ const confirm = async () => {
+ if (!plan) return;
+ setWorking(true);
+ setError(null);
+ try {
+ const r = await post<{ jobId: string; iteration: number }>({ article, iteration: plan.parent.n, confirm: true });
+ onDone(`Refresh i${r.iteration} is running (job ${r.jobId})`);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setWorking(false);
+ }
+ };
+
+ const blocked = !plan || plan.refusals.length > 0;
+ return (
+ <Dialog open={open} onClose={onClose} title="Refresh: fetch what's new, see what changed" data-refresh-dialog={article}>
+ {!plan && !error && (
+ <p role="status" className="text-[12.5px] text-text-2">
+ Reading the plan…
+ </p>
+ )}
+ {plan && <PlanBody p={plan} />}
+ {plan && plan.refusals.length > 0 && (
+ <ul data-refusals="" className="mt-3 grid list-none gap-1 p-0 text-[12.5px] text-reject-text">
+ {plan.refusals.map((r) => (
+ <li key={r}>{r}</li>
+ ))}
+ </ul>
+ )}
+ {plan && plan.warnings.length > 0 && (
+ <ul data-warnings="" className="mt-3 grid list-none gap-1 p-0 text-[12px] text-doubt-text">
+ {plan.warnings.map((w) => (
+ <li key={w}>{w}</li>
+ ))}
+ </ul>
+ )}
+ {error && (
+ <p role="alert" className="mt-3 text-[12.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ <div className="mt-4 flex items-center justify-end gap-2">
+ <button type="button" className={buttonVariants({ variant: "quiet" })} onClick={onClose}>
+ Cancel
+ </button>
+ <button type="button" data-confirm="" disabled={blocked || working} className={buttonVariants({ variant: "go" })} onClick={confirm}>
+ {working ? "Starting…" : "Refresh"}
+ </button>
+ </div>
+ </Dialog>
+ );
+}
+
+/** The ⋯ menu's item: opens the page's one Refresh dialog. */
+export function RefreshMenuItem({ article }: { article: string }) {
+ const hydrated = useHydrated();
+ return (
+ <button
+ type="button"
+ disabled={!hydrated}
+ data-refresh-open=""
+ className={buttonVariants({ variant: "quiet", size: "sm", className: "justify-start" })}
+ onClick={() => window.dispatchEvent(new CustomEvent(OPEN_EVENT, { detail: { article } }))}
+ >
+ Refresh…
+ </button>
+ );
+}
+
+/** The Iterations tab's Refresh: the same dialog, from the tab's own line. */
+export function RefreshButton({ article }: { article: string }) {
+ const hydrated = useHydrated();
+ return (
+ <button
+ type="button"
+ disabled={!hydrated}
+ data-refresh-open="iterations"
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ onClick={() => window.dispatchEvent(new CustomEvent(OPEN_EVENT, { detail: { article } }))}
+ >
+ Refresh…
+ </button>
+ );
+}
+
+/** The page's Refresh dialog: opened by the menu item, or on arrival with `?refresh=1` (the Next card's action). */
+export function RefreshHost({ article, initialOpen = false, href }: { article: string; initialOpen?: boolean; href: string }) {
+ const router = useRouter();
+ const [open, setOpen] = useState(initialOpen);
+ const [said, setSaid] = useState<string | null>(null);
+ // A client navigation to `?refresh=1` on the page already showing (the Next
+ // card's action) keeps this mounted: open on the new address too.
+ useEffect(() => {
+ if (initialOpen) setOpen(true);
+ }, [initialOpen]);
+ useEffect(() => {
+ const onOpen = (e: Event) => {
+ if ((e as CustomEvent<{ article?: string }>).detail?.article === article) {
+ setSaid(null);
+ setOpen(true);
+ }
+ };
+ window.addEventListener(OPEN_EVENT, onOpen);
+ return () => window.removeEventListener(OPEN_EVENT, onOpen);
+ }, [article]);
+ const close = () => {
+ setOpen(false);
+ // The address no longer opens it.
+ if (initialOpen) router.replace(href, { scroll: false });
+ };
+ return (
+ <>
+ <RefreshDialog
+ article={article}
+ open={open}
+ onClose={close}
+ onDone={(what) => {
+ setSaid(what);
+ setOpen(false);
+ router.replace(href, { scroll: false });
+ router.refresh();
+ }}
+ />
+ {said && (
+ <p role="status" data-refresh-started="" className="px-4 pt-2 text-[12.5px] text-signal-text">
+ {said}
+ </p>
+ )}
+ </>
+ );
+}
diff --git a/umtool/components/articles/RefreshSummary.tsx b/umtool/components/articles/RefreshSummary.tsx
@@ -0,0 +1,90 @@
+import Link from "next/link";
+import { badgeVariants } from "@/components/ui/badge";
+import { Card } from "@/components/ui/panel";
+import type { RefreshRow } from "@/lib/articles/refresh";
+import RefreshWatch from "./RefreshWatch";
+
+// ---------------------------------------------------------------------------
+// The newest REFRESH on an article's Overview (plans/umtool-redesign.md, R4):
+// what its refresh.json kept, in one line — "4 new recordings match · 2 quotes
+// changed · 1 source deleted", or "Nothing new since <date>" — then the new
+// recordings, the quotes that changed and what was fetched and built; the
+// update's spend, or the cap that held it. While it runs, the page reads
+// again every few seconds (RefreshWatch).
+// ---------------------------------------------------------------------------
+
+const STATUS: Record<string, { label: string; variant: "neutral" | "on" | "blocking" | "open" | "info" | "meter" }> = {
+ running: { label: "running", variant: "meter" },
+ "no-change": { label: "no change", variant: "info" },
+ updated: { label: "updated", variant: "on" },
+ "held-by-cap": { label: "held by the cap", variant: "open" },
+ failed: { label: "failed", variant: "blocking" },
+ cancelled: { label: "cancelled", variant: "info" },
+};
+
+const usd = (n: number) => `$${n.toFixed(2)}`;
+
+export default function RefreshSummary({ row, iterationsHref }: { row: RefreshRow; iterationsHref: string }) {
+ const live = row.status === "queued" || row.status === "running";
+ const state = live ? "running" : (row.refresh ?? (row.status === "failed" ? "failed" : row.status === "cancelled" ? "cancelled" : "running"));
+ const s = STATUS[state] ?? STATUS.running!;
+ const fetched = row.fetch.filter((f) => f.status === "done").length;
+ const skipped = row.fetch.filter((f) => f.status === "skipped" || f.status === "refused");
+ return (
+ <section data-refresh-summary={row.n} data-refresh-state={state}>
+ <div className="mb-2 flex items-baseline gap-3">
+ <h2 className="micro">Refresh · i{row.n}</h2>
+ <span className={badgeVariants({ variant: s.variant, size: "sm" })} data-refresh-status={state}>
+ {s.label}
+ </span>
+ <Link href={iterationsHref} prefetch={false} className="ink-link ml-auto text-[12px]">
+ {row.hasReport ? "Review in Iterations →" : "Iterations →"}
+ </Link>
+ </div>
+ <Card className="space-y-2">
+ <p className="text-[15px] font-semibold leading-snug" data-refresh-line="">
+ {live ? "Fetching and searching again…" : row.summary.split(" — ")[0]}
+ </p>
+ {!live && row.summary.includes(" — ") && <p className="text-[12.5px] text-muted">{row.summary.split(" — ").slice(1).join(" — ")}</p>}
+ {row.news.length > 0 && (
+ <ul className="m-0 grid list-none gap-0.5 p-0 text-[12.5px]" data-refresh-new={row.counts.newIds}>
+ {row.news.map((r) => (
+ <li key={r.id} className="truncate">
+ <span className="font-mono text-[11.5px] text-muted-2">{r.date ?? ""}</span> {r.title ?? r.id}
+ </li>
+ ))}
+ {row.counts.newIds > row.news.length && <li className="text-muted">and {row.counts.newIds - row.news.length} more</li>}
+ </ul>
+ )}
+ {row.drifted.length > 0 && (
+ <ul className="m-0 grid list-none gap-1 p-0 text-[12.5px]" data-refresh-drifted={row.counts.drifted}>
+ {row.drifted.map((d) => (
+ <li key={d.citation}>
+ <span className="text-muted-2">{d.citation}</span> <span className="font-serif">“{d.quote}”</span>
+ {d.now !== null && <span className="block text-muted">now: “{d.now.slice(0, 200)}”</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {row.deleted.length > 0 && (
+ <p className="text-[12.5px] text-doubt-text" data-refresh-deleted={row.deleted.length}>
+ {row.gone.join(" · ")}: <span className="font-mono">{row.deleted.join(", ")}</span>
+ </p>
+ )}
+ {row.counts.changed === null && (
+ <p className="text-[12px] text-muted" data-refresh-untracked="">
+ {row.warnings.find((w) => w.startsWith("changed recordings are not tracked")) ?? "changed recordings are not tracked for this iteration"}
+ </p>
+ )}
+ <p className="text-[12px] text-muted" data-refresh-steps="">
+ {row.fetch.length ? `${fetched} fetch${fetched === 1 ? "" : "es"} done` : "no fetch"}
+ {skipped.length ? ` · skipped: ${skipped.map((f) => `${f.channel} ${f.action} (${f.reason ?? f.status})`).join("; ")}` : ""}
+ {row.build ? ` · build ${row.build.site ?? "none"} ${row.build.status}${row.build.reason ? ` (${row.build.reason})` : ""}` : ""}
+ {row.update?.usd ? ` · ${usd(row.update.usd)} spent` : !live && row.refresh === "no-change" && !row.update ? " · $0" : ""}
+ {row.update?.refusal ? ` · about ${usd(row.update.estimateUsd)} to update` : ""}
+ </p>
+ </Card>
+ {live && <RefreshWatch />}
+ </section>
+ );
+}
diff --git a/umtool/components/articles/RefreshWatch.tsx b/umtool/components/articles/RefreshWatch.tsx
@@ -0,0 +1,17 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useEffect } from "react";
+
+// While a refresh runs, the page reads again every few seconds (only while the
+// tab is visible): its Overview then shows what the refresh found.
+export default function RefreshWatch({ everyMs = 4000 }: { everyMs?: number }) {
+ const router = useRouter();
+ useEffect(() => {
+ const t = setInterval(() => {
+ if (document.visibilityState === "visible") router.refresh();
+ }, everyMs);
+ return () => clearInterval(t);
+ }, [router, everyMs]);
+ return null;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -112,6 +112,12 @@ function writeWindow(dir, name, seconds) {
// the stub's acquisition jobs, then
// approved (a job: running after 1 s,
// done after 3 s) or rejected
+// A `refresh` report-draft (R4): `dryRun` answers a plan (the iteration
+// refreshed, a fetch per channel and one held platform skipped, a site built,
+// the policy's model and cap); else a `refresh` iteration, running after 1 s,
+// done after 3 s with its refresh.json — `updated` (one new recording, one
+// quote changed, a report.json), or `no-change` for an article whose id ends
+// in "-quiet".
// A `research` report-draft proposes three acquisitions (an archive.org import
// waits, a new channel waits, a Twitch VOD refused); a `sweep` with
// `iteration` continues a research run, as the editor does.
@@ -644,6 +650,137 @@ function startDraft(body) {
return { jobId: id, iteration: n };
}
+// ─── a refresh (R4) ───
+
+// The iteration a refresh refreshes: the one named, else the current report's,
+// else the newest done one with a report.json.
+function refreshTarget(article, asked) {
+ if (asked) return Number(asked);
+ try {
+ const cur = JSON.parse(readFileSync(path.join(ARTICLES, article, "iterations", "current.json"), "utf8"));
+ if (cur.report) return cur.report;
+ } catch {
+ // none: the newest done one
+ }
+ const dir = path.join(ARTICLES, article, "iterations");
+ const ns = existsSync(dir) ? readdirSync(dir).filter((d) => /^\d+$/.test(d)).map(Number).sort((a, b) => b - a) : [];
+ for (const n of ns) if (readIt(article, n).status === "done" && existsSync(path.join(itDir(article, n), "report.json"))) return n;
+ throw new Error(`"${article}" has no report to refresh: no iteration is current and none that is done carries a report`);
+}
+
+function refreshPlan(body) {
+ const n = refreshTarget(body.article, body.iteration);
+ const it = readIt(body.article, n);
+ const fetch = body.fetch !== false;
+ const channels = it.scope?.channels?.length ? it.scope.channels : ["sitechan"];
+ return {
+ article: body.article,
+ parent: { n, kind: it.kind, model: it.model, question: it.question ?? null, at: it.endedAt ?? it.updatedAt, from: "trace", queries: ["lighthouse budget"], knownCount: 4, knownComplete: true, citedCount: 1 },
+ scope: { channels },
+ fetch,
+ channels: [
+ ...channels.map((slug) => ({ slug, kind: "video", platform: "youtube", actions: fetch ? ["sync", "refresh-report", "transcribe-bucket (what lands)"] : [] })),
+ ...(fetch ? [{ slug: "otherchan", kind: "video", platform: "rumble", actions: [], skip: "rumble is held: its rate limit outlasted the cooldown cap (3 failures in a row)" }] : []),
+ ],
+ build: fetch ? { site: "priv", builtAt: "2026-10-13T22:00:00.000Z" } : { site: null, reason: "no fetch: the corpus is read as it stands" },
+ corpus: { source: "local:/stub/.export-builds/priv/out", build: "priv" },
+ model: generation.models.api,
+ provider: "api",
+ extractor: generation.models.extractor,
+ capUsd: generation.caps.sweep,
+ daily: { usd: 1.2, cap: generation.caps.daily },
+ estimate: { perRecordingUsd: 0.1, revisionUsd: 0.3, from: "parent" },
+ refusals: [],
+ warnings: [],
+ };
+}
+
+function startRefresh(body) {
+ const { article } = body;
+ const parent = refreshTarget(article, body.iteration);
+ const p = readIt(article, parent);
+ const now = new Date().toISOString();
+ const id = `stub-draft-${nextJob++}`;
+ const n = nextN(article);
+ mkdirSync(itDir(article, n), { recursive: true });
+ writeIt({ format: "archilyzer-iteration", version: 1, article, n, kind: "refresh", parent, copyOf: null, ...(p.question ? { question: p.question } : {}), scope: p.scope ?? { channels: ["sitechan"] }, model: body.model ?? generation.models.api, status: "queued", usage: {}, steps: [], jobId: id, createdAt: now, updatedAt: now });
+ const job = { id, article, n, task: "refresh", status: "queued", at: Date.now(), log: [`report-draft refresh ${article} i${n} (stub)`], timers: [] };
+ draftJobs.set(id, job);
+ job.timers.push(
+ setTimeout(() => {
+ job.status = "running";
+ job.log.push("stage 1: fetch (stub)");
+ patchIt(article, n, { status: "running" });
+ }, 1000),
+ );
+ job.timers.push(setTimeout(() => finishRefresh(job, parent, p), 3000));
+ return { jobId: id, iteration: n };
+}
+
+function finishRefresh(job, parent, p) {
+ const { article, n } = job;
+ if (readIt(article, n).status === "cancelled") return;
+ const quiet = article.endsWith("-quiet");
+ const at = new Date().toISOString();
+ const since = p.endedAt ?? p.updatedAt;
+ const quote = "the lighthouse budget was never approved";
+ const delta = quiet
+ ? { at, status: "no-change", matched: 4, newIds: [], new: [], changed: [], changedTracked: true, unmatched: [], drifted: [], deleted: [], goneFromArchive: [], removedOnPlatform: [], enOrig: [], quotes: [{ citation: "c1", kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, status: "ok", quote }], partial: false, unreached: [], matchedSet: { "hr-2019a": 1, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 } }
+ : {
+ at,
+ status: "changed",
+ matched: 5,
+ newIds: ["hr-2021a"],
+ new: [{ id: "hr-2021a", channel: "Harbor Radio", date: "2021-09-07", title: "Harbor Radio 52: storm season", matches: 2 }],
+ changed: [],
+ unmatched: [],
+ drifted: ["c1"],
+ changedTracked: true,
+ deleted: [],
+ goneFromArchive: [],
+ removedOnPlatform: [],
+ enOrig: [],
+ quotes: [{ citation: "c1", kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, status: "drifted", quote, now: "the lighthouse budget was not approved that year", nowAt: 600 }],
+ partial: false,
+ unreached: [],
+ matchedSet: { "hr-2019a": 1, "hr-2021a": 2, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 },
+ };
+ const line = quiet ? `Nothing new since ${String(since).slice(0, 10)}` : "1 new recording matches · 1 quote changed";
+ const status = quiet ? "no-change" : "updated";
+ const summary = quiet ? line : `${line} — updated: 2 op(s) applied, 0 refused — “Refreshed”`;
+ const file = {
+ format: "archilyzer-refresh",
+ version: 1,
+ article,
+ n,
+ parent,
+ status,
+ summary,
+ startedAt: at,
+ endedAt: at,
+ basis: { article, n: parent, queriesOf: parent, question: p.question ?? null, scope: p.scope ?? { channels: [] }, queries: [{ query: "lighthouse budget" }], from: "trace", knownComplete: true, source: null, at: since, knownCount: 4, citedCount: 1, known: {} },
+ fetch: [
+ { channel: "harbor-radio", action: "sync", status: "done", jobId: "stub-sync" },
+ { channel: "harbor-radio", action: "refresh-report", status: "done", jobId: "stub-report" },
+ { channel: "harbor-radio", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe" },
+ ],
+ build: { site: "priv", status: "done", jobIds: ["stub-build"] },
+ corpus: { source: "local:/stub/.export-builds/priv/out", build: "priv", origin: "https://archive.example" },
+ delta,
+ ...(quiet ? {} : { update: { model: readIt(article, n).model, estimateUsd: 0.4, capUsd: generation.caps.sweep, sweep: { ids: ["hr-2021a"], status: "done", summary: "1 finding", findings: 1 }, revision: { status: "done", summary: "2 op(s) applied" }, usd: 0.31 } }),
+ warnings: [],
+ };
+ writeFileSync(path.join(itDir(article, n), "refresh.json"), JSON.stringify(file, null, 2) + "\n");
+ const patch = { status: "done", minutes: 0.1, endedAt: at, refresh: { status, newIds: delta.newIds.length, changed: 0, drifted: delta.drifted.length, deleted: 0, summary } };
+ if (!quiet) {
+ writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, "Refreshed", " One recording more."), null, 2) + "\n");
+ patch.usage = { [readIt(article, n).model]: { usd: 0.31, inputTokens: 21000, outputTokens: 900, calls: 4 } };
+ }
+ patchIt(article, n, patch);
+ job.status = "done";
+ job.log.push(`refresh: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task: "refresh", status: "done", summary, refresh: patch.refresh })}`);
+}
+
function cancelDraft(id) {
const job = draftJobs.get(id);
if (!job || !["queued", "running"].includes(job.status)) return false;
@@ -715,6 +852,10 @@ function generationRoute(req, res, url, auth) {
if (!body || !body.task || !body.article) return json(res, 400, { ok: false, error: "task and article are required" });
if (body.feedback === "refuse") return json(res, 400, { ok: false, error: "the stub refuses this feedback" });
try {
+ if (body.task === "refresh") {
+ if (body.dryRun === true) return json(res, 200, { ok: true, plan: refreshPlan(body) });
+ return json(res, 202, { ok: true, ...startRefresh(body) });
+ }
return json(res, 202, { ok: true, ...startDraft(body) });
} catch (err) {
return json(res, 400, { ok: false, error: String(err.message) });
diff --git a/umtool/e2e/fixtures/refresh-fixture.mjs b/umtool/e2e/fixtures/refresh-fixture.mjs
@@ -0,0 +1,94 @@
+// The REFRESH fixture (plans/umtool-redesign.md, R4): an article whose current
+// report was made by a traced sweep over Research's local corpus, and which
+// one recording there now matches that the sweep did not see.
+//
+// refreshfix/report.json the article (a draft), i1's report
+// refreshfix/iterations/1 a done sweep over harbor-radio: its
+// trace's enumeration of the research
+// phrase matched four recordings —
+// hr-2021a ("storm season") is not
+// among them, so the daily check finds
+// it new
+// refreshfix/iterations/current.json report i1
+//
+// e2e/refresh.spec.ts plans and starts a Refresh against the editor stub
+// (which writes the refresh iteration and its refresh.json), and runs the
+// daily check through /api/articles/refresh/check. Synthetic, like every
+// fixture: the words are the research fixture's invented lines.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { RESEARCH_PHRASE } from "./research-fixture.mjs";
+
+export const REFRESH_ARTICLE = "refreshfix";
+export const REFRESH_QUESTION = "What did Harbor Radio say about the lighthouse budget?";
+/** The recording the check finds new (in the research fixture, not in i1's enumeration). */
+export const REFRESH_NEW = { id: "hr-2021a", title: "Harbor Radio 52: storm season" };
+const AT = "2026-10-14T09:00:00.000Z";
+
+const put = (file, value) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`);
+};
+
+const QUOTE = `the ${RESEARCH_PHRASE} was never approved`;
+
+export const REFRESH_REPORT = {
+ format: "archilyzer-report",
+ version: 1,
+ id: REFRESH_ARTICLE,
+ kind: "sweep",
+ title: "The lighthouse budget, on Harbor Radio",
+ summary: "What the station said about it.",
+ citations: {
+ c1: { kind: "video", channel: "harbor-radio", id: "hr-2019a", start: 600, end: 604, quote: QUOTE, label: "Harbor Radio 1: the old pier", date: "2019-03-14" },
+ },
+ sections: [{ id: "the-budget", title: "The budget", claims: [{ id: "k1", text: "The budget was never approved", citations: ["c1"] }] }],
+};
+
+// `article` and `channels`: another article like it (the unit tests' checks of
+// a build that is gone, or a scope the research corpus does not hold).
+export function makeRefreshFixture({ articles, source, article = REFRESH_ARTICLE, channels = ["harbor-radio"] }) {
+ const REFRESH_ARTICLE_ = article;
+ const it1 = path.join(articles, REFRESH_ARTICLE_, "iterations", "1");
+ put(path.join(it1, "iteration.json"), {
+ format: "archilyzer-iteration",
+ version: 1,
+ article: REFRESH_ARTICLE_,
+ n: 1,
+ kind: "sweep",
+ parent: null,
+ copyOf: null,
+ model: "claude-sonnet-5-5",
+ question: REFRESH_QUESTION,
+ scope: { channels },
+ status: "done",
+ usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 20000, outputTokens: 1000, calls: 3 } },
+ coverage: { matched: 4, read: 4, partial: false, unreached: [] },
+ steps: [],
+ createdAt: AT,
+ updatedAt: AT,
+ endedAt: AT,
+ });
+ const ev = (e) => JSON.stringify({ at: AT, run: 1, ...e });
+ put(
+ path.join(it1, "trace.jsonl"),
+ [
+ ev({ t: "run", phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }),
+ ev({ t: "scope", source, channels, question: REFRESH_QUESTION, model: "claude-sonnet-5-5" }),
+ ev({ t: "enumerate", query: RESEARCH_PHRASE, n: 4, ids: ["hr-2019a", "hr-2022a", "hr-2024a", "hr-2026a"], partial: false, unreached: [], counts: { "hr-2019a": 1, "hr-2022a": 1, "hr-2024a": 1, "hr-2026a": 1 } }),
+ ev({ t: "run", phase: "end", status: "done", summary: "ok", usd: 0.4, minutes: 1 }),
+ ].join("\n") + "\n",
+ );
+ const report = { ...REFRESH_REPORT, id: REFRESH_ARTICLE_ };
+ put(path.join(it1, "report.json"), report);
+ put(path.join(articles, REFRESH_ARTICLE_, "report.json"), report);
+ put(path.join(articles, REFRESH_ARTICLE_, "iterations", "current.json"), {
+ format: "archilyzer-iterations-current",
+ version: 1,
+ report: 1,
+ reportFrom: 1,
+ video: null,
+ reportAt: AT,
+ });
+ return { article: REFRESH_ARTICLE_ };
+}
diff --git a/umtool/e2e/refresh.spec.ts b/umtool/e2e/refresh.spec.ts
@@ -0,0 +1,137 @@
+import { test, expect, type Page } from "@playwright/test";
+import { existsSync, readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { REFRESH_ARTICLE, REFRESH_NEW, makeRefreshFixture } from "./fixtures/refresh-fixture.mjs";
+import * as urls from "./urls";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Refresh (plans/umtool-redesign.md, R4) on the refresh fixture
+// (e2e/fixtures/refresh-fixture.mjs, written here and removed after): the
+// plan from the article's ⋯ menu — the iteration refreshed and its queries,
+// each channel's fetches (a held platform skipped), the site built, the cap —
+// with nothing written until Refresh; the daily check finding the recording
+// the report's sweep never saw, the Inbox's suggestion card and the Next
+// card, whose action opens the plan; then the refresh run as one editor job
+// (the stub: running, then done with its refresh.json), and the Overview's
+// summary of what it found.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const ARTICLES = path.join(FIXTURE, "articles");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const CHECK_FILE = path.join(FIXTURE, ".umtool", "refresh-check.json");
+const PIECE = `a:articles/${REFRESH_ARTICLE}`;
+const page_ = () => urls.articleHref({ site: "articles", id: REFRESH_ARTICLE });
+
+const stubAsked = (): Record<string, unknown>[] => {
+ try {
+ return JSON.parse(readFileSync(STUB_LOG, "utf8")) as Record<string, unknown>[];
+ } catch {
+ return [];
+ }
+};
+const dialog = (page: Page) => page.locator(`dialog[data-refresh-dialog='${REFRESH_ARTICLE}']`);
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ makeRefreshFixture({ articles: ARTICLES, source: `local:${path.join(FIXTURE, "research-public")}` });
+ await warm(playwright, [page_(), "/", "/api/articles/refresh?article=refreshfix", "/api/articles/refresh/check"]);
+});
+
+test.afterAll(() => {
+ rmSync(path.join(ARTICLES, REFRESH_ARTICLE), { recursive: true, force: true });
+ rmSync(CHECK_FILE, { force: true });
+});
+
+test("the ⋯ menu's Refresh: the plan — the iteration, its queries, the fetches (a held platform skipped), the build, the cap — and nothing written until Refresh", async ({ page }) => {
+ await page.goto(page_());
+ await page.getByRole("button", { name: "More" }).click();
+ await page.getByRole("button", { name: "Refresh…" }).click();
+ const d = dialog(page);
+ await expect(d).toBeVisible();
+ const plan = d.locator(`[data-refresh-plan='${REFRESH_ARTICLE}']`);
+ await expect(plan).toContainText("i1");
+ await expect(plan.locator("[data-refresh-queries]")).toHaveText("“lighthouse budget”");
+ await expect(plan.locator("[data-refresh-channel='harbor-radio']")).toContainText("sync → refresh-report → transcribe-bucket (what lands)");
+ await expect(plan.locator("[data-refresh-channel='otherchan']")).toContainText("skipped — rumble is held");
+ await expect(plan.locator("[data-refresh-build='priv']")).toContainText("locally, if anything changed — never deployed");
+ await expect(plan.locator("[data-refresh-cap]")).toContainText("spends up to $5.00");
+ // The plan was the editor's dry run; no iteration was made.
+ expect(stubAsked().filter((r) => r.route === "report-draft" && r.task === "refresh").at(-1)).toMatchObject({ article: REFRESH_ARTICLE, dryRun: true });
+ expect(existsSync(path.join(ARTICLES, REFRESH_ARTICLE, "iterations", "2"))).toBe(false);
+ await d.getByRole("button", { name: "Cancel" }).click();
+ await expect(d).toBeHidden();
+});
+
+test("the daily check finds the recording the sweep never saw: the Inbox's suggestion card, and the Next card, open the plan", async ({ page, request }) => {
+ const r = await request.post("/api/articles/refresh/check", { data: { article: REFRESH_ARTICLE, force: true } });
+ expect(r.ok()).toBe(true);
+ const out = (await r.json()) as { checked: { article: string; newCount: number; newIds: string[]; titles: string[]; since: string }[] };
+ expect(out.checked).toHaveLength(1);
+ expect(out.checked[0]).toMatchObject({ article: REFRESH_ARTICLE, status: "checked", newCount: 1, newIds: [REFRESH_NEW.id], titles: [REFRESH_NEW.title] });
+
+ await page.goto(urls.homeHref());
+ const card = page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='refresh-available']`);
+ await expect(card).toBeVisible();
+ await expect(card).toContainText(`1 new recording mentions this since 2026-10-14: ${REFRESH_NEW.title}`);
+ await expect(page.locator(`[data-group=review] [data-piece='${PIECE}'][data-card='refresh-available']`)).toBeVisible();
+ const action = card.locator("[data-action-link]");
+ await expect(action).toHaveText("Refresh");
+ await expect(action).toHaveAttribute("href", `/articles/${REFRESH_ARTICLE}?refresh=1`);
+
+ // The piece's Next card is the same call, and its action opens the plan.
+ await page.goto(page_());
+ await expect(page.locator("[data-next-kind='refresh-available']")).toBeVisible();
+ await page.locator("[data-next-action] a").click();
+ await expect(page).toHaveURL(new RegExp(`/articles/${REFRESH_ARTICLE}\\?refresh=1$`));
+ await expect(dialog(page)).toBeVisible();
+ await expect(dialog(page).locator("[data-refresh-queries]")).toHaveText("“lighthouse budget”");
+ await dialog(page).getByRole("button", { name: "Cancel" }).click();
+ await expect(page).toHaveURL(new RegExp(`/articles/${REFRESH_ARTICLE}$`));
+});
+
+test("Refresh: one editor job, then the Overview says what it found — the new recording, the quote that changed; the Review card", async ({ page }) => {
+ test.setTimeout(60_000);
+ await page.goto(urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }, { refresh: true }));
+ await expect(dialog(page).locator("[data-refresh-plan]")).toBeVisible();
+ await dialog(page).getByRole("button", { name: "Refresh", exact: true }).click();
+ await expect(page.locator("[data-refresh-started]")).toContainText("Refresh i2 is running");
+ expect(stubAsked().filter((r) => r.route === "report-draft" && r.task === "refresh").at(-1)).toMatchObject({ article: REFRESH_ARTICLE, iteration: 1 });
+ // The Overview follows it (it reads again while the refresh runs).
+ const summary = page.locator("[data-refresh-summary='2']");
+ await expect(summary).toBeVisible();
+ await expect(summary).toHaveAttribute("data-refresh-state", "updated", { timeout: 20_000 });
+ await expect(summary.locator("[data-refresh-line]")).toHaveText("1 new recording matches · 1 quote changed");
+ await expect(summary.locator("[data-refresh-new]")).toContainText(REFRESH_NEW.title);
+ await expect(summary.locator("[data-refresh-drifted]")).toContainText("now: “the lighthouse budget was not approved that year”");
+ await expect(summary.locator("[data-refresh-steps]")).toContainText("build priv done");
+ await expect(summary.getByRole("link", { name: "Review in Iterations →" })).toHaveAttribute("href", `/articles/${REFRESH_ARTICLE}?tab=iterations`);
+ // A refresh with a report is a finished iteration to review; the suggestion is spent.
+ await page.goto(urls.homeHref());
+ await expect(page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='iteration-ready']`)).toBeVisible();
+ await expect(page.locator(`[data-lit-line][data-piece='${PIECE}'][data-card='refresh-available']`)).toHaveCount(0);
+});
+
+test("the Iterations tab: the refresh's outcome on its card, and Refresh… opens the plan", async ({ page }) => {
+ await page.goto(urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }, { tab: "iterations" }));
+ await expect(page.locator("[data-iteration='2'][data-kind='refresh'] [data-refresh-outcome='updated']")).toContainText("1 new recording matches · 1 quote changed");
+ await page.locator("[data-refresh-open='iterations']").click();
+ await expect(dialog(page).locator("[data-refresh-plan]")).toBeVisible();
+ await dialog(page).getByRole("button", { name: "Cancel" }).click();
+ await expect(dialog(page)).toBeHidden();
+});
+
+test("1366×768: the plan fits without scrolling the page", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(urls.articleHref({ site: "articles", id: REFRESH_ARTICLE }, { refresh: true }));
+ const d = dialog(page);
+ await expect(d.locator("[data-refresh-plan]")).toBeVisible();
+ const box = await d.boundingBox();
+ expect(box).not.toBeNull();
+ expect(box!.y).toBeGreaterThanOrEqual(0);
+ expect(box!.y + box!.height).toBeLessThanOrEqual(768);
+ await expect(d.getByRole("button", { name: "Refresh", exact: true })).toBeInViewport();
+});
diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -300,7 +300,8 @@ export async function cancelDraftJob(id: string): Promise<void> {
// (the editor refuses an unknown key; this refuses it first, by name). `source`
// and `seed` are a research board's hand-off (R2, lib/research/handoff.ts): the
// corpus the board was read through, and the board as the sweep's seed.md.
-const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed"];
+// `fetch` is a refresh's (R4: false skips its fetch and build).
+const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed", "fetch"];
export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> {
const out: Record<string, unknown> = {};
@@ -346,6 +347,8 @@ export type IterationRow = {
hasManifest: boolean;
currentReport: boolean;
currentVideo: boolean;
+ /** A refresh's outcome (R4: iteration.json's `refresh`), else null. */
+ refresh: { status: string; summary: string } | null;
};
/** A project directory's id: its path under REPORTS_ROOT, posix, or null outside it. */
@@ -384,6 +387,12 @@ const exists = (p: string) => {
}
};
+// A refresh iteration's outcome as iteration.json keeps it (common's RefreshOutcome), or null.
+function refreshOutcomeOf(it: Iteration): IterationRow["refresh"] {
+ const r = (it as { refresh?: { status?: unknown; summary?: unknown } }).refresh;
+ return r && typeof r.status === "string" ? { status: r.status, summary: typeof r.summary === "string" ? r.summary : "" } : null;
+}
+
function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number, Iteration>, current: IterationsCurrent): IterationRow {
let reportFrom: number | null = null;
for (let at: number | null = it.n; at !== null; at = byN.get(at)?.parent ?? null) {
@@ -430,6 +439,7 @@ function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number,
hasManifest: projectDir ? exists(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")) : false,
currentReport: current.report === it.n,
currentVideo: current.video === it.n,
+ refresh: refreshOutcomeOf(it),
};
}
diff --git a/umtool/lib/articles/refresh.ts b/umtool/lib/articles/refresh.ts
@@ -0,0 +1,107 @@
+import { readIterationFile, readIterations, type Iteration } from "yt-dlp-transcript-common/lib/report/iterations";
+import { REFRESH_FORMAT, deltaLine, goneParts, type RefreshFile, type RefreshPlan } from "yt-dlp-transcript-common/lib/report/draft/refresh/types";
+import { articleHref } from "@/lib/hrefs";
+import { ARTICLES_KEY } from "@/lib/articles/key.mjs";
+import { askEditor, enqueueDraft } from "./generation";
+import { sitesPaths } from "./sites";
+
+// ---------------------------------------------------------------------------
+// A REFRESH, AS UMTOOL SEES IT (plans/umtool-redesign.md, R4): re-fetch an
+// article's scope, see what changed, update. The editor plans it and runs it
+// (`report-draft {"task": "refresh"}`, common's controller/reportRefresh.ts);
+// umtool asks for the plan, confirms it, and reads what each refresh kept
+// (its iteration's refresh.json) -- it writes nothing of the article store.
+//
+// SERVER-ONLY.
+// ---------------------------------------------------------------------------
+
+export type { RefreshPlan };
+
+/** What a refresh of `article` would do (the editor's `dryRun`): nothing is written. */
+export async function planArticleRefresh(article: string, o: { iteration?: number; fetch?: boolean } = {}): Promise<RefreshPlan> {
+ const answer = await askEditor<{ plan: RefreshPlan }>("/api/ops/report-draft", {
+ method: "POST",
+ body: { task: "refresh", article, dryRun: true, ...(o.iteration ? { iteration: o.iteration } : {}), ...(o.fetch === false ? { fetch: false } : {}) },
+ });
+ return answer.plan;
+}
+
+/** Start it: one editor job. Answers its job, the new iteration, and where to watch it. */
+export async function startArticleRefresh(article: string, o: { iteration?: number; fetch?: boolean } = {}): Promise<{ jobId: string; iteration: number; href: string }> {
+ const out = await enqueueDraft({ task: "refresh", article, ...(o.iteration ? { iteration: o.iteration } : {}), ...(o.fetch === false ? { fetch: false } : {}) });
+ return { ...out, href: articleHref({ site: ARTICLES_KEY, id: article }) };
+}
+
+/** One refresh iteration, as a page shows it. */
+export type RefreshRow = {
+ n: number;
+ parent: number | null;
+ status: Iteration["status"];
+ // The refresh's own: running, no-change, updated, held-by-cap, failed, cancelled.
+ refresh: RefreshFile["status"] | null;
+ summary: string;
+ // changed: null when the refreshed iteration recorded no matching-line counts (not tracked).
+ counts: { newIds: number; changed: number | null; drifted: number; deleted: number };
+ // The new recordings' titles (up to 8), the quotes that changed.
+ news: { id: string; title: string | null; date: string | null }[];
+ drifted: { citation: string; quote: string; now: string | null }[];
+ deleted: string[];
+ // The sources gone, said by where ("1 source deleted on YouTube", "1 source gone from the archive").
+ gone: string[];
+ fetch: { channel: string; action: string; status: string; reason: string | null }[];
+ build: { site: string | null; status: string; reason: string | null } | null;
+ update: { estimateUsd: number; capUsd: number | null; refusal: string | null; usd: number | null; model: string } | null;
+ since: string | null;
+ at: string;
+ endedAt: string | null;
+ jobId: string | null;
+ hasReport: boolean;
+ warnings: string[];
+};
+
+function rowOf(it: Iteration, f: RefreshFile | null, hasReport: boolean): RefreshRow {
+ const d = f?.delta;
+ return {
+ n: it.n,
+ parent: it.parent,
+ status: it.status,
+ refresh: f?.status ?? null,
+ summary: f?.summary || (d ? deltaLine(d, f?.basis.at) : it.status === "queued" ? "Queued" : it.status === "running" ? "Fetching and searching again…" : (it.error ?? "")),
+ counts: { newIds: d?.newIds.length ?? 0, changed: d && d.changedTracked === false ? null : (d?.changed.length ?? 0), drifted: d?.drifted.length ?? 0, deleted: d?.deleted.length ?? 0 },
+ news: (d?.new ?? []).slice(0, 8).map((r) => ({ id: r.id, title: r.title, date: r.date })),
+ drifted: (d?.quotes ?? []).filter((q) => q.status === "drifted").slice(0, 8).map((q) => ({ citation: q.citation, quote: q.quote, now: q.now ?? null })),
+ deleted: d?.deleted ?? [],
+ gone: d ? goneParts(d) : [],
+ fetch: (f?.fetch ?? []).map((s) => ({ channel: s.channel, action: s.action, status: s.status, reason: s.reason ?? null })),
+ build: f?.build ? { site: f.build.site, status: f.build.status, reason: f.build.reason ?? null } : null,
+ update: f?.update ? { estimateUsd: f.update.estimateUsd, capUsd: f.update.capUsd, refusal: f.update.refusal ?? null, usd: f.update.usd ?? null, model: f.update.model } : null,
+ since: f?.basis.at ?? null,
+ at: it.createdAt,
+ endedAt: it.endedAt ?? null,
+ jobId: it.jobId ?? null,
+ hasReport,
+ warnings: f?.warnings ?? [],
+ };
+}
+
+/** A refresh iteration's refresh.json, or null. */
+export async function readRefreshFile(article: string, n: number): Promise<RefreshFile | null> {
+ const text = await readIterationFile(article, n, "refresh.json", sitesPaths()).catch(() => null);
+ if (!text) return null;
+ try {
+ const f = JSON.parse(text) as RefreshFile;
+ return f?.format === REFRESH_FORMAT ? f : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Every refresh of an article, newest first. */
+export async function readRefreshes(article: string): Promise<RefreshRow[]> {
+ const read = await readIterations(article, sitesPaths()).catch(() => null);
+ if (!read) return [];
+ const its = read.iterations.filter((it) => it.kind === "refresh").sort((a, b) => b.n - a.n);
+ return Promise.all(
+ its.map(async (it) => rowOf(it, await readRefreshFile(article, it.n), (await readIterationFile(article, it.n, "report.json", sitesPaths()).catch(() => null)) !== null)),
+ );
+}
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -212,7 +212,8 @@ export type ArticleRef = { site: string; id: string };
* `project` the video project the video tabs show when it is not the one the
* article's Cut opens (an article that claims two); `all` the cut's every quote.
*/
-export type ArticleQuery = { tab?: string; status?: string; ws?: string; rel?: string; project?: string; all?: boolean } & NoteOpt;
+// `refresh`: the Overview opens the Refresh plan (R4; the suggestion card's action).
+export type ArticleQuery = { tab?: string; status?: string; ws?: string; rel?: string; project?: string; all?: boolean; refresh?: boolean } & NoteOpt;
function articleBase(a: ArticleRef): string {
return a.site === ARTICLES_KEY
diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts
@@ -19,6 +19,7 @@ import { currentIteration } from "yt-dlp-transcript-common/lib/report/iterations
import { scheduleDecisions } from "./inbox/schedules.mjs";
import { readSchedules } from "./schedules";
import type { ScheduleView } from "./schedule-types";
+import { refreshDecisions } from "./inbox/refresh";
// ---------------------------------------------------------------------------
// THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the
@@ -40,6 +41,9 @@ import type { ScheduleView } from "./schedule-types";
// edition-ready nothing current yet (Review) -- lib/inbox/schedules.mjs;
// an edition's article raises no iteration cards of its
// own (they are its series')
+// refresh-available new recordings match an active article's current
+// refresh-held report since it was made (a cached daily check); a
+// refresh the cap held (lib/inbox/refresh.ts, R4)
// drafts-unreviewed a report cut's field a model drafted that nobody has
// reviewed (r28's draftsView; lib/inbox/drafts.mjs), one
// row per field, kept per project against
@@ -310,7 +314,10 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro
.map((p) => iterationDecisions(p, spend)),
);
const recurring = await recurringDecisions(schedules.schedules).catch(() => [] as Decision[]);
- return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...recurring];
+ const refresh = await readMutes()
+ .then((mutes) => refreshDecisions(graph, life, mutes))
+ .catch(() => [] as Decision[]);
+ return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...refresh, ...recurring];
}
/**
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -54,6 +54,10 @@ const KIND_CATEGORY = {
"tick-failed": "spend",
"tick-held": "spend",
"edition-ready": "review",
+ // R4: a refresh the cap held is money waiting on a yes or no; new
+ // recordings since the current report are something to review.
+ "refresh-held": "spend",
+ "refresh-available": "review",
};
const CATEGORY_GROUP = {
@@ -82,7 +86,7 @@ export function groupOf(d) {
// Within a group: the brief's order first (proposals before failed runs), then
// everything else as equals.
-const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0 };
+const KIND_RANK = { "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "unreadable-notes": 0, "refresh-held": 2, "refresh-available": 2 };
const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 };
// ONE primary action per decision, its button copy naming the result.
@@ -124,6 +128,8 @@ const ACTION_LABEL = {
"shadowed-name": "Rename the project",
"unroutable-name": "Rename the project",
"ambiguous-project": "Fix the project's files",
+ "refresh-held": "Refresh",
+ "refresh-available": "Refresh",
};
const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" };
diff --git a/umtool/lib/inbox/refresh.test.ts b/umtool/lib/inbox/refresh.test.ts
@@ -0,0 +1,159 @@
+// Refresh, as umtool sees it (R4): the daily check over the refresh fixture
+// (an article whose sweep never saw one recording of Research's local corpus),
+// the two Inbox kinds it adds (refresh-available, refresh-held) and when they
+// go, and the plan and start asked of a stand-in editor.
+//
+// Run with: pnpm --filter umtool exec tsx --test lib/inbox/refresh.test.ts
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+let tmp: string;
+let editor: Server;
+const asked: Record<string, unknown>[] = [];
+let mod: {
+ refresh: typeof import("./refresh");
+ articles: typeof import("../articles/refresh");
+ pieces: typeof import("../pieces");
+ lifecycle: typeof import("../lifecycle");
+ mutes: typeof import("../mutes");
+ groups: typeof import("./groups.mjs");
+};
+let fixture: typeof import("../../e2e/fixtures/refresh-fixture.mjs");
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-refresh-"));
+ const research = await import("../../e2e/fixtures/research-fixture.mjs");
+ const { pub } = research.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") });
+ fixture = await import("../../e2e/fixtures/refresh-fixture.mjs");
+ fixture.makeRefreshFixture({ articles: path.join(tmp, "articles"), source: `local:${pub}` });
+ // The stand-in editor: report-draft's dry run answers a plan; a start, a job.
+ editor = createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ const body = JSON.parse(raw || "{}") as Record<string, unknown>;
+ asked.push(body);
+ res.setHeader("content-type", "application/json");
+ if (body.dryRun) return res.end(JSON.stringify({ ok: true, plan: { article: body.article, parent: { n: 1 }, refusals: [], warnings: [] } }));
+ res.end(JSON.stringify({ ok: true, jobId: "job-1", iteration: 2 }));
+ });
+ });
+ await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r));
+ process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${(editor.address() as AddressInfo).port}`;
+ process.env.WORKER_TOKEN = "t";
+ process.env.TRANSCRIPT_LOCAL_DIR = pub;
+ process.env.CHANNELS_DIR = path.join(tmp, "channels");
+ process.env.SITES_DIR = path.join(tmp, "sites");
+ process.env.ARTICLES_DIR = path.join(tmp, "articles");
+ process.env.REPORTS_DIR = path.join(tmp, "reports");
+ process.env.SETTINGS_FILE = path.join(tmp, "settings.json");
+ delete process.env.TRANSCRIPT_HUB_URL;
+ await mkdir(process.env.REPORTS_DIR, { recursive: true });
+ mod = {
+ refresh: await import("./refresh"),
+ articles: await import("../articles/refresh"),
+ pieces: await import("../pieces"),
+ lifecycle: await import("../lifecycle"),
+ mutes: await import("../mutes"),
+ groups: await import("./groups.mjs"),
+ };
+});
+
+after(async () => {
+ editor?.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+const ctx = async () => {
+ mod.pieces.clearPiecesCache();
+ return Promise.all([mod.pieces.readPieceGraph(), mod.lifecycle.readLifecycle(), mod.mutes.readMutes()]);
+};
+
+test("the daily check: the current report's enumeration again over the corpus it read — the one recording it never saw, kept a day", async () => {
+ const [graph, life, mutes] = await ctx();
+ const pieces = mod.refresh.checkable(graph, life, mutes);
+ assert.ok(pieces.some((p) => p.report === fixture.REFRESH_ARTICLE));
+ const first = await mod.refresh.runRefreshChecks(pieces, { only: fixture.REFRESH_ARTICLE });
+ assert.equal(first.checked.length, 1);
+ const c = first.checked[0]!;
+ assert.equal(c.error, undefined, c.error);
+ assert.deepEqual({ newCount: c.newCount, newIds: c.newIds, titles: c.titles, iteration: c.iteration }, { newCount: 1, newIds: [fixture.REFRESH_NEW.id], titles: [fixture.REFRESH_NEW.title], iteration: 1 });
+ assert.match(c.source, /^local:.*research-public$/);
+ assert.equal(c.status, "checked");
+ assert.match(c.corpus ?? "", /^its own build \(local:.*research-public\)$/);
+ // Kept: today's is not checked again.
+ const again = await mod.refresh.runRefreshChecks(pieces, { only: fixture.REFRESH_ARTICLE });
+ assert.deepEqual(again, { checked: [], skipped: [{ article: fixture.REFRESH_ARTICLE, why: "checked today" }] });
+ assert.equal((await mod.refresh.readRefreshChecks()).articles[fixture.REFRESH_ARTICLE]?.newCount, 1);
+});
+
+test("the Inbox's cards: refresh-available in Review (action Refresh, the plan open); gone once a refresh looks; refresh-held is Your call", async () => {
+ let [graph, life, mutes] = await ctx();
+ let rows = await mod.refresh.refreshDecisions(graph, life, mutes, { background: false });
+ const avail = rows.find((r) => r.kind === "refresh-available")!;
+ assert.ok(avail, JSON.stringify(rows));
+ assert.equal(avail.why, `1 new recording mentions this since 2026-10-14: ${fixture.REFRESH_NEW.title}`);
+ assert.equal(avail.href, `/articles/${fixture.REFRESH_ARTICLE}?refresh=1`);
+ const [a] = mod.groups.annotate([avail], { pieceOf: () => `a:articles/${fixture.REFRESH_ARTICLE}`, lifecycleOf: () => "active" });
+ assert.deepEqual({ group: a.group, label: a.action.label }, { group: "review", label: "Refresh" });
+
+ // A refresh after the check, held by the cap: the suggestion is spent, the hold is the call.
+ const dir = path.join(process.env.ARTICLES_DIR!, fixture.REFRESH_ARTICLE, "iterations", "2");
+ await mkdir(dir, { recursive: true });
+ const at = new Date(Date.now() + 1000).toISOString();
+ await writeFile(
+ path.join(dir, "iteration.json"),
+ JSON.stringify({
+ format: "archilyzer-iteration", version: 1, article: fixture.REFRESH_ARTICLE, n: 2, kind: "refresh", parent: 1, copyOf: null, model: "claude-sonnet-5-5",
+ status: "done", usage: {}, steps: [], createdAt: at, updatedAt: at, endedAt: at,
+ refresh: { status: "held-by-cap", newIds: 1, changed: 0, drifted: 0, deleted: 0, summary: "1 new recording matches — held by the cap (about $0.40 to update): the daily cap" },
+ }),
+ );
+ [graph, life, mutes] = await ctx();
+ rows = await mod.refresh.refreshDecisions(graph, life, mutes, { background: false });
+ assert.deepEqual(rows.map((r) => r.kind), ["refresh-held"]);
+ assert.equal(rows[0]!.why, "i2 1 new recording matches — held by the cap (about $0.40 to update): the daily cap");
+ const [h] = mod.groups.annotate([rows[0]!], { pieceOf: () => `a:articles/${fixture.REFRESH_ARTICLE}`, lifecycleOf: () => "active" });
+ assert.deepEqual({ group: h.group, label: h.action.label }, { group: "your-call", label: "Refresh" });
+ // Parked: no check is for it.
+ await mod.lifecycle.setLifecycle(`a:articles/${fixture.REFRESH_ARTICLE}`, "parked");
+ [graph, life, mutes] = await ctx();
+ assert.equal(mod.refresh.checkable(graph, life, mutes).some((p) => p.report === fixture.REFRESH_ARTICLE), false);
+ await mod.lifecycle.setLifecycle(`a:articles/${fixture.REFRESH_ARTICLE}`, "active");
+});
+
+test("the coverage rule: its own build gone, the research corpus holding the scope is a real check (said); a scope no corpus here holds is UNCHECKED with why — never 0 new, never a card", async () => {
+ const articles = process.env.ARTICLES_DIR!;
+ fixture.makeRefreshFixture({ articles, source: `local:${path.join(tmp, "gone-build", "out")}`, article: "refresh-gone" });
+ fixture.makeRefreshFixture({ articles, source: `local:${path.join(tmp, "gone-build", "out")}`, article: "refresh-wide", channels: ["harbor-radio", "nowhere-chan"] });
+ const [graph, life, mutes] = await ctx();
+ const pieces = mod.refresh.checkable(graph, life, mutes);
+ const gone = (await mod.refresh.runRefreshChecks(pieces, { only: "refresh-gone" })).checked[0]!;
+ assert.equal(gone.status, "checked");
+ assert.match(gone.corpus ?? "", /^the research corpus \(local:.*research-public\)$/);
+ assert.equal(gone.newCount, 1, "the research corpus holds harbor-radio: a real answer");
+ const wide = (await mod.refresh.runRefreshChecks(pieces, { only: "refresh-wide" })).checked[0]!;
+ assert.equal(wide.status, "unchecked");
+ assert.equal(wide.reason, "the build holding harbor-radio, nowhere-chan is not on this machine; channels not in the research corpus: nowhere-chan");
+ assert.deepEqual({ newCount: wide.newCount, newIds: wide.newIds }, { newCount: 0, newIds: [] });
+ const rows = await mod.refresh.refreshDecisions(graph, life, mutes, { background: false });
+ assert.ok(rows.some((r) => r.kind === "refresh-available" && r.piece === "a:articles/refresh-gone"));
+ assert.ok(!rows.some((r) => r.piece === "a:articles/refresh-wide"), "an unchecked article gets no card");
+});
+
+test("the plan and the start are the editor's: a dry run, then report-draft refresh", async () => {
+ const plan = await mod.articles.planArticleRefresh(fixture.REFRESH_ARTICLE, { fetch: false });
+ assert.equal(plan.article, fixture.REFRESH_ARTICLE);
+ assert.deepEqual(asked.at(-1), { task: "refresh", article: fixture.REFRESH_ARTICLE, dryRun: true, fetch: false });
+ const started = await mod.articles.startArticleRefresh(fixture.REFRESH_ARTICLE, { iteration: 1 });
+ assert.deepEqual(started, { jobId: "job-1", iteration: 2, href: `/articles/${fixture.REFRESH_ARTICLE}` });
+ assert.deepEqual(asked.at(-1), { task: "refresh", article: fixture.REFRESH_ARTICLE, iteration: 1 });
+ // What the refreshes kept, newest first.
+ const rows = await mod.articles.readRefreshes(fixture.REFRESH_ARTICLE);
+ assert.deepEqual(rows.map((r) => [r.n, r.status, r.refresh]), [[2, "done", null]]);
+});
diff --git a/umtool/lib/inbox/refresh.ts b/umtool/lib/inbox/refresh.ts
@@ -0,0 +1,308 @@
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { currentIteration, readIterations } from "yt-dlp-transcript-common/lib/report/iterations";
+import { refreshBasis } from "yt-dlp-transcript-common/lib/report/draft/refresh/basis";
+import { deltaCandidates, type EnumerateFn } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta";
+import type { RefreshOutcome } from "yt-dlp-transcript-common/lib/report/draft/refresh/types";
+import { enumerate, SourceRegistry, type ShardSource } from "yt-dlp-transcript-mcp/research";
+import { ARTICLES_KEY } from "@/lib/articles/key.mjs";
+import { sitesPaths } from "@/lib/articles/sites";
+import { articleHref } from "@/lib/hrefs";
+import type { Decision } from "@/lib/decisions";
+import { lifecycleOf, type LifecycleRead } from "@/lib/lifecycle";
+import { isMuted, type MutesRead } from "@/lib/mutes";
+import { REPORTS_ROOT } from "@/lib/paths";
+import type { Piece, PieceGraph } from "@/lib/pieces";
+import { localDir, openSource } from "@/lib/research/sources";
+
+// ---------------------------------------------------------------------------
+// A REFRESH, SUGGESTED (plans/umtool-redesign.md, R4) -- two Inbox kinds:
+//
+// refresh-available a cheap daily check per active article with a current
+// report: its recorded enumerations run again over the
+// corpus it read (its build, else Research's local
+// corpus) -- stage 2's enumerate ONLY, common's
+// deltaCandidates: no fetch, no model -- and "3 new
+// recordings mention this since <date>". Its action is
+// Refresh (the article's Overview, the plan open).
+// refresh-held a refresh the cap held (refresh.json `held-by-cap`):
+// Your call, with the delta and the estimate, until a
+// later iteration supersedes it.
+//
+// The check is CACHED a day (UTC) per article and its current iteration, in
+// REPORTS_ROOT/.umtool/refresh-check.json (umtool's own state; one writer,
+// temp + rename). The Inbox only READS the cache; a stale one is checked in
+// the background, one article at a time, never twice at once
+// (`kickRefreshChecks`); `POST /api/articles/refresh/check` and
+// `umtool refresh --check` run it now. Muted, parked and done pieces are
+// skipped; so is an article a refresh newer than the check already covers.
+//
+// THE COVERAGE RULE — no silent zeros. A check reads the build the iteration
+// read when it is on this machine and holds every channel of its scope; else
+// Research's local corpus, when THAT holds every channel. When neither does,
+// the article is `unchecked`, with the reason ("the build holding harbor-radio
+// is not on this machine; channels not in the research corpus: x, y") — never
+// "0 new" — and it gets no card; `umtool refresh --check` prints it.
+//
+// SERVER-ONLY.
+// ---------------------------------------------------------------------------
+
+export const REFRESH_AVAILABLE = "refresh-available";
+export const REFRESH_HELD = "refresh-held";
+export const CHECK_FILE = () => path.join(/* turbopackIgnore: true */ REPORTS_ROOT, ".umtool", "refresh-check.json");
+const CHECK_FORMAT = "umtool-refresh-check";
+// A check runs the enumerations of an article, at most this many.
+export const MAX_CHECK_QUERIES = 12;
+
+export type CheckEntry = {
+ article: string;
+ // checked: a real answer (`corpus` says over which); unchecked: no corpus here
+ // holds the scope (`reason`), so nothing is claimed.
+ status: "checked" | "unchecked";
+ corpus?: string;
+ reason?: string;
+ // The iteration checked (the current report's) and when it was made.
+ iteration: number;
+ since: string;
+ day: string;
+ checkedAt: string;
+ newCount: number;
+ newIds: string[];
+ titles: string[];
+ source: string;
+ partial: boolean;
+ error?: string;
+};
+type CheckFile = { format: typeof CHECK_FORMAT; version: 1; articles: Record<string, CheckEntry> };
+
+const utcDay = (d = new Date()) => d.toISOString().slice(0, 10);
+
+export async function readRefreshChecks(): Promise<CheckFile> {
+ try {
+ const f = JSON.parse(await readFile(/* turbopackIgnore: true */ CHECK_FILE(), "utf8")) as CheckFile;
+ if (f?.format === CHECK_FORMAT && f.articles && typeof f.articles === "object") return f;
+ } catch {
+ // none yet, or torn: checked again
+ }
+ return { format: CHECK_FORMAT, version: 1, articles: {} };
+}
+
+// One writer at a time, in this process (temp + rename: a reader never sees half).
+let writing: Promise<unknown> = Promise.resolve();
+function saveCheck(entry: CheckEntry): Promise<void> {
+ const next = writing.then(async () => {
+ const f = await readRefreshChecks();
+ f.articles[entry.article] = entry;
+ const file = CHECK_FILE();
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(f, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ });
+ writing = next.catch(() => {});
+ return next;
+}
+
+// enumerate_matches over a live source, as data (the MCP's own scan).
+function enumerateOver(source: ShardSource): EnumerateFn {
+ return async (args) => {
+ const e = await enumerate(source, args);
+ if ("error" in e) throw new Error(e.error);
+ return {
+ rows: e.result.hits.map((h) => ({
+ id: h.videoId,
+ kind: h.contentType === "post" ? "post" : "video",
+ channel: h.channelName ?? null,
+ date: h.uploadDate ?? null,
+ matches: typeof h.matches === "number" ? h.matches : null,
+ title: h.title ?? null,
+ })),
+ partial: e.result.truncated,
+ unreached: e.result.coverage?.channelsNotReached ?? [],
+ };
+ };
+}
+
+// The channels a composed dir holds (its corpus.json), or null when it is not there.
+async function heldChannels(dir: string): Promise<string[] | null> {
+ try {
+ const c = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(dir, "corpus.json"), "utf8")) as { channels?: { slug?: unknown }[] };
+ return (c.channels ?? []).map((x) => x?.slug).filter((x): x is string => typeof x === "string");
+ } catch {
+ return null;
+ }
+}
+
+type Picked = { ok: true; handle: string; source: ShardSource; corpus: string } | { ok: false; reason: string };
+
+// The corpus an article's check reads (the coverage rule, above): the build its
+// iteration read when it is here and holds the scope, else Research's local
+// corpus when it holds the scope, else none — with why.
+export async function pickCheckCorpus(recorded: string | null, channels: readonly string[]): Promise<Picked> {
+ const lacking = (held: string[]) => channels.filter((c) => !held.includes(c));
+ let own: string;
+ if (recorded?.startsWith("local:")) {
+ const dir = recorded.slice("local:".length);
+ const held = await heldChannels(dir);
+ if (held && !lacking(held).length) {
+ const reg = new SourceRegistry({ kind: "local", dir });
+ return { ok: true, handle: recorded, source: (await reg.resolve(undefined)).source, corpus: `its own build (${recorded})` };
+ }
+ own = held ? `its build does not hold ${lacking(held).join(", ")}` : `the build holding ${channels.join(", ")} is not on this machine`;
+ } else {
+ own = recorded ? `it read ${recorded}, not a build on this machine` : "it recorded no corpus";
+ }
+ const dir = localDir();
+ const held = await heldChannels(dir);
+ if (!held) return { ok: false, reason: `${own}; the research corpus (${dir}) is not there` };
+ const missing = lacking(held);
+ if (missing.length) return { ok: false, reason: `${own}; channels not in the research corpus: ${missing.join(", ")}` };
+ const opened = await openSource(null);
+ return { ok: true, handle: opened.option.handle, source: opened.source, corpus: `the research corpus (${opened.option.handle})` };
+}
+
+/** The articles a check is for: the store's, active (not parked, done or muted). */
+export function checkable(graph: PieceGraph, life: LifecycleRead, mutes: MutesRead): Piece[] {
+ return graph.pieces.filter(
+ (p) => p.kind === "article" && p.site === ARTICLES_KEY && p.report && lifecycleOf(life, p.id) === "active" && !isMuted(mutes, p.id, REFRESH_AVAILABLE),
+ );
+}
+
+/** Check one article now: its current report's enumerations again (no fetch, no model). */
+export async function checkArticle(article: string, now = new Date()): Promise<CheckEntry | null> {
+ const cur = await currentIteration(article, sitesPaths()).catch(() => null);
+ if (cur?.report == null) return null;
+ const n = cur.report;
+ const base = { article, iteration: n, day: utcDay(now), checkedAt: now.toISOString() };
+ try {
+ // Since the newest refresh of the current report, when one has looked
+ // (its refresh.json holds what it saw), else since the report itself.
+ const its = (await readIterations(article, sitesPaths()).catch(() => null))?.iterations ?? [];
+ const looked = its.filter((it) => it.kind === "refresh" && it.parent === n && it.status === "done").sort((a, b) => b.n - a.n)[0];
+ const basis = await refreshBasis(article, looked?.n ?? n, sitesPaths());
+ const picked = await pickCheckCorpus(basis.source, basis.scope.channels);
+ if (!picked.ok) {
+ return { ...base, status: "unchecked", reason: picked.reason, since: basis.at, newCount: 0, newIds: [], titles: [], source: "", partial: false };
+ }
+ const { handle, source } = picked;
+ const c = await deltaCandidates({ queries: basis.queries.slice(0, MAX_CHECK_QUERIES), scope: basis.scope }, enumerateOver(source), {
+ ...(basis.knownComplete ? { known: basis.known } : { since: basis.at }),
+ });
+ const newIds = c.newIds.filter((id) => !(id in basis.known));
+ return {
+ ...base,
+ status: "checked",
+ corpus: picked.corpus,
+ since: basis.at,
+ newCount: newIds.length,
+ newIds: newIds.slice(0, 20),
+ titles: newIds.slice(0, 5).map((id) => c.rows.get(id)?.title ?? id),
+ source: handle,
+ partial: c.partial,
+ };
+ } catch (e) {
+ return { ...base, status: "unchecked", reason: (e as Error).message, since: "", newCount: 0, newIds: [], titles: [], source: "", partial: false, error: (e as Error).message };
+ }
+}
+
+/** Every checkable article whose check is not today's (or `force`): checked, one at a time, and kept. */
+export async function runRefreshChecks(
+ pieces: Piece[],
+ o: { force?: boolean; only?: string; now?: Date } = {},
+): Promise<{ checked: CheckEntry[]; skipped: { article: string; why: string }[] }> {
+ const kept = await readRefreshChecks();
+ const now = o.now ?? new Date();
+ const checked: CheckEntry[] = [];
+ const skipped: { article: string; why: string }[] = [];
+ for (const p of pieces) {
+ const article = p.report!;
+ if (o.only && article !== o.only) continue;
+ const cur = await currentIteration(article, sitesPaths()).catch(() => null);
+ if (cur?.report == null) {
+ skipped.push({ article, why: "no current report" });
+ continue;
+ }
+ const had = kept.articles[article];
+ if (!o.force && had && had.day === utcDay(now) && had.iteration === cur.report) {
+ skipped.push({ article, why: "checked today" });
+ continue;
+ }
+ const entry = await checkArticle(article, now);
+ if (!entry) continue;
+ await saveCheck(entry);
+ checked.push(entry);
+ }
+ return { checked, skipped };
+}
+
+// The background check: one at a time, never awaited by a page.
+const g = globalThis as typeof globalThis & { __umtoolRefreshCheck?: Promise<unknown> | null };
+
+/** Check the stale articles in the background (a page never waits on it). */
+export function kickRefreshChecks(pieces: Piece[], kept: CheckFile, now = new Date()): void {
+ if (g.__umtoolRefreshCheck) return;
+ const day = utcDay(now);
+ const stale = pieces.filter((p) => kept.articles[p.report!]?.day !== day);
+ if (!stale.length) return;
+ g.__umtoolRefreshCheck = runRefreshChecks(stale)
+ .catch(() => null)
+ .finally(() => {
+ g.__umtoolRefreshCheck = null;
+ });
+}
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+/**
+ * The two kinds' rows for the Inbox. `refresh-available` from the cache (and
+ * the stale ones checked in the background); `refresh-held` from each
+ * article's latest refresh iteration.
+ */
+export async function refreshDecisions(graph: PieceGraph, life: LifecycleRead, mutes: MutesRead, o: { background?: boolean } = {}): Promise<Decision[]> {
+ const pieces = checkable(graph, life, mutes);
+ const kept = await readRefreshChecks();
+ // In the app's server only (a CLI's read must not wait on a check), and not
+ // where it is switched off (UMTOOL_REFRESH_CHECK=0: the e2e server).
+ if (o.background !== false && process.env.NEXT_RUNTIME && process.env.UMTOOL_REFRESH_CHECK !== "0") kickRefreshChecks(pieces, kept);
+ const out: Decision[] = [];
+ for (const p of graph.pieces.filter((x) => x.kind === "article" && x.site === ARTICLES_KEY && x.report)) {
+ const article = p.report!;
+ const read = await readIterations(article, sitesPaths()).catch(() => null);
+ if (!read) continue;
+ const its = read.iterations;
+ const row = { project: `sites/${ARTICLES_KEY}/${article}`, projectKind: "article", projectTitle: p.title, piece: p.id };
+ const href = articleHref({ site: ARTICLES_KEY, id: article }, { refresh: true });
+ // A refresh the cap held, nothing after it.
+ const latest = [...its].filter((it) => it.kind === "refresh").sort((a, b) => b.n - a.n)[0];
+ const outcome = latest ? ((latest as { refresh?: RefreshOutcome }).refresh ?? null) : null;
+ if (latest && outcome?.status === "held-by-cap" && !its.some((x) => x.n > latest.n && x.status !== "failed" && x.status !== "cancelled")) {
+ out.push({
+ ...row,
+ kind: REFRESH_HELD,
+ target: `i${latest.n}`,
+ why: `i${latest.n} ${outcome.summary}`,
+ href,
+ severity: "open",
+ at: Date.parse(latest.endedAt ?? latest.updatedAt) || 0,
+ } as Decision);
+ }
+ // New recordings since the current report, by today's check.
+ if (!pieces.includes(p)) continue;
+ const c = kept.articles[article];
+ // An unchecked article (no corpus here holds its scope) claims nothing: no card.
+ if (!c || c.error || c.status === "unchecked" || c.newCount <= 0 || c.iteration !== read.current.report) continue;
+ // A refresh made after the check already looked (or is looking).
+ if (its.some((it) => it.kind === "refresh" && it.parent === c.iteration && Date.parse(it.createdAt) >= Date.parse(c.checkedAt))) continue;
+ if (its.some((it) => it.kind === "refresh" && (it.status === "queued" || it.status === "running"))) continue;
+ out.push({
+ ...row,
+ kind: REFRESH_AVAILABLE,
+ target: `i${c.iteration}`,
+ why: `${plural(c.newCount, "new recording")} mention${c.newCount === 1 ? "s" : ""} this since ${c.since.slice(0, 10)}${c.titles.length ? `: ${c.titles.slice(0, 3).join(", ")}${c.newCount > 3 ? ", …" : ""}` : ""}`,
+ href,
+ severity: "open",
+ at: Date.parse(c.checkedAt) || 0,
+ } as Decision);
+ }
+ return out;
+}
diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs
@@ -15,6 +15,8 @@ export const WHAT = {
"tick-failed": "tick failed",
"tick-held": "tick held by a cap",
"edition-ready": "edition ready",
+ "refresh-available": "new recordings match",
+ "refresh-held": "refresh held by the cap",
"claim-unadjudicated": "claims never ruled",
"claim-incoherent": "claims that don't hold together",
"clip-no-cues": "clips with no cues",
diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts
@@ -4,7 +4,8 @@ import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl
import { clock } from "yt-dlp-transcript-common/lib/search/window";
import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId";
import { REPORTS_ROOT } from "../paths.mjs";
-import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes, wordsOf } from "./board.mjs";
+import { checkWordsInWindow, enOrigDifference } from "yt-dlp-transcript-common/lib/report/quoteWords";
+import { exportMarkdown, groupsOf, holdsWords, localOnlyQuotes } from "./board.mjs";
import {
CaseError,
addQuote,
@@ -205,7 +206,6 @@ export async function pinQuote(id: string, body: PinBody): Promise<{ case: CaseD
export type VerifyResult = { id: string; verify: QuoteVerify };
-const joined = (cs: { text: string }[]) => cs.map((c) => c.text.replace(/\s+/g, " ").trim()).join(" ");
/**
* One quote against the CURRENT transcript at its cite: R1's window (±30 s)
@@ -232,29 +232,16 @@ export async function verifyQuote(q: Quote, now = new Date()): Promise<QuoteVeri
if (e instanceof SourceError && e.status === 404) return { status: "missing", at, message: e.message };
throw e;
}
- const cues = win.cues;
- let status: QuoteVerify = { status: "ok", at };
- if (!cues.length) {
+ // The words, against the window: common's check (lib/report/quoteWords.ts),
+ // shared with a refresh's re-verify (R4).
+ const v = checkWordsInWindow(q.text, { t: c.t, end: c.end }, win);
+ let status: QuoteVerify;
+ if (v.status === "ok") {
+ status = v.nowAt !== undefined ? { status: "ok", at, nowAt: v.nowAt, message: `the words now start at ${clock(v.nowAt)} (pinned at ${clock(c.t)})` } : { status: "ok", at };
+ } else if (v.empty) {
status = { status: "drifted", at, now: "", message: `no cues within 30 s of ${clock(c.t)}${c.trackId ? ` on the ${c.trackId} track` : ""} now` };
- } else if (holdsWords(joined(cues), q.text)) {
- // Where the words start now: the cue the shortest run holding them
- // starts with -- a run that still holds them without its first cue
- // started too early.
- let nowAt: number | null = null;
- for (let i = 0; i < cues.length && nowAt === null; i++) {
- for (let k = i; k < Math.min(cues.length, i + MAX_PIN_CUES); k++) {
- if (!holdsWords(joined(cues.slice(i, k + 1)), q.text)) continue;
- if (k === i || !holdsWords(joined(cues.slice(i + 1, k + 1)), q.text)) nowAt = cues[i].t;
- break;
- }
- }
- if (nowAt !== null && Math.abs(nowAt - c.t) >= 1) status = { status: "ok", at, nowAt, message: `the words now start at ${clock(nowAt)} (pinned at ${clock(c.t)})` };
} else {
- // What the transcript says over the quote's own seconds now.
- const lit = win.lit >= 0 ? win.lit : 0;
- const length = Math.max(0, c.end - c.t);
- const over = cues.slice(lit).filter((x, i) => i === 0 || x.t <= cues[lit].t + length - 0.25);
- status = { status: "drifted", at, now: joined(over).slice(0, 3000), nowAt: cues[lit].t };
+ status = { status: "drifted", at, now: v.now, ...(v.nowAt !== undefined ? { nowAt: v.nowAt } : {}) };
}
const enOrig = await enOrigCheck(opened.source, q);
return enOrig ? { ...status, enOrig } : status;
@@ -273,13 +260,11 @@ async function enOrigCheck(source: Awaited<ReturnType<typeof openSource>>["sourc
const enId = ids.find((t) => t === "en");
const origId = ids.find((t) => trackKind(t) === "original");
if (!enId || !origId) return undefined;
- const textOn = (track: string) => {
- const cues = (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[];
- return joined(cues.filter((x) => x.end > c.t + 0.25 && x.start < Math.max(c.end, c.t + 1) - 0.25));
- };
- const en = textOn(enId);
- const orig = textOn(origId);
- if (wordsOf(en) === wordsOf(orig)) return undefined;
+ const cuesOn = (track: string) => (cuesOfTrack(found.record, track) ?? []) as { start: number; end: number; text: string }[];
+ const diff = enOrigDifference(cuesOn(enId), cuesOn(origId), { t: c.t, end: c.end });
+ if (!diff) return undefined;
+ const orig = diff.orig;
+ const en = diff.en;
const quoted = c.trackId ?? rec.track;
return { text: orig, quoted, other: en };
}
diff --git a/umtool/package.json b/umtool/package.json
@@ -8,7 +8,7 @@
"build": "next build",
"start": "next start --port ${UMTOOL_PORT:-3050}",
"typecheck": "tsc --noEmit",
- "test": "tsx --test lib/research/*.test.ts",
+ "test": "tsx --test lib/research/*.test.ts lib/inbox/*.test.ts",
"e2e": "node ../scripts/worktree.mjs run -- node ../scripts/queue-lock.mjs --name e2e-umtool --estimate 1500 --prebuild umtool --ports UMTOOL_E2E_PORT:3051,EDITOR_STUB_PORT:3052 -- playwright test"
},
"dependencies": {
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -166,6 +166,10 @@ export default defineConfig({
// the middle of a job and prove that cancelling abandons the rest while
// the next run resumes. Read only by bin/cut-from-cache.mjs.
`E2E_UMTOOL_CUT_DELAY_MS=2000 ` +
+ // No background refresh check (R4, lib/inbox/refresh.ts): an Inbox read
+ // would otherwise enumerate every fixture article's corpus and add cards
+ // other specs count. refresh.spec runs the check itself, through its route.
+ `UMTOOL_REFRESH_CHECK=0 ` +
APP_SERVER,
port: PORT,
reuseExistingServer: false,