// 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) or a site build's 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: — 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, onResearchSettled, researchState, takeWatchedRun } from "./researchRuns"; export const CLAIM_STALE_MS = 10 * 60_000; // The jobs whose end runs the scan: a generation's (the research job's own // among them) and a site build's (a held run may now have its build). export const SCAN_ON_END = new Set([REPORT_DRAFT_JOB_KIND, "publish-build-site", "build-export", "build-deploy", "build-all", "build-deploy-all"]); 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>(); function serial(key: string, fn: () => Promise): Promise { 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 { 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 { return serial(`${article}/${n}`, () => attempt(article, n, deps)); } async function attempt(article: string, n: number, deps: ReportDraftDeps): Promise { 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(); let scanning: Promise | 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 { if (!scanning) { scanning = scan(deps, log).finally(() => { scanning = null; }); } return scanning; } async function scan(deps: ReportDraftDeps, log?: (line: string) => void): Promise { 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; 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 (SCAN_ON_END.has(job.kind)) { // A research job's end (or any generation's) — the scan finds its run — // or a site build's, which may hold what a held run waits for. void scanAutoContinue(state.deps, state.log).catch(() => {}); } }); // The operator's last decision on a run's proposals (approve-research): the // run may be ready with no job left to end. const offJobs = state.off; const offSettled = onResearchSettled((article, n) => { void maybeAutoContinue(article, n, state.deps).then( (r) => report(article, n, r, null, state.log), (e) => state.log?.(`research auto-continue: ${article} i${n}: ${(e as Error).message}`), ); }); state.off = () => { offJobs(); offSettled(); }; 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 { const armed = globalThis.__yttResearchAutoContinue__; if (!armed) return null; return scanAutoContinue(armed.deps, armed.log); }