commit 5b0f0002271ac853525234c393e6685c918d5dfe
parent cb1a1c5ceba2288fd4afe9d8ed245b9c8d2f3445
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 22:16:55 -0400
common: an `auto` research run continues into its sweep by itself (release 28 F1)
maybeAutoContinue(article, n) is the one function: a done `auto` run with
nothing waiting for approval and every acquisition job ended is continued as
"Continue into a sweep" does (report-draft sweep with iteration), on the run's
own model, under caps.sweep and the daily cap. The once-only mark is a claim
taken under the article store's lock; a daily-cap refusal is recorded and
tried again on a later UTC day; channels in no composed build are left out
with a warning (a failed `unbuilt channels` check on the sweep), and a run
with nothing left is held until a newer build. Outcomes are on the run:
research.autoContinue and an auto-continue line in turns.jsonl.
Two triggers: the registry's new job-end listener (onJobEnd), for the jobs
settle names an auto run waiting on and for any report-draft job's end, and
the scan of research runs, on the editor's heartbeat and once at boot. The
editor arms both below the idle gate (armResearchAutoContinue refuses an idle
boot); the heartbeat's call is a no-op unarmed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 812 insertions(+), 1 deletion(-)
diff --git a/common/controller/researchAutoContinue.test.ts b/common/controller/researchAutoContinue.test.ts
@@ -0,0 +1,313 @@
+// An `auto` research run continues into its sweep by itself (release 28 F1):
+// the job-end trigger and the scan, once only, the caps, the builds, the idle
+// boot. A temp store, temp builds, real registry jobs; the sweep it enqueues
+// fails at its corpus (a stub that throws) — what is asserted is that it was
+// asked for, once, as Continue asks it. No LLM is called.
+
+import { after, afterEach, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { sanitizeGeneration, type GenerationSettings } from "../lib/generationSettings";
+import { getRegistry } from "../jobs/registry";
+import { runManagedFunction } from "../jobs/streamCommand";
+import { createIteration, iterationFile, listIterations, readIteration, updateIteration, type Iteration } from "../lib/report/iterations";
+import { newResearchState, writeResearchState, type ResearchRecord } from "../lib/report/draft/research/state";
+import { DEFAULT_RESEARCH_LIMITS, type Autonomy, type Proposal } from "../lib/report/draft/research/decide";
+import { appendGenerationUsage, utcDay } from "./generationUsage";
+import type { ReportDraftDeps } from "./reportDraft";
+import {
+ armResearchAutoContinue,
+ disarmResearchAutoContinue,
+ isResearchAutoContinueArmed,
+ maybeAutoContinue,
+ researchAutoContinueTick,
+ UNBUILT_CHECK,
+} from "./researchAutoContinue";
+
+let tmp: string;
+let paths: Paths;
+let gen: GenerationSettings;
+const MODEL = "claude-sonnet-5-5";
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "research-auto-"));
+ 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;
+ await mkdir(paths.channelsDir, { recursive: true });
+ gen = sanitizeGeneration({ anthropicBaseUrl: "http://127.0.0.1:9", caps: { sweep: 2, daily: 20, max: 5 } });
+ await writeBuild("synth", ["synth-kitchen"]);
+});
+
+afterEach(() => disarmResearchAutoContinue());
+
+after(async () => {
+ // Every job this file started has ended (asserted per test).
+ await rm(tmp, { recursive: true, force: true });
+});
+
+async function writeBuild(build: string, channels: string[], mtime?: Date) {
+ const dir = path.join(paths.exportBuildsDir, build, "out");
+ await mkdir(dir, { recursive: true });
+ const file = path.join(dir, "corpus.json");
+ await writeFile(file, JSON.stringify({ channels: channels.map((slug) => ({ slug })) }));
+ if (mtime) await utimes(file, mtime, mtime);
+}
+
+const corpusAsked: string[] = [];
+const deps = (o: { now?: () => Date; jobOf?: ReportDraftDeps["jobOf"] } = {}): ReportDraftDeps => ({
+ paths,
+ corpusTools: async (source) => {
+ corpusAsked.push(source);
+ throw new Error("the test's corpus is a stub");
+ },
+ settings: () => ({ generation: gen }),
+ ...o,
+});
+
+const prop = (id: string, action: Proposal["action"], args: Record<string, unknown>, status: Proposal["status"], extra: Partial<Proposal> = {}): Proposal => ({
+ id,
+ action,
+ args,
+ reason: "r",
+ evidence: [],
+ status,
+ ...extra,
+});
+
+// A research run whose job has ended: its proposals and autonomy.
+async function makeRun(article: string, o: { autonomy?: Autonomy; channels?: string[]; proposals?: Proposal[] } = {}): Promise<number> {
+ const it = await createIteration(article, { kind: "research", model: MODEL, question: "Where did the second shop story start?", scope: o.channels ? { channels: o.channels } : {} }, paths);
+ const state = newResearchState(o.autonomy ?? "auto", DEFAULT_RESEARCH_LIMITS);
+ state.proposals = o.proposals ?? [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/1" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" })];
+ await writeResearchState(article, it.n, state, paths);
+ await updateIteration(article, it.n, { status: "done", research: { autonomy: o.autonomy ?? "auto", phase: "wait" } } as never, paths);
+ return it.n;
+}
+
+const recOf = async (article: string, n: number) => ((await readIteration(article, n, paths)) as Iteration & { research?: ResearchRecord }).research!;
+const sweepsOf = async (article: string, n: number) => (await listIterations(article, paths)).filter((x) => x.kind === "sweep" && x.parent === n);
+const turnsOf = async (article: string, n: number) =>
+ (await readFile(iterationFile(paths, article, n, "turns.jsonl"), "utf8").catch(() => ""))
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l) as { kind: string; outcome: string });
+
+// A job's end, waited for (the sweep the continuation enqueued fails at its stub corpus).
+async function ended(jobId: string) {
+ for (let i = 0; i < 200; i++) {
+ const s = getRegistry().get(jobId)?.status;
+ if (s && s !== "queued" && s !== "running") return s;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`job ${jobId} did not end`);
+}
+
+async function until<T>(fn: () => Promise<T | undefined | null | false>, what: string): Promise<T> {
+ for (let i = 0; i < 250; i++) {
+ const v = await fn();
+ if (v) return v;
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ throw new Error(`timed out waiting for ${what}`);
+}
+
+test("an auto run continues once, by itself, when its last acquisition's job ends", async () => {
+ // A real editor job stands for the acquisition: it runs until released.
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const acq = await runManagedFunction({ kind: "import-video", queueKey: "", paths, fn: async () => gate });
+ assert.ok(acq.ok);
+ void acq.stream.cancel();
+ const article = "synth-auto-end";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/2" }, "enqueued", { jobId: acq.jobId })],
+ });
+ assert.ok(armResearchAutoContinue(deps(), { bootScan: false, env: {} }));
+
+ // While the job runs: not now, and nothing written but the phase.
+ const early = await maybeAutoContinue(article, n, deps());
+ assert.deepEqual(early, { outcome: "not-now", why: `waits on job(s): ${acq.jobId}` });
+ assert.equal((await recOf(article, n)).autoContinue, undefined);
+
+ // The job ends: the listener continues the run, with nothing else asked.
+ release();
+ await acq.done;
+ const rec = await until(async () => {
+ const r = await recOf(article, n);
+ return r.autoContinue?.status === "continued" ? r : null;
+ }, "the continuation");
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ const sweep = sweeps[0]!;
+ assert.deepEqual(rec.continuedBy, [sweep.n]);
+ assert.equal(rec.phase, "continued");
+ assert.equal(rec.autoContinue!.by, sweep.n);
+ assert.equal(sweep.model, MODEL, "the run's own model");
+ assert.equal(sweep.question, "Where did the second shop story start?");
+ assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]);
+ assert.equal(getRegistry().get(sweep.jobId!)?.queueKey, "draft:api");
+ assert.equal(await ended(sweep.jobId!), "failed", "the stub corpus");
+ assert.deepEqual((await turnsOf(article, n)).map((t) => [t.kind, t.outcome]), [["auto-continue", "continued"]]);
+
+ // Again, by either trigger: nothing more.
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "continued already", final: true });
+ await researchAutoContinueTick();
+ assert.equal((await sweepsOf(article, n)).length, 1);
+});
+
+test("the heartbeat and job ends racing continue once; a claim held elsewhere is respected, a stale one looked into", async () => {
+ const article = "synth-auto-race";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ armResearchAutoContinue(deps(), { bootScan: false, env: {} });
+ const [tick, a, b] = await Promise.all([researchAutoContinueTick(), maybeAutoContinue(article, n, deps()), maybeAutoContinue(article, n, deps())]);
+ const outcomes = [...(tick?.continued.filter((c) => c.article === article).map(() => "continued") ?? []), a.outcome, b.outcome];
+ assert.equal(outcomes.filter((o) => o === "continued").length, 1, JSON.stringify({ tick, a, b }));
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ assert.deepEqual((await recOf(article, n)).continuedBy, [sweeps[0]!.n]);
+ await ended(sweeps[0]!.jobId!);
+ // The sweep's end starts a scan: let it finish, then stop listening.
+ await researchAutoContinueTick();
+ disarmResearchAutoContinue();
+
+ // Another process's fresh claim (the store's lock is what it took): not now.
+ const held = await makeRun("synth-auto-claimed", { channels: ["synth-kitchen"] });
+ await updateIteration("synth-auto-claimed", held, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: new Date().toISOString() } } }) as never, paths);
+ assert.deepEqual(await maybeAutoContinue("synth-auto-claimed", held, deps()), { outcome: "not-now", why: "being continued" });
+ assert.equal((await sweepsOf("synth-auto-claimed", held)).length, 0);
+
+ // A stale claim whose sweep was made (the editor died before marking it): recorded, not made again.
+ const stale = await makeRun("synth-auto-stale", { channels: ["synth-kitchen"] });
+ await updateIteration("synth-auto-stale", stale, (cur) => ({ research: { ...(cur as unknown as { research: ResearchRecord }).research, autoContinue: { status: "claimed", at: "2026-01-01T00:00:00.000Z" } } }) as never, paths);
+ const made = await createIteration("synth-auto-stale", { kind: "sweep", model: MODEL, parent: stale, question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const r = await maybeAutoContinue("synth-auto-stale", stale, deps());
+ assert.deepEqual(r, { outcome: "continued", by: made.n, warnings: [] });
+ assert.deepEqual((await recOf("synth-auto-stale", stale)).continuedBy, [made.n]);
+ assert.equal((await sweepsOf("synth-auto-stale", stale)).length, 1);
+});
+
+test("propose and limits never continue by themselves; a proposal waiting for approval holds an auto run", async () => {
+ for (const autonomy of ["propose", "limits"] as const) {
+ const article = `synth-auto-${autonomy}`;
+ const n = await makeRun(article, { autonomy, channels: ["synth-kitchen"] });
+ const r = await maybeAutoContinue(article, n, deps());
+ assert.deepEqual(r, { outcome: "not-now", why: `autonomy ${autonomy}: the operator continues it`, final: true });
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ }
+ const article = "synth-auto-pending";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [
+ prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/3" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" }),
+ prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/4" }, "proposed", { note: "a download of unknown size waits" }),
+ ],
+ });
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "waits for approval: p02" });
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ assert.equal((await recOf(article, n)).autoContinue, undefined, "nothing recorded");
+ // A run still running is not read further.
+ await updateIteration(article, n, { status: "running" }, paths);
+ assert.deepEqual(await maybeAutoContinue(article, n, deps()), { outcome: "not-now", why: "the run is running" });
+});
+
+test("the daily cap: refused and recorded, not tried again the same UTC day, continued the next", async () => {
+ const day1 = new Date("2031-03-04T12:00:00.000Z");
+ const day2 = new Date("2031-03-05T00:30:00.000Z");
+ await appendGenerationUsage(paths.generationUsageFile, [
+ { at: day1.toISOString(), day: utcDay(day1), jobId: "x", article: "other", iteration: 1, task: "sweep", model: MODEL, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 20 },
+ ]);
+ const article = "synth-auto-cap";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ const r = await maybeAutoContinue(article, n, deps({ now: () => day1 }));
+ assert.equal(r.outcome, "refused");
+ assert.match((r as { reason: string }).reason, /daily/i);
+ const rec = await recOf(article, n);
+ assert.equal(rec.autoContinue!.status, "refused");
+ assert.equal(rec.autoContinue!.day, "2031-03-04");
+ const updatedAt = (await readIteration(article, n, paths))!.updatedAt;
+
+ // The same day, later: not tried, nothing written.
+ const again = await maybeAutoContinue(article, n, deps({ now: () => new Date("2031-03-04T23:59:00.000Z") }));
+ assert.equal(again.outcome, "not-now");
+ assert.match((again as { why: string }).why, /^refused today .*tried again tomorrow \(UTC\)$/);
+ assert.equal((await readIteration(article, n, paths))!.updatedAt, updatedAt);
+ assert.equal((await sweepsOf(article, n)).length, 0);
+
+ // The next UTC day: the day's total is 0 again, and it continues.
+ const next = await maybeAutoContinue(article, n, deps({ now: () => day2 }));
+ assert.equal(next.outcome, "continued", JSON.stringify(next));
+ const sweeps = await sweepsOf(article, n);
+ assert.equal(sweeps.length, 1);
+ await ended(sweeps[0]!.jobId!);
+ assert.deepEqual((await turnsOf(article, n)).map((t) => t.outcome), ["refused", "continued"]);
+});
+
+test("channels in no build are left out with a warning; with nothing left the run is held until a newer build", async () => {
+ // Acquired into a new channel (in no build) beside the run's own.
+ const article = "synth-auto-unbuilt";
+ const n = await makeRun(article, {
+ channels: ["synth-kitchen"],
+ proposals: [
+ prop("p01", "create-channel", { fields: { name: "Synth Radio" } }, "done", { channel: "synth-radio", doneAt: "2026-10-13T10:00:00.000Z" }),
+ prop("p02", "import-video", { slug: "synth-radio", url: "https://video.example/v/5" }, "done", { doneAt: "2026-10-13T10:05:00.000Z" }),
+ ],
+ });
+ const r = await maybeAutoContinue(article, n, deps());
+ assert.equal(r.outcome, "continued", JSON.stringify(r));
+ const warning = "not in any build yet: synth-radio — rebuild the site and continue again";
+ assert.ok((r as { warnings: string[] }).warnings.includes(warning));
+ const sweep = (await sweepsOf(article, n))[0]!;
+ assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]);
+ assert.deepEqual(
+ (await readIteration(article, sweep.n, paths))!.checks?.find((c) => c.name === UNBUILT_CHECK),
+ { name: UNBUILT_CHECK, ok: false, detail: warning },
+ );
+ assert.ok((await recOf(article, n)).autoContinue!.warnings!.includes(warning));
+ await ended(sweep.jobId!);
+
+ // Nothing of its own, and its one acquisition in no build: held.
+ const only = "synth-auto-held";
+ const h = await makeRun(only, {
+ proposals: [prop("p01", "create-channel", { fields: { name: "Synth Late" } }, "done", { channel: "synth-late", doneAt: "2026-10-13T10:00:00.000Z" })],
+ });
+ const held = await maybeAutoContinue(only, h, deps());
+ assert.deepEqual(held, { outcome: "held", reason: "not in any build yet: synth-late — rebuild the site, and it continues by itself" });
+ assert.equal((await recOf(only, h)).autoContinue!.status, "held");
+ const before = (await readIteration(only, h, paths))!.updatedAt;
+ const quiet = await maybeAutoContinue(only, h, deps());
+ assert.equal(quiet.outcome, "not-now", "the same day and no newer build: not read further");
+ assert.equal((await readIteration(only, h, paths))!.updatedAt, before);
+ // A build that holds it, newer than the hold: it continues.
+ await writeBuild("synth-late", ["synth-late"], new Date(Date.now() + 60_000));
+ const now = await maybeAutoContinue(only, h, deps());
+ assert.equal(now.outcome, "continued", JSON.stringify(now));
+ const s = (await sweepsOf(only, h))[0]!;
+ assert.deepEqual(s.scope?.channels, ["synth-late"]);
+ await ended(s.jobId!);
+});
+
+test("an idle boot arms nothing: no listener, and the heartbeat's call is a no-op", async () => {
+ const article = "synth-auto-idle";
+ const n = await makeRun(article, { channels: ["synth-kitchen"] });
+ assert.equal(armResearchAutoContinue(deps(), { env: { ARCHILYZER_IDLE_BOOT: "1" } }), false);
+ assert.equal(isResearchAutoContinueArmed(), false);
+ assert.equal(await researchAutoContinueTick(), null);
+ assert.equal((await sweepsOf(article, n)).length, 0);
+ // Armed, the boot scan finds it.
+ assert.equal(armResearchAutoContinue(deps(), { env: {}, bootScan: false }), true);
+ const tick = await researchAutoContinueTick();
+ assert.ok(tick?.continued.some((c) => c.article === article && c.n === n), JSON.stringify(tick));
+ await ended((await sweepsOf(article, n))[0]!.jobId!);
+});
diff --git a/common/controller/researchAutoContinue.ts b/common/controller/researchAutoContinue.ts
@@ -0,0 +1,351 @@
+// AN `auto` RESEARCH RUN CONTINUES INTO ITS SWEEP BY ITSELF (release 28 F1).
+//
+// What the operator's "Continue into a sweep" does — `report-draft {task:
+// "sweep", iteration: n}` (controller/reportDraft.ts, through continuationOf)
+// — done by the editor once the run's acquisitions settle, for a run whose
+// autonomy is `auto` (`propose` and `limits` are always continued by the
+// operator). maybeAutoContinue(article, n) is the one function; it is
+// idempotent, and two triggers call it:
+// - the end of a job the run waits on: settle (researchRuns.ts) names an
+// `auto` run's pending editor jobs, and the registry's job-end listener
+// takes the run of one that ended; a `report-draft` job's end (the
+// research job itself, among others) runs the scan below;
+// - the scan, on the editor's heartbeat and once at boot: the research
+// iterations (a proposals.json) of every article, a run already finished
+// with (continued, or not `auto`) remembered and not read again.
+// Both are armed by the editor's instrumentation BELOW the idle gate
+// (armResearchAutoContinue refuses an idle boot too): ARCHILYZER_IDLE_BOOT
+// arms nothing, and the heartbeat's call is a no-op unarmed.
+//
+// A run continues when:
+// - it is a done research run, `auto`, not continued (no `continuedBy`, no
+// fresh claim), with nothing waiting for the operator's yes or no and
+// every acquisition job ended (done, failed or cancelled);
+// - something it would sweep is in a composed build: a channel in none
+// (a created channel is on no site until the operator puts it on one and
+// builds it) is left out, and the sweep carries the warning "not in any
+// build yet: <slug> — rebuild the site and continue again". With nothing
+// left the run is `held`, and tried again once a newer build exists (or
+// on a later day);
+// - the caps hold: the sweep is the run's own model, its per-job cap the
+// sweep's (caps.sweep), and an API model is refused past the daily cap —
+// `refused`, tried again on a later UTC day, never in a loop. Any other
+// refusal of the ask is recorded and retried the same way.
+// The once-only mark is a claim taken under the article store's lock
+// (updateIteration's read-patch-write): a heartbeat and a job end racing, in
+// this process or another, continue once. A claim older than CLAIM_STALE_MS
+// (the editor died between the claim and the enqueue) is looked into: a
+// sweep it made is recorded, else it is claimed again.
+//
+// Every outcome is on the run: `research.autoContinue` in its iteration.json
+// (the umtool queue shows it), a `{kind: "auto-continue"}` line in its
+// turns.jsonl, and — for channels left out — a failed `unbuilt channels`
+// check on the sweep it made.
+
+import { readdir, stat } from "node:fs/promises";
+import { isIdleBoot } from "../lib/idleBoot";
+import { getSettings } from "../lib/settings";
+import { providerOf } from "../lib/llm";
+import { onJobEnd } from "../jobs/registry";
+import { REPORT_ID_RE } from "../lib/report/schema";
+import {
+ appendIterationTurns,
+ iterationDirNumbers,
+ iterationFile,
+ listIterations,
+ readIteration,
+ updateIteration,
+ type Iteration,
+} from "../lib/report/iterations";
+import { listCorpusBuilds } from "../lib/report/draft/tasks/corpusSource";
+import { readResearchState, widenedChannels, type AutoContinueRecord, type ResearchRecord } from "../lib/report/draft/research/state";
+import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage";
+import { enqueueReportDraft, REPORT_DRAFT_JOB_KIND, type ReportDraftDeps } from "./reportDraft";
+import { markContinued, researchState, takeWatchedRun } from "./researchRuns";
+
+export const CLAIM_STALE_MS = 10 * 60_000;
+export const UNBUILT_CHECK = "unbuilt channels";
+
+export type AutoContinueResult =
+ | { outcome: "continued"; by: number; jobId?: string; warnings: string[] }
+ | { outcome: "held" | "refused"; reason: string }
+ // Not now (nothing written). `final`: never — the scan stops reading it.
+ | { outcome: "not-now"; why: string; final?: boolean };
+
+const recordOf = (it: Iteration): ResearchRecord | undefined => (it as { research?: ResearchRecord }).research;
+
+// One attempt per run at a time, in this process (the claim below is the
+// guard across processes).
+const chains = new Map<string, Promise<unknown>>();
+function serial<T>(key: string, fn: () => Promise<T>): Promise<T> {
+ const prev = chains.get(key) ?? Promise.resolve();
+ const next = prev.then(fn, fn);
+ const tail = next.catch(() => {});
+ chains.set(key, tail);
+ void tail.then(() => {
+ if (chains.get(key) === tail) chains.delete(key);
+ });
+ return next;
+}
+
+class NotNow extends Error {}
+
+async function record(article: string, n: number, ac: AutoContinueRecord, deps: ReportDraftDeps, now: Date): Promise<void> {
+ await updateIteration(
+ article,
+ n,
+ (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: "auto" as const, phase: "ready" as const }), autoContinue: ac } }),
+ deps.paths,
+ now,
+ );
+ const { status, ...rest } = ac;
+ await appendIterationTurns(article, n, [{ kind: "auto-continue", outcome: status, ...rest }], deps.paths).catch(() => {});
+}
+
+// Why run `it` is not continued now, from its iteration.json alone (null:
+// read on). `final` when it never will be.
+function notYet(it: Iteration | null, now: Date): { why: string; final?: boolean } | null {
+ if (!it) return { why: "no such iteration", final: true };
+ if (it.kind !== "research") return { why: `a ${it.kind} iteration, not a research run`, final: true };
+ const rec = recordOf(it);
+ if (rec && rec.autonomy !== "auto") return { why: `autonomy ${rec.autonomy}: the operator continues it`, final: true };
+ if ((rec?.continuedBy?.length ?? 0) > 0 || rec?.autoContinue?.status === "continued") return { why: "continued already", final: true };
+ if (it.status === "failed" || it.status === "cancelled") return { why: `the run ${it.status}`, final: true };
+ if (it.status !== "done") return { why: `the run is ${it.status}` };
+ const ac = rec?.autoContinue;
+ if (ac?.status === "claimed" && now.getTime() - Date.parse(ac.at) < CLAIM_STALE_MS) return { why: "being continued" };
+ if (ac?.status === "refused" && ac.day === utcDay(now)) return { why: `refused today (${ac.reason}); tried again tomorrow (UTC)` };
+ return null;
+}
+
+// Continue research run `n` of `article` into its sweep if it is ready to be
+// (see the head of this file). Idempotent.
+export function maybeAutoContinue(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> {
+ return serial(`${article}/${n}`, () => attempt(article, n, deps));
+}
+
+async function attempt(article: string, n: number, deps: ReportDraftDeps): Promise<AutoContinueResult> {
+ const paths = deps.paths;
+ const now = deps.now?.() ?? new Date();
+ const today = utcDay(now);
+ const it = await readIteration(article, n, paths).catch(() => null);
+ const no = notYet(it, now);
+ if (no) return { outcome: "not-now", ...no };
+ const run = it!;
+ const rec = recordOf(run);
+ if (!rec) {
+ // A record is written with the run's first proposals; without one, its
+ // autonomy is proposals.json's.
+ const state = await readResearchState(article, n, paths);
+ if (!state) return { outcome: "not-now", why: "no proposals yet" };
+ if (state.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${state.autonomy}: the operator continues it`, final: true };
+ }
+ const builds = await listCorpusBuilds(paths.exportBuildsDir);
+ const newest = Math.max(0, ...builds.map((b) => b.mtimeMs));
+ const ac = rec?.autoContinue;
+ if (ac?.status === "held" && ac.day === today && newest <= (ac.buildsAt ?? 0)) {
+ return { outcome: "not-now", why: `held (${ac.reason}) until a newer build` };
+ }
+
+ // The run now: its acquisitions refreshed from their jobs (and its phase
+ // written, and its pending jobs watched).
+ const view = await researchState(article, n, { paths, ...(deps.jobOf ? { jobOf: deps.jobOf } : {}) });
+ if (view.autonomy !== "auto") return { outcome: "not-now", why: `autonomy ${view.autonomy}: the operator continues it`, final: true };
+ if (view.waitingOn.approval.length) return { outcome: "not-now", why: `waits for approval: ${view.waitingOn.approval.join(", ")}` };
+ if (view.waitingOn.jobs.length) return { outcome: "not-now", why: `waits on job(s): ${view.waitingOn.jobs.join(", ")}` };
+ if (view.phase !== "ready") return { outcome: "not-now", why: `its phase is ${view.phase}`, ...(view.phase === "continued" ? { final: true } : {}) };
+
+ // The scope: the run's channels and what it acquired into, less any in no build.
+ const channels = widenedChannels(run.scope?.channels ?? [], view);
+ const built = new Set(builds.flatMap((b) => b.channels));
+ const unbuilt = channels.filter((c) => !built.has(c));
+ const kept = channels.filter((c) => built.has(c));
+ const warnings = unbuilt.length ? [`not in any build yet: ${unbuilt.join(", ")} — rebuild the site and continue again`] : [];
+ if (!kept.length) {
+ const reason = channels.length ? `not in any build yet: ${unbuilt.join(", ")} — rebuild the site, and it continues by itself` : "it names no channel and acquired into none";
+ await record(article, n, { status: "held", at: now.toISOString(), reason, day: today, buildsAt: newest }, deps, now);
+ return { outcome: "held", reason };
+ }
+
+ // The caps: an API model is refused past the day's total (and the ask
+ // refuses again; the job, at its turn).
+ const gen = (deps.settings ?? getSettings)().generation;
+ const model = run.model;
+ if (providerOf(model) === "api") {
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, today), gen.caps.daily);
+ if (refusal) {
+ await record(article, n, { status: "refused", at: now.toISOString(), reason: refusal, day: today }, deps, now);
+ return { outcome: "refused", reason: refusal };
+ }
+ }
+
+ // A stale claim: the sweep it made, if any, is the continuation.
+ if (ac?.status === "claimed") {
+ const made = (await listIterations(article, paths)).find((x) => x.kind === "sweep" && x.parent === n && Date.parse(x.createdAt) >= Date.parse(ac.at));
+ if (made) {
+ await markContinued(article, n, made.n, paths);
+ await record(article, n, { status: "continued", at: now.toISOString(), by: made.n, ...(ac.warnings?.length ? { warnings: ac.warnings } : {}) }, deps, now);
+ return { outcome: "continued", by: made.n, warnings: ac.warnings ?? [] };
+ }
+ }
+
+ // THE CLAIM: checked and marked in one write under the store's lock.
+ try {
+ await updateIteration(
+ article,
+ n,
+ (cur) => {
+ const r = recordOf(cur);
+ if ((r?.continuedBy?.length ?? 0) > 0 || r?.autoContinue?.status === "continued") throw new NotNow("continued already");
+ const c = r?.autoContinue;
+ if (c?.status === "claimed" && now.getTime() - Date.parse(c.at) < CLAIM_STALE_MS) throw new NotNow("being continued");
+ return {
+ research: {
+ ...(r ?? { autonomy: "auto" as const, phase: "ready" as const }),
+ autoContinue: { status: "claimed" as const, at: now.toISOString(), ...(warnings.length ? { warnings } : {}) },
+ },
+ };
+ },
+ paths,
+ now,
+ );
+ } catch (e) {
+ if (e instanceof NotNow) return { outcome: "not-now", why: e.message };
+ throw e;
+ }
+
+ // The continuation, as the operator's Continue asks it.
+ const out = await enqueueReportDraft({ task: "sweep", article, iteration: n, model, channels: kept }, deps);
+ if (!out.result.ok || !("iteration" in out)) {
+ const reason = (out.result as { error: string }).error;
+ await record(article, n, { status: "refused", at: now.toISOString(), reason, day: today }, deps, now);
+ return { outcome: "refused", reason };
+ }
+ // Nobody reads the job's stream (the ops routes release it the same way).
+ void out.result.stream.cancel();
+ const all = [...warnings, ...(out.warnings ?? [])];
+ await record(article, n, { status: "continued", at: now.toISOString(), by: out.iteration, ...(all.length ? { warnings: all } : {}) }, deps, now);
+ if (unbuilt.length) {
+ await updateIteration(
+ article,
+ out.iteration,
+ (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => c.name !== UNBUILT_CHECK), { name: UNBUILT_CHECK, ok: false, detail: warnings[0] }] }),
+ paths,
+ now,
+ ).catch(() => {});
+ }
+ return { outcome: "continued", by: out.iteration, jobId: out.result.jobId, warnings: all };
+}
+
+// ─── the scan ───
+
+// Runs the scan has finished with (continued, or never `auto`): not read again.
+const finished = new Set<string>();
+let scanning: Promise<ScanResult> | null = null;
+
+export type ScanResult = { runs: number; continued: { article: string; n: number; by: number }[]; held: string[]; refused: string[] };
+
+// Every research run that might continue, tried once. One scan at a time (a
+// second caller shares the one going).
+export function scanAutoContinue(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> {
+ if (!scanning) {
+ scanning = scan(deps, log).finally(() => {
+ scanning = null;
+ });
+ }
+ return scanning;
+}
+
+async function scan(deps: ReportDraftDeps, log?: (line: string) => void): Promise<ScanResult> {
+ const out: ScanResult = { runs: 0, continued: [], held: [], refused: [] };
+ let articles: string[];
+ try {
+ articles = (await readdir(deps.paths.articlesDir, { withFileTypes: true })).filter((e) => e.isDirectory() && REPORT_ID_RE.test(e.name)).map((e) => e.name);
+ } catch {
+ return out;
+ }
+ for (const article of articles) {
+ let ns: number[];
+ try {
+ ns = await iterationDirNumbers(article, deps.paths);
+ } catch {
+ continue;
+ }
+ for (const n of ns) {
+ const key = `${article}/${n}`;
+ if (finished.has(key)) continue;
+ // Only a research run has a proposals.json.
+ if (!(await stat(iterationFile(deps.paths, article, n, "proposals.json")).then(() => true, () => false))) continue;
+ out.runs++;
+ const r: AutoContinueResult = await maybeAutoContinue(article, n, deps).catch((e): AutoContinueResult => ({ outcome: "not-now", why: (e as Error).message }));
+ report(article, n, r, out, log);
+ if (r.outcome === "continued" || (r.outcome === "not-now" && r.final)) finished.add(key);
+ }
+ }
+ return out;
+}
+
+function report(article: string, n: number, r: AutoContinueResult, out: ScanResult | null, log?: (line: string) => void) {
+ if (r.outcome === "continued") {
+ out?.continued.push({ article, n, by: r.by });
+ log?.(`research auto-continue: ${article} i${n} continued by i${r.by}${r.warnings.length ? ` (${r.warnings.join("; ")})` : ""}`);
+ } else if (r.outcome === "held" || r.outcome === "refused") {
+ out?.[r.outcome].push(`${article}/${n}`);
+ log?.(`research auto-continue: ${article} i${n} ${r.outcome}: ${r.reason}`);
+ }
+}
+
+// ─── arming (the editor's instrumentation, below the idle gate) ───
+
+type Armed = { deps: ReportDraftDeps; log?: (line: string) => void; off: () => void };
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttResearchAutoContinue__: Armed | undefined;
+}
+
+// Arm both triggers: the job-end listener now, the boot scan now, and the
+// heartbeat's tick from here on. Refused (false) on an idle boot. Idempotent:
+// a second call only replaces the deps.
+export function armResearchAutoContinue(deps: ReportDraftDeps, o: { log?: (line: string) => void; env?: Record<string, string | undefined>; bootScan?: boolean } = {}): boolean {
+ if (isIdleBoot(o.env)) return false;
+ const armed = globalThis.__yttResearchAutoContinue__;
+ if (armed) {
+ armed.deps = deps;
+ armed.log = o.log;
+ return true;
+ }
+ const state: Armed = { deps, ...(o.log ? { log: o.log } : {}), off: () => {} };
+ state.off = onJobEnd((job) => {
+ const run = takeWatchedRun(job.id);
+ if (run) {
+ void maybeAutoContinue(run.article, run.n, state.deps).then(
+ (r) => report(run.article, run.n, r, null, state.log),
+ (e) => state.log?.(`research auto-continue: ${run.article} i${run.n}: ${(e as Error).message}`),
+ );
+ } else if (job.kind === REPORT_DRAFT_JOB_KIND) {
+ // A research job's end (or any generation's): the scan finds its run.
+ void scanAutoContinue(state.deps, state.log).catch(() => {});
+ }
+ });
+ globalThis.__yttResearchAutoContinue__ = state;
+ if (o.bootScan !== false) void scanAutoContinue(deps, o.log).catch(() => {});
+ return true;
+}
+
+export function disarmResearchAutoContinue(): void {
+ globalThis.__yttResearchAutoContinue__?.off();
+ globalThis.__yttResearchAutoContinue__ = undefined;
+ finished.clear();
+}
+
+export function isResearchAutoContinueArmed(): boolean {
+ return globalThis.__yttResearchAutoContinue__ !== undefined;
+}
+
+// The heartbeat's call: a scan when armed, else nothing (null).
+export async function researchAutoContinueTick(): Promise<ScanResult | null> {
+ const armed = globalThis.__yttResearchAutoContinue__;
+ if (!armed) return null;
+ return scanAutoContinue(armed.deps, armed.log);
+}
diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts
@@ -18,7 +18,9 @@
// THE CONTINUATION is `report-draft {task: "sweep", iteration: <research n>}`
// (controller/reportDraft.ts, through continuationOf here): a sweep iteration
// whose parent is the research run, over the run's channels and every channel
-// a done acquisition wrote into.
+// a done acquisition wrote into. An `auto` run asks it by itself once its
+// acquisitions settle (release 28 F1, controller/researchAutoContinue.ts):
+// settle below names the jobs such a run still waits on (watchResearchJobs).
import type { Paths } from "../lib/paths";
import { getJobEntry } from "../jobs/listJobs";
@@ -35,6 +37,7 @@ import {
waitingOn,
widenedChannels,
writeResearchState,
+ type AutoContinueRecord,
type JobOf,
type ResearchPhase,
type ResearchRecord,
@@ -95,9 +98,48 @@ async function settle(article: string, it: Iteration, state: ResearchState, chan
if (it.status !== "queued" && it.status !== "running" && rec?.phase !== phase) {
await updateIteration(article, it.n, (cur) => ({ research: { ...(recordOf(cur) ?? { autonomy: state.autonomy }), phase } }), paths);
}
+ // An `auto` run hears its acquisitions end (release 28 F1).
+ if (state.autonomy === "auto" && phase !== "continued") watchResearchJobs(article, it.n, waitingOn(state).jobs);
return phase;
}
+// ─── the jobs an `auto` run waits on (release 28 F1) ───
+//
+// Job id → the run, in this process: whoever refreshes an `auto` run (settle,
+// above) names the editor jobs it still waits on, and the job-end listener
+// (controller/researchAutoContinue.ts) takes the run of a job that ended. A
+// restart forgets them; the boot pass and the heartbeat find the runs again.
+
+const WATCH_MAX = 2000;
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttResearchJobWatch__: Map<string, { article: string; n: number }> | undefined;
+}
+
+const watch = () => (globalThis.__yttResearchJobWatch__ ??= new Map());
+
+export function watchResearchJobs(article: string, n: number, jobIds: readonly string[]): void {
+ const m = watch();
+ for (const id of jobIds) {
+ m.delete(id);
+ m.set(id, { article, n });
+ }
+ // Oldest first out: a map past its bound forgets the longest-watched.
+ for (const id of m.keys()) {
+ if (m.size <= WATCH_MAX) break;
+ m.delete(id);
+ }
+}
+
+// The run waiting on job `id`, once (the watch is taken).
+export function takeWatchedRun(id: string): { article: string; n: number } | undefined {
+ const m = watch();
+ const run = m.get(id);
+ if (run) m.delete(id);
+ return run;
+}
+
export type ResearchView = {
article: string;
iteration: number;
@@ -111,6 +153,9 @@ export type ResearchView = {
continuedBy: number[];
// The agent's closing words: what the archive holds, what it asked for.
notes?: string;
+ // An `auto` run's own continuation: continued (by), refused or held, and
+ // why (release 28 F1).
+ autoContinue?: AutoContinueRecord;
};
function viewOf(article: string, it: Iteration, state: ResearchState, phase: ResearchPhase): ResearchView {
@@ -126,6 +171,7 @@ function viewOf(article: string, it: Iteration, state: ResearchState, phase: Res
waitingOn: waitingOn(state),
continuedBy: recordOf(it)?.continuedBy ?? [],
...(recordOf(it)?.notes ? { notes: recordOf(it)!.notes } : {}),
+ ...(recordOf(it)?.autoContinue ? { autoContinue: recordOf(it)!.autoContinue } : {}),
};
}
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -191,6 +191,45 @@ function markTerminal(
if (typeof exitCode === "number") job.exitCode = exitCode;
}
+// WHO HEARS A JOB END (release 28 F1): a listener is told once per job, after
+// its terminal state is set, on a later turn of the event loop (so the job's
+// own end — its sidecar write — goes first), and a listener that throws never
+// touches the job. Kept on globalThis like the registry. An `auto` research
+// run listens for its acquisitions here (controller/researchAutoContinue.ts).
+export type JobEndListener = (job: Readonly<Pick<JobRecord, "id" | "kind" | "status" | "channelSlug">>) => void;
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttJobEndListeners__: Set<JobEndListener> | undefined;
+}
+
+const endNotified = new WeakSet<JobRecord>();
+
+// Listen for every job's end; the answer stops listening.
+export function onJobEnd(listener: JobEndListener): () => void {
+ const set = (globalThis.__yttJobEndListeners__ ??= new Set());
+ set.add(listener);
+ return () => {
+ set.delete(listener);
+ };
+}
+
+function notifyJobEnd(job: JobRecord): void {
+ const set = globalThis.__yttJobEndListeners__;
+ if (!set?.size || endNotified.has(job)) return;
+ endNotified.add(job);
+ const seen = { id: job.id, kind: job.kind, status: job.status, ...(job.channelSlug ? { channelSlug: job.channelSlug } : {}) };
+ setImmediate(() => {
+ for (const fn of set) {
+ try {
+ fn(seen);
+ } catch {
+ // a listener never breaks a job's end
+ }
+ }
+ });
+}
+
// The registry owns job LIFECYCLE/STATE (the JobRecord, meta sidecars, tasks,
// terminal transitions). Queue ORDERING — which job runs vs. waits, and the
// foreground-before-background priority — is delegated to the shared Scheduler
@@ -292,6 +331,7 @@ class JobRegistry {
job.tasks = [];
job.drainController = undefined;
getScheduler().complete(id);
+ notifyJobEnd(job);
}
cancel(id: string): boolean {
diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts
@@ -51,6 +51,28 @@ export type ResearchRecord = {
continuedBy?: number[];
// The agent's closing words (what the corpus holds, what it proposed).
notes?: string;
+ // An `auto` run continuing by itself (release 28 F1).
+ autoContinue?: AutoContinueRecord;
+};
+
+// What became of an `auto` run's own continuation (controller/
+// researchAutoContinue.ts):
+// claimed a continuation is being enqueued (the once-only mark, taken
+// under the article store's lock; stale after 10 minutes)
+// continued sweep `by` continues it (`warnings`: channels left out)
+// refused the ask was refused (the daily cap, a build, a route): tried
+// again on a later UTC day than `day`
+// held nothing it could sweep is in a build yet: tried again once a
+// build newer than `buildsAt` (ms) exists, or on a later day
+export const AUTO_CONTINUE_STATUSES = ["claimed", "continued", "refused", "held"] as const;
+export type AutoContinueRecord = {
+ status: (typeof AUTO_CONTINUE_STATUSES)[number];
+ at: string;
+ by?: number;
+ reason?: string;
+ warnings?: string[];
+ day?: string;
+ buildsAt?: number;
};
export function newResearchState(autonomy: Autonomy, limits: ResearchLimits): ResearchState {
diff --git a/editor/app/api/ops/_autoContinue.ts b/editor/app/api/ops/_autoContinue.ts
@@ -0,0 +1,16 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { armResearchAutoContinue } from "yt-dlp-transcript-common/controller/researchAutoContinue";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { researchEditor } from "./_researchEditor";
+
+// AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1), armed by
+// instrumentation.ts below the idle gate: the job-end listener and a boot
+// scan now, the heartbeat's scan from then on. The deps are the report-draft
+// route's own, so a continuation is the job "Continue into a sweep" posts.
+// See common/controller/researchAutoContinue.ts.
+export function armAutoContinue(): boolean {
+ return armResearchAutoContinue(
+ { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }), researchEditor },
+ { log: (line) => console.log(line) },
+ );
+}
diff --git a/editor/app/scheduler/heartbeat.ts b/editor/app/scheduler/heartbeat.ts
@@ -73,6 +73,18 @@ async function fire(generation: number): Promise<void> {
// already records its own outcome; the heartbeat just keeps beating.
}
+ // An `auto` research run whose acquisitions settled continues into its
+ // sweep (release 28 F1). A no-op unless instrumentation armed it (never on
+ // an idle boot). See common/controller/researchAutoContinue.ts.
+ try {
+ const { researchAutoContinueTick } = await import(
+ "yt-dlp-transcript-common/controller/researchAutoContinue"
+ );
+ await researchAutoContinueTick();
+ } catch {
+ // the scan records its own outcomes on the runs it reads
+ }
+
// Re-read the cadence each fire so a live settings change is honored without a
// restart. If it has been turned off (0), the loop simply stops here.
if (generation !== state.generation) return;
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -236,6 +236,17 @@ export async function register() {
/* a runner that fails to start must not block server readiness */
}
+ // AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end
+ // listener and one scan of the research runs now; the heartbeat scans again
+ // on each beat. Below the idle gate: a continuation is a generation job.
+ // See common/controller/researchAutoContinue.ts.
+ try {
+ const { armAutoContinue } = await import("./app/api/ops/_autoContinue");
+ armAutoContinue();
+ } catch {
+ /* auto-continue that fails to arm must not block server readiness */
+ }
+
// NO SECOND RESUME HOOK. There used to be two more here, one per sweep, and
// each re-launched a corpus-wide pass from its own persisted flag. Both lanes
// are runner lanes now, so `startAutoRunnersIfEnabled` above resumes all four