// 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"; import { approveResearch } from "./researchRuns"; 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, status: Proposal["status"], extra: Partial = {}): 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 { 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(fn: () => Promise, what: string): Promise { 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((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("the operator's last decision settles an auto run, and it continues by itself — no job has to end (release 28 smoke)", async () => { const article = "synth-auto-decided"; const n = await makeRun(article, { channels: ["synth-kitchen"], proposals: [ prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/5" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" }), prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/6" }, "proposed", { note: "past the run's caps" }), ], }); assert.ok(armResearchAutoContinue(deps(), { bootScan: false, env: {} })); const r = await approveResearch({ article, iteration: n, ids: ["p02"], approve: false, note: "too large" }, { paths, editor: {} as never }); assert.ok(r.ok); assert.equal(r.view.phase, "ready"); const rec = await until(async () => { const x = await recOf(article, n); return x.autoContinue?.status === "continued" ? x : null; }, "the continuation"); const sweeps = await sweepsOf(article, n); assert.equal(sweeps.length, 1); assert.deepEqual(rec.continuedBy, [sweeps[0]!.n]); await ended(sweeps[0]!.jobId!); // A decision that leaves the run waiting fires nothing. const other = "synth-auto-still-waiting"; const m = await makeRun(other, { channels: ["synth-kitchen"], proposals: [ prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/7" }, "proposed"), prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/8" }, "proposed"), ], }); const w = await approveResearch({ article: other, iteration: m, ids: ["p01"], approve: false }, { paths, editor: {} as never }); assert.ok(w.ok); assert.equal(w.view.phase, "wait"); await new Promise((res) => setTimeout(res, 100)); assert.equal((await sweepsOf(other, m)).length, 0); }); 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("a held run continues when a site build that holds its channel ends", async () => { const article = "synth-auto-rebuilt"; const n = await makeRun(article, { proposals: [prop("p01", "create-channel", { fields: { name: "Synth Rebuilt" } }, "done", { channel: "synth-rebuilt", doneAt: "2026-10-13T10:00:00.000Z" })], }); assert.equal((await maybeAutoContinue(article, n, deps())).outcome, "held"); armResearchAutoContinue(deps(), { bootScan: false, env: {} }); // The operator puts it on a site and builds it: the build job's end runs the scan. const build = await runManagedFunction({ kind: "build-export", queueKey: "", paths, fn: async () => writeBuild("synth-rebuilt", ["synth-rebuilt"], new Date(Date.now() + 120_000)), }); assert.ok(build.ok); void build.stream.cancel(); await build.done; const rec = await until(async () => { const r = await recOf(article, n); return r.autoContinue?.status === "continued" ? r : null; }, "the continuation after the build"); const sweep = (await sweepsOf(article, n))[0]!; assert.equal(rec.autoContinue!.by, sweep.n); assert.deepEqual(sweep.scope?.channels, ["synth-rebuilt"]); await ended(sweep.jobId!); await researchAutoContinueTick(); }); 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!); });