// RESEARCH RUNS, after their job (release 27 S11): the operator's yes or no // on an acquisition, the refresh of enqueued ones from their editor jobs, and // the scope a continuation sweeps. // // `pnpm ops research-approve {article, iteration, ids?, approve?, note?}` → // POST /api/ops/research-approve → approveResearch: // - every call first REFRESHES the run: an enqueued acquisition whose jobs // have all ended becomes done (or failed, saying which job), so a call // with no ids is the run's state now (the umtool queue polls it); // - `approve: true` runs each named proposal's editor action (past the // run's autonomy and caps — the operator decided — never past a standing // rule); `approve: false` rejects it, with the `note` as why; // - proposals.json is rewritten once, under a per-run lock in this process, // and the iteration's `research.phase` follows. // A run whose job is still going is refused: its proposals are the job's // until it ends. // // THE CONTINUATION is `report-draft {task: "sweep", iteration: }` // (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. 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"; import { readIteration, updateIteration, type Iteration } from "../lib/report/iterations"; import { REPORT_ID_RE } from "../lib/report/schema"; import { rejectProposal, runApprovedProposal, type ResearchEditor } from "../lib/report/draft/research/tools"; import type { Proposal } from "../lib/report/draft/research/decide"; import { isSettled, lastAcquiredAt, phaseOf, readResearchState, refreshProposals, waitingOn, widenedChannels, writeResearchState, type AutoContinueRecord, type JobOf, type ResearchPhase, type ResearchRecord, type ResearchState, } from "../lib/report/draft/research/state"; export const RESEARCH_APPROVE_BODY_KEYS = ["article", "iteration", "ids", "approve", "note"] as const; export class ResearchInputError extends Error {} type StorePaths = Pick; // An editor job's state, from the registry or its `.jobs` sidecar — THE // WORK's state: a job that ended `done` having handed its work on to another // (`handedOffTo`: a whisper-video's transcription, queued as a transcribe-one // job once the audio is down) answers with that job's state, followed to the // end of the chain (`via` names the job answering). A caller asking "is the // transcript there" would otherwise read `done` while it still waits for a // worker. export function jobOfPaths(paths: Pick): JobOf { return async (id) => { let e = await getJobEntry(paths as Paths, id); let via: string | undefined; for (let hops = 0; e && e.status === "done" && e.handedOffTo && hops < 5; hops++) { const next = await getJobEntry(paths as Paths, e.handedOffTo); if (!next) return { status: "archived", via: e.handedOffTo }; via = next.id; e = next; } return e ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}), ...(via ? { via } : {}) } : null; }; } // One run's read-modify-write at a time, in this process (the editor is one). 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; } const recordOf = (it: Iteration): ResearchRecord | undefined => (it as { research?: ResearchRecord }).research; function phaseNow(it: Iteration, state: ResearchState): ResearchPhase { if (it.status === "queued" || it.status === "running") return "discover"; const continued = (recordOf(it)?.continuedBy?.length ?? 0) > 0; return isSettled(state) && continued ? "continued" : phaseOf(state); } async function readRun(article: string, n: number, paths: StorePaths): Promise<{ it: Iteration; state: ResearchState }> { const it = await readIteration(article, n, paths); if (!it) throw new ResearchInputError(`"${article}" has no iteration i${n}`); if (it.kind !== "research") throw new ResearchInputError(`"${article}" i${n} is a ${it.kind} iteration, not a research run`); const state = await readResearchState(article, n, paths); if (!state) throw new ResearchInputError(`"${article}" i${n} has no proposals yet (its run has not started)`); return { it, state }; } // Refresh, write what changed, set the phase. Under the run's lock. async function settle(article: string, it: Iteration, state: ResearchState, changed: boolean, paths: StorePaths): Promise { // While the run's job is going its own ledger owns proposals.json: a read // then answers the refreshed state without writing it. if (changed && it.status !== "queued" && it.status !== "running") await writeResearchState(article, it.n, state, paths); const phase = phaseNow(it, state); const rec = recordOf(it); 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 | 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; status: Iteration["status"]; phase: ResearchPhase; autonomy: ResearchState["autonomy"]; limits: ResearchState["limits"]; spent: ResearchState["spent"]; proposals: Proposal[]; waitingOn: { approval: string[]; jobs: string[] }; 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 { return { article, iteration: it.n, status: it.status, phase, autonomy: state.autonomy, limits: state.limits, spent: state.spent, proposals: state.proposals, waitingOn: waitingOn(state), continuedBy: recordOf(it)?.continuedBy ?? [], ...(recordOf(it)?.notes ? { notes: recordOf(it)!.notes } : {}), ...(recordOf(it)?.autoContinue ? { autoContinue: recordOf(it)!.autoContinue } : {}), }; } export type ResearchApproveBody = { article: string; iteration: number; ids: string[]; approve?: boolean; note?: string }; export function parseResearchApproveBody(b: Record): ResearchApproveBody { const fail = (m: string): never => { throw new ResearchInputError(m); }; if (typeof b.article !== "string" || !REPORT_ID_RE.test(b.article)) fail('"article" is an article id (a lowercase slug)'); if (typeof b.iteration !== "number" || !Number.isInteger(b.iteration) || b.iteration < 1) fail('"iteration" is the research iteration\'s number (1, 2, …)'); let ids: string[] = []; if (b.ids !== undefined && b.ids !== null) { const raw = typeof b.ids === "string" ? b.ids.split(",") : b.ids; if (!Array.isArray(raw) || !raw.every((x) => typeof x === "string" && /^p\d+$/.test(x.trim()))) fail('"ids" is a list of proposal ids (p01, p02, …)'); ids = [...new Set((raw as string[]).map((x) => x.trim()))]; } if (b.approve !== undefined && typeof b.approve !== "boolean") fail('"approve" is true (run them) or false (reject them)'); if (ids.length && b.approve === undefined) fail('say "approve": true or false for the ids'); if (b.note !== undefined && (typeof b.note !== "string" || !b.note.trim())) fail('"note" is text (why not)'); return { article: b.article as string, iteration: b.iteration as number, ids, ...(b.approve !== undefined ? { approve: b.approve as boolean } : {}), ...(typeof b.note === "string" ? { note: b.note.trim() } : {}), }; } export type ResearchOutcome = { id: string; status?: Proposal["status"]; jobId?: string; note?: string; error?: string }; // SETTLED: the operator's decisions left a run with nothing to wait for. The // auto-continue (./researchAutoContinue.ts) listens: a decision is the trigger // a job's end is for an acquisition, and nothing else would notice it while // the heartbeat is off. On globalThis, as onJobEnd's listeners are, so every // copy of this module the server bundles shares one set. type SettledListener = (article: string, n: number) => void; declare global { // eslint-disable-next-line no-var var __yttResearchSettled__: Set | undefined; } const settledListeners = (): Set => (globalThis.__yttResearchSettled__ ??= new Set()); export function onResearchSettled(l: SettledListener): () => void { settledListeners().add(l); return () => { settledListeners().delete(l); }; } // The operator's yes or no on a research run's proposals (no ids: its state). export async function approveResearch( raw: Record, deps: { paths: StorePaths; editor: ResearchEditor; jobOf?: JobOf }, ): Promise<{ ok: true; view: ResearchView; outcomes: ResearchOutcome[] } | { ok: false; error: string }> { let body: ResearchApproveBody; try { body = parseResearchApproveBody(raw); } catch (e) { return { ok: false, error: (e as Error).message }; } const jobOf = deps.jobOf ?? jobOfPaths(deps.paths); try { const res = await serial(`${body.article}/${body.iteration}`, async () => { const { it, state } = await readRun(body.article, body.iteration, deps.paths); if (body.ids.length && (it.status === "queued" || it.status === "running")) { throw new ResearchInputError(`"${body.article}" i${it.n} is ${it.status}: its proposals are the run's until it ends`); } let changed = await refreshProposals(state, jobOf); const outcomes: ResearchOutcome[] = []; for (const id of body.ids) { try { const p = body.approve ? await runApprovedProposal({ editor: deps.editor, ledger: state }, id) : rejectProposal(state, id, body.note ? `the operator said no: ${body.note}` : "the operator said no"); changed = true; outcomes.push({ id, status: p.status, ...(p.jobId ? { jobId: p.jobId } : {}), ...(p.note ? { note: p.note } : {}) }); } catch (e) { outcomes.push({ id, error: (e as Error).message }); } } const phase = await settle(body.article, it, state, changed, deps.paths); const now = (await readIteration(body.article, it.n, deps.paths)) ?? it; return { ok: true as const, view: viewOf(body.article, now, state, phase), outcomes }; }); // Outside the run's lock: a listener may take it. if (body.ids.length && res.view.phase === "ready") { for (const l of settledListeners()) { try { l(body.article, body.iteration); } catch { // a listener's failure is its own } } } return res; } catch (e) { return { ok: false, error: (e as Error).message }; } } // A run's state now (refreshed), for a reader that does not approve. export async function researchState(article: string, n: number, deps: { paths: StorePaths; jobOf?: JobOf }): Promise { return serial(`${article}/${n}`, async () => { const { it, state } = await readRun(article, n, deps.paths); const changed = await refreshProposals(state, deps.jobOf ?? jobOfPaths(deps.paths)); const phase = await settle(article, it, state, changed, deps.paths); return viewOf(article, it, state, phase); }); } export type Continuation = { research: Iteration; question: string; channels: string[]; from?: string; to?: string; // When the newest acquisition finished (ms), for the build's freshness. lastAcquired: number | null; }; // What a sweep continuing research run `n` sweeps. Refused while the run is // not done, or while it still waits (unless `force`: what is done so far). export async function continuationOf( article: string, n: number, o: { paths: StorePaths; jobOf?: JobOf; force?: boolean; question?: string; channels?: string[]; from?: string; to?: string }, ): Promise { return serial(`${article}/${n}`, async () => { const it = await readIteration(article, n, o.paths); if (!it) throw new ResearchInputError(`"${article}" has no iteration i${n} to continue`); if (it.kind !== "research") throw new ResearchInputError(`a sweep with "iteration" continues a research run; "${article}" i${n} is a ${it.kind} iteration`); if (it.status !== "done") throw new ResearchInputError(`"${article}" i${n} is ${it.status}: only a done research run is continued`); const state = (await readResearchState(article, n, o.paths)) ?? null; if (state) { const changed = await refreshProposals(state, o.jobOf ?? jobOfPaths(o.paths)); await settle(article, it, state, changed, o.paths); if (!isSettled(state) && !o.force) { const w = waitingOn(state); throw new ResearchInputError( `"${article}" i${n} still waits — ${[ w.approval.length ? `for approval: ${w.approval.join(", ")}` : "", w.jobs.length ? `on job(s): ${w.jobs.join(", ")}` : "", ] .filter(Boolean) .join("; ")}. Settle them (research-approve), or continue with "force": true over what is done so far`, ); } } const question = (o.question ?? it.question ?? "").trim(); if (!question) throw new ResearchInputError(`"${article}" i${n} has no question to continue with: give one`); const channels = o.channels ?? widenedChannels(it.scope?.channels ?? [], state ?? { proposals: [] }); if (!channels.length) throw new ResearchInputError(`"${article}" i${n} names no channel and acquired into none: give "channels"`); const from = o.from ?? it.scope?.from; const to = o.to ?? it.scope?.to; return { research: it, question, channels, ...(from ? { from } : {}), ...(to ? { to } : {}), lastAcquired: state ? lastAcquiredAt(state) : null, }; }); } // Record that sweep `by` continues research run `n`. export async function markContinued(article: string, n: number, by: number, paths: StorePaths): Promise { await serial(`${article}/${n}`, () => updateIteration( article, n, (cur) => { const rec = recordOf(cur) ?? { autonomy: "propose" as const, phase: "ready" as const }; return { research: { ...rec, phase: "continued", continuedBy: [...(rec.continuedBy ?? []), by] } }; }, paths, ), ); }