commit 8e575fad68dffeb50ded5a82857043f9d74be20b
parent 7aec7f0eddcbe3c04e42b4fa8510b1beb2abf678
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 13:28:09 -0400
Merge branch 'r27/integration' into r27/umtool-ui
Diffstat:
27 files changed, 1787 insertions(+), 56 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -135,7 +135,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` |
| `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -> {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/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, 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", "article", ...} -> {jobId, iteration}. 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". "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. | `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."}'` |
+| `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", ...} -> {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". "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"?} -> {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}'` |
### Usage, flags and environment
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -954,7 +954,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| Key | Default | Description |
|---|---|---|
-| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. |
+| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. |
| `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). |
| `models` | object — see below | The model each route runs (below). |
| `caps` | object — see below | The spend caps in USD (below). |
@@ -965,6 +965,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`. |
| `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. |
| `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. |
+| `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. |
#### `generation.routes`
@@ -974,6 +975,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `revise-report` | `"api"` | A report iteration from feedback, through checked ops. |
| `revise-video` | `"local"` | A video-cut iteration from feedback, through checked ops. |
| `narrate` | `"local"` | Card narration for an iteration's cut, under the narration rules and the grounding checks. |
+| `research` | `"api"` | A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP. |
#### `generation.models`
@@ -987,7 +989,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| Key | Default | Description |
|---|---|---|
-| `sweep` | `5` | A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap. |
+| `sweep` | `5` | A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap. |
| `revision` | `2` | A report or video revision job's cap when it names none. |
| `narration` | `1` | A narration job's cap when it names none. |
| `daily` | `20` | The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap. |
@@ -1000,6 +1002,17 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `provider` | `"duckduckgo"` | The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search. |
| `searchUrl` | `""` | Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake. |
+#### `generation.research`
+
+| 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. |
+| `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. |
+| `newChannelsNeedApproval` | `true` | Under `limits`, a new channel waits for approval. (A new channel is always created on no site.) |
+| `postWalksNeedApproval` | `true` | Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval. |
+
Default:
```json
@@ -1009,7 +1022,8 @@ Default:
"sweep": "code",
"revise-report": "api",
"revise-video": "local",
- "narrate": "local"
+ "narrate": "local",
+ "research": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -1032,6 +1046,14 @@ Default:
"provider": "duckduckgo",
"searchUrl": ""
},
- "citationOrigin": ""
+ "citationOrigin": "",
+ "research": {
+ "autonomy": "propose",
+ "maxItemsPerRun": 20,
+ "maxGbPerRun": 5,
+ "maxTranscribeHours": 6,
+ "newChannelsNeedApproval": true,
+ "postWalksNeedApproval": true
+ }
}
```
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -2,16 +2,22 @@
// (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft →
// here.
//
-// task sweep | revise-report | revise-video | narrate
+// task sweep | revise-report | revise-video | narrate | research
// article the article id (an article in the making is fine for a sweep)
-// iteration a revision's parent; the iteration a narration voices; else none
+// iteration a revision's parent; the iteration a narration voices; for a
+// sweep, the research run it CONTINUES (S11: its question, and its
+// channels widened by what it acquired, are the defaults); else none
// model default: settings.generation.models[route] for the task's route
// question / channels / from / to a sweep's
// feedback a revision's
// copyOf run iteration N again on another model (same kind and inputs)
// maxUsd the job's cap (default by task; never above caps.max)
// source / build the corpus (default: the newest build holding the channels)
-// cards / force a narration's
+// cards / force a narration's (force: a continuation over a research
+// run that still waits, with what is done so far)
+// autonomy a research run's: propose | limits | auto (default:
+// settings.generation.research.autonomy; the limits are the
+// settings')
//
// The iteration is created `queued` before the job, and the job's id set on it;
// the job runs the S5 task in process. Its queue is the model's provider's:
@@ -50,6 +56,12 @@ import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
import type { CorpusToolsLike } from "../lib/report/draft/tasks/types";
import { verifyReportQuotes } from "../bin/reports-check";
import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { AUTONOMIES, type Autonomy, type ResearchLimits } from "../lib/report/draft/research/decide";
+import type { ResearchEditor } from "../lib/report/draft/research/tools";
+import type { JobOf } from "../lib/report/draft/research/state";
+import type { EditorChannel } from "../lib/report/draft/tasks/types";
+import { listChannelConfigs } from "./channels";
+import { continuationOf, markContinued } from "./researchRuns";
import { gpuGatedFetch } from "./gpuArbiter";
export const REPORT_DRAFT_JOB_KIND = "report-draft";
@@ -71,6 +83,7 @@ export const REPORT_DRAFT_BODY_KEYS = [
"build",
"cards",
"force",
+ "autonomy",
] as const;
export class ReportDraftInputError extends Error {}
@@ -91,9 +104,10 @@ export type ReportDraftBody = {
build?: string;
cards?: string[];
force?: boolean;
+ autonomy?: Autonomy;
};
-const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
+const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate", "research"];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -151,13 +165,24 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod
if (typeof b.force !== "boolean") fail('"force" is true or false');
out.force = b.force;
}
+ if (b.autonomy !== undefined && b.autonomy !== null) {
+ if (!(AUTONOMIES as readonly unknown[]).includes(b.autonomy)) fail(`"autonomy" is one of ${AUTONOMIES.join(", ")}`);
+ if (out.task !== "research") fail('"autonomy" is a research run\'s');
+ out.autonomy = b.autonomy as Autonomy;
+ }
if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>');
if (out.source && out.build) fail('give "source" or "build", not both');
// What each task needs.
- if (out.task === "sweep" && out.copyOf === undefined) {
+ // A sweep with "iteration" continues that research run (its question and
+ // widened channels are the defaults).
+ if (out.task === "sweep" && out.copyOf === undefined && out.iteration === undefined) {
if (!out.question) fail("a sweep needs its question");
if (!out.channels?.length) fail("a sweep needs its channels");
}
+ if (out.task === "research" && out.copyOf === undefined) {
+ if (!out.question) fail("a research run needs its question");
+ if (out.iteration !== undefined) fail('a research run starts from its question: it takes no "iteration"');
+ }
if ((out.task === "revise-report" || out.task === "revise-video") && out.copyOf === undefined) {
if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`);
if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`);
@@ -172,6 +197,7 @@ const KIND_OF: Record<GenerationTask, Iteration["kind"]> = {
"revise-report": "revise-report",
"revise-video": "revise-video",
narrate: "sweep", // (a step: no iteration of its own)
+ research: "research",
};
const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = {
@@ -179,6 +205,7 @@ const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = {
"revise-report": "revision",
"revise-video": "revision",
narrate: "narration",
+ research: "sweep",
};
export function expandHome(p: string): string {
@@ -221,8 +248,23 @@ export type ReportDraftDeps = {
corpusTools: (source: string) => Promise<CorpusToolsLike & { close(): Promise<void> }>;
settings?: () => { generation: GenerationSettings };
now?: () => Date;
+ // A research run's editor: its ops actions, in process (the editor's route
+ // passes itself). Without it a research run is refused.
+ researchEditor?: ResearchEditor;
+ // An editor job's state (default: the registry and the .jobs sidecars).
+ jobOf?: JobOf;
};
+// The editor's channels, as a research run lists them.
+async function editorChannelsOf(paths: Paths): Promise<EditorChannel[]> {
+ return (await listChannelConfigs(paths)).map(({ slug, config }) => {
+ const c = config as Record<string, unknown>;
+ const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined);
+ const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling"));
+ return { slug, ...(s("name") ? { name: s("name") } : {}), ...(s("platform") ? { platform: s("platform") } : {}), ...(kind ? { kind } : {}), ...(s("url") ? { url: s("url") } : {}) };
+ });
+}
+
// The channels a revision or narration reads: its report's citations'.
async function channelsOfReport(article: string, n: number, paths: Paths): Promise<string[]> {
const from = await reportSourceOf(article, n, paths).catch(() => null);
@@ -245,7 +287,7 @@ export async function resolveCorpus(
return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build };
}
-export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number };
+export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number; warnings?: string[] };
export async function enqueueReportDraft(raw: Record<string, unknown>, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> {
const paths = deps.paths;
@@ -264,6 +306,32 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`);
if (src.kind !== KIND_OF[body.task]) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`);
}
+ if (body.task === "research" && !deps.researchEditor) {
+ return refuse("a research run runs in the editor (its reads and acquisitions are the editor's actions)");
+ }
+ // A sweep continuing a research run: its question and widened scope.
+ const cont =
+ body.task === "sweep" && body.copyOf === undefined && body.iteration !== undefined
+ ? await continuationOf(body.article, body.iteration, {
+ paths,
+ ...(deps.jobOf ? { jobOf: deps.jobOf } : {}),
+ ...(body.force ? { force: true } : {}),
+ ...(body.question ? { question: body.question } : {}),
+ ...(body.channels ? { channels: body.channels } : {}),
+ ...(body.from ? { from: body.from } : {}),
+ ...(body.to ? { to: body.to } : {}),
+ })
+ : null;
+ const warnings: string[] = [];
+ if (cont && !body.source) {
+ // The sweep reads a composed build: one must hold the widened channels
+ // (a channel on no site is in none until the operator puts it on one
+ // and builds it), and an acquisition after the build is not in it.
+ const b = await pickCorpusBuild(cont.channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) });
+ if (cont.lastAcquired !== null && b.mtimeMs < cont.lastAcquired) {
+ warnings.push(`the build ${b.build} predates the run's last acquisition (${new Date(cont.lastAcquired).toISOString()}): rebuild it to read what was acquired`);
+ }
+ }
const model = modelFor(gen, body.task, body.model);
const provider = providerOf(model);
let maxUsd: number | undefined;
@@ -281,6 +349,20 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
n = it.n;
} else if (src) {
n = (await copyIteration(body.article, src.n, { model }, paths)).n;
+ } else if (cont) {
+ n = (
+ await createIteration(
+ body.article,
+ {
+ kind: "sweep",
+ model,
+ parent: cont.research.n,
+ question: cont.question,
+ scope: { channels: cont.channels, ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}) },
+ },
+ paths,
+ )
+ ).n;
} else {
n = (
await createIteration(
@@ -288,8 +370,8 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
{
kind: KIND_OF[body.task],
model,
- ...(body.task === "sweep"
- ? { question: body.question, scope: { channels: body.channels!, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }
+ ...(body.task === "sweep" || body.task === "research"
+ ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } }
: { parent: body.iteration!, feedback: body.feedback }),
},
paths,
@@ -307,6 +389,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
return { result };
}
if (body.task !== "narrate") await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {});
+ if (cont) await markContinued(body.article, cont.research.n, n, paths).catch(() => {});
// A job cancelled (or refused) before it ran leaves its iteration queued: end it.
void result.done.then(async (d) => {
if (body.task === "narrate") return;
@@ -315,7 +398,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep
await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {});
}
});
- return { result, iteration: n };
+ return { result, iteration: n, ...(warnings.length ? { warnings } : {}) };
} catch (e) {
return refuse((e as Error).message);
}
@@ -339,7 +422,7 @@ async function runReportDraft(
}
}
const it = (await readIteration(body.article, n, paths))!;
- const channels = body.task === "sweep" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths);
+ const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths);
let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
let result: TaskResult | null = null;
try {
@@ -374,6 +457,7 @@ async function runReportDraft(
log: onLog,
signal,
...(deps.now ? { now: deps.now } : {}),
+ ...(body.task === "research" && deps.researchEditor ? { editor: deps.researchEditor, editorChannels: () => editorChannelsOf(paths) } : {}),
};
const projectsRoot = projectsRootOf(gen);
// A local run costs nothing: it has no dollar cap.
@@ -393,6 +477,19 @@ async function runReportDraft(
case "revise-video":
input = { task: "revise-video", article: body.article, n, origin: where.origin, maxUsd: cap, projectsRoot };
break;
+ case "research": {
+ const r = gen.research;
+ const was = (it as { research?: { autonomy?: Autonomy } }).research?.autonomy;
+ const limits: ResearchLimits = {
+ maxItemsPerRun: r.maxItemsPerRun,
+ maxGbPerRun: r.maxGbPerRun,
+ maxTranscribeHours: r.maxTranscribeHours,
+ newChannelsNeedApproval: r.newChannelsNeedApproval,
+ postWalksNeedApproval: r.postWalksNeedApproval,
+ };
+ input = { task: "research", article: body.article, n, origin: where.origin, maxUsd: cap, autonomy: body.autonomy ?? was ?? r.autonomy, limits };
+ break;
+ }
case "narrate":
input = { task: "narrate", article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.cards ? { cards: body.cards } : {}), ...(body.force ? { force: true } : {}) };
break;
diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts
@@ -0,0 +1,273 @@
+// 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: <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.
+
+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 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<Paths, "articlesDir" | "exportIndexDir" | "jobsDir">;
+
+// An editor job's state, from the registry or its `.jobs` sidecar.
+export function jobOfPaths(paths: Pick<Paths, "jobsDir">): JobOf {
+ return async (id) => {
+ const e = await getJobEntry(paths as Paths, id);
+ return e ? { status: e.status, ...(e.endedAt ? { endedAt: e.endedAt } : {}) } : null;
+ };
+}
+
+// One run's read-modify-write at a time, in this process (the editor is one).
+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;
+}
+
+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<ResearchPhase> {
+ if (changed) 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);
+ }
+ return phase;
+}
+
+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[];
+};
+
+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 ?? [],
+ };
+}
+
+export type ResearchApproveBody = { article: string; iteration: number; ids: string[]; approve?: boolean; note?: string };
+
+export function parseResearchApproveBody(b: Record<string, unknown>): 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 };
+
+// The operator's yes or no on a research run's proposals (no ids: its state).
+export async function approveResearch(
+ raw: Record<string, unknown>,
+ 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 {
+ return 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 };
+ });
+ } 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<ResearchView> {
+ 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<Continuation> {
+ 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<void> {
+ 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,
+ ),
+ );
+}
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -50,3 +50,27 @@ test("caps: a task's default, an asked one within max, a larger one refused; URL
assert.equal(u.models.api, "claude-sonnet-5-5");
assert.equal(sanitizeGeneration({ cacheTtl: "1h" }).cacheTtl, "1h");
});
+
+test("research (S11): a route of its own, a file from before it keeps its preset, and the run's autonomy and limits", () => {
+ const d = sanitizeGeneration(undefined);
+ assert.equal(d.routes.research, "api", "balanced runs research on the API");
+ assert.deepEqual(d.research, {
+ autonomy: "propose",
+ maxItemsPerRun: 20,
+ maxGbPerRun: 5,
+ maxTranscribeHours: 6,
+ newChannelsNeedApproval: true,
+ postWalksNeedApproval: true,
+ });
+ // routes written before research had one: the preset they are keeps its name.
+ const { research: _r, ...localOld } = GENERATION_PRESETS.local;
+ const old = sanitizeGeneration({ routes: localOld });
+ assert.equal(old.routes.research, "local");
+ assert.equal(old.preset, "local");
+ const { research: _c, ...codeOld } = GENERATION_PRESETS.code;
+ assert.equal(sanitizeGeneration({ routes: codeOld }).preset, "code");
+ assert.equal(sanitizeGeneration({ routes: { ...GENERATION_PRESETS.balanced, research: "local" } }).preset, "custom");
+ const r = sanitizeGeneration({ research: { autonomy: "auto", maxItemsPerRun: 3.7, maxGbPerRun: -1, newChannelsNeedApproval: false, extra: 1 } }).research;
+ assert.deepEqual(r, { autonomy: "auto", maxItemsPerRun: 3, maxGbPerRun: 5, maxTranscribeHours: 6, newChannelsNeedApproval: false, postWalksNeedApproval: true });
+ assert.equal(sanitizeGeneration({ research: { autonomy: "yolo" } }).research.autonomy, "propose");
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -8,18 +8,19 @@
// that looks like a key is refused, and never stored).
import type { FieldDocs } from "./fieldDocs";
+import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, type Autonomy } from "./report/draft/research/decide";
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate"] as const;
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
export const GENERATION_ROUTES = ["code", "api", "local"] as const;
export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code" },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code" },
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -30,6 +31,16 @@ export type GenerationModels = { api: string; local: string; extractor: string }
// `daily` refuses a job that would start past it.
export type GenerationCaps = { sweep: number; revision: number; narration: number; daily: number; max: number };
export type GenerationWeb = { provider: "duckduckgo"; searchUrl: string };
+// A research run's autonomy and limits (release 27 S11): the default a run
+// takes when it names none.
+export type GenerationResearch = {
+ autonomy: Autonomy;
+ maxItemsPerRun: number;
+ maxGbPerRun: number;
+ maxTranscribeHours: number;
+ newChannelsNeedApproval: boolean;
+ postWalksNeedApproval: boolean;
+};
export type GenerationSettings = {
preset: GenerationPreset | "custom";
@@ -43,8 +54,11 @@ export type GenerationSettings = {
projectsRoot: string;
web: GenerationWeb;
citationOrigin: string;
+ research: GenerationResearch;
};
+export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS };
+
export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env";
export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
@@ -59,11 +73,12 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
projectsRoot: "",
web: { provider: "duckduckgo", searchUrl: "" },
citationOrigin: "",
+ research: { ...DEFAULT_GENERATION_RESEARCH },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
preset:
- "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.",
+ "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.",
routes: "Where each task runs: `code`, `api` or `local` (below).",
models: "The model each route runs (below).",
caps: "The spend caps in USD (below).",
@@ -77,6 +92,7 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.",
citationOrigin:
"The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.",
+ research: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.",
};
export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
@@ -84,6 +100,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
"revise-report": "A report iteration from feedback, through checked ops.",
"revise-video": "A video-cut iteration from feedback, through checked ops.",
narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.",
+ research:
+ "A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP.",
};
export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = {
@@ -93,7 +111,7 @@ export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = {
};
export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = {
- sweep: "A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap.",
+ sweep: "A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap.",
revision: "A report or video revision job's cap when it names none.",
narration: "A narration job's cap when it names none.",
daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.",
@@ -105,6 +123,16 @@ export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = {
searchUrl: "Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake.",
};
+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.",
+ 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.",
+ newChannelsNeedApproval: "Under `limits`, a new channel waits for approval. (A new channel is always created on no site.)",
+ postWalksNeedApproval: "Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval.",
+};
+
// What a key looks like: the API's own prefix, or one long unbroken token with
// no path in it.
export function looksLikeApiKey(v: string): boolean {
@@ -133,6 +161,12 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
const v = rr[t];
routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t];
}
+ // A file from before research had a route (S11) keeps its preset: research
+ // takes the route of the preset the other tasks' routes are.
+ if (!(typeof rr.research === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr.research))) {
+ const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => t === "research" || routes[t] === GENERATION_PRESETS[p][t]));
+ if (was) routes.research = GENERATION_PRESETS[was].research;
+ }
// The ROUTES are the truth; the preset names them (the preset whose routes
// they are, else `custom`). Choosing a preset is writing its routes.
const preset: GenerationSettings["preset"] = presetOf(routes);
@@ -143,6 +177,10 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
const max = usd(c.max, d.caps.max);
const w = r.web && typeof r.web === "object" ? (r.web as Record<string, unknown>) : {};
const keyFile = str(r.apiKeyFile, d.apiKeyFile);
+ const rs = r.research && typeof r.research === "object" && !Array.isArray(r.research) ? (r.research as Record<string, unknown>) : {};
+ const count = (v: unknown, def: number, max: number) =>
+ typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v * 100) / 100) : def;
+ const dr = d.research;
return {
preset,
routes,
@@ -162,6 +200,14 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
projectsRoot: str(r.projectsRoot, d.projectsRoot),
web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) },
citationOrigin: url(r.citationOrigin, d.citationOrigin),
+ research: {
+ autonomy: (AUTONOMIES as readonly string[]).includes(String(rs.autonomy)) ? (rs.autonomy as Autonomy) : dr.autonomy,
+ maxItemsPerRun: Math.floor(count(rs.maxItemsPerRun, dr.maxItemsPerRun, 10_000)),
+ maxGbPerRun: count(rs.maxGbPerRun, dr.maxGbPerRun, 10_000),
+ maxTranscribeHours: count(rs.maxTranscribeHours, dr.maxTranscribeHours, 10_000),
+ newChannelsNeedApproval: typeof rs.newChannelsNeedApproval === "boolean" ? rs.newChannelsNeedApproval : dr.newChannelsNeedApproval,
+ postWalksNeedApproval: typeof rs.postWalksNeedApproval === "boolean" ? rs.postWalksNeedApproval : dr.postWalksNeedApproval,
+ },
};
}
diff --git a/common/lib/report/draft/research/decide.ts b/common/lib/report/draft/research/decide.ts
@@ -9,11 +9,13 @@
//
// propose every acquisition waits for the operator's yes or no.
// limits an acquisition into an EXISTING channel runs on its own while it
-// is under the caps and its size is known; a new channel, a post
-// walk (when the limits say they need approval), a priority bump,
-// anything over a cap or of unknown size waits for approval.
-// auto everything runs on its own, through the editor, until a cap is
-// reached (then it waits) — and the approval flags still hold.
+// is under the caps and its size is known; a new channel and a post
+// walk wait while the limits say they need approval (the default),
+// a priority bump always waits, and so does anything over a cap or
+// of unknown size.
+// auto everything runs on its own, through the editor: the approval
+// flags are lifted (ruled 2026-10-13), but the caps stay hard
+// ceilings — past one (or of unknown size), it waits for approval.
//
// THE STANDING RULES are checked first and refuse in every mode — they are
// not the run's to relax:
@@ -82,6 +84,11 @@ export type Proposal = {
jobId?: string;
// Why it waits, was refused or failed (the decision's or the editor's words).
note?: string;
+ // The channel a create-channel made (the editor's answer), for the scope
+ // a continuation widens to.
+ channel?: string;
+ // When its job (all of its jobs) ended done.
+ doneAt?: string;
};
export type Spent = { items: number; gb: number; transcribeHours: number };
@@ -154,7 +161,9 @@ function cost(p: Pick<Proposal, "action" | "args" | "estimate">): { items: numbe
return {
items: e.items ?? listed("items") ?? 1,
gb: e.gb ?? (p.args.dryRun === true ? 0 : null),
- hours: 0,
+ // An import into a transcribing channel queues its transcription:
+ // what the run says it will take counts against the cap.
+ hours: e.transcribeHours ?? 0,
};
case "import-post":
return { items: e.items ?? 1, gb: e.gb ?? 0, hours: 0 };
@@ -193,15 +202,13 @@ export function decideAcquisition(
return { decision: "refuse", reason: `unknown autonomy "${String(autonomy)}"` };
}
if (autonomy === "propose") return { decision: "approval", reason: "this run proposes; the operator approves each acquisition" };
- if (proposal.action === "create-channel" && limits.newChannelsNeedApproval) {
- return { decision: "approval", reason: "a new channel needs the operator's approval" };
- }
- if (isPostWalk(proposal) && limits.postWalksNeedApproval) {
- return { decision: "approval", reason: "a walk over an account's post history needs the operator's approval" };
- }
+ // Under limits the approval flags hold; under auto they are lifted.
if (autonomy === "limits") {
- if (proposal.action === "create-channel") {
- return { decision: "approval", reason: "under limits, only acquisitions into existing channels run on their own" };
+ if (proposal.action === "create-channel" && limits.newChannelsNeedApproval) {
+ return { decision: "approval", reason: "a new channel needs the operator's approval" };
+ }
+ if (isPostWalk(proposal) && limits.postWalksNeedApproval) {
+ return { decision: "approval", reason: "a walk over an account's post history needs the operator's approval" };
}
if (proposal.action === "priority-bump") {
return { decision: "approval", reason: "a priority change is the operator's under limits" };
diff --git a/common/lib/report/draft/research/research.test.ts b/common/lib/report/draft/research/research.test.ts
@@ -71,22 +71,25 @@ test("limits: an import into an existing channel under the caps runs; over a cap
assert.equal(decideAcquisition(p("import-post", { slug: "synth-social", url: "https://x.com/a/status/1" }), "limits", LIMITS).decision, "enqueue");
});
-test("limits: new channels, post walks and priority bumps wait; auto runs them unless the limits say they need approval", () => {
+test("limits: new channels and post walks wait while the flags say so, a priority bump always; auto lifts the flags", () => {
const create = p("create-channel", { fields: { name: "Synth Other", handling: "youtube", url: "https://video.example/@other" } });
const walk = p("fetch-posts", { slug: "synth-social", older: true });
const fresh = p("fetch-posts", { slug: "synth-social" });
const bump = p("priority-bump", { slug: "synth-kitchen" });
assert.match((decideAcquisition(create, "limits", LIMITS) as { reason: string }).reason, /new channel needs the operator's approval/);
- assert.match((decideAcquisition(create, "limits", OPEN) as { reason: string }).reason, /only acquisitions into existing channels/);
+ assert.equal(decideAcquisition(create, "limits", OPEN).decision, "enqueue", "the flag off: a new channel runs under limits");
assert.match((decideAcquisition(walk, "limits", LIMITS) as { reason: string }).reason, /post history needs the operator's approval/);
assert.equal(decideAcquisition(walk, "limits", OPEN).decision, "enqueue");
assert.equal(decideAcquisition(fresh, "limits", LIMITS).decision, "enqueue");
assert.match((decideAcquisition(bump, "limits", LIMITS) as { reason: string }).reason, /priority change/);
- assert.equal(decideAcquisition(create, "auto", LIMITS).decision, "approval");
- assert.equal(decideAcquisition(create, "auto", OPEN).decision, "enqueue");
+ // auto: the approval flags are lifted (ruled 2026-10-13) …
+ assert.equal(decideAcquisition(create, "auto", LIMITS).decision, "enqueue");
+ assert.equal(decideAcquisition(walk, "auto", LIMITS).decision, "enqueue");
assert.equal(decideAcquisition(bump, "auto", LIMITS).decision, "enqueue");
- // auto still stops at a cap.
- assert.equal(decideAcquisition(p("import-video", { slug: "s", url: "https://v.example/1" }, { gb: 9 }), "auto", OPEN).decision, "approval");
+ // … but the caps are hard ceilings: past one, or of unknown size, it waits.
+ assert.match((decideAcquisition(p("import-video", { slug: "s", url: "https://v.example/1" }, { gb: 9 }), "auto", LIMITS) as { reason: string }).reason, /cap of 2 GB/);
+ assert.equal(decideAcquisition(p("import-video", { slug: "s", url: "https://v.example/1" }), "auto", LIMITS).decision, "approval");
+ assert.equal(decideAcquisition(p("import-post", { slug: "s", url: "https://x.com/a/status/1" }), "auto", LIMITS, { items: 3, gb: 0, transcribeHours: 0 }).decision, "approval");
});
test("standing rule: create-channel is always on NO site — refused with sites in every mode, even auto", () => {
diff --git a/common/lib/report/draft/research/runs.test.ts b/common/lib/report/draft/research/runs.test.ts
@@ -0,0 +1,252 @@
+// Research RUNS (release 27 S11): the state a run keeps (proposals.json, the
+// refresh from job states, the phase, the continuation's scope) and the
+// `research` task end to end against the fake Anthropic and ollama servers,
+// a stub corpus and a fake editor. The editor job, the approval and the
+// continuation through `report-draft` are editor/app/api/ops/_researchRuns.test.ts.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { FAKE_KEY, startFakeAnthropic, type FakeAnthropic } from "../../../../testing/llm/fakeAnthropic.mjs";
+import { startFakeOllama, toolCallsReply, reply, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { ORIGIN } from "../../../../testing/draft/corpus.mjs";
+import { createIteration, readIteration } from "../../iterations";
+import type { AgentTool } from "../../../llm";
+import { research } from "../tasks/research";
+import type { TaskDeps } from "../tasks/types";
+import { DEFAULT_RESEARCH_LIMITS, type Proposal } from "./decide";
+import type { ResearchEditor } from "./tools";
+import {
+ isSettled,
+ lastAcquiredAt,
+ newResearchState,
+ parseResearchState,
+ phaseOf,
+ readResearchState,
+ refreshProposals,
+ waitingOn,
+ widenedChannels,
+} from "./state";
+
+const RUN = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../testing/draft/runs/research.json");
+
+let tmp: string;
+let api: FakeAnthropic;
+let ol: FakeOllama;
+let caseN = 0;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "research-runs-"));
+ api = await startFakeAnthropic();
+ ol = await startFakeOllama();
+});
+after(async () => {
+ await api.close();
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+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,
+});
+
+test("state: an enqueued acquisition settles from its jobs — all done is done, one failed or lost is failed, a running one waits", async () => {
+ const s = newResearchState("limits", DEFAULT_RESEARCH_LIMITS);
+ s.proposals = [
+ prop("p01", "import-archive-org", { slug: "synth-kitchen" }, "enqueued", { jobId: "j1,j2" }),
+ prop("p02", "import-video", { slug: "synth-kitchen" }, "enqueued", { jobId: "j3" }),
+ prop("p03", "import-post", { slug: "synth-social" }, "enqueued", { jobId: "j4" }),
+ prop("p04", "fetch-posts", { slug: "synth-social" }, "enqueued", { jobId: "j5" }),
+ prop("p05", "create-channel", { fields: {} }, "proposed", { note: "a new channel needs the operator's approval" }),
+ ];
+ const jobs: Record<string, { status: string; endedAt?: number }> = {
+ j1: { status: "done", endedAt: Date.UTC(2026, 9, 13, 10) },
+ j2: { status: "done", endedAt: Date.UTC(2026, 9, 13, 11) },
+ j3: { status: "failed" },
+ j4: { status: "running" },
+ j5: { status: "archived" },
+ };
+ assert.deepEqual(waitingOn(s), { approval: ["p05"], jobs: ["j1", "j2", "j3", "j4", "j5"] });
+ assert.equal(await refreshProposals(s, async (id) => jobs[id] ?? null), true);
+ assert.deepEqual(
+ s.proposals.map((p) => [p.id, p.status, p.note ?? ""]),
+ [
+ ["p01", "done", ""],
+ ["p02", "failed", "job j3 ended failed"],
+ ["p03", "enqueued", ""],
+ ["p04", "failed", "job j5 was lost (the editor restarted)"],
+ ["p05", "proposed", "a new channel needs the operator's approval"],
+ ],
+ );
+ assert.equal(s.proposals[0]!.doneAt, "2026-10-13T11:00:00.000Z", "the last of its jobs");
+ assert.equal(phaseOf(s), "wait");
+ assert.equal(await refreshProposals(s, async (id) => jobs[id] ?? null), false, "nothing new");
+ jobs.j4 = { status: "done", endedAt: Date.UTC(2026, 9, 13, 12) };
+ s.proposals[4]!.status = "rejected";
+ await refreshProposals(s, async (id) => jobs[id] ?? null);
+ assert.equal(isSettled(s), true);
+ assert.equal(phaseOf(s), "ready");
+ assert.equal(phaseOf(s, true), "continued");
+ assert.equal(lastAcquiredAt(s), Date.UTC(2026, 9, 13, 12));
+ assert.deepEqual(waitingOn(s), { approval: [], jobs: [] });
+});
+
+test("state: a continuation sweeps the run's channels and every channel a done acquisition wrote into", () => {
+ const s = newResearchState("auto", DEFAULT_RESEARCH_LIMITS);
+ s.proposals = [
+ prop("p01", "create-channel", { fields: { name: "Synth Radio" } }, "done", { channel: "synth-radio" }),
+ prop("p02", "import-archive-org", { slug: "synth-radio", item: "x" }, "done"),
+ prop("p03", "import-post", { slug: "synth-social", url: "u" }, "done"),
+ prop("p04", "persist-videos", { items: [{ slug: "synth-other", id: "a" }] }, "done"),
+ prop("p05", "priority-bump", { slug: "synth-bumped" }, "done"),
+ prop("p06", "import-video", { slug: "synth-failed", url: "u" }, "failed"),
+ prop("p07", "import-video", { slug: "synth-waiting", url: "u" }, "proposed"),
+ ];
+ assert.deepEqual(widenedChannels(["synth-kitchen"], s), ["synth-kitchen", "synth-radio", "synth-social", "synth-other"]);
+});
+
+test("state: proposals.json is read leniently — a bare list, unknown statuses dropped, limits defaulted", () => {
+ const s = parseResearchState([{ id: "p01", action: "import-video", args: { slug: "s" }, status: "proposed" }, { id: "p02", status: "weird", action: "x" }]);
+ assert.equal(s.proposals.length, 1);
+ assert.equal(s.autonomy, "propose");
+ assert.deepEqual(s.limits, DEFAULT_RESEARCH_LIMITS);
+ assert.deepEqual(s.proposals[0]!.evidence, []);
+});
+
+// ─── the task ───
+
+function stubCorpus(): TaskDeps["corpus"] {
+ const tool = (name: string, out: string): AgentTool => ({ name, description: name, inputSchema: { type: "object", properties: { query: { type: "string" } } }, run: async () => out });
+ return {
+ source: "local:/stub",
+ tools: [
+ tool("search_transcripts", `1 match: synth-kitchen/pie-stream-02 @ 0:30 "the second shop" ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=30`),
+ tool("list_channels", "synth-kitchen, synth-other"),
+ tool("get_video_metadata", "{}"),
+ tool("get_transcripts", "never offered to a research run"),
+ ],
+ call: async () => "",
+ };
+}
+
+function fakeEditor() {
+ const calls: { action: string; args: Record<string, unknown> }[] = [];
+ const editor: ResearchEditor = {
+ run: async (action, args) => {
+ calls.push({ action, args });
+ if (action === "archive-search") return { ok: true, found: 1, items: [{ identifier: "synth-kitchen-episodes-2026", title: "Synth Kitchen — episodes" }] };
+ if (action === "archive-item") return { ok: true, item: { identifier: "synth-kitchen-episodes-2026", files: [{ name: "Bread day.mp4", size: 104857600 }] } };
+ return { ok: true, jobId: `job-${calls.length}` };
+ },
+ };
+ return { editor, calls };
+}
+
+async function newRun(autonomy: "propose" | "limits" | "auto", model: string) {
+ caseN++;
+ const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) };
+ await mkdir(paths.articlesDir, { recursive: true });
+ const r = JSON.parse(await readFile(RUN, "utf8"));
+ await createIteration("synth-research", { kind: "research", model, question: r.question, scope: { channels: r.channels } }, paths);
+ const lines: string[] = [];
+ const { editor, calls } = fakeEditor();
+ const deps: TaskDeps = {
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, ollama: { baseUrl: ol.url } },
+ corpus: stubCorpus(),
+ cuesOf: async () => null,
+ paths,
+ editor,
+ editorChannels: async () => [{ slug: "synth-kitchen", name: "Synth Kitchen", platform: "youtube", kind: "videos" }],
+ log: (l) => lines.push(l),
+ };
+ return { r, paths, deps, calls, lines, autonomy };
+}
+
+test("research (API, limits): discovers, enqueues the import under the caps, leaves the new channel waiting, refuses the Twitch VOD", async () => {
+ const run = await newRun("limits", "claude-sonnet-5-5");
+ api.push(...run.r.turns);
+ const before = api.requests.length;
+ const out = await research(
+ { article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 2, autonomy: "limits", limits: DEFAULT_RESEARCH_LIMITS },
+ run.deps,
+ );
+ assert.equal(out.status, "done", out.summary);
+ assert.match(out.summary, /^3 acquisition\(s\) \(1 enqueued, 1 waiting for approval, 1 refused\) — waiting/);
+ // The editor saw the reads and ONE acquisition, its body the action's own keys.
+ assert.deepEqual(
+ run.calls.map((c) => c.action),
+ ["archive-search", "archive-item", "import-archive-org"],
+ );
+ assert.deepEqual(run.calls[2]!.args, { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", files: ["Bread day.mp4"] });
+ const state = (await readResearchState("synth-research", 1, run.paths))!;
+ assert.equal(state.autonomy, "limits");
+ assert.deepEqual(
+ state.proposals.map((p) => [p.id, p.action, p.status]),
+ [
+ ["p01", "import-archive-org", "enqueued"],
+ ["p02", "create-channel", "proposed"],
+ ["p03", "import-video", "rejected"],
+ ],
+ );
+ assert.equal(state.proposals[0]!.jobId, "job-3");
+ assert.match(state.proposals[1]!.note!, /new channel needs the operator's approval/);
+ assert.match(state.proposals[2]!.note!, /Twitch VOD is never fetched again/);
+ assert.deepEqual(state.spent, { items: 1, gb: 0.1, transcribeHours: 0.02 });
+ const it = (await readIteration("synth-research", 1, run.paths))!;
+ assert.equal(it.status, "done");
+ const rec = (it as { research?: Record<string, unknown> }).research!;
+ assert.equal(rec.autonomy, "limits");
+ assert.equal(rec.phase, "wait");
+ assert.match(String(rec.notes), /radio tape/);
+ // The model was told its autonomy and the standing rules, and offered no bulk transcript read.
+ const first = api.requests[before]!;
+ const system = JSON.stringify(first.system);
+ assert.match(system, /WITHIN LIMITS/);
+ assert.match(system, /never a Twitch VOD URL/);
+ assert.match(system, /always created on NO site/);
+ const names = (first.tools as { name: string }[]).map((t) => t.name);
+ assert.ok(names.includes("editor_channels") && names.includes("archive-item") && names.includes("persist-videos"), names.join(","));
+ assert.ok(!names.includes("get_transcripts"), "no bulk transcript read");
+});
+
+test("research (API, propose): every acquisition waits; nothing but the reads reaches the editor", async () => {
+ const run = await newRun("propose", "claude-sonnet-5-5");
+ api.push(...run.r.turns);
+ const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 2, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, run.deps);
+ assert.equal(out.status, "done", out.summary);
+ assert.deepEqual(run.calls.map((c) => c.action), ["archive-search", "archive-item"]);
+ const state = (await readResearchState("synth-research", 1, run.paths))!;
+ assert.deepEqual(state.proposals.map((p) => p.status), ["proposed", "proposed", "rejected"]);
+ assert.deepEqual(state.spent, { items: 0, gb: 0, transcribeHours: 0 });
+});
+
+test("research (local): the tool loop fits the 8k prompt, and a run with nothing to acquire is ready", async () => {
+ const run = await newRun("auto", "qwen3:8b");
+ ol.push(toolCallsReply([{ name: "search_transcripts", arguments: { query: "second shop" } }]), reply("The archive already holds the whole story; nothing to acquire."));
+ const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: Number.POSITIVE_INFINITY, autonomy: "auto", limits: DEFAULT_RESEARCH_LIMITS }, run.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${run.lines.join("\n")}`);
+ assert.match(out.summary, /^0 acquisition\(s\) — nothing pending: ready to continue/);
+ const it = (await readIteration("synth-research", 1, run.paths))!;
+ assert.equal((it as { research?: { phase?: string } }).research!.phase, "ready");
+});
+
+test("research: refused without the editor, or on an iteration that is not a research run", async () => {
+ const run = await newRun("propose", "claude-sonnet-5-5");
+ const { editor: _e, ...noEditor } = run.deps;
+ const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 1, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, noEditor);
+ assert.equal(out.status, "failed");
+ assert.match(out.summary, /needs the editor/);
+ await createIteration("synth-research", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, run.paths);
+ await assert.rejects(
+ research({ article: "synth-research", n: 2, origin: ORIGIN, maxUsd: 1, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, run.deps),
+ /is a sweep iteration, not research/,
+ );
+});
diff --git a/common/lib/report/draft/research/state.ts b/common/lib/report/draft/research/state.ts
@@ -0,0 +1,222 @@
+// 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;
+};
+
+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<string, unknown>) : {};
+ 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<string, unknown>) : {};
+ 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<string, unknown>) : {};
+ 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<ResearchState | null> {
+ 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<void> {
+ 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).
+export type JobState = { status: string; endedAt?: number };
+export type JobOf = (id: string) => Promise<JobState | null>;
+
+export const jobIdsOf = (p: Pick<Proposal, "jobId">): 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<ResearchState, "proposals">, jobOf: JobOf): Promise<boolean> {
+ 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<Proposal["status"], number>;
+
+export function countProposals(state: Pick<ResearchState, "proposals">): 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<ResearchState, "proposals">): { 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<ResearchState, "proposals">): 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<ResearchState, "proposals">, 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<ResearchState, "proposals">): 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<ResearchState, "proposals">): 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;
+}
diff --git a/common/lib/report/draft/research/tools.ts b/common/lib/report/draft/research/tools.ts
@@ -194,6 +194,8 @@ async function enqueue(ctx: Pick<ResearchToolsContext, "editor" | "ledger">, p:
const jobId = jobIdOf(answer);
p.status = jobId ? "enqueued" : "done";
if (jobId) p.jobId = jobId;
+ else p.doneAt = new Date().toISOString();
+ if (p.action === "create-channel" && typeof answer.slug === "string") p.channel = answer.slug;
delete p.note;
ctx.ledger.spent = addSpent(ctx.ledger.spent, spendOf(p));
} catch (e) {
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -2,11 +2,12 @@
// `report-draft` job runs (S6).
import { narrate, type NarrateInput } from "./narrate";
+import { research, type ResearchInput } from "./research";
import { reviseReport, type ReviseReportInput } from "./revise-report";
import { reviseVideo, type ReviseVideoInput } from "./revise-video";
import { sweepAgent, type SweepAgentInput } from "./sweep-agent";
import { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline";
-import type { TaskDeps, TaskName, TaskResult } from "./types";
+import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types";
export * from "./types";
export { TaskInputError, runOnIteration, usageOf } from "./run";
@@ -15,6 +16,7 @@ export { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline";
export { reviseReport, type ReviseReportInput } from "./revise-report";
export { reviseVideo, type ReviseVideoInput } from "./revise-video";
export { narrate, type NarrateInput } from "./narrate";
+export { research, RESEARCH_READ_TOOLS, type ResearchInput } from "./research";
export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource";
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes";
@@ -25,7 +27,8 @@ export type TaskInput =
| ({ task: "sweep-pipeline" } & SweepPipelineInput)
| ({ task: "revise-report" } & ReviseReportInput)
| ({ task: "revise-video" } & ReviseVideoInput)
- | ({ task: "narrate" } & NarrateInput);
+ | ({ task: "narrate" } & NarrateInput)
+ | ({ task: "research" } & ResearchInput);
export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> {
switch (input.task) {
@@ -39,8 +42,10 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> {
return reviseVideo(input, deps);
case "narrate":
return narrate(input, deps);
+ case "research":
+ return research(input, deps);
}
}
export const isTaskName = (v: unknown): v is TaskName =>
- typeof v === "string" && ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate"].includes(v);
+ typeof v === "string" && (TASK_NAMES as readonly string[]).includes(v);
diff --git a/common/lib/report/draft/tasks/research.ts b/common/lib/report/draft/tasks/research.ts
@@ -0,0 +1,225 @@
+// TASK research — find what the corpus lacks for a question and acquire it
+// through the editor (release 27 S11; the plan's "Research").
+//
+// One agent run over an iteration of kind `research`, in the plan's phases:
+// discover the corpus first (the MCP's read tools), then the web and
+// archive.org (search, an item's file list — the editor's paced
+// read actions);
+// propose each acquisition is a tool call naming its editor action, its
+// args, the reason and the evidence links, and what it will cost;
+// acquire decideAcquisition judges it against the run's autonomy and
+// limits: an `enqueue` becomes an editor job at once (the editor's
+// queues, holds and pacing), an `approval` waits in proposals.json
+// for the operator, a standing rule refuses it;
+// wait the job ends; the run is resumable — research-approve and a
+// continuation refresh its acquisitions from their jobs' states
+// (research/state.ts), with no process waiting;
+// continue a `sweep` iteration over the widened scope, its parent this one
+// (`report-draft {task: "sweep", iteration: <this>}`).
+//
+// The run's own record: proposals.json (written on every change) and the
+// iteration's `research` key ({autonomy, phase, notes}). A research iteration
+// has no report: its result is its acquisitions.
+
+import { providerOf, runAgent, type AgentTool } from "../../../llm";
+import { iterationLabel, updateIteration } from "../../iterations";
+import { UNATTENDED_RULE } from "../authoringRules";
+import type { Autonomy, ResearchLimits } from "../research/decide";
+import { acquisitionTools, archiveReadTools } from "../research/tools";
+import {
+ countProposals,
+ newResearchState,
+ phaseOf,
+ readResearchState,
+ writeResearchState,
+ type ResearchRecord,
+ type ResearchState,
+} from "../research/state";
+import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import type { EditorChannel, TaskDeps, TaskResult } from "./types";
+
+// The corpus reads a research run makes: enough to know what is already
+// held, never whole transcripts in bulk (that is the sweep's).
+export const RESEARCH_READ_TOOLS = [
+ "list_channels",
+ "search_transcripts",
+ "enumerate_matches",
+ "get_video_metadata",
+ "channel_coverage",
+ "get_post",
+] as const;
+
+// The local model's smaller set: its prompt is capped at 8k tokens, the tool
+// schemas included.
+const LOCAL_READ_TOOLS = ["list_channels", "search_transcripts", "get_video_metadata"] as const;
+
+export const RESEARCH_NOTES_CHARS = 4000;
+
+export type ResearchInput = {
+ article: string;
+ n: number;
+ // Default: the iteration's question, scope and model.
+ question?: string;
+ channels?: string[];
+ from?: string;
+ to?: string;
+ model?: string;
+ // The article's citation origin (evidence links into the corpus).
+ origin: string;
+ maxUsd: number;
+ autonomy: Autonomy;
+ limits: ResearchLimits;
+ web?: boolean;
+ webSearchMaxUses?: number;
+ maxTurns?: number;
+};
+
+function autonomyLine(a: Autonomy, l: ResearchLimits): string {
+ const caps = `${l.maxItemsPerRun} item(s), ${l.maxGbPerRun} GB and ${l.maxTranscribeHours} h of transcription`;
+ switch (a) {
+ case "propose":
+ return "This run PROPOSES: every acquisition you ask for waits for the operator's yes or no. Ask for everything the report needs, each once, with its reason and evidence.";
+ case "limits":
+ return (
+ `This run acts WITHIN LIMITS: an acquisition into an existing channel runs at once while the run stays under ${caps} and its size is known` +
+ `${l.newChannelsNeedApproval ? "; a new channel waits for the operator" : ""}${l.postWalksNeedApproval ? "; a walk over an account's post history waits" : ""}` +
+ "; a priority change waits; anything past a cap waits."
+ );
+ case "auto":
+ return `This run is AUTONOMOUS: acquisitions run at once, through the editor, while the run stays under ${caps}; past a cap, or of unknown size, they wait for the operator.`;
+ }
+}
+
+function systemPrompt(o: { autonomy: Autonomy; limits: ResearchLimits; origin: string; maxUsd: number; local: boolean }): string {
+ return [
+ UNATTENDED_RULE,
+ "",
+ "You RESEARCH a question for a report from an archive of transcripts and posts. You do not write the report: you find what the archive lacks for a complete answer and ask the editor to acquire it. A sweep reads the widened archive afterwards.",
+ "",
+ "1. Discover. Search the archive first (search_transcripts, enumerate_matches, list_channels, get_video_metadata): what does it already hold on the question, and from whom? editor_channels lists every channel the editor archives (some are on no public site). Then look outside: web_search / web_fetch for where the missing material is, and archive-search / archive-item for archive.org items (a show's archive, a deleted stream someone saved) — read an item's file list before you propose it.",
+ "2. Propose. For each acquisition the report needs for complete context, call its tool once: the editor action's own arguments, a `reason` (what the report gains), `evidence` (the links that show it: search results, item pages, posts) and an `estimate` (items; gb from the item's file sizes; transcribeHours from its lengths). An honest estimate matters: one of unknown size waits for approval.",
+ " - import-archive-org / import-video: media into an EXISTING channel (prefer a whole archive.org item over one-by-one platform fetches; name the files or a match when only some are needed).",
+ " - create-channel: a new channel, only when no existing one fits. It is always created on NO site: never pass `sites` — the operator puts it on one.",
+ " - fetch-posts / capture-posts / import-post: posts — a channel's new posts, one post by its URL, screenshots of archived ones. A full or older walk is a post walk.",
+ " - transcribe-one, persist-videos, priority-bump: transcription and keeping media for what is already held.",
+ "3. The standing rules (refused in every mode): never a Twitch VOD URL (expired VODs are gone — look for the stream on archive.org or elsewhere); an X channel never goes on a site; nothing bypasses the editor's queues. The editor paces every platform and holds one that is rate-limited: do not repeat an acquisition, and do not fetch anything yourself.",
+ `4. ${autonomyLine(o.autonomy, o.limits)}`,
+ "",
+ `Links into the archive are on ${o.origin}. This run's budget is about $${o.maxUsd === Number.POSITIVE_INFINITY ? "0 (a local model)" : o.maxUsd.toFixed(2)}.`,
+ o.local ? "Be brief: your context is small. One search at a time." : "",
+ "When you are done, stop calling tools and answer in a few lines: what the archive already holds on the question, what you asked for and why, and what is still missing.",
+ ]
+ .filter((l) => l !== "")
+ .join("\n");
+}
+
+function channelsTool(list: () => Promise<EditorChannel[]>): AgentTool {
+ return {
+ name: "editor_channels",
+ description: "Every channel the editor archives (slug, name, platform, what it holds) — the channels an import goes into. Some are on no public site.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ run: async () => {
+ const all = await list();
+ if (!all.length) return "The editor archives no channels.";
+ return all
+ .map((c) => `- ${c.slug}${c.name ? ` — ${c.name}` : ""}${[c.platform, c.kind].filter(Boolean).length ? ` (${[c.platform, c.kind].filter(Boolean).join(", ")})` : ""}${c.url ? ` ${c.url}` : ""}`)
+ .join("\n");
+ },
+ };
+}
+
+export async function research(input: ResearchInput, deps: TaskDeps): Promise<TaskResult> {
+ return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["research"] }, (h) => researchBody(h, input));
+}
+
+async function researchBody(h: TaskHandle, input: ResearchInput): Promise<TaskOutcome> {
+ const { deps, iteration } = h;
+ const editor = deps.editor;
+ if (!editor) throw new TaskInputError("a research run needs the editor (its archive.org reads and acquisitions are editor actions)");
+ const question = (input.question ?? iteration.question ?? "").trim();
+ if (!question) throw new TaskInputError("a research run needs its question");
+ const channels = input.channels ?? iteration.scope?.channels ?? [];
+ const from = input.from ?? iteration.scope?.from;
+ const to = input.to ?? iteration.scope?.to;
+ const model = input.model ?? iteration.model;
+ const local = providerOf(model) === "local";
+ const origin = input.origin.replace(/\/+$/, "");
+
+ // Resumed (the job ran before): its proposals stand, with their autonomy.
+ const state: ResearchState = (await readResearchState(h.article, h.n, h.paths)) ?? newResearchState(input.autonomy, input.limits);
+ const save = () => writeResearchState(h.article, h.n, state, h.paths);
+ await save();
+ const record = (patch: Partial<ResearchRecord>): ResearchRecord => ({
+ autonomy: state.autonomy,
+ phase: "discover",
+ ...((iteration as { research?: ResearchRecord }).research ?? {}),
+ ...patch,
+ });
+ await updateIteration(h.article, h.n, { research: record({ phase: "discover" }) }, h.paths);
+ h.log(`${iterationLabel(h.n)} research on ${model} (${state.autonomy}), corpus ${deps.corpus.source}`);
+
+ const readNames: readonly string[] = local ? LOCAL_READ_TOOLS : RESEARCH_READ_TOOLS;
+ const corpusTools = deps.corpus.tools.filter((t) => readNames.includes(t.name));
+ const web = input.web === false ? [] : (deps.web ?? []);
+ const tools: AgentTool[] = [
+ ...corpusTools,
+ ...(deps.editorChannels ? [channelsTool(deps.editorChannels)] : []),
+ ...archiveReadTools({ editor }),
+ ...acquisitionTools({
+ editor,
+ autonomy: state.autonomy,
+ limits: state.limits,
+ ledger: state,
+ onChange: async () => {
+ await save();
+ },
+ }),
+ ...web,
+ ];
+
+ const scope = [
+ channels.length ? `The archive's channels on it so far: ${channels.join(", ")}.` : "No channel is named yet: find who and where.",
+ from || to ? `The question is dated${from ? ` from ${from}` : ""}${to ? ` to ${to}` : ""}.` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+ const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => {
+ if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`);
+ else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`);
+ else if (e.type === "note") h.log(e.text);
+ };
+ const run = await runAgent({
+ llm: deps.llm,
+ model,
+ system: systemPrompt({ autonomy: state.autonomy, limits: state.limits, origin, maxUsd: input.maxUsd, local }),
+ user: `Research this for a report: ${question}\n\n${scope}`,
+ tools,
+ meter: h.meter,
+ maxUsd: input.maxUsd,
+ maxTurns: input.maxTurns ?? 60,
+ ...(!local && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 5 } } : {}),
+ signal: deps.signal,
+ onEvent,
+ });
+ h.turns(run.transcript);
+ if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" };
+
+ const c = countProposals(state);
+ const phase = phaseOf(state);
+ const notes = run.text.trim().slice(0, RESEARCH_NOTES_CHARS);
+ const parts = [
+ c.enqueued && `${c.enqueued} enqueued`,
+ c.done && `${c.done} done`,
+ c.proposed && `${c.proposed} waiting for approval`,
+ c.rejected && `${c.rejected} refused`,
+ c.failed && `${c.failed} failed`,
+ ].filter(Boolean);
+ h.log(`agent ended: ${run.stopReason}; ${state.proposals.length} acquisition(s)${parts.length ? `: ${parts.join(", ")}` : ""}`);
+ return {
+ status: "done",
+ summary:
+ `${state.proposals.length} acquisition(s)${parts.length ? ` (${parts.join(", ")})` : ""} — ${phase === "ready" ? "nothing pending: ready to continue" : "waiting"}` +
+ `${run.stopReason === "end_turn" ? "" : ` (the agent stopped: ${run.stopReason})`} — ~$${h.meter.usd.toFixed(2)}`,
+ patch: { research: record({ phase, ...(notes ? { notes } : {}) }) },
+ };
+}
diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts
@@ -12,6 +12,7 @@ import type { AgentTool, LlmConfig } from "../../../llm";
import type { CuesOf, PostChannelOf } from "../../convertShared";
import type { readIteration } from "../../iterations";
import type { Report } from "../../schema";
+import type { ResearchEditor } from "../research/tools";
// The iterations store's paths (S4 takes them on every call).
export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>;
@@ -42,6 +43,11 @@ export type TaskDeps = {
postChannelOf?: PostChannelOf;
// An extra check of a converted report (the editor's verify-quotes).
verifyReport?: (report: Report) => Promise<ExternalQuoteProblem[]>;
+ // A research run's editor: the ops actions it reads archive.org through and
+ // enqueues acquisitions with (S11; the editor passes itself, in process).
+ editor?: ResearchEditor;
+ // The editor's channels (a research run imports into these first).
+ editorChannels?: () => Promise<EditorChannel[]>;
// The iterations store (default: getPaths()).
paths?: StorePaths;
now?: () => Date;
@@ -49,6 +55,9 @@ export type TaskDeps = {
signal?: AbortSignal;
};
+// One editor channel, as a research run sees it.
+export type EditorChannel = { slug: string; name?: string; platform?: string; kind?: string; url?: string };
+
export type TaskStatus = "done" | "failed" | "cancelled";
export type TaskResult = {
@@ -61,5 +70,5 @@ export type TaskResult = {
minutes: number;
};
-export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate"] as const;
+export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate", "research"] as const;
export type TaskName = (typeof TASK_NAMES)[number];
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -26,6 +26,7 @@ import {
ORPHEUS_TTS_SETTINGS_FIELD_DOCS,
GENERATION_CAPS_FIELD_DOCS,
GENERATION_MODELS_FIELD_DOCS,
+ GENERATION_RESEARCH_FIELD_DOCS,
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
@@ -285,6 +286,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.models", docs: GENERATION_MODELS_FIELD_DOCS, defaults: fromObject(d.generation.models) },
{ path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) },
{ path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) },
+ { path: "generation.research", docs: GENERATION_RESEARCH_FIELD_DOCS, defaults: fromObject(d.generation.research) },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -83,6 +83,7 @@ import { sanitizeGeneration, type GenerationSettings } from "./generationSetting
export {
GENERATION_CAPS_FIELD_DOCS,
GENERATION_MODELS_FIELD_DOCS,
+ GENERATION_RESEARCH_FIELD_DOCS,
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -18,7 +18,7 @@ transcript, channel or person goes in these fixtures, ever.
| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. |
| `web/fakeWeb.mjs` | A fake web on loopback: a DuckDuckGo-shaped HTML search (`POST /html/`, links in the `uddg` redirect, an ad), pages, plain text, a long page, redirects and a redirect loop, a PDF, a 429 that clears (`busyTimes`), a 503 that does not. `web.searchUrl` is what `webSearch` takes. |
| `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. |
-| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`) or the fake ollama (`sweep-pipeline`, `narrate`), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
+| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. |
| `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. |
As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and
diff --git a/common/testing/draft/runs/research.json b/common/testing/draft/runs/research.json
@@ -0,0 +1,124 @@
+{
+ "task": "research",
+ "model": "claude-sonnet-5-5",
+ "question": "Where did the second shop story start?",
+ "channels": [
+ "synth-kitchen"
+ ],
+ "turns": [
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "First, what the archive already holds."
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_r01",
+ "name": "search_transcripts",
+ "input": {
+ "query": "second shop"
+ }
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_r02",
+ "name": "editor_channels",
+ "input": {}
+ }
+ ],
+ "stop_reason": "tool_use"
+ },
+ {
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_r03",
+ "name": "archive-search",
+ "input": {
+ "query": "synth kitchen"
+ }
+ }
+ ],
+ "stop_reason": "tool_use"
+ },
+ {
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_r04",
+ "name": "archive-item",
+ "input": {
+ "item": "synth-kitchen-episodes-2026"
+ }
+ }
+ ],
+ "stop_reason": "tool_use"
+ },
+ {
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_r05",
+ "name": "import-archive-org",
+ "input": {
+ "slug": "synth-kitchen",
+ "item": "synth-kitchen-episodes-2026",
+ "files": [
+ "Bread day.mp4"
+ ],
+ "reason": "The bread day episode, where the second shop is first named, is not in the archive.",
+ "evidence": [
+ "https://archive.org/details/synth-kitchen-episodes-2026"
+ ],
+ "estimate": {
+ "items": 1,
+ "gb": 0.1,
+ "transcribeHours": 0.02
+ }
+ }
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_r06",
+ "name": "create-channel",
+ "input": {
+ "fields": {
+ "name": "Synth Radio",
+ "handling": "transcribe",
+ "url": "https://archive.org/details/synth-radio-tape-01"
+ },
+ "reason": "The radio call-in where the shop story is told has no channel.",
+ "evidence": [
+ "https://archive.org/details/synth-radio-tape-01"
+ ]
+ }
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_r07",
+ "name": "import-video",
+ "input": {
+ "slug": "synth-kitchen",
+ "url": "https://www.twitch.tv/videos/123456789",
+ "reason": "The launch stream.",
+ "estimate": {
+ "items": 1,
+ "gb": 1
+ }
+ }
+ }
+ ],
+ "stop_reason": "tool_use"
+ },
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "The archive holds the pie stream on the shop. I asked for the bread day episode from archive.org and a channel for the radio tape; the launch stream is a Twitch VOD and is gone."
+ }
+ ],
+ "stop_reason": "end_turn"
+ }
+ ]
+}
diff --git a/common/testing/llm/fakeAnthropic.mjs b/common/testing/llm/fakeAnthropic.mjs
@@ -28,7 +28,7 @@
import http from "node:http";
import { createHash } from "node:crypto";
-export const FAKE_KEY = "sk-ant-fake-0000-TESTKEY-never-real";
+export const FAKE_KEY = "fake-anthropic-0000-TESTKEY-never-a-real-key";
export const DEFAULT_STRICT_MODELS = ["claude-sonnet-5-5"];
const tok = (v) => Math.max(1, Math.ceil(JSON.stringify(v ?? "").length / 4));
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **Research runs: the editor finds what an article's archive lacks and asks for it.** `pnpm ops report-draft --json '{"task": "research", "article", "question", "channels"?, "autonomy"?}'` runs a research iteration: a model searches the corpus, the web and archive.org (an item's file list included), then proposes each acquisition it needs (an archive.org import, a video, a new channel, a post, a transcription, a persist) with its reason, evidence links and estimated size. Under `propose` every one waits for your yes or no; under `limits` imports into existing channels under the caps run at once; under `auto` everything runs, through the editor's own queues and holds, until a cap. A new channel is always created on no site, an X channel is never put on one, and a Twitch VOD is never fetched, in every mode. The proposals are kept in the iteration's `proposals.json`.
+- **`pnpm ops research-approve` settles a research run.** `{"article", "iteration", "ids": ["p01", …], "approve": true | false, "note"?}` runs the approved proposals through the editor (past the run's autonomy and caps, never past a standing rule) or rejects them; with no ids it answers the run's state. Every call first checks the jobs of what was enqueued, so the run moves from waiting to ready as they finish. `report-draft {"task": "sweep", "article", "iteration": <the research run>}` then continues it: a sweep over the run's channels and every channel it acquired into, its question by default (refused while the run still waits, unless `"force": true`).
+- **New settings: `generation.research`** (SETTINGS.md): a research run's default autonomy (`propose`), and its limits — 20 items, 5 GB and 6 hours of transcription a run, new channels and post walks waiting for approval under `limits`. `generation.routes.research` says where a research run runs (`api` in the balanced preset); a settings file from before keeps its preset.
- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
- **Spending on the Claude API is capped.** A job is capped by its task ($5 a sweep, $2 a revision, $1 a narration, or the `maxUsd` it asks for, never above `settings.generation.caps.max`), and the editor refuses a job once the day's API spend (UTC) has reached `caps.daily` ($20), naming the day's total. Each finished API job adds its spend to a ledger beside the checkout (`.generation/usage.jsonl`), which is where the day's total comes from.
- **New settings block `generation`** (SETTINGS.md): where each task runs (`code` = Claude Code, `api`, `local`, with the presets `code`, `balanced`, `api`, `local`), the models, the caps, the API key FILE (mode 600; the key itself is refused as a setting and never stored), and where video projects live (`projectsRoot`, which `umtool chain` now reads too).
diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts
@@ -0,0 +1,58 @@
+import { getWorkerToken } from "yt-dlp-transcript-common/lib/workerToken";
+import type { ResearchEditor } from "yt-dlp-transcript-common/lib/report/draft/research/tools";
+
+// A RESEARCH RUN'S EDITOR IS THIS EDITOR (release 27 S11).
+//
+// A research job's archive.org reads and acquisitions are ops actions — the
+// same routes `pnpm ops` posts to — called IN PROCESS: the route handler with
+// a Request carrying the editor's own worker token. So an acquisition meets
+// exactly the door an agent over HTTP meets (the body's keys, the slug check,
+// the platform's hold, the queue), with the same refusal in the same words,
+// and no URL of its own to know. Only the actions a research run may ask for
+// are here.
+
+type Post = (request: Request) => Promise<Response>;
+
+const ROUTES: Record<string, () => Promise<{ POST: Post }>> = {
+ "archive-search": () => import("./archive-search/route"),
+ "archive-item": () => import("./archive-item/route"),
+ "import-archive-org": () => import("./import-archive-org/route"),
+ "import-video": () => import("./import-video/route"),
+ "create-channel": () => import("./create-channel/route"),
+ "fetch-posts": () => import("./fetch-posts/route"),
+ "capture-posts": () => import("./capture-posts/route"),
+ "import-post": () => import("./import-post/route"),
+ "transcribe-one": () => import("./transcribe-one/route"),
+ "channel-priority": () => import("./channel-priority/route"),
+ "persist-videos": () => import("./persist-videos/route"),
+};
+
+export const RESEARCH_EDITOR_ACTIONS = Object.keys(ROUTES);
+
+export const researchEditor: ResearchEditor = {
+ async run(action, args) {
+ const load = ROUTES[action];
+ if (!load) throw new Error(`"${action}" is not an action a research run may ask the editor for`);
+ const token = getWorkerToken();
+ if (!token) throw new Error("the editor's ops actions are off (WORKER_TOKEN is unset)");
+ const { POST } = await load();
+ const res = await POST(
+ new Request(`http://localhost/api/ops/${action}`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify(args),
+ }),
+ );
+ let body: Record<string, unknown> = {};
+ try {
+ const j = await res.json();
+ if (j && typeof j === "object" && !Array.isArray(j)) body = j as Record<string, unknown>;
+ } catch {
+ // not JSON: refused below with the status
+ }
+ if (res.status < 200 || res.status >= 300 || body.ok === false) {
+ throw new Error(typeof body.error === "string" && body.error ? body.error : `HTTP ${res.status}`);
+ }
+ return body;
+ },
+};
diff --git a/editor/app/api/ops/_researchRuns.test.ts b/editor/app/api/ops/_researchRuns.test.ts
@@ -0,0 +1,222 @@
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
+import { ORIGIN, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
+import { FAKE_KEY, startFakeAnthropic, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft";
+import { approveResearch, researchState } from "yt-dlp-transcript-common/controller/researchRuns";
+import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import { createIteration, readIteration, updateIteration } from "yt-dlp-transcript-common/lib/report/iterations";
+import { readResearchState, writeResearchState, newResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state";
+import { DEFAULT_RESEARCH_LIMITS } from "yt-dlp-transcript-common/lib/report/draft/research/decide";
+import type { ResearchEditor } from "yt-dlp-transcript-common/lib/report/draft/research/tools";
+import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths";
+import { callPost, setupOpsCorpus, type OpsCorpus } from "./_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_researchRuns.test.ts"
+//
+// Research runs (release 27 S11) end to end in this process: a `report-draft`
+// research job over the synthetic corpus (the MCP's tools) against the fake
+// Anthropic server and a fake editor; the operator's yes and no
+// (research-approve's controller), the refresh from job states, and the
+// continuation into a sweep. Then the in-process editor and the route's door
+// over the ops test corpus.
+
+const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft");
+let tmp: string;
+let api: FakeAnthropic;
+let source: string;
+let paths: Paths;
+let gen: GenerationSettings;
+let ops: OpsCorpus;
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "research-runs-"));
+ source = `local:${await writeDraftCorpus(path.join(tmp, "corpus"))}`;
+ api = await startFakeAnthropic();
+ const keyFile = path.join(tmp, "anthropic.env");
+ await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`);
+ await chmod(keyFile, 0o600);
+ await mkdir(path.join(tmp, "channels"), { recursive: true });
+ 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;
+ gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, citationOrigin: ORIGIN, caps: { sweep: 2, daily: 20, max: 5 } });
+ ops = await setupOpsCorpus("one-youtube-channel-with-data");
+});
+
+after(async () => {
+ await api.close();
+ await ops.cleanup();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+// A fake editor: the archive reads answer, every acquisition is a job.
+const editorCalls: { action: string; args: Record<string, unknown> }[] = [];
+const fakeEditor: ResearchEditor = {
+ run: async (action, args) => {
+ editorCalls.push({ action, args });
+ if (action === "archive-search") return { ok: true, found: 1, items: [{ identifier: "synth-kitchen-episodes-2026" }] };
+ if (action === "archive-item") return { ok: true, item: { identifier: "synth-kitchen-episodes-2026", files: [{ name: "Bread day.mp4", size: 104857600 }] } };
+ if (action === "create-channel") return { ok: true, slug: "synth-radio", jobIds: ["job-c1"], jobId: "job-c1" };
+ return { ok: true, jobId: `job-${action}` };
+ },
+};
+const jobs: Record<string, { status: string; endedAt?: number }> = {};
+const jobOf = async (id: string) => jobs[id] ?? (getRegistry().get(id) ? { status: getRegistry().get(id)!.status } : null);
+
+const deps = (g: Partial<GenerationSettings> = {}) => ({
+ paths,
+ corpusTools: (s: string) => createCorpusTools({ source: s }),
+ settings: () => ({ generation: { ...gen, ...g } }),
+ researchEditor: fakeEditor,
+ jobOf,
+});
+
+const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8"));
+
+test("the body: research needs its question and takes an autonomy; a sweep with an iteration continues", () => {
+ assert.throws(() => parseReportDraftBody({ task: "research", article: "a" }), /research run needs its question/);
+ assert.throws(() => parseReportDraftBody({ task: "research", article: "a", question: "q", autonomy: "yolo" }), /"autonomy" is one of propose, limits, auto/);
+ assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: "x", autonomy: "auto" }), /a research run's/);
+ assert.deepEqual(parseReportDraftBody({ task: "research", article: "a", question: "q", autonomy: "limits" }), { task: "research", article: "a", question: "q", autonomy: "limits" });
+ assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", iteration: 2 }), { task: "sweep", article: "a", iteration: 2 });
+});
+
+test("refused: research with no editor in the deps; a continuation of what is not a research run", async () => {
+ const { researchEditor: _e, ...noEditor } = deps();
+ const out = await enqueueReportDraft({ task: "research", article: "synth-noeditor", model: "claude-sonnet-5-5", question: "q", source }, noEditor);
+ assert.match((out.result as { error: string }).error, /research run runs in the editor/);
+ await createIteration("synth-notresearch", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const cont = await enqueueReportDraft({ task: "sweep", article: "synth-notresearch", iteration: 1, model: "claude-sonnet-5-5", source }, deps());
+ assert.match((cont.result as { error: string }).error, /continues a research run; "synth-notresearch" i1 is a sweep iteration/);
+});
+
+test("a research run: the job proposes, the operator approves and rejects, the jobs settle, a sweep continues it", async () => {
+ const r = await run("research");
+ api.push(...r.turns);
+ const article = "synth-research";
+ const out = await enqueueReportDraft({ task: "research", article, model: r.model, question: r.question, channels: r.channels, source }, deps());
+ assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error);
+ const job = getRegistry().get(out.result.jobId)!;
+ assert.equal(job.queueKey, "draft:api");
+ void out.result.stream.cancel();
+ const done = await out.result.done;
+ const log = await readFile(job.logPath, "utf8");
+ assert.equal(done.status, "done", log);
+ assert.match(log, /@@report-draft \{"article":"synth-research","iteration":1,"task":"research","status":"done"/);
+ // settings' autonomy: propose — only the reads reached the editor.
+ assert.deepEqual(editorCalls.map((c) => c.action), ["archive-search", "archive-item"]);
+ let it = (await readIteration(article, 1, paths))!;
+ assert.equal(it.kind, "research");
+ assert.equal((it as { research?: { phase?: string } }).research!.phase, "wait");
+
+ // Not continued while it waits.
+ const early = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: "claude-sonnet-5-5", source }, deps());
+ assert.match((early.result as { error: string }).error, /i1 still waits — for approval: p01, p02/);
+
+ // The operator: yes to the import, no to the channel; the refused one cannot be approved.
+ jobs["job-import-archive-org"] = { status: "running" };
+ const yes = await approveResearch({ article, iteration: 1, ids: ["p01", "p03"], approve: true }, { paths, editor: fakeEditor, jobOf });
+ assert.ok(yes.ok, (yes as { error?: string }).error);
+ assert.deepEqual(yes.outcomes[0], { id: "p01", status: "enqueued", jobId: "job-import-archive-org" });
+ assert.match(yes.outcomes[1]!.error!, /p03 is rejected, not waiting for approval/);
+ assert.deepEqual(editorCalls.at(-1), { action: "import-archive-org", args: { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", files: ["Bread day.mp4"] } });
+ const no = await approveResearch({ article, iteration: 1, ids: ["p02"], approve: false, note: "not this one" }, { paths, editor: fakeEditor, jobOf });
+ assert.ok(no.ok);
+ assert.equal(no.view.proposals[1]!.note, "the operator said no: not this one");
+ assert.equal(no.view.phase, "wait");
+ assert.deepEqual(no.view.waitingOn, { approval: [], jobs: ["job-import-archive-org"] });
+
+ // The import's job ends: the next read settles it, and the run is ready.
+ jobs["job-import-archive-org"] = { status: "done", endedAt: Date.now() };
+ const ready = await researchState(article, 1, { paths, jobOf });
+ assert.equal(ready.phase, "ready");
+ assert.equal(ready.proposals[0]!.status, "done");
+ assert.equal((await readResearchState(article, 1, paths))!.proposals[0]!.status, "done", "written");
+
+ // Continue: a sweep over the widened scope, its parent the research run.
+ const sw = await run("sweep-agent");
+ api.push(...sw.turns);
+ const cont = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: sw.model, source }, deps());
+ assert.ok(cont.result.ok && "iteration" in cont, (cont.result as { error?: string }).error);
+ void cont.result.stream.cancel();
+ const cdone = await cont.result.done;
+ assert.equal(cdone.status, "done", await readFile(getRegistry().get(cont.result.jobId)!.logPath, "utf8"));
+ const sweep = (await readIteration(article, cont.iteration, paths))!;
+ assert.equal(sweep.kind, "sweep");
+ assert.equal(sweep.parent, 1);
+ assert.equal(sweep.question, r.question);
+ assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]);
+ assert.equal(sweep.status, "done");
+ it = (await readIteration(article, 1, paths))!;
+ assert.deepEqual((it as { research?: { phase?: string; continuedBy?: number[] } }).research, {
+ ...(it as { research?: object }).research,
+ phase: "continued",
+ continuedBy: [cont.iteration],
+ });
+});
+
+test("approve is refused while the run's job is going; force continues a run that still waits", async () => {
+ const article = "synth-research-two";
+ await createIteration(article, { kind: "research", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const state = newResearchState("propose", DEFAULT_RESEARCH_LIMITS);
+ state.proposals.push({ id: "p01", action: "import-video", args: { slug: "synth-kitchen", url: "https://video.example/v/9" }, reason: "r", evidence: [], status: "proposed" });
+ await writeResearchState(article, 1, state, paths);
+ await updateIteration(article, 1, { status: "running" }, paths);
+ const busy = await approveResearch({ article, iteration: 1, ids: ["p01"], approve: true }, { paths, editor: fakeEditor, jobOf });
+ assert.equal(busy.ok, false);
+ assert.match((busy as { error: string }).error, /is running: its proposals are the run's until it ends/);
+ await updateIteration(article, 1, { status: "done" }, paths);
+ const sw = await run("sweep-agent");
+ api.push(...sw.turns);
+ const forced = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: sw.model, source, force: true }, deps());
+ assert.ok(forced.result.ok && "iteration" in forced, (forced.result as { error?: string }).error);
+ void forced.result.stream.cancel();
+ await forced.result.done;
+});
+
+// ─── the editor, in process, and the route's door ───
+
+test("the research editor is this editor's own ops routes, in process: their doors and words", async () => {
+ const { researchEditor } = await import("./_researchEditor");
+ await assert.rejects(researchEditor.run("archive-item", { item: "../../etc" }), /is not an archive\.org identifier/);
+ await assert.rejects(researchEditor.run("import-post", { slug: "test-youtube", url: "https://x.com/synthbaker/status/1" }), /test-youtube is not a posts channel/);
+ await assert.rejects(researchEditor.run("delete-channel", { slug: "test-youtube" }), /not an action a research run may ask the editor for/);
+});
+
+test("research-approve: the door — keys, ids, a run that is not there", async () => {
+ const route = (await import("./research-approve/route")).POST as Parameters<typeof callPost>[0];
+ const extra = await callPost(route, { article: "a", iteration: 1, sites: [] });
+ assert.equal(extra.status, 400);
+ assert.match(String(extra.body.error), /unknown key\(s\): sites/);
+ const badIds = await callPost(route, { article: "a", iteration: 1, ids: ["x1"], approve: true });
+ assert.match(String(badIds.body.error), /"ids" is a list of proposal ids/);
+ const noSay = await callPost(route, { article: "a", iteration: 1, ids: ["p01"] });
+ assert.match(String(noSay.body.error), /say "approve": true or false/);
+ const none = await callPost(route, { article: "synth-nothing", iteration: 1 });
+ assert.equal(none.status, 400);
+ assert.match(String(none.body.error), /"synth-nothing" has no iteration i1/);
+ // A run on the corpus the route reads: its state, refreshed.
+ const p = getPaths();
+ await createIteration("synth-door", { kind: "research", model: "claude-sonnet-5-5", question: "q" }, p);
+ await writeResearchState("synth-door", 1, newResearchState("limits", DEFAULT_RESEARCH_LIMITS), p);
+ await updateIteration("synth-door", 1, { status: "done" }, p);
+ const view = await callPost(route, { article: "synth-door", iteration: 1 });
+ assert.equal(view.status, 200, String(view.body.error));
+ const research = view.body.research as { phase: string; autonomy: string };
+ assert.equal(research.phase, "ready");
+ assert.equal(research.autonomy, "limits");
+});
diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts
@@ -3,12 +3,14 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft } from "yt-dlp-transcript-common/controller/reportDraft";
import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
import { jobResponse, ops } from "../_lib";
+import { researchEditor } from "../_researchEditor";
export const dynamic = "force-dynamic";
// POST { task, article, iteration?, model?, feedback?, question?, channels?,
-// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force? }
-// -> { ok: true, jobId, iteration }
+// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force?,
+// autonomy? }
+// -> { ok: true, jobId, iteration, warnings? }
//
// A generation over an article's iteration (release 27 S6), as a
// `report-draft` job on `draft:api` or `draft:local` by the model's provider:
@@ -17,6 +19,13 @@ export const dynamic = "force-dynamic";
// - "revise-report" / "revise-video": a new iteration revising `iteration`
// from `feedback`;
// - "narrate": a step on the done iteration `iteration` (`cards`, `force`);
+// - "research" (S11): a new research run from `question` (`channels`
+// optional, `autonomy` propose | limits | auto, default the settings'):
+// it discovers, proposes, and enqueues what its autonomy allows through
+// this editor's own ops actions (research-approve settles the rest);
+// - "sweep" with `iteration` N: CONTINUES research run N — its question and
+// its channels widened by what it acquired, the sweep's parent N (refused
+// while N still waits, unless `force`);
// - `copyOf` N: iteration N again on `model` (same kind and inputs).
// `model` defaults to settings.generation's route for the task (a task routed
// to `code` needs one named). An API job's cap is `maxUsd`, else the task's
@@ -30,9 +39,18 @@ export const dynamic = "force-dynamic";
// the corpus tools are the MCP's own, in process (mcp/src/callTool.ts).
export async function POST(request: Request) {
return ops(request, REPORT_DRAFT_BODY_KEYS, async (body) => {
- const out = await enqueueReportDraft(body, { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }) });
+ const out = await enqueueReportDraft(body, {
+ paths: getPaths(),
+ corpusTools: (source) => createCorpusTools({ source }),
+ researchEditor,
+ });
if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result);
void out.result.stream.cancel();
- return NextResponse.json({ ok: true, jobId: out.result.jobId, iteration: out.iteration });
+ return NextResponse.json({
+ ok: true,
+ jobId: out.result.jobId,
+ iteration: out.iteration,
+ ...(out.warnings?.length ? { warnings: out.warnings } : {}),
+ });
});
}
diff --git a/editor/app/api/ops/research-approve/route.ts b/editor/app/api/ops/research-approve/route.ts
@@ -0,0 +1,33 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { RESEARCH_APPROVE_BODY_KEYS, approveResearch } from "yt-dlp-transcript-common/controller/researchRuns";
+import { opsFail, ops } from "../_lib";
+import { researchEditor } from "../_researchEditor";
+
+export const dynamic = "force-dynamic";
+
+// POST { article, iteration, ids?, approve?, note? }
+// -> { ok: true, outcomes: [{id, status?, jobId?, note?, error?}], research }
+//
+// A research run's acquisitions (release 27 S11), after its job:
+// - first, always, the run is REFRESHED: an enqueued acquisition whose
+// editor jobs have all ended is done (or failed, naming the job), and
+// the run's phase follows (wait → ready);
+// - `ids` with `approve: true` runs each proposal's editor action — past
+// the run's autonomy and caps, never past a standing rule (no site for a
+// new channel, no Twitch VOD) — through this editor's own ops actions,
+// 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>}.
+//
+// AN ADAPTER: the rules are the controller's (controller/researchRuns.ts).
+export async function POST(request: Request) {
+ return ops(request, RESEARCH_APPROVE_BODY_KEYS, async (body) => {
+ const out = await approveResearch(body, { paths: getPaths(), editor: researchEditor });
+ if (!out.ok) return opsFail(out.error);
+ return NextResponse.json({ ok: true, outcomes: out.outcomes, research: out.view });
+ });
+}
diff --git a/plans/release-27.md b/plans/release-27.md
@@ -246,7 +246,7 @@ Each slice is merged `--no-ff` as it finishes, with its suites re-run.
### S0, as shipped (2026-10-13, orchestrator)
-`r27/integration` from `main` `9f05d557`, in the worktree `/home/user/Projects/r27-integration` (ports 4700–4720).
+`r27/integration` from `main` `9f05d557`, in the worktree `r27-integration`.
| Commit | What |
| --- | --- |
@@ -472,6 +472,49 @@ Gates:
- Editor build: the e2e prebuild's capped `next build` (heavy slot, 5 GB) at `12a4f48c`, 72 s, clean. (A standalone `next build` waited 33 min under the 6000 MB floor at 5.1–5.5 GB available and was stopped; the e2e run's build is the same app.)
- e2e `report-draft.spec.ts` + `digest.spec.ts`, one run: 18 passed, 0 failed, 41.5 s (report-draft 3 in 0.6 s, digest 15 in 21.2 s). The first attempt timed out in the heavy-slot queue and was re-run.
+### S11, as shipped — the backend (2026-10-13, lane G, `r27/research`)
+
+Research runs, on `r27/research` from `r27/integration` `5962c543`. The umtool queue lands after S8.
+
+| Commit | What |
+| --- | --- |
+| `ae2ed4dd` | `report/draft/tasks/research.ts`; `report/draft/research/state.ts`; `decide.ts` (the auto ruling); `controller/researchRuns.ts`; `report-draft` task `research` and the continuation; `settings.generation.research` and `routes.research`; the editor's `research-approve` route and `_researchEditor.ts`; ACTIONS row, help, COMMANDS.md, SETTINGS.md; tests and `testing/draft/runs/research.json` |
+| (this commit) | this record; the CHANGELOG bullets |
+
+- **The task** (`research`, an iteration of kind `research`): one agent run.
+ - It reads the corpus (`list_channels`, `search_transcripts`, `enumerate_matches`, `get_video_metadata`, `channel_coverage`, `get_post`; a local model gets three of them), `editor_channels` (every channel the editor archives), the web, and archive.org through the editor's `archive-search` / `archive-item`.
+ - It then calls S3b's acquisition tools. Each call is judged by `decideAcquisition`, then enqueued through the editor, left waiting, or refused.
+ - `proposals.json` (`{format, version, autonomy, limits, spent, proposals}`) is written on every change. The iteration's `research` key is `{autonomy, phase, notes, continuedBy?}`.
+ - A research iteration has no report. It ends `done` with its acquisitions, also when some still wait.
+- **Phases:** `discover` (the job runs), `wait` (a proposal waits for a yes or no, or an enqueued one's job has not ended), `ready` (nothing pending), `continued`.
+ - Nothing waits in a process. Every read through `research-approve`, and every continuation, first refreshes the enqueued acquisitions from their editor jobs (`getJobEntry`). All of a proposal's jobs done makes it `done` with `doneAt`. One failed, cancelled, lost (`archived`) or unknown makes it `failed`, naming the job.
+- **Autonomy (ruled 2026-10-13):**
+ - `auto` lifts the approval flags. The caps are hard ceilings: past one, or of unknown size, a proposal waits.
+ - Under `limits`, `newChannelsNeedApproval` and `postWalksNeedApproval` decide whether a new channel or a post walk waits. A priority bump always waits.
+ - An import's `estimate.transcribeHours` counts against `maxTranscribeHours`.
+ - The standing rules refuse in every mode.
+- **`pnpm ops research-approve {article, iteration, ids?, approve?, note?}`** → `{outcomes, research}`:
+ - `approve: true` runs each proposal through the editor (`runApprovedProposal`: past the autonomy and caps, never past a standing rule).
+ - `false` rejects it, with the note as why. No ids: the run's state.
+ - A run whose job is queued or running is refused: its proposals are the job's until it ends.
+ - Writes are serialized per run in the process.
+- **Continue = `report-draft {task: "sweep", iteration: <research n>}`**, chosen over a new ops verb.
+ - The sweep's parent is the research run. Its question is the run's, and its channels are the run's plus every channel a done acquisition wrote into (a created channel, an import's, a post's, a persisted item's); each can be given instead.
+ - Refused while the run waits, unless `force` (what is done so far).
+ - At the ask, a build must hold the widened channels (a channel on no site is in none until the operator puts it on a site and builds it). A build older than the last acquisition is answered as a `warnings` line.
+ - The run records `continuedBy`.
+- **The research job's editor is the editor itself.** `_researchEditor.ts` calls the ops route handlers in process, with a Request carrying the editor's worker token. An acquisition therefore meets the same door, holds and queues as `pnpm ops`, and the editor needs no URL of its own.
+- **Settings:**
+ - `generation.research {autonomy: "propose", maxItemsPerRun: 20, maxGbPerRun: 5, maxTranscribeHours: 6, newChannelsNeedApproval: true, postWalksNeedApproval: true}`.
+ - `generation.routes.research`: `api` in `balanced` and `api`, `local` in `local`, `code` in `code`. A settings file without it takes the research route of the preset its other routes match, so its preset is unchanged.
+ - A research job's cap is `caps.sweep`.
+
+Gates:
+- tsc clean (all packages).
+- common 3984/3984 (8 new: `research/runs.test.ts` 7, `generationSettings` 1; the S3b test now pins the auto ruling); mcp 323/323; editor unit 282/282 (6 new, `_researchRuns.test.ts`); `test:scripts` 851 pass + 3 skipped.
+- `docs env|files|cli --check`, `settings example --check`: clean.
+- Editor build (heavy slot, 5 GB cap): clean in 49 s, `/api/ops/research-approve` and `/api/ops/report-draft` built. No editor e2e: the route has no spec of its own (its door and the job are in `_researchRuns.test.ts`).
+
## Rollout
- Fast-forward `main`.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -102,6 +102,9 @@
// pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
+// pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
+// pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'
+// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -382,6 +385,10 @@ const ACTIONS = [
// model?, feedback?, question?, channels?, copyOf?, maxUsd?, …}), as a
// report-draft job on draft:api or draft:local. `job cancel` stops it.
"report-draft",
+ // RESEARCH RUNS (release 27 S11): a research run's acquisitions, after its
+ // job — refreshed from their jobs, then approved (run through the editor) or
+ // rejected ({article, iteration, ids?, approve?, note?}). Synchronous.
+ "research-approve",
];
// The log line a transcribe job ends with: this marker, then the result as
@@ -1146,7 +1153,8 @@ export function usage() {
"",
'report-draft runs a generation over an article\'s iteration as a',
' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |',
- ' "narrate", "article", ...} -> {jobId, iteration}. A sweep takes "question"',
+ ' "narrate" | "research", "article", ...} -> {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',
@@ -1159,6 +1167,28 @@ export function usage() {
' "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).',
+ "",
+ 'research-approve settles a research run\'s acquisitions: {"article",',
+ ' "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",
+ " 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.',
"",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
diff --git a/settings.json.example b/settings.json.example
@@ -243,7 +243,8 @@
"sweep": "code",
"revise-report": "api",
"revise-video": "local",
- "narrate": "local"
+ "narrate": "local",
+ "research": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -266,6 +267,14 @@
"provider": "duckduckgo",
"searchUrl": ""
},
- "citationOrigin": ""
+ "citationOrigin": "",
+ "research": {
+ "autonomy": "propose",
+ "maxItemsPerRun": 20,
+ "maxGbPerRun": 5,
+ "maxTranscribeHours": 6,
+ "newChannelsNeedApproval": true,
+ "postWalksNeedApproval": true
+ }
}
}