commit 2dca633de4d7ab0f7ea9f112ded06c6f184fb4cf
parent 289320c7cf669cc0c3de1ca0c322fc2eb7662478
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 13:54:45 -0400
umtool, common: release 27 S11 — the research queue in the Iterations tab, the autonomy selector on /articles/new
- ResearchSlot: a research iteration's acquisitions (reason, evidence links,
estimate, note), yes or no per waiting one (the editor's research-approve),
each enqueued one's job followed live, the run's spend against its limits,
the agent's closing notes, and Continue into a sweep (report-draft
{task: "sweep", iteration: n}) once nothing is pending.
- /api/articles/research and lib/articles/research.ts: the queue through
the editor's research-approve (GET = the run refreshed; POST = yes/no).
- /articles/new: start with a sweep or with research; research takes an
autonomy (default the settings'), channels optional, the run's limits shown.
- researchRuns: a read while the run's job is going writes nothing; the
view carries the agent's notes.
- e2e: article-research.spec.ts; the editor stub gains research runs,
research-approve, acquisition jobs and the continuation.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 782 insertions(+), 38 deletions(-)
diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts
@@ -87,7 +87,9 @@ async function readRun(article: string, n: number, paths: StorePaths): Promise<{
// 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<ResearchPhase> {
- if (changed) await writeResearchState(article, it.n, state, paths);
+ // 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) {
@@ -107,6 +109,8 @@ export type ResearchView = {
proposals: Proposal[];
waitingOn: { approval: string[]; jobs: string[] };
continuedBy: number[];
+ // The agent's closing words: what the archive holds, what it asked for.
+ notes?: string;
};
function viewOf(article: string, it: Iteration, state: ResearchState, phase: ResearchPhase): ResearchView {
@@ -121,6 +125,7 @@ function viewOf(article: string, it: Iteration, state: ResearchState, phase: Res
proposals: state.proposals,
waitingOn: waitingOn(state),
continuedBy: recordOf(it)?.continuedBy ?? [],
+ ...(recordOf(it)?.notes ? { notes: recordOf(it)!.notes } : {}),
};
}
diff --git a/umtool/app/api/articles/generate/route.ts b/umtool/app/api/articles/generate/route.ts
@@ -4,13 +4,16 @@ export const dynamic = "force-dynamic";
// START A GENERATION (release 27 S8): the body is `pnpm ops report-draft`'s —
// { task, article, iteration?, model?, feedback?, question?, channels?, from?,
-// to?, copyOf?, maxUsd?, cards?, force? } — forwarded to the editor, which
+// to?, copyOf?, maxUsd?, cards?, force?, autonomy? } — forwarded to the editor, which
// creates the iteration and runs the job. Answers { ok, jobId, iteration }.
//
// a new article task sweep, question, channels (from, to)
// a new iteration task revise-report | revise-video, iteration, feedback
// copy with model the iteration's task, copyOf, model
// narration task narrate, iteration, model (a step)
+// research task research, question, channels?, model, autonomy
+// (release 27 S11: its queue is /api/articles/research)
+// continue research task sweep, iteration (the research run), model
export async function POST(request: Request) {
try {
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
diff --git a/umtool/app/api/articles/research/route.ts b/umtool/app/api/articles/research/route.ts
@@ -0,0 +1,46 @@
+import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
+import { errorResponse } from "@/lib/articles/generation";
+import { readResearch, settleResearch } from "@/lib/articles/research";
+
+export const dynamic = "force-dynamic";
+
+// A RESEARCH RUN'S QUEUE (release 27 S11), through the editor's
+// `research-approve`:
+//
+// GET ?article=<id>&n=<n> -> { research }: its proposals and phase, the
+// enqueued ones refreshed from their jobs
+// POST { article, n, ids, approve, note? }
+// -> { research, outcomes }: yes runs each
+// proposal through the editor's own action;
+// no rejects it (note: why)
+// The continuation is /api/articles/generate { task: "sweep", iteration: n }.
+const bad = (error: string) => Response.json({ error }, { status: 400 });
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const article = url.searchParams.get("article") ?? "";
+ const n = Number(url.searchParams.get("n"));
+ if (!isReportId(article)) return bad(`"${article}" is not an article id`);
+ if (!Number.isInteger(n) || n < 1) return bad("n is an iteration number");
+ try {
+ return Response.json({ research: await readResearch(article, n) }, { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
+
+export async function POST(request: Request) {
+ const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; ids?: unknown; approve?: unknown; note?: unknown };
+ const article = String(body.article ?? "");
+ const n = Number(body.n);
+ if (!isReportId(article)) return bad(`"${article}" is not an article id`);
+ if (!Number.isInteger(n) || n < 1) return bad("n is an iteration number");
+ if (!Array.isArray(body.ids) || !body.ids.every((x) => typeof x === "string")) return bad("ids is a list of proposal ids");
+ if (typeof body.approve !== "boolean") return bad("approve is true or false");
+ try {
+ const out = await settleResearch(article, n, body.ids as string[], body.approve, typeof body.note === "string" ? body.note : undefined);
+ return Response.json({ ok: true, ...out }, { headers: { "cache-control": "no-store" } });
+ } catch (err) {
+ return errorResponse(err);
+ }
+}
diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx
@@ -297,7 +297,15 @@ function IterationCard({
{active && it.jobId && <JobProgress jobId={it.jobId} label={it.label} onEnd={ctx.refresh} />}
{runningStep?.jobId && <JobProgress jobId={runningStep.jobId} label={`${it.label} ${runningStep.task}`} onEnd={ctx.refresh} />}
- {it.kind === "research" && <ResearchSlot article={ctx.article} iteration={it} />}
+ {it.kind === "research" && (
+ <ResearchSlot
+ article={ctx.article}
+ iteration={it}
+ post={ctx.post}
+ models={ctx.allModels}
+ sweepModel={g?.routes.sweep === "local" ? g.models.local : (g?.models.api ?? "")}
+ />
+ )}
<div className="mt-2 flex flex-wrap items-center gap-2">
{done && it.reportFrom !== null && !it.currentReport && (
diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx
@@ -10,12 +10,25 @@ import type { EditorChannel, PolicyView } from "@/lib/articles/generation";
// first iteration — a `report-draft` sweep the editor runs and writes. The
// sweep is the agent on a Claude model, or the code-driven pipeline on the
// local model; the cap starts at the policy's per-job default and goes down.
+//
+// Or it starts with RESEARCH (release 27 S11): a run that finds what the
+// archive lacks for the question and proposes acquisitions, under the
+// autonomy chosen here (propose, limits, auto); its queue is on the article's
+// Iterations tab, and a sweep continues it from there.
const field =
"rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] text-[var(--color-text)] focus-visible:border-[var(--color-sel)] focus-visible:outline-none";
const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
type Task = "agent" | "pipeline";
+type Start = "sweep" | "research";
+type Autonomy = "propose" | "limits" | "auto";
+
+const AUTONOMY_SAYS: Record<Autonomy, string> = {
+ propose: "every acquisition waits for your yes or no",
+ limits: "imports into existing channels under the caps run; the rest waits",
+ auto: "everything runs through the editor until a cap; past it, it waits",
+};
function ChannelPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
const [all, setAll] = useState<EditorChannel[] | null>(null);
@@ -93,9 +106,19 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
const onPolicy = useCallback((p: PolicyView) => setPolicy(p), []);
const defaultTask: Task = policy?.generation.routes.sweep === "local" ? "pipeline" : "agent";
const [task, setTask] = useState<Task>(defaultTask);
- const models = task === "agent" ? (policy?.models.api ?? []) : (policy?.models.local ?? []);
- const routeModel = task === "agent" ? policy?.generation.models.api : policy?.generation.models.local;
+ const [begin, setBegin] = useState<Start>("sweep");
+ const [autonomy, setAutonomy] = useState<Autonomy>(policy?.generation.research?.autonomy ?? "propose");
+ const researchModel = policy?.generation.routes.research === "local" ? policy.generation.models.local : policy?.generation.models.api;
+ const models =
+ begin === "research"
+ ? [...(policy?.models.api ?? []), ...(policy?.models.local ?? [])]
+ : task === "agent"
+ ? (policy?.models.api ?? [])
+ : (policy?.models.local ?? []);
+ const routeModel = begin === "research" ? researchModel : task === "agent" ? policy?.generation.models.api : policy?.generation.models.local;
const [model, setModel] = useState(routeModel ?? "");
+ // A cap is a Claude run's: the agent, or research on a Claude model.
+ const capped = begin === "research" ? model.startsWith("claude-") : task === "agent";
const capDefault = policy?.generation.caps.sweep ?? 5;
const [cap, setCap] = useState(String(capDefault));
const [id, setId] = useState("");
@@ -107,8 +130,9 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
const [sending, setSending] = useState(false);
useEffect(() => {
- setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? ""));
- }, [task, policy]);
+ if (begin === "research") setModel(researchModel ?? "");
+ else setModel(task === "agent" ? (policy?.generation.models.api ?? "") : (policy?.generation.models.local ?? ""));
+ }, [task, begin, policy, researchModel]);
const idProblem = !id ? null : !ID_RE.test(id) ? "a lowercase slug: a-z, 0-9 and -" : taken.includes(id) ? "an article by that id exists — add an iteration on its page" : null;
@@ -116,22 +140,23 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
e.preventDefault();
setError("");
if (idProblem) return setError(`article id: ${idProblem}`);
- if (!channels.length) return setError("pick at least one channel");
+ if (begin === "sweep" && !channels.length) return setError("pick at least one channel");
const maxUsd = Number(cap);
- if (task === "agent" && !(maxUsd > 0 && maxUsd <= capDefault)) return setError(`the cap is above $0 and at most the policy's $${capDefault}`);
+ if (capped && !(maxUsd > 0 && maxUsd <= capDefault)) return setError(`the cap is above $0 and at most the policy's $${capDefault}`);
setSending(true);
try {
const r = await fetch("/api/articles/generate", {
method: "POST",
body: JSON.stringify({
- task: "sweep",
+ task: begin,
article: id,
question,
- channels,
+ ...(channels.length ? { channels } : {}),
model,
...(from ? { from } : {}),
...(to ? { to } : {}),
- ...(task === "agent" ? { maxUsd } : {}),
+ ...(capped ? { maxUsd } : {}),
+ ...(begin === "research" ? { autonomy } : {}),
}),
});
const b = await r.json();
@@ -159,8 +184,22 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
<textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" />
</label>
+ <fieldset className="flex flex-col gap-1" aria-label="start with">
+ <legend className="micro mb-1">start with</legend>
+ <div className="flex gap-3 text-[12px]">
+ <label className="flex items-center gap-1">
+ <input type="radio" name="start" checked={begin === "sweep"} onChange={() => setBegin("sweep")} />
+ a sweep <span className="text-[var(--color-dim)]">(read the archive)</span>
+ </label>
+ <label className="flex items-center gap-1">
+ <input type="radio" name="start" checked={begin === "research"} onChange={() => setBegin("research")} />
+ research <span className="text-[var(--color-dim)]">(find what the archive lacks first)</span>
+ </label>
+ </div>
+ </fieldset>
+
<div className="flex flex-col gap-1">
- <span className="micro">channels</span>
+ <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span>
<ChannelPicker value={channels} onChange={setChannels} />
</div>
@@ -188,19 +227,33 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
{idProblem && <p className="text-[12px] text-[var(--color-dirty)]">article id: {idProblem}</p>}
<div className="flex flex-wrap items-end gap-4">
- <fieldset className="flex flex-col gap-1">
- <legend className="micro mb-1">sweep</legend>
- <div className="flex gap-3 text-[12px]">
- <label className="flex items-center gap-1">
- <input type="radio" name="task" checked={task === "agent"} onChange={() => setTask("agent")} />
- agent <span className="text-[var(--color-dim)]">(Claude)</span>
- </label>
- <label className="flex items-center gap-1">
- <input type="radio" name="task" checked={task === "pipeline"} onChange={() => setTask("pipeline")} />
- pipeline <span className="text-[var(--color-dim)]">(local)</span>
- </label>
- </div>
- </fieldset>
+ {begin === "research" && (
+ <label className="flex flex-col gap-1">
+ <span className="micro">autonomy</span>
+ <select className={field} aria-label="autonomy" value={autonomy} onChange={(e) => setAutonomy(e.target.value as Autonomy)}>
+ {(["propose", "limits", "auto"] as const).map((a) => (
+ <option key={a} value={a}>
+ {a} — {AUTONOMY_SAYS[a]}
+ </option>
+ ))}
+ </select>
+ </label>
+ )}
+ {begin === "sweep" && (
+ <fieldset className="flex flex-col gap-1">
+ <legend className="micro mb-1">sweep</legend>
+ <div className="flex gap-3 text-[12px]">
+ <label className="flex items-center gap-1">
+ <input type="radio" name="task" checked={task === "agent"} onChange={() => setTask("agent")} />
+ agent <span className="text-[var(--color-dim)]">(Claude)</span>
+ </label>
+ <label className="flex items-center gap-1">
+ <input type="radio" name="task" checked={task === "pipeline"} onChange={() => setTask("pipeline")} />
+ pipeline <span className="text-[var(--color-dim)]">(local)</span>
+ </label>
+ </div>
+ </fieldset>
+ )}
<label className="flex flex-col gap-1">
<span className="micro">model</span>
<select className={`${field} font-mono`} aria-label="model" value={model} onChange={(e) => setModel(e.target.value)}>
@@ -211,7 +264,7 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
))}
</select>
</label>
- {task === "agent" && (
+ {capped && (
<label className="flex flex-col gap-1">
<span className="micro">cap $</span>
<input
@@ -228,7 +281,13 @@ export default function NewArticleForm({ initialPolicy, today, taken }: { initia
{sending ? "Starting…" : "Start"}
</Button>
</div>
- {task === "agent" && policy && !policy.keyFile.exists && (
+ {begin === "research" && policy && (
+ <p className="text-[12px] text-[var(--color-dim)]" data-research-limits>
+ Limits a run: {policy.generation.research.maxItemsPerRun} items, {policy.generation.research.maxGbPerRun} GB,{" "}
+ {policy.generation.research.maxTranscribeHours} h of transcription. A new channel is created on no site.
+ </p>
+ )}
+ {capped && policy && !policy.keyFile.exists && (
<p className="text-[12px] text-[var(--color-dirty)]">
No key file at <code className="font-mono">{policy.keyFile.path}</code>; the editor needs ANTHROPIC_API_KEY in its environment.
</p>
diff --git a/umtool/components/articles/ResearchSlot.tsx b/umtool/components/articles/ResearchSlot.tsx
@@ -1,18 +1,304 @@
"use client";
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { badgeVariants } from "@/components/ui/badge";
import type { IterationRow } from "@/lib/articles/generation";
+import type { ResearchProposal, ResearchView } from "@/lib/articles/research";
-// THE RESEARCH QUEUE's place in an iteration of kind `research` (release 27
-// S11 fills it: the proposals, yes/no per item, the acquisition jobs, and
-// continue). Until then it names the run's phase by its status.
-export default function ResearchSlot({ article, iteration }: { article: string; iteration: IterationRow }) {
+// THE RESEARCH QUEUE of an iteration of kind `research` (release 27 S11): each
+// acquisition the run proposed, with its reason, its evidence and its
+// estimate; a yes or no for each that waits (the editor runs a yes through its
+// own action, past the run's autonomy and caps, never past a standing rule);
+// the live state of each enqueued one's editor job; and, once nothing is
+// pending, Continue — a sweep over the run's channels and every channel it
+// acquired into (`report-draft {task: "sweep", iteration: n}`).
+//
+// The run is read through the editor's research-approve (umtool's
+// /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.
+
+const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]";
+
+const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neutral" | "meter"> = {
+ proposed: "open",
+ approved: "open",
+ enqueued: "meter",
+ done: "on",
+ failed: "blocking",
+ rejected: "info",
+};
+
+const PHASE_SAYS: Record<ResearchView["phase"], string> = {
+ discover: "discovering",
+ wait: "waiting",
+ ready: "ready to continue",
+ continued: "continued",
+};
+
+// What an acquisition is for, in one line: its channel and what it fetches.
+function target(p: ResearchProposal): string {
+ const a = p.args;
+ const s = (k: string) => (typeof a[k] === "string" && a[k] ? (a[k] as string) : null);
+ const parts: string[] = [];
+ if (p.action === "create-channel") {
+ const f = (a.fields ?? {}) as Record<string, unknown>;
+ if (typeof f.name === "string") parts.push(f.name);
+ if (typeof f.url === "string") parts.push(f.url);
+ }
+ if (s("slug")) parts.push(s("slug")!);
+ if (s("item")) parts.push(s("item")!);
+ if (Array.isArray(a.files)) parts.push((a.files as unknown[]).map(String).join(", "));
+ if (s("match")) parts.push(`/${s("match")}/`);
+ if (s("url")) parts.push(s("url")!);
+ if (s("id")) parts.push(s("id")!);
+ if (Array.isArray(a.ids)) parts.push(`${(a.ids as unknown[]).length} post(s)`);
+ if (Array.isArray(a.items)) parts.push(`${(a.items as unknown[]).length} item(s)`);
+ if (a.older === true) parts.push("older walk");
+ if (a.full === true) parts.push("full walk");
+ return parts.join(" · ");
+}
+
+function estimateOf(p: ResearchProposal): string {
+ const e = p.estimate;
+ if (!e) return "";
+ return [e.items !== undefined && `${e.items} item(s)`, e.gb !== undefined && `${e.gb} GB`, e.transcribeHours !== undefined && `${e.transcribeHours} h`]
+ .filter(Boolean)
+ .join(", ");
+}
+
+/** One editor job's status, read while it goes. */
+function JobState({ id }: { id: string }) {
+ const [status, setStatus] = useState("asking…");
+ useEffect(() => {
+ let alive = true;
+ let t: ReturnType<typeof setInterval> | null = null;
+ const tick = async () => {
+ try {
+ const r = await fetch(`/api/articles/job?id=${encodeURIComponent(id)}&tail=1`, { cache: "no-store" });
+ const b = await r.json();
+ if (!alive) return;
+ const s = r.ok ? String(b.job?.status ?? "unknown") : String(b.error ?? `HTTP ${r.status}`);
+ setStatus(s);
+ if (r.ok && ["done", "failed", "cancelled", "archived"].includes(s) && t) clearInterval(t);
+ } catch (e) {
+ if (alive) setStatus((e as Error).message);
+ }
+ };
+ void tick();
+ t = setInterval(tick, 4000);
+ return () => {
+ alive = false;
+ if (t) clearInterval(t);
+ };
+ }, [id]);
+ return (
+ <span className="font-mono text-[11px]" data-acq-job={id} data-acq-job-status={status}>
+ {id} <span className="text-[var(--color-dirty)]">{status}</span>
+ </span>
+ );
+}
+
+function ProposalRow({
+ p,
+ canDecide,
+ busy,
+ decide,
+}: {
+ p: ResearchProposal;
+ canDecide: boolean;
+ busy: boolean;
+ decide: (id: string, approve: boolean, note?: string) => void;
+}) {
+ const [why, setWhy] = useState("");
+ const waits = p.status === "proposed" || p.status === "approved";
+ const est = estimateOf(p);
+ return (
+ <li
+ data-proposal={p.id}
+ data-proposal-status={p.status}
+ className="flex flex-col gap-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2"
+ >
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <span className="font-mono text-[12px] text-[var(--color-dim)]">{p.id}</span>
+ <span className="font-mono text-[12px] text-[var(--color-text)]">{p.action}</span>
+ <span className="text-[12px]">{target(p)}</span>
+ {est && <span className="num text-[11px] text-[var(--color-dim)]">({est})</span>}
+ <span className={`${badgeVariants({ variant: STATUS_VARIANT[p.status] ?? "neutral", size: "sm" })} ml-auto`}>{p.status}</span>
+ </div>
+ {p.reason && <p className="text-[13px]">{p.reason}</p>}
+ {p.evidence.length > 0 && (
+ <ul className="flex flex-wrap gap-x-3 text-[11px]" aria-label={`${p.id} evidence`}>
+ {p.evidence.map((href) => (
+ <li key={href}>
+ <a href={href} target="_blank" rel="noreferrer noopener" className="break-all text-[var(--color-sel)] hover:underline">
+ {href}
+ </a>
+ </li>
+ ))}
+ </ul>
+ )}
+ {p.note && (
+ <p data-proposal-note className={`text-[12px] ${p.status === "failed" ? "text-[var(--color-bad)]" : "text-[var(--color-dirty)]"}`}>
+ {p.note}
+ </p>
+ )}
+ {p.status === "enqueued" && p.jobId && (
+ <div className="flex flex-wrap gap-3">
+ {p.jobId
+ .split(",")
+ .filter(Boolean)
+ .map((id) => (
+ <JobState key={id} id={id} />
+ ))}
+ </div>
+ )}
+ {p.status === "done" && p.channel && <p className="font-mono text-[11px] text-[var(--color-dim)]">channel {p.channel}</p>}
+ {waits && canDecide && (
+ <div className="flex flex-wrap items-center gap-2">
+ <Button size="sm" variant="primary" disabled={busy} aria-label={`Yes to ${p.id}`} onClick={() => decide(p.id, true)}>
+ Yes
+ </Button>
+ <Button size="sm" variant="destructive" disabled={busy} aria-label={`No to ${p.id}`} onClick={() => decide(p.id, false, why)}>
+ No
+ </Button>
+ <input aria-label={`why not ${p.id}`} className={`${field} w-64`} placeholder="why not (optional)" value={why} onChange={(e) => setWhy(e.target.value)} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+export default function ResearchSlot({
+ article,
+ iteration,
+ post,
+ models,
+ sweepModel,
+}: {
+ article: string;
+ iteration: IterationRow;
+ /** Start a report-draft job (the continuation). */
+ post: (body: Record<string, unknown>) => Promise<boolean>;
+ models: string[];
+ /** The sweep route's model, the continuation's default. */
+ sweepModel: string;
+}) {
+ const n = iteration.n;
+ const [view, setView] = useState<ResearchView | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [model, setModel] = useState(sweepModel);
+ const active = iteration.status === "queued" || iteration.status === "running";
+
+ const load = useCallback(async () => {
+ try {
+ const r = await fetch(`/api/articles/research?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" });
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setView(b.research);
+ setError("");
+ } catch (e) {
+ setError((e as Error).message);
+ }
+ }, [article, n]);
+
+ // Read when the iteration's status moves (a queued run has nothing yet);
+ // re-read while its job or an acquisition's is going.
+ useEffect(() => {
+ if (iteration.status === "queued") return;
+ void load();
+ }, [load, iteration.status]);
+ const going = active || (view?.waitingOn.jobs.length ?? 0) > 0;
+ useEffect(() => {
+ if (!going) return;
+ const t = setInterval(() => void load(), 4000);
+ return () => clearInterval(t);
+ }, [going, load]);
+
+ const decide = useCallback(
+ async (id: string, approve: boolean, note?: string) => {
+ setBusy(true);
+ setError("");
+ try {
+ const r = await fetch("/api/articles/research", {
+ method: "POST",
+ body: JSON.stringify({ article, n, ids: [id], approve, ...(note?.trim() ? { note } : {}) }),
+ });
+ const b = await r.json();
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setView(b.research);
+ const failed = (b.outcomes as { id: string; error?: string }[]).find((o) => o.error);
+ if (failed) setError(`${failed.id}: ${failed.error}`);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ },
+ [article, n],
+ );
+
+ const canContinue = iteration.status === "done" && (view?.phase === "ready" || view?.phase === "continued");
return (
<section
aria-label={`${iteration.label} research`}
- data-research-slot={`${article}/${iteration.n}`}
- className="mt-2 rounded border border-dashed border-[var(--color-line)] p-2 text-[12px] text-[var(--color-dim)]"
+ data-research-slot={`${article}/${n}`}
+ data-research-phase={view?.phase ?? (active ? "discover" : "")}
+ className="mt-2 flex flex-col gap-2 rounded border border-dashed border-[var(--color-line)] p-2 text-[12px]"
>
- <span className="micro">research</span> {iteration.status}
+ <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-[var(--color-dim)]">
+ <span>
+ <span className="micro">research</span> {view ? PHASE_SAYS[view.phase] : active ? "discovering" : iteration.status}
+ </span>
+ {view && (
+ <>
+ <span data-research-autonomy={view.autonomy}>autonomy {view.autonomy}</span>
+ <span className="num" data-research-spent={`${view.spent.items}/${view.spent.gb}/${view.spent.transcribeHours}`}>
+ {view.spent.items} of {view.limits.maxItemsPerRun} items · {view.spent.gb.toFixed(1)} of {view.limits.maxGbPerRun} GB ·{" "}
+ {view.spent.transcribeHours.toFixed(1)} of {view.limits.maxTranscribeHours} h
+ </span>
+ {view.waitingOn.approval.length > 0 && <span className="text-[var(--color-dirty)]">{view.waitingOn.approval.length} waiting for you</span>}
+ {view.continuedBy.length > 0 && (
+ <span data-continued-by={view.continuedBy.join(",")}>continued by {view.continuedBy.map((c) => `i${c}`).join(", ")}</span>
+ )}
+ </>
+ )}
+ </div>
+ {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 && (
+ <ol className="flex flex-col gap-1.5" aria-label={`${iteration.label} acquisitions`}>
+ {view.proposals.map((p) => (
+ <ProposalRow key={p.id} p={p} canDecide={!active} busy={busy} decide={decide} />
+ ))}
+ </ol>
+ )}
+ {canContinue && (
+ <div className="flex flex-wrap items-center gap-2">
+ <select
+ aria-label={`continuation model for ${iteration.label}`}
+ className={`${field} font-mono`}
+ value={model}
+ onChange={(e) => setModel(e.target.value)}
+ >
+ {[...new Set([model, ...models].filter(Boolean))].map((m) => (
+ <option key={m} value={m}>
+ {m}
+ </option>
+ ))}
+ </select>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void post({ task: "sweep", article, iteration: n, model })}>
+ Continue into a sweep
+ </Button>
+ </div>
+ )}
+ {error && (
+ <p role="alert" className="text-[var(--color-bad)]">
+ {error}
+ </p>
+ )}
</section>
);
}
diff --git a/umtool/e2e/article-research.spec.ts b/umtool/e2e/article-research.spec.ts
@@ -0,0 +1,120 @@
+import { test, expect } from "@playwright/test";
+import { readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Research runs (release 27 S11) over the editor stub: /articles/new starts an
+// article with RESEARCH under a chosen autonomy; its Iterations tab shows the
+// run's queue — each acquisition with its reason, evidence and note, a yes or
+// no for each that waits, the live state of an approved one's job — and, once
+// nothing is pending, Continue into a sweep whose parent is the run.
+//
+// WRITES articles/research-e2e/ (through the stub; removed after)
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const ARTICLE = "research-e2e";
+const stubAsked = (route: string) =>
+ (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === route);
+
+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 }));
+
+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);
+ await page.goto("/articles/new");
+ const form = page.getByRole("form", { name: "new article" });
+ await form.getByRole("radio", { name: /^research/ }).check();
+ // The settings' default autonomy, and the run's limits, before anything is sent.
+ const autonomy = form.getByRole("combobox", { name: "autonomy" });
+ await expect(autonomy).toHaveValue("propose");
+ await expect(form.locator("[data-research-limits]")).toContainText("20 items, 5 GB, 6 h of transcription");
+ await expect(form.getByRole("combobox", { name: "model" })).toHaveValue("claude-sonnet-5-5");
+ await autonomy.selectOption("limits");
+ await form.getByRole("textbox", { name: "question" }).fill("Where did the vote story start?");
+ // No channel needed: research finds who and where.
+ await form.getByRole("textbox", { name: "article id" }).fill(ARTICLE);
+ await form.getByRole("button", { name: "Start" }).click();
+
+ await expect(page).toHaveURL(new RegExp(`/articles/${ARTICLE}\\?tab=iterations$`));
+ const started = stubAsked("report-draft").at(-1)!;
+ expect(started).toMatchObject({ task: "research", article: ARTICLE, question: "Where did the vote story start?", model: "claude-sonnet-5-5", autonomy: "limits", maxUsd: 5 });
+ expect(started).not.toHaveProperty("channels");
+
+ const run = page.locator("[data-iteration='1']");
+ await expect(run).toHaveAttribute("data-kind", "research");
+ await expect(run).toHaveAttribute("data-status", "done", { timeout: 20_000 });
+ const slot = run.getByRole("region", { name: "i1 research" });
+ await expect(slot).toHaveAttribute("data-research-phase", "wait");
+ await expect(slot.locator("[data-research-autonomy]")).toHaveAttribute("data-research-autonomy", "limits");
+ await expect(slot).toContainText("The archive holds one stream on it.");
+
+ // Each acquisition: what, why, the evidence, and why it waits or was refused.
+ const p01 = slot.locator("[data-proposal='p01']");
+ const p02 = slot.locator("[data-proposal='p02']");
+ const p03 = slot.locator("[data-proposal='p03']");
+ await expect(p01).toHaveAttribute("data-proposal-status", "proposed");
+ await expect(p01).toContainText("import-archive-org");
+ await expect(p01).toContainText("sitechan · site-channel-episodes · Vote day.mp4");
+ await expect(p01).toContainText("The vote-day episode, where the claim is first made");
+ await expect(p01.getByRole("link", { name: "https://archive.org/details/site-channel-episodes" })).toHaveAttribute("target", "_blank");
+ await expect(p01.locator("[data-proposal-note]")).toContainText("the operator approves each acquisition");
+ await expect(p03).toHaveAttribute("data-proposal-status", "rejected");
+ await expect(p03.locator("[data-proposal-note]")).toContainText("a Twitch VOD is never fetched again");
+ await expect(p03.getByRole("button", { name: "Yes to p03" })).toHaveCount(0);
+ // Nothing continues while it waits.
+ await expect(slot.getByRole("button", { name: "Continue into a sweep" })).toHaveCount(0);
+
+ // No to the new channel, with why.
+ await p02.getByRole("textbox", { name: "why not p02" }).fill("not this one");
+ await p02.getByRole("button", { name: "No to p02" }).click();
+ await expect(p02).toHaveAttribute("data-proposal-status", "rejected");
+ await expect(p02.locator("[data-proposal-note]")).toHaveText("the operator said no: not this one");
+ expect(stubAsked("research-approve").at(-1)).toMatchObject({
+ article: ARTICLE,
+ iteration: 1,
+ ids: ["p02"],
+ approve: false,
+ note: "not this one",
+ authorization: "Bearer umtool-e2e-token",
+ });
+
+ // Yes to the import: the editor enqueues it; its job is followed to done.
+ await p01.getByRole("button", { name: "Yes to p01" }).click();
+ await expect(p01).toHaveAttribute("data-proposal-status", "enqueued");
+ expect(stubAsked("research-approve").at(-1)).toMatchObject({ ids: ["p01"], approve: true });
+ await expect(p01.locator("[data-acq-job]")).toBeVisible();
+ await expect(slot.locator("[data-research-spent]")).toHaveAttribute("data-research-spent", "1/0.2/0");
+ await expect(p01).toHaveAttribute("data-proposal-status", "done", { timeout: 20_000 });
+ await expect(slot).toHaveAttribute("data-research-phase", "ready");
+
+ // Continue: a sweep whose parent is the run, over its widened scope.
+ await slot.getByRole("combobox", { name: "continuation model for i1" }).selectOption("qwen3:8b");
+ await slot.getByRole("button", { name: "Continue into a sweep" }).click();
+ expect(stubAsked("report-draft").at(-1)).toMatchObject({ task: "sweep", article: ARTICLE, iteration: 1, model: "qwen3:8b" });
+ const sweep = page.locator("[data-iteration='2']");
+ await expect(sweep).toHaveAttribute("data-kind", "sweep");
+ await expect(sweep).toContainText("of i1");
+ await expect(sweep).toContainText("Where did the vote story start?");
+ await expect(sweep).toContainText("sitechan");
+ await expect(sweep).toHaveAttribute("data-status", "done", { timeout: 20_000 });
+ await page.reload();
+ await expect(page.locator("[data-iteration='1']").getByRole("region", { name: "i1 research" })).toHaveAttribute("data-research-phase", "continued");
+ await expect(page.locator("[data-iteration='1'] [data-continued-by]")).toHaveAttribute("data-continued-by", "2");
+});
+
+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);
+ expect((await bad.json()).error).toContain("approve is true or false");
+ const notId = await request.post("/api/articles/research", { data: { article: ARTICLE, n: 1, ids: ["x"], approve: true } });
+ expect(notId.status()).toBe(400);
+ expect((await notId.json()).error).toContain("proposal ids");
+});
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -92,6 +92,14 @@ function writeWindow(dir, name, seconds) {
// never an LLM
// GET /api/ops/job/<id>?tail=N that job's state and log
// POST /api/ops/job {verb: cancel, ids} cancelled, its iteration too
+// POST /api/ops/research-approve a research run's queue (release 27
+// S11): its proposals refreshed from
+// the stub's acquisition jobs, then
+// approved (a job: running after 1 s,
+// done after 3 s) or rejected
+// A `research` report-draft proposes three acquisitions (an archive.org import
+// waits, a new channel waits, a Twitch VOD refused); a `sweep` with
+// `iteration` continues a research run, as the editor does.
// Sentinels: a question or feedback containing "slow" keeps running until
// cancelled; feedback "refuse" is refused (400) as the editor refuses.
const ARTICLES = process.env.ARTICLES_DIR ?? "";
@@ -169,7 +177,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 }] };
- if (it.kind === "sweep") {
+ 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." };
+ 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");
writeFileSync(path.join(itDir(article, n), "sweep.md"), `# Sweep\n\n## The claim\n\n- She said [the vote was rigged](https://priv.example/?v=sv1&t=3).\n`);
} else if (it.kind === "revise-report") {
@@ -190,6 +203,150 @@ function finishDraft(job) {
job.log.push("stub: wrote the iteration", `@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "done" })}`);
}
+// ─── research (release 27 S11) ───
+
+// 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) {
+ return {
+ format: "archilyzer-research-proposals",
+ version: 1,
+ autonomy,
+ limits: { maxItemsPerRun: 20, maxGbPerRun: 5, maxTranscribeHours: 6, newChannelsNeedApproval: true, postWalksNeedApproval: true },
+ spent: { items: 0, gb: 0, transcribeHours: 0 },
+ proposals: [
+ {
+ id: "p01",
+ action: "import-archive-org",
+ args: { slug: "sitechan", item: "site-channel-episodes", files: ["Vote day.mp4"] },
+ reason: "The vote-day episode, where the claim is first made, is not in the archive.",
+ evidence: ["https://archive.org/details/site-channel-episodes"],
+ estimate: { items: 1, gb: 0.2 },
+ status: "proposed",
+ note: "this run proposes; the operator approves each acquisition",
+ },
+ {
+ id: "p02",
+ action: "create-channel",
+ args: { fields: { name: "Radio Tape", handling: "transcribe", url: "https://archive.org/details/radio-tape-01" } },
+ reason: "The radio call-in has no channel.",
+ evidence: ["https://archive.org/details/radio-tape-01"],
+ status: "proposed",
+ note: "this run proposes; the operator approves each acquisition",
+ },
+ {
+ id: "p03",
+ action: "import-video",
+ args: { slug: "sitechan", url: "https://www.twitch.tv/videos/123456789" },
+ reason: "The launch stream.",
+ evidence: [],
+ status: "rejected",
+ note: "a Twitch VOD is never fetched again (expired VODs are gone; look for the stream on archive.org or elsewhere): https://www.twitch.tv/videos/123456789",
+ },
+ ],
+ };
+}
+
+const propsFile = (article, n) => path.join(itDir(article, n), "proposals.json");
+const readProps = (article, n) => JSON.parse(readFileSync(propsFile(article, n), "utf8"));
+const writeProps = (article, n, st) => writeFileSync(propsFile(article, n), JSON.stringify(st, null, 2) + "\n");
+const pending = (st) => st.proposals.some((p) => ["proposed", "approved", "enqueued"].includes(p.status));
+
+// Enqueued acquisitions whose stub job has ended: done (or failed).
+function refreshProps(st) {
+ for (const p of st.proposals) {
+ if (p.status !== "enqueued") continue;
+ const j = draftJobs.get(p.jobId);
+ if (!j || j.status === "queued" || j.status === "running") continue;
+ p.status = j.status === "done" ? "done" : "failed";
+ if (j.status === "done") p.doneAt = new Date().toISOString();
+ else p.note = `job ${p.jobId} ended ${j.status}`;
+ }
+}
+
+function researchView(article, n, st) {
+ const it = readIt(article, n);
+ const rec = it.research ?? {};
+ const phase = pending(st) ? "wait" : rec.continuedBy?.length ? "continued" : "ready";
+ if (rec.phase !== phase && it.status === "done") patchIt(article, n, { research: { ...rec, phase } });
+ return {
+ article,
+ iteration: n,
+ status: it.status,
+ phase,
+ autonomy: st.autonomy,
+ limits: st.limits,
+ spent: st.spent,
+ proposals: st.proposals,
+ waitingOn: {
+ approval: st.proposals.filter((p) => p.status === "proposed" || p.status === "approved").map((p) => p.id),
+ jobs: st.proposals.filter((p) => p.status === "enqueued").map((p) => p.jobId),
+ },
+ continuedBy: rec.continuedBy ?? [],
+ ...(rec.notes ? { notes: rec.notes } : {}),
+ };
+}
+
+function startAcquisition(p) {
+ const id = `stub-acq-${nextJob++}`;
+ const job = { id, kind: p.action, status: "queued", log: [`${p.action} (stub)`], timers: [] };
+ draftJobs.set(id, job);
+ job.timers.push(setTimeout(() => ((job.status = "running"), job.log.push("fetching (stub)")), 1000));
+ job.timers.push(setTimeout(() => ((job.status = "done"), job.log.push("done")), 3000));
+ return id;
+}
+
+function settleResearch(body) {
+ const { article, iteration: n } = body;
+ const it = readIt(article, n);
+ if (it.kind !== "research") throw new Error(`"${article}" i${n} is a ${it.kind} iteration, not a research run`);
+ const st = readProps(article, n);
+ refreshProps(st);
+ const outcomes = [];
+ for (const id of body.ids ?? []) {
+ const p = st.proposals.find((x) => x.id === id);
+ if (!p) {
+ outcomes.push({ id, error: `no proposal ${id}` });
+ continue;
+ }
+ if (p.status !== "proposed" && p.status !== "approved") {
+ outcomes.push({ id, error: `${id} is ${p.status}, not waiting for approval` });
+ continue;
+ }
+ if (body.approve) {
+ p.status = "enqueued";
+ p.jobId = startAcquisition(p);
+ delete p.note;
+ st.spent.items += p.estimate?.items ?? 0;
+ st.spent.gb += p.estimate?.gb ?? 0;
+ } else {
+ p.status = "rejected";
+ p.note = body.note ? `the operator said no: ${body.note}` : "the operator said no";
+ }
+ outcomes.push({ id, status: p.status, ...(p.jobId ? { jobId: p.jobId } : {}), ...(p.note ? { note: p.note } : {}) });
+ }
+ writeProps(article, n, st);
+ return { outcomes, research: researchView(article, n, st) };
+}
+
+// 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) {
+ 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`);
+ const st = readProps(article, rn);
+ refreshProps(st);
+ writeProps(article, rn, st);
+ if (pending(st) && !force) throw new Error(`"${article}" i${rn} still waits`);
+ const channels = [...(r.scope?.channels ?? [])];
+ for (const p of st.proposals) {
+ 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 } };
+}
+
function startDraft(body) {
const { task, article } = body;
const now = new Date().toISOString();
@@ -206,6 +363,10 @@ function startDraft(body) {
if (body.copyOf) {
const src = readIt(article, body.copyOf);
base = { kind: src.kind, parent: src.parent, copyOf: src.n, ...(src.question ? { question: src.question } : {}), ...(src.feedback ? { feedback: src.feedback } : {}), ...(src.scope ? { scope: src.scope } : {}) };
+ } 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);
} 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 {
@@ -216,9 +377,13 @@ function startDraft(body) {
const model = body.model ?? (generation.routes[task] === "local" ? generation.models.local : generation.models.api);
mkdirSync(itDir(article, n), { recursive: true });
writeIt({ format: "archilyzer-iteration", version: 1, article, n, ...base, model, status: "queued", usage: {}, steps: [], jobId: id, createdAt: now, updatedAt: now });
+ if (task === "sweep" && body.iteration) {
+ const r = readIt(article, body.iteration);
+ patchIt(article, body.iteration, { research: { ...(r.research ?? {}), phase: "continued", continuedBy: [...(r.research?.continuedBy ?? []), n] } });
+ }
}
const slow = /slow/.test(String(body.question ?? body.feedback ?? ""));
- const job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] };
+ const job = { id, article, n, task, autonomy: body.autonomy, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] };
draftJobs.set(id, job);
job.timers.push(
setTimeout(() => {
@@ -307,6 +472,18 @@ function generationRoute(req, res, url, auth) {
}
});
}
+ if (req.method === "POST" && url.pathname === "/api/ops/research-approve") {
+ return readBody(req, (body) => {
+ requests.push({ route: "research-approve", ...(body ?? {}), authorization: auth });
+ record();
+ if (!body?.article || !body?.iteration) return json(res, 400, { ok: false, error: "article and iteration are required" });
+ try {
+ return json(res, 200, { ok: true, ...settleResearch(body) });
+ } catch (err) {
+ return json(res, 400, { ok: false, error: String(err.message) });
+ }
+ });
+ }
if (req.method === "POST" && url.pathname === "/api/ops/job") {
return readBody(req, (body) => {
requests.push({ route: "job", ...(body ?? {}), authorization: auth });
@@ -323,7 +500,7 @@ function generationRoute(req, res, url, auth) {
const tail = Number(url.searchParams.get("tail") ?? 0);
return json(res, 200, {
ok: true,
- job: { id: j.id, kind: "report-draft", status: j.status, ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}) },
+ job: { id: j.id, kind: j.kind ?? "report-draft", status: j.status, ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}) },
...(tail ? { tail: j.log.slice(-tail) } : {}),
});
}
diff --git a/umtool/lib/articles/research.ts b/umtool/lib/articles/research.ts
@@ -0,0 +1,40 @@
+import type { ResearchOutcome, ResearchView } from "yt-dlp-transcript-common/controller/researchRuns";
+import { askEditor, EditorError } from "./generation";
+
+// A RESEARCH RUN, AS UMTOOL SEES IT (release 27 S11): its acquisitions and
+// their state, from the EDITOR's `research-approve` action — which refreshes
+// every enqueued acquisition from its jobs first, so each read is the run as
+// it is now. The operator's yes or no is the same action with `ids`. Umtool
+// writes nothing here: the editor runs an approved acquisition through its own
+// ops action and rewrites the run's proposals.json.
+//
+// SERVER-ONLY.
+
+// The editor's answer's shape is common's (type-only imports: nothing of the
+// controller is bundled here).
+export type { ResearchOutcome, ResearchView };
+export type { Proposal as ResearchProposal } from "yt-dlp-transcript-common/lib/report/draft/research/decide";
+
+const ID = /^p\d+$/;
+
+/** The run now (refreshed by the editor). */
+export async function readResearch(article: string, n: number): Promise<ResearchView> {
+ const answer = await askEditor<{ research: ResearchView }>("/api/ops/research-approve", { method: "POST", body: { article, iteration: n } });
+ return answer.research;
+}
+
+/** The operator's yes (`approve: true`) or no to proposals of a run. */
+export async function settleResearch(
+ article: string,
+ n: number,
+ ids: string[],
+ approve: boolean,
+ note?: string,
+): Promise<{ research: ResearchView; outcomes: ResearchOutcome[] }> {
+ if (!ids.length || !ids.every((id) => ID.test(id))) throw new EditorError("ids are proposal ids (p01, p02, …)", 400);
+ const answer = await askEditor<{ research: ResearchView; outcomes: ResearchOutcome[] }>("/api/ops/research-approve", {
+ method: "POST",
+ body: { article, iteration: n, ids, approve, ...(note?.trim() ? { note: note.trim() } : {}) },
+ });
+ return { research: answer.research, outcomes: answer.outcomes ?? [] };
+}