Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 6ba140ee558532148ea445e7e61f30f02e1763f6
parent 52fe4b5fdbf026d40239e5276b79274d5a360148
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 22:41:00 -0400

Merge r28/research-f: release 28 F1 — an auto research run continues into its sweep by itself

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	COMMANDS.md
#	plans/FACTS.md
#	plans/release-28.md

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 9++++++++-
MSETTINGS.md | 2+-
Acommon/controller/researchAutoContinue.test.ts | 341+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/researchAutoContinue.ts | 357+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/researchRuns.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/jobs/registry.ts | 40++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.ts | 2+-
Mcommon/lib/report/draft/research/state.ts | 22++++++++++++++++++++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/_autoContinue.ts | 16++++++++++++++++
Meditor/app/api/ops/research-approve/route.ts | 7++++---
Meditor/app/scheduler/heartbeat.ts | 12++++++++++++
Meditor/instrumentation.ts | 11+++++++++++
Mplans/FACTS.md | 30++++++++++++++++++++++++++++++
Mplans/release-28.md | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 6++++--
Mumtool/components/articles/ResearchSlot.tsx | 29+++++++++++++++++++++++++++++
Mumtool/e2e/article-research.spec.ts | 32+++++++++++++++++++++++++++++++-
Mumtool/e2e/fixtures/editor-stub.mjs | 38+++++++++++++++++++++++++++++++++-----
20 files changed, 1044 insertions(+), 16 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -146,7 +146,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {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/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, 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" \| "narrate" \| "research", "article", ...} -&gt; {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 narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "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). | `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}'` | -| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy}}. 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. Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | +| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {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"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -&gt; {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/&lt;run&gt;/ (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` | ### Usage, flags and environment diff --git a/OPERATING.md b/OPERATING.md @@ -247,7 +247,14 @@ pnpm ops report-draft --json '{"task":"sweep","article":"example-article","i - **Continue** (umtool's **Continue into a sweep**, shown once the run is done and nothing is pending) is a sweep with `"iteration"` naming the research run: its question, over its channels and every channel an acquisition wrote into. It is refused while the run waits, unless `"force": true`. A channel on no site - is in no build: put it on a site and build before continuing. Nothing continues on its own. + is in no build: put it on a site and build before continuing. +- **An `auto` run continues by itself** once its acquisitions settle (every job ended, nothing waiting for you): the + editor asks that same sweep, on the run's own model, at the job's end or on its heartbeat. The caps hold (the + sweep's per-job cap; past the daily cap it is refused, and tried again the next UTC day). A channel in no build is + left out, with the warning `not in any build yet: <slug> — rebuild the site and continue again` (a failed check on + the sweep); with nothing left to sweep it waits for a newer build. The queue says "continued automatically by iN", + or why not. `propose` and `limits` runs are continued by you. An idle boot (`ARCHILYZER_IDLE_BOOT`) continues + nothing. - **The standing rules hold in every mode**, and a proposal that breaks one is refused: a new channel is created on no site; an X channel never goes on a site; a Twitch VOD URL is refused (look for the stream on archive.org); every fetch goes through the editor's queues, holds and cooldowns (one stream, real gaps, backing off on a 429), never yt-dlp or gallery-dl by diff --git a/SETTINGS.md b/SETTINGS.md @@ -1007,7 +1007,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | Key | Default | Description | |---|---|---| -| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. | +| `autonomy` | `"propose"` | `propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD. | | `maxItemsPerRun` | `20` | The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits. | | `maxGbPerRun` | `5` | The most GB one run may download without approval. An acquisition of unknown size waits. | | `maxTranscribeHours` | `6` | The most hours of transcription one run may queue without approval. One of unknown length waits. | diff --git a/common/controller/researchAutoContinue.test.ts b/common/controller/researchAutoContinue.test.ts @@ -0,0 +1,341 @@ +// 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("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!); +}); diff --git a/common/controller/researchAutoContinue.ts b/common/controller/researchAutoContinue.ts @@ -0,0 +1,357 @@ +// 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: <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; + +// 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<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 (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(() => {}); + } + }); + 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/generationSettings.ts b/common/lib/generationSettings.ts @@ -149,7 +149,7 @@ export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = { export const GENERATION_RESEARCH_FIELD_DOCS: FieldDocs<GenerationResearch> = { autonomy: - "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.", + "`propose` (every acquisition waits for the operator's yes or no), `limits` (acquisitions into existing channels under the caps run on their own; the rest waits) or `auto` (everything runs on its own, through the editor; the approval flags are lifted, the caps are not; once its acquisitions settle the run continues into its sweep by itself, leaving out a channel in no build). Every mode refuses the standing rules: a new channel on any site, an X channel on a site, a Twitch VOD.", maxItemsPerRun: "The most items (videos, archive.org files, posts) one run may acquire without approval. Past it, an acquisition waits.", maxGbPerRun: "The most GB one run may download without approval. An acquisition of unknown size waits.", maxTranscribeHours: "The most hours of transcription one run may queue without approval. One of unknown length waits.", 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/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A research run on `auto` continues into its sweep by itself.** Once its acquisitions settle — every job it started has ended and nothing waits for your yes or no — the editor runs the same sweep **Continue into a sweep** would, on the run's own model, and the run's queue in umtool says **continued automatically by i<n>**. The caps hold: the sweep's per-job cap applies, and past the day's API total it is not started; the queue says so, and it is tried again the next day (UTC). A channel the run acquired into that is in no site build yet is left out of the sweep, with the warning "not in any build yet: <slug> — rebuild the site and continue again" on the queue and on the sweep; a run with nothing it could sweep waits for a newer build. `propose` and `limits` runs are still continued by you, and an editor booted idle (`ARCHILYZER_IDLE_BOOT`) continues nothing. Needs a restart of the editor and umtool. - **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`). - **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes). - **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts. 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/api/ops/research-approve/route.ts b/editor/app/api/ops/research-approve/route.ts @@ -19,9 +19,10 @@ export const dynamic = "force-dynamic"; // their doors and queues; `approve: false` rejects them (`note`: why); // - no `ids`: the run's state now (the umtool queue polls this). // `research` is {article, iteration, status, phase, autonomy, limits, spent, -// proposals, waitingOn: {approval, jobs}, continuedBy}. A run whose job is -// still going is refused. The CONTINUATION is report-draft {task: "sweep", -// iteration: <this run>}. +// proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}. A run +// whose job is still going is refused. The CONTINUATION is report-draft +// {task: "sweep", iteration: <this run>}; an `auto` run's is asked by the +// editor itself (release 28 F1, controller/researchAutoContinue.ts). // // AN ADAPTER: the rules are the controller's (controller/researchRuns.ts). export async function POST(request: Request) { 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 diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9265,3 +9265,33 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `export/.export-builds/<id>/` and `export/.export-index/sites/<id>/`; nothing else on disk names a site by id (channel membership is site.json's own pool). The editor's Danger → Delete (`deleteSiteAction` → `deleteSite`) still removes `sites/<id>/` alone. +## Release 28 F1: an `auto` research run continues by itself (verified 2026-10-14, branch `r28/research-f`) + +- **`maybeAutoContinue(article, n, deps)`** (`common/controller/researchAutoContinue.ts`, `deps` = `ReportDraftDeps`) + is the one function; it answers `{outcome: "continued", by, jobId?, warnings} | {outcome: "held" | "refused", + reason} | {outcome: "not-now", why, final?}` and is idempotent. Only `auto` continues by itself; `propose` and + `limits` are final not-nows. The continuation is `enqueueReportDraft({task: "sweep", article, iteration: n, + model: <the research run's own model>, channels: <the kept ones>})` — Continue's own path, so `markContinued`, + caps.sweep and the daily cap at the ask and at the job's turn are unchanged. +- **The record** is `research.autoContinue` in the run's `iteration.json` (`AutoContinueRecord`, + `lib/report/draft/research/state.ts`): `{status: "claimed" | "continued" | "refused" | "held", at, by?, reason?, + warnings?, day?, buildsAt?}`, mirrored as `ResearchView.autoContinue` (research-approve's answer), plus a + `{kind: "auto-continue", outcome, …}` line in the run's `turns.jsonl`. **The claim is the once-only mark**, taken by + `updateIteration`'s function patch under the article store's lock; a claim is fresh for `CLAIM_STALE_MS` (10 min), + and a stale one with a sweep made after it (`parent` n) is recorded as the continuation. `refused` is retried + only on a later UTC day than `day`; `held` (nothing it would sweep is in any composed build) on a build newer than + `buildsAt` or a later day. A channel in no build (`listCorpusBuilds`) is left out with the warning `not in any + build yet: <slug> — rebuild the site and continue again`, also a failed `unbuilt channels` check on the sweep. +- **The triggers.** `onJobEnd(listener)` (`common/jobs/registry.ts`, new): every job's end, once, on a later turn + (`setImmediate`) after `finalize`. `settle` in `researchRuns.ts` watches an `auto` run's pending job ids + (`watchResearchJobs` / `takeWatchedRun`, in-process, bounded at 2000); the listener continues a watched job's + run, and the end of a `report-draft` job or a site build (`SCAN_ON_END`) runs the scan. `scanAutoContinue(deps)` reads every article's iteration + dirs holding a `proposals.json` (a run finished with is remembered, not re-read), one scan at a time. + `armResearchAutoContinue(deps, {log?, env?, bootScan?})` arms the listener and a boot scan and refuses an idle + boot (false); `researchAutoContinueTick()` is the heartbeat's call (`editor/app/scheduler/heartbeat.ts` `fire`) + and returns null unarmed. The editor arms it in `instrumentation.ts` BELOW the idle gate, through + `editor/app/api/ops/_autoContinue.ts` (the report-draft route's deps). +- **The heartbeat is off by default** (`syncScheduler.heartbeatSeconds` 0; the live `settings.json` has 0, verified + 2026-10-14): live, the job-end listener and the boot scan are the triggers, and a `refused` or `held` run is + retried only at the next end of a report-draft job or a site build, the next boot, or a heartbeat if one is + configured. diff --git a/plans/release-28.md b/plans/release-28.md @@ -523,6 +523,61 @@ a file in them. The real verdict bench runs once, after the rollout, through the route, and qwen needs the editor's GPU arbiter); its results land in the primary checkout's `.generation/`. Lane C's leftovers: `relocateDir.ts` reports a directory-mtime-only difference as "changed"; the editor's Danger → Delete still removes only `sites/<id>/` (M9 routes it through the plan-first delete). +### F1, as shipped (2026-10-14, lane F, `r28/research-f`) + +An `auto` research run continues into its sweep by itself once its acquisitions settle. + +| Commit | What | +| --- | --- | +| `7739bce5` | `controller/researchAutoContinue.ts`: `maybeAutoContinue`, `scanAutoContinue`, `armResearchAutoContinue` / `researchAutoContinueTick`; `onJobEnd` in `jobs/registry.ts`; `researchRuns.ts` watches an `auto` run's pending jobs (`watchResearchJobs`, `takeWatchedRun`) and its view carries `autoContinue`; `AutoContinueRecord` in `research/state.ts`; the heartbeat's call; the editor arms it below the idle gate (`_autoContinue.ts`); 6 tests | +| `526261f1` | umtool: the research queue says "continued automatically by iN", or why not; the editor stub continues an `auto` run as the editor does; `article-research.spec` asserts it | +| `a3084416` | OPERATING.md's research section, the `autonomy` field doc and SETTINGS.md, research-approve's help and COMMANDS.md | +| `62f732d3` | a site build's end runs the scan too (`SCAN_ON_END`), so a held run continues after the rebuild; 1 test | +| (this commit) | this record, FACTS "Release 28 F1", CHANGELOG | + +- **Who continues by itself:** autonomy `auto` only. `propose` and `limits` are continued by the operator, as in r27. +- **When:** the run is done; nothing waits for a yes or no; every acquisition job has ended (done, failed or + cancelled); it is not continued already. +- **The once-only mark** is a claim taken under the article store's lock (`updateIteration`'s function patch), so a + heartbeat and a job end racing continue once. A claim is fresh for 10 minutes. A stale claim whose sweep exists is + recorded as the continuation, not made again. +- **What it asks:** Continue's own path, `report-draft {task: "sweep", iteration: n, model, channels}`. + - The model is the research run's own (the brief's "the run's model/route"). The umtool button still defaults to the + sweep route's. + - The per-job cap is `caps.sweep`; the daily cap is checked first, again at the ask, and again at the job's turn. + - A daily-cap refusal, like any refusal of the ask, is recorded as `refused` and tried again only on a later UTC + day. +- **Builds:** a channel in no composed build is left out. The warning `not in any build yet: <slug> — rebuild the site + and continue again` is on the run's record and is a failed `unbuilt channels` check on the sweep. With nothing left, + the run is `held` (nothing enqueued) until a build newer than the hold, or a later day. +- **Triggers:** + - the registry's new `onJobEnd`: a watched acquisition job's end continues its run; the end of a `report-draft` job + (the research job's own) or a site build runs the scan; + - the scan: on the heartbeat (`fire`, after the tick) and once at boot. + - The editor arms both in `instrumentation.ts` below the idle gate, and `armResearchAutoContinue` refuses an idle + boot itself. +- **On the run:** `research.autoContinue` (status, at, by, reason, warnings, day, buildsAt) in `iteration.json`, an + `auto-continue` line in `turns.jsonl`, `ResearchView.autoContinue` in research-approve's answer, and umtool's + queue line. +- **Found:** the editor's heartbeat is off by default (`syncScheduler.heartbeatSeconds` 0; the live `settings.json` + says 0). Live, the triggers are the job ends and the boot scan. A refused run is retried the next day only when a + report-draft or site-build job ends, the editor restarts, or a heartbeat is configured. +- **No change to `reportDraft.ts`:** the continuation is asked from code through `enqueueReportDraft`, and the daily + cap is pre-checked with `generationUsage`'s exports. No settings key was added; the `autonomy` doc says what `auto` + now does. + +Gates (from the worktree root; counts at the branch start → the tip): +- tsc clean (all packages) before every commit. +- common 4042 → 4049/4049 (7 new, `controller/researchAutoContinue.test.ts`, five runs each clean); editor unit + 290 → 290/290; mcp 345 of 346 at the start (1 failure, "a real editor that stops answering a poll hands back the + job", not reproduced since) → 346/346; `test:scripts` 870 + 3 skipped, 1 failure at the start (`queue-lock`, H2's + flake) → 871 + 3 skipped, 0 failed (874; the count unchanged, the failure not reproduced). +- `settings example --check`, `docs env|files|cli --check`: clean. +- Editor build (heavy slot, 5 GB cap): clean in 52 s. +- e2e, single specs in the foreground: + - umtool `article-research.spec.ts` 3/3 (31.2 s; its prebuild's capped build 29 s), the new auto-continue test included; + - umtool `article-iterations.spec.ts` + `article-new.spec.ts` 7/7 (40.6 s); + - editor `report-draft.spec.ts` 3/3 (19.2 s; its prebuild's capped build 48 s), with the new boot arming in its server. ## Not in this release diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1246,13 +1246,15 @@ export function usage() { ' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->', " {outcomes: [{id, status?, jobId?, note?, error?}], research: {phase,", " autonomy, limits, spent, proposals, waitingOn: {approval, jobs},", - " continuedBy}}. It first refreshes every enqueued acquisition from its", + " 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. Refused while the run\'s job is going.', + ' "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.", "", 'bench-verdicts runs the verdict bench as a bench-verdicts job: {"models":', ' ["…"], "run"?, "reports"?: ["<article>"], "window"? (seconds, default 60),', diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx @@ -19,6 +19,11 @@ import type { ResearchProposal, ResearchView } from "@/lib/articles/research"; // /api/articles/research), which refreshes the enqueued acquisitions from // their jobs; it is re-read every 4 s while the run's job or an acquisition's // is going. +// +// An `auto` run continues by itself once its acquisitions settle (release 28 +// F1, the editor's researchAutoContinue): the queue says "continued +// automatically" with the channels it left out, or why it has not (held for +// a build, refused by a cap). const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; @@ -38,6 +43,29 @@ const PHASE_SAYS: Record<ResearchView["phase"], string> = { continued: "continued", }; +// An `auto` run's own continuation: done (by which sweep, and what it left +// out), or why not yet. +function AutoContinued({ ac }: { ac: NonNullable<ResearchView["autoContinue"]> }) { + if (ac.status === "continued") { + return ( + <div data-auto-continued={ac.by ?? ""} className="flex flex-col gap-0.5"> + <span className="text-[var(--color-text)]">continued automatically{ac.by ? ` by i${ac.by}` : ""}</span> + {(ac.warnings ?? []).map((w, i) => ( + <span key={i} className="text-[var(--color-dirty)]"> + {w} + </span> + ))} + </div> + ); + } + if (ac.status === "claimed") return <span data-auto-continue="claimed">continuing automatically…</span>; + return ( + <p data-auto-continue={ac.status} className="text-[var(--color-dirty)]"> + {ac.status === "held" ? "not continued automatically yet" : "not continued automatically today"}: {ac.reason} + </p> + ); +} + // What an acquisition is for, in one line: its channel and what it fetches. function target(p: ResearchProposal): string { const a = p.args; @@ -273,6 +301,7 @@ export default function ResearchSlot({ </> )} </div> + {view?.autoContinue && <AutoContinued ac={view.autoContinue} />} {view?.notes && <p className="whitespace-pre-wrap text-[13px] text-[var(--color-text)]">{view.notes}</p>} {view && view.proposals.length === 0 && !active && <p className="text-[var(--color-dim)]">no acquisitions proposed</p>} {view && view.proposals.length > 0 && ( diff --git a/umtool/e2e/article-research.spec.ts b/umtool/e2e/article-research.spec.ts @@ -25,7 +25,10 @@ test.beforeAll(async ({ playwright }) => { test.setTimeout(WARM_TIMEOUT); await warm(playwright, ["/articles/new", "/api/articles/policy", "/api/articles/channels", "/articles/zeta?tab=iterations"]); }); -test.afterAll(() => rmSync(path.join(FIXTURE, "articles", ARTICLE), { recursive: true, force: true })); +const AUTO = "research-auto-e2e"; +test.afterAll(() => { + for (const a of [ARTICLE, AUTO]) rmSync(path.join(FIXTURE, "articles", a), { recursive: true, force: true }); +}); test("research: started with an autonomy, its queue answered yes and no, its job followed, then continued into a sweep", async ({ page }) => { test.setTimeout(120_000); @@ -110,6 +113,33 @@ test("research: started with an autonomy, its queue answered yes and no, its job await expect(page.locator("[data-iteration='1'] [data-continued-by]")).toHaveAttribute("data-continued-by", "2"); }); +// Release 28 F1: an `auto` run whose acquisitions settled is continued by the +// editor itself — umtool asks for nothing, and its queue says so. +test("research: an auto run continues into its sweep by itself, and the queue says so", async ({ page }) => { + test.setTimeout(120_000); + await page.goto("/articles/new"); + const form = page.getByRole("form", { name: "new article" }); + await form.getByRole("radio", { name: /^research/ }).check(); + await form.getByRole("combobox", { name: "autonomy" }).selectOption("auto"); + await form.getByRole("textbox", { name: "question" }).fill("Where did the recount story start?"); + await form.getByRole("textbox", { name: "article id" }).fill(AUTO); + await form.getByRole("button", { name: "Start" }).click(); + await expect(page).toHaveURL(new RegExp(`/articles/${AUTO}\\?tab=iterations$`)); + expect(stubAsked("report-draft").at(-1)).toMatchObject({ task: "research", article: AUTO, autonomy: "auto" }); + + const slot = page.locator("[data-iteration='1']").getByRole("region", { name: "i1 research" }); + await expect(slot.locator("[data-auto-continued]")).toHaveAttribute("data-auto-continued", "2", { timeout: 20_000 }); + await expect(slot.locator("[data-auto-continued]")).toContainText("continued automatically by i2"); + await expect(slot.locator("[data-auto-continued]")).toContainText("not in any build yet: radio-tape"); + await expect(slot).toHaveAttribute("data-research-phase", "continued"); + const sweep = page.locator("[data-iteration='2']"); + await expect(sweep).toHaveAttribute("data-kind", "sweep"); + await expect(sweep).toContainText("of i1"); + await expect(sweep).toContainText("unbuilt channels: not in any build yet: radio-tape"); + // Umtool posted no sweep: the editor made it. + expect(stubAsked("report-draft").filter((r) => r.article === AUTO).map((r) => r.task)).toEqual(["research"]); +}); + test("the research route refuses what is not a decision", async ({ request }) => { const bad = await request.post("/api/articles/research", { data: { article: ARTICLE, n: 1, ids: ["p01"] } }); expect(bad.status()).toBe(400); diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -185,11 +185,12 @@ function finishDraft(job) { } const claude = it.model.startsWith("claude-"); const usage = claude ? { [it.model]: { usd: 0.37, inputTokens: 41000, outputTokens: 2100, calls: 6 } } : {}; - const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [{ name: "strict-quotes", ok: true }] }; + // A check written beside the job (auto-continue's) is kept, as the task's own merge does. + const patch = { status: "done", usage, minutes: 0.1, endedAt: now, checks: [...(it.checks ?? []).filter((c) => c.name !== "strict-quotes"), { name: "strict-quotes", ok: true }] }; if (it.kind === "research") { const autonomy = job.autonomy ?? "propose"; writeFileSync(path.join(itDir(article, n), "proposals.json"), JSON.stringify(stubProposals(autonomy), null, 2) + "\n"); - patch.research = { autonomy, phase: "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." }; + patch.research = { autonomy, phase: autonomy === "auto" ? "ready" : "wait", notes: "The archive holds one stream on it. I asked for the episode and a channel for the radio tape." }; delete patch.checks; } else if (it.kind === "sweep") { writeFileSync(path.join(itDir(article, n), "report.json"), JSON.stringify(stubReport(article, `Sweep: ${it.question ?? "a copy"}`), null, 2) + "\n"); @@ -212,6 +213,20 @@ function finishDraft(job) { patchIt(article, n, patch); job.status = "done"; job.log.push("stub: wrote the iteration", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`); + if (it.kind === "research" && job.autonomy === "auto") autoContinue(article, n); +} + +// An `auto` run's acquisitions have settled: the editor continues it by +// itself (release 28 F1, controller/researchAutoContinue.ts) — a sweep on the +// run's model over the channels in a build (the new channel is in none: left +// out, with the warning), recorded on the run and as a failed check on the sweep. +function autoContinue(article, n) { + const r = readIt(article, n); + const warning = "not in any build yet: radio-tape — rebuild the site and continue again"; + const { iteration: by } = startDraft({ task: "sweep", article, iteration: n, model: r.model, channels: ["sitechan"] }); + patchIt(article, by, { checks: [{ name: "unbuilt channels", ok: false, detail: warning }] }); + const now = readIt(article, n); + patchIt(article, n, { research: { ...now.research, autoContinue: { status: "continued", at: new Date().toISOString(), by, warnings: [warning] } } }); } // ─── research (release 27 S11) ─── @@ -219,6 +234,18 @@ function finishDraft(job) { // What the stub's research run proposes: as the real run under `propose` // (every acquisition waits; the Twitch VOD refused by the standing rule). function stubProposals(autonomy) { + // Under `auto` (release 28 F1): the import ran and the channel was made; + // the Twitch VOD is refused in every mode. + if (autonomy === "auto") { + const base = stubProposals("propose"); + const doneAt = new Date().toISOString(); + base.autonomy = "auto"; + base.spent = { items: 1, gb: 0.2, transcribeHours: 0 }; + base.proposals[0] = { ...base.proposals[0], status: "done", jobId: "stub-acq-auto", doneAt }; + base.proposals[1] = { ...base.proposals[1], status: "done", channel: "radio-tape", doneAt }; + for (const p of base.proposals.slice(0, 2)) delete p.note; + return base; + } return { format: "archilyzer-research-proposals", version: 1, @@ -295,6 +322,7 @@ function researchView(article, n, st) { }, continuedBy: rec.continuedBy ?? [], ...(rec.notes ? { notes: rec.notes } : {}), + ...(rec.autoContinue ? { autoContinue: rec.autoContinue } : {}), }; } @@ -342,7 +370,7 @@ function settleResearch(body) { // A sweep continuing research run `rn`: its question, its channels widened by // what was acquired (refused while it waits, unless force). -function continuation(article, rn, force) { +function continuation(article, rn, force, given) { const r = readIt(article, rn); if (r.kind !== "research") throw new Error(`a sweep with "iteration" continues a research run; "${article}" i${rn} is a ${r.kind} iteration`); if (r.status !== "done") throw new Error(`"${article}" i${rn} is ${r.status}: only a done research run is continued`); @@ -355,7 +383,7 @@ function continuation(article, rn, force) { if (p.status !== "done") continue; for (const c of [p.channel, p.args?.slug]) if (typeof c === "string" && !channels.includes(c)) channels.push(c); } - return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels } }; + return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels: given ?? channels } }; } function startDraft(body) { @@ -377,7 +405,7 @@ function startDraft(body) { } else if (task === "research") { base = { kind: "research", parent: null, copyOf: null, question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}) } }; } else if (task === "sweep" && body.iteration) { - base = continuation(article, body.iteration, body.force === true); + base = continuation(article, body.iteration, body.force === true, Array.isArray(body.channels) ? body.channels : undefined); } else if (task === "sweep") { base = { kind: "sweep", parent: null, copyOf: null, question: body.question, scope: { channels: body.channels, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }; } else {