// A RESEARCH RUN'S STATE (release 27 S11): its acquisitions, in the // iteration's proposals.json, and the phase the run is in. // // discover the run's job is reading the corpus, the web and archive.org, // and proposing (and, as its autonomy allows, enqueueing) // wait the job has ended; an acquisition waits for the operator's yes // or no, or an enqueued one's editor job has not ended // ready nothing is pending: every acquisition is done, failed or // rejected — the run may continue // continued a sweep iteration continues it (its `continuedBy`) // // A run is RESUMABLE: nothing waits in a process. Whoever reads it next (the // research-approve action, a continuation, the umtool queue through that // action) refreshes the enqueued acquisitions from their jobs' states, and // the phase follows. // // Pure, but for the iteration store's read and write (proposals.json goes // through writeIterationFile: the registry's lock, validated, atomic). import { readIterationFile, writeIterationFile } from "../../iterations"; import type { StorePaths } from "../tasks/types"; import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, NOTHING_SPENT, PROPOSAL_STATUSES, type Autonomy, type Proposal, type ResearchLimits, type Spent, } from "./decide"; import type { ResearchLedger } from "./tools"; export const RESEARCH_FORMAT = "archilyzer-research-proposals"; export const RESEARCH_PHASES = ["discover", "wait", "ready", "continued"] as const; export type ResearchPhase = (typeof RESEARCH_PHASES)[number]; // proposals.json. export type ResearchState = ResearchLedger & { format: typeof RESEARCH_FORMAT; version: 1; autonomy: Autonomy; limits: ResearchLimits; }; // What the iteration.json of a research run carries beside its usual keys. export type ResearchRecord = { autonomy: Autonomy; phase: ResearchPhase; // The sweep iterations that continue it. 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 { return { format: RESEARCH_FORMAT, version: 1, autonomy, limits: { ...limits }, proposals: [], spent: { ...NOTHING_SPENT } }; } const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0); // proposals.json, read leniently (a hand-made or older file keeps what it can). export function parseResearchState(raw: unknown): ResearchState { const r = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : {}; const list = Array.isArray(raw) ? raw : Array.isArray(r.proposals) ? r.proposals : []; const autonomy = (AUTONOMIES as readonly string[]).includes(String(r.autonomy)) ? (r.autonomy as Autonomy) : "propose"; const l = r.limits && typeof r.limits === "object" ? (r.limits as Record) : {}; const limits: ResearchLimits = { maxItemsPerRun: typeof l.maxItemsPerRun === "number" ? l.maxItemsPerRun : DEFAULT_RESEARCH_LIMITS.maxItemsPerRun, maxGbPerRun: typeof l.maxGbPerRun === "number" ? l.maxGbPerRun : DEFAULT_RESEARCH_LIMITS.maxGbPerRun, maxTranscribeHours: typeof l.maxTranscribeHours === "number" ? l.maxTranscribeHours : DEFAULT_RESEARCH_LIMITS.maxTranscribeHours, newChannelsNeedApproval: typeof l.newChannelsNeedApproval === "boolean" ? l.newChannelsNeedApproval : true, postWalksNeedApproval: typeof l.postWalksNeedApproval === "boolean" ? l.postWalksNeedApproval : true, }; const s = r.spent && typeof r.spent === "object" ? (r.spent as Record) : {}; const spent: Spent = { items: num(s.items), gb: num(s.gb), transcribeHours: num(s.transcribeHours) }; const proposals = (list as unknown[]).filter( (p): p is Proposal => !!p && typeof p === "object" && typeof (p as Proposal).id === "string" && typeof (p as Proposal).action === "string" && (PROPOSAL_STATUSES as readonly string[]).includes((p as Proposal).status), ); for (const p of proposals) { if (!p.args || typeof p.args !== "object") p.args = {}; if (!Array.isArray(p.evidence)) p.evidence = []; if (typeof p.reason !== "string") p.reason = ""; } return { format: RESEARCH_FORMAT, version: 1, autonomy, limits, proposals, spent }; } export async function readResearchState(article: string, n: number, paths?: StorePaths): Promise { const text = await readIterationFile(article, n, "proposals.json", paths); if (text === null) return null; try { return parseResearchState(JSON.parse(text)); } catch { return null; } } export async function writeResearchState(article: string, n: number, state: ResearchState, paths?: StorePaths): Promise { await writeIterationFile( article, n, "proposals.json", { format: RESEARCH_FORMAT, version: 1, autonomy: state.autonomy, limits: state.limits, spent: state.spent, proposals: state.proposals, }, paths, ); } // ─── jobs ─── // One editor job as the refresh needs it (common/jobs/listJobs getJobEntry). // `via`: the job that answered, when the one asked handed its work on to it // (researchRuns.ts jobOfPaths). export type JobState = { status: string; endedAt?: number; via?: string }; export type JobOf = (id: string) => Promise; export const jobIdsOf = (p: Pick): string[] => (p.jobId ?? "") .split(",") .map((s) => s.trim()) .filter(Boolean); // Settle the enqueued acquisitions whose jobs have ended: every job done → // `done`; any failed, cancelled or lost → `failed`, saying which. A job still // queued or running leaves it enqueued. Answers whether anything changed. export async function refreshProposals(state: Pick, jobOf: JobOf): Promise { let changed = false; for (const p of state.proposals) { if (p.status !== "enqueued") continue; const ids = jobIdsOf(p); if (!ids.length) continue; const jobs = await Promise.all(ids.map(async (id) => ({ id, job: await jobOf(id).catch(() => null) }))); const pending = jobs.filter((j) => j.job && (j.job.status === "queued" || j.job.status === "running")); if (pending.length) continue; const bad = jobs.filter((j) => !j.job || j.job.status !== "done"); if (bad.length) { p.status = "failed"; p.note = bad .map((j) => !j.job ? `job ${j.id} is not known to the editor` : j.job.status === "archived" ? `job ${j.id} was lost (the editor restarted)` : `job ${j.id} ended ${j.job.status}`, ) .join("; "); } else { p.status = "done"; const ended = Math.max(...jobs.map((j) => j.job?.endedAt ?? 0)); p.doneAt = new Date(ended || Date.now()).toISOString(); delete p.note; } changed = true; } return changed; } // ─── the phase ─── export type ResearchCounts = Record; export function countProposals(state: Pick): ResearchCounts { const c = Object.fromEntries(PROPOSAL_STATUSES.map((s) => [s, 0])) as ResearchCounts; for (const p of state.proposals) c[p.status]++; return c; } // What a finished run waits on: the proposals awaiting a yes or no, and the // editor jobs not yet ended. export function waitingOn(state: Pick): { approval: string[]; jobs: string[] } { return { approval: state.proposals.filter((p) => p.status === "proposed" || p.status === "approved").map((p) => p.id), jobs: state.proposals.filter((p) => p.status === "enqueued").flatMap(jobIdsOf), }; } export function isSettled(state: Pick): boolean { const w = waitingOn(state); return !w.approval.length && !state.proposals.some((p) => p.status === "enqueued"); } // The phase of a run whose job has ended (`continued` once a sweep took it). export function phaseOf(state: Pick, continued = false): ResearchPhase { if (continued) return "continued"; return isSettled(state) ? "ready" : "wait"; } // ─── the continuation's scope ─── // The channels a continuation sweeps: the run's own, and every channel a done // acquisition wrote into (a created channel, an import's, a post's, a // persisted item's) — in that order, each once. export function widenedChannels(scope: readonly string[], state: Pick): string[] { const out = [...scope]; const add = (s: unknown) => { if (typeof s === "string" && s && !out.includes(s)) out.push(s); }; for (const p of state.proposals) { if (p.status !== "done") continue; if (p.action === "priority-bump") continue; add(p.channel); add(p.args.slug); if (p.action === "persist-videos" && Array.isArray(p.args.items)) { for (const it of p.args.items as { slug?: unknown }[]) add(it?.slug); } } return out; } // The newest time an acquisition finished (ms), for "is the build older". export function lastAcquiredAt(state: Pick): number | null { const t = state.proposals .filter((p) => p.status === "done" && p.doneAt && p.action !== "priority-bump") .map((p) => Date.parse(p.doneAt!)) .filter(Number.isFinite); return t.length ? Math.max(...t) : null; }