commit e25ed384e2bb1a52ea97a66227ac564fd49c9c3f
parent 1356cf8fb16e7ab72344b099c8ec5fa61a4722c4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 11:46:29 -0400
editor: report-draft refresh over ops (dryRun plan, the in-process refresh door), R5's fetchScope seam, COMMANDS.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 234 insertions(+), 5 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` |
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -35,6 +35,7 @@ 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 { readCitedRecord } from "../publish/composeReports";
import { diskPostChannelOf } from "../lib/report/convert-server";
import { readAllPosts } from "../lib/posts-server";
@@ -148,7 +149,7 @@ export async function planRefresh(body: ReportDraftBody, deps: ReportDraftDeps):
continue;
}
const kind = isPostsChannel(c) ? "posts" : "video";
- const platform = typeof c.platform === "string" ? c.platform : null;
+ const platform = platformOfConfig(c);
const skip = fetch && platform ? await platformRefusalOf(platform, paths) : null;
channels.push({
slug,
@@ -206,7 +207,11 @@ export async function planRefresh(body: ReportDraftBody, deps: ReportDraftDeps):
};
}
-const isPostsChannel = (c: Record<string, unknown>) => c.sourceKind === "posts" || (typeof c.postFetcher === "string" && !!c.postFetcher);
+// 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> {
@@ -279,7 +284,8 @@ export function fetchHooksOf(deps: ReportDraftDeps): FetchHooks {
channelOf: async (slug) => {
const c = (await configs()).get(slug);
if (!c) return null;
- return { kind: isPostsChannel(c) ? "posts" : "video", ...(typeof c.platform === "string" ? { platform: c.platform } : {}) };
+ const platform = platformOfConfig(c);
+ return { kind: isPostsChannel(c) ? "posts" : "video", ...(platform ? { platform } : {}) };
},
platformRefusal: (platform) => platformRefusalOf(platform, paths),
bucketOf: async (slug) => {
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/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
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
@@ -1247,7 +1249,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"?} ->',