// TASK sweep-agent — /sweep as an agent, on Claude or a local model (release
// 27, S5; the stopgap's api_sweep.py).
//
// The plan text is the MCP's own `sweep_plan` (what Claude Code runs), worked
// with the MCP's read-only corpus tools in process; `extract_batch` stands in
// for the plan's extractor subagent (a cheap model returns the batch's
// relevant lines verbatim; the orchestrator does every bit of synthesis); the
// report tools write the iteration's sweep.md only. Then: the link backstop,
// convert, the strict quote check, ONE bounded repair round (the report tools
// only, the transcript ±45 s inline, an allowance of min($0.25, cap/4)), and a
// finding whose quote still fails is dropped.
//
// The run is TRACED (trace.jsonl, ./trace.ts; umtool R3): its scope, every
// enumeration (ids, partial, the channels never reached), every read, every
// extractor batch with the lines it returned, each turn's cost, every quote
// check — the ones dropped too, with why — and the findings it kept. The
// iteration's `coverage` is what it enumerated and read.
import { providerOf, runAgent, type AgentTool } from "../../../llm";
import type { Report } from "../../schema";
import { iterationLabel, readIterationFile, writeIterationFile } from "../../iterations";
import {
CLAIM_QUOTES_RULE,
COVERAGE_RULE,
EXTRACTOR_SYSTEM,
ONE_QUOTE_PER_FINDING_RULE,
POST_CITATION_RULE,
REPORT_STYLE_RULE,
UNATTENDED_RULE,
VERBATIM_QUOTES_RULE,
WHOLE_SENTENCE_QUOTE_RULE,
momentLinkRule,
} from "../authoringRules";
import { plainAnswer, userCharsFor } from "./llmText";
import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep, type QuoteProblem } from "./quotes";
import { reportFile } from "./reportFile";
import { restrictTools } from "./restrict";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
import { CoverageTally, countsOf, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace";
import type { TaskDeps, TaskResult } from "./types";
// The corpus reads the agent may make (no fetch_clip, enqueue, notes or jobs:
// clip media is the chain's, through the editor).
export const SWEEP_READ_TOOLS = [
"enumerate_matches",
"search_transcripts",
"get_transcript",
"get_transcripts",
"get_video_metadata",
"get_post",
"get_thread",
"list_channels",
"list_tags",
"channel_coverage",
] as const;
export const EXTRACT_INPUT_CAP = 400_000; // chars one extractor call reads (~110k tokens)
export const REPAIR_ALLOWANCE_USD = 0.25;
export const REPAIR_MAX_TURNS = 12;
export type SweepAgentInput = {
article: string;
n: number;
// Default: the iteration's question, scope and model.
question?: string;
channels?: string[];
from?: string;
to?: string;
model?: string;
extractorModel: string;
// The article's citation origin (links are built on it).
origin: string;
maxUsd: number;
batchSize?: number;
maxTurns?: number;
terms?: string[];
// Only these recordings (umtool R4: a refresh's new ones; R6's escalation):
// an enumeration shows only them, a read of any other is refused, and the
// free-text search is not offered. Default: the iteration's scope.ids.
ids?: string[];
// The web: Claude's server search (max uses) plus the deps' web_fetch; a
// local model gets the deps' web tools. Default on.
web?: boolean;
webSearchMaxUses?: number;
};
function runPreamble(o: { origin: string; maxUsd: number; terms?: string[]; from?: string; to?: string; ids?: string[] }): string {
const terms = o.terms?.length ? ` The operator chose these terms: ${o.terms.join(", ")} — use them.` : "";
const only = o.ids?.length
? `\n- THIS SWEEP IS RESTRICTED to ${o.ids.length} recording(s): ${o.ids.join(", ")}. Read only these — enumerate_matches shows only them, and a read of any other is refused. Report what they say; nothing else is in scope.`
: "";
const dates =
o.from || o.to
? `\n- The scope is dated${o.from ? ` from ${o.from}` : ""}${o.to ? ` to ${o.to}` : ""}: pass date_from / date_to on every enumerate and search.`
: "";
return [
UNATTENDED_RULE,
"",
"Your tools, mapped to the plan:",
"- The corpus tools (enumerate_matches, get_transcripts, …) are the MCP tools the plan names. `source` is filled in for you.",
"- `extract_batch` IS the plan's extractor subagent: give it the batch's video ids, the sweep's queries and the directive; it returns the verbatim lines. You may call it for several batches in one turn.",
"- `write_report` / `edit_report` / `read_report` are your Write/Edit tools, for the report file only.",
"- You cannot fetch clips, enqueue jobs or write notes here: skip those steps (the clips for every citation are fetched after you finish).",
`- The plan's \`query\` is the request's own wording. Search with real terms instead — a few words or phrases the question is about (and their obvious variants), not the sentence.${terms}${dates}${only}`,
"- Your context is trimmed as you go: a tool result older than the last few is dropped once you have merged it. Merge each fragment into the report BEFORE asking for many more, and use read_report rather than memory.",
"",
"The report must convert as a sweep:",
"- The first line is `#
`. The text before the first `##` is the summary.",
`- ${ONE_QUOTE_PER_FINDING_RULE}`,
`- ${CLAIM_QUOTES_RULE}`,
`- ${VERBATIM_QUOTES_RULE}`,
`- ${WHOLE_SENTENCE_QUOTE_RULE}`,
`- ${momentLinkRule(o.origin)}`,
`- ${POST_CITATION_RULE}`,
`- ${COVERAGE_RULE}`,
`- ${REPORT_STYLE_RULE}`,
"",
`This run's budget is about $${o.maxUsd.toFixed(2)}; read the whole worklist when it fits, and say so when it does not.`,
"When the report is final, stop calling tools and answer with one short line: the counts.",
].join("\n");
}
// What a seeded sweep is told (the seed is already the report file).
export const SEED_NOTE = [
"THE REPORT FILE ALREADY HOLDS THE OPERATOR'S RESEARCH BOARD (read_report): findings a person pinned after reading them, in sections, each a claim, a verbatim quote and its link, some with a `Note:` line.",
"- Start from it: keep its sections, its order and its claims. Check every quote against its transcript with get_transcripts like any other; correct a quote the transcript does not hold word for word, or remove it, and say which in the summary.",
"- A `Note:` line is the operator's: heed what it says (a speaker not checked, a drifted quote, a different en-orig track), then drop the Note lines from the final report.",
"- Its links may be on another origin: cite every finding as the rules say.",
"- Then sweep the plan for what the board does not cover, and merge it into the board's sections (or new ones).",
].join("\n");
const REPAIR_SYSTEM = [
UNATTENDED_RULE,
"",
"You repair a sweep report whose quote checks failed. You have the report tools only (read_report, edit_report, write_report); the transcript each fix needs is in the message.",
`- ${VERBATIM_QUOTES_RULE}`,
`- ${CLAIM_QUOTES_RULE}`,
`- ${WHOLE_SENTENCE_QUOTE_RULE}`,
"For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second); a fragment's fix is the whole sentence given with it; or remove the finding. Never invent words. Edit the report only, then stop.",
].join("\n");
// Where the agent is (the turn its tool calls belong to), and what it has
// enumerated and read: the trace's and the coverage's.
type Watch = { turn: number; phase: "agent" | "repair"; batches: number; cov: CoverageTally };
function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise, count: { n: number }, watch: Watch): AgentTool {
const batch = input.batchSize ?? 10;
return {
name: "extract_batch",
description:
`The extractor subagent for one batch (up to ${batch} ids): fetches the batch's transcripts (get_transcripts, ` +
"link_style base, the given queries) and returns ONLY the lines relevant to the directive, verbatim, grouped per " +
"video with its moment_base. Merge what it returns into the report.",
inputSchema: {
type: "object",
properties: {
video_ids: { type: "array", items: { type: "string" }, maxItems: Math.max(batch, 1) * 2 },
queries: { type: "array", items: { type: "string" }, description: "the sweep's search queries (the matched windows are what is read)" },
directive: { type: "string", description: "what to extract" },
channel: { type: "string", description: "optional channel slug, when every id is one channel's" },
},
required: ["video_ids", "queries", "directive"],
},
run: async (inp: { video_ids?: unknown; queries?: unknown; directive?: unknown; channel?: unknown }, ctx) => {
const ids = Array.isArray(inp.video_ids) ? inp.video_ids.filter((x): x is string => typeof x === "string") : [];
if (!ids.length) throw new Error("extract_batch needs video_ids");
const k = ++watch.batches;
const { turn, phase } = watch;
const before = h.meter.usd;
const args: Record = {
video_ids: ids,
queries: Array.isArray(inp.queries) ? inp.queries : [],
link_style: "base",
...(typeof inp.channel === "string" && inp.channel ? { channel: inp.channel } : {}),
};
let text = await rewrite(await h.deps.corpus.call("get_transcripts", args));
const cap = userCharsFor(h.deps.llm, input.extractorModel, EXTRACTOR_SYSTEM, EXTRACT_INPUT_CAP);
let note = "";
if (text.length > cap) {
text = text.slice(0, cap);
note = "\n(the batch's text was cut at the extractor's input cap — split the batch to read the rest)";
}
const out = await plainAnswer({
llm: h.deps.llm,
model: input.extractorModel,
system: EXTRACTOR_SYSTEM,
user: `Directive: ${String(inp.directive ?? "")}\n\n${text}`,
meter: h.meter,
signal: ctx?.signal ?? h.deps.signal,
// The model log: the extractor's batch, handed back to the agent as it read.
call: { phase: "reading", label: `extract batch ${k} (${ids.length} recording${ids.length === 1 ? "" : "s"})` },
});
count.n++;
// The batch, traced: its ids and the extractor's own lines.
const usd = h.meter.usd - before;
watch.cov.readIds(ids);
const of = Math.max(k, Math.ceil(watch.cov.matched.size / Math.max(batch, 1)));
h.trace({ t: "batch", k, of, ids, lines: linesOf(out), model: input.extractorModel, usd, ...(note ? { cut: true } : {}), turn, phase });
h.trace({ t: "cost", step: `batch ${k}`, usd, model: input.extractorModel, total: h.meter.usd, turn, phase });
return out + note;
},
};
}
export async function sweepAgent(input: SweepAgentInput, deps: TaskDeps): Promise {
return runOnIteration(
{
article: input.article,
n: input.n,
deps,
maxUsd: input.maxUsd,
kinds: ["sweep"],
trace: { task: "sweep-agent", ...(input.model ? { model: input.model } : {}), extractor: input.extractorModel },
},
(h) => sweepAgentBody(h, input),
);
}
// The sweep's body over a handle (exported: a refresh runs it on its own
// iteration, restricted to its new recordings — draft/refresh/task.ts).
export async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise {
const { deps, iteration } = h;
const question = (input.question ?? iteration.question ?? "").trim();
const channels = input.channels ?? iteration.scope?.channels ?? [];
const model = input.model ?? iteration.model;
const from = input.from ?? iteration.scope?.from;
const to = input.to ?? iteration.scope?.to;
const only = input.ids ?? iteration.scope?.ids;
if (!question) throw new TaskInputError("a sweep needs its question");
if (!channels.length) throw new TaskInputError("a sweep needs its channels");
const origin = input.origin.replace(/\/+$/, "");
const batch = input.batchSize ?? 10;
const resolver = slugResolver(deps.corpus, channels);
const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin);
// A SEEDED sweep (reportDraft's `seed`, a research board): the report starts
// as the seed, and the agent verifies and extends it.
const seed = (await readIterationFile(h.article, h.n, "seed.md", h.paths).catch(() => null))?.trim() || null;
const file = reportFile({ article: h.article, n: h.n, paths: h.paths, ...(seed ? { initial: seed } : {}) });
if (seed) await file.set(seed); // sweep.md holds it from the first turn, as a run cut short keeps it
const extracts = { n: 0 };
const watch: Watch = { turn: 0, phase: "agent", batches: 0, cov: new CoverageTally() };
h.setCoverage(() => watch.cov.value());
h.trace({
t: "scope",
source: deps.corpus.source,
channels,
...(from ? { from } : {}),
...(to ? { to } : {}),
question,
model,
extractor: input.extractorModel,
origin,
maxUsd: input.maxUsd,
batchSize: batch,
...(seed ? { seed: { chars: seed.length } } : {}),
...(only?.length ? { ids: only } : {}),
});
h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}${only?.length ? `, restricted to ${only.length} recording(s)` : ""}`);
const request =
`${question} channels=${channels.join(",")} batch_size=${batch} parse_model=${input.extractorModel} report=sweep.md`;
const plan = await deps.corpus.call("sweep_plan", { request });
// A restricted sweep's tools are narrowed BEFORE they are watched: the trace
// records what the agent was answered.
const corpusTools = restrictTools(
deps.corpus.tools
.filter((t) => (SWEEP_READ_TOOLS as readonly string[]).includes(t.name))
.map((t) =>
t.name === "get_transcripts"
? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) }
: t,
),
only,
).map((t) => watched(h, t, watch));
const web = input.web === false ? [] : (deps.web ?? []);
const tools = [...corpusTools, ...restrictTools([extractTool(h, input, rewrite, extracts, watch)], only), ...file.tools, ...web];
const isApi = providerOf(model) === "api";
const maxTurns = input.maxTurns ?? 150;
// The job's progress: every model turn, the repair round's included.
let turnsTaken = 0;
const onEvent = (e: Parameters[0]["onEvent"]>>[0]) => {
if (e.type === "turn") {
watch.turn = e.turn;
h.trace({
t: "cost",
step: `${watch.phase === "repair" ? "repair " : ""}turn ${e.turn}`,
usd: e.usd,
model,
total: h.meter.usd,
turn: e.turn,
phase: watch.phase,
calls: e.calls,
...(e.text.trim() ? { text: e.text.trim() } : {}),
});
turnsTaken++;
h.progress({ metric: "turns", current: turnsTaken, total: Math.max(turnsTaken, maxTurns) });
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`);
h.trace({ t: "note", text: `budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`, turn: e.turn, phase: watch.phase });
} else if (e.type === "note") {
h.log(e.text);
h.trace({ t: "note", text: e.text, turn: e.turn, phase: watch.phase });
}
};
const run = await runAgent({
llm: deps.llm,
model,
system: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to, ...(only?.length ? { ids: only } : {}) }),
user: seed ? `${plan}\n\n${SEED_NOTE}` : plan,
tools,
meter: h.meter,
maxUsd: input.maxUsd,
maxTurns,
...(isApi && 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" };
h.log(`agent ended: ${run.stopReason}${extracts.n ? `, ${extracts.n} extract batch(es)` : ""}`);
h.trace({ t: "note", text: `agent ended: ${run.stopReason}`, turn: watch.turn, phase: watch.phase });
if (!file.text().trim()) {
return { status: "failed", summary: `no report was written (the agent stopped: ${run.stopReason})` };
}
const finish = await convertAndCheck(h, file, { origin, resolver, round: 1 });
let { problems } = finish;
if (finish.convertProblems) {
return { status: "failed", summary: `the report does not convert: ${finish.convertProblems.slice(0, 3).join("; ")}` };
}
if (problems.length && !deps.signal?.aborted) {
h.log(`${problems.length} quote problem(s) — one repair round`);
watch.phase = "repair";
watch.turn = 0;
h.trace({ t: "note", text: `${problems.length} quote problem(s) — one repair round`, phase: "repair" });
const allowance = Math.min(REPAIR_ALLOWANCE_USD, input.maxUsd * 0.25);
const repair = await runAgent({
llm: deps.llm,
model,
system: REPAIR_SYSTEM,
user:
"The quote checks refused these citations — the quoted words are not, word for word, what the transcript says " +
`at that moment, or the quote is a fragment:\n${describeProblems(problems)}\n\nThe report now:\n\n${file.text()}`,
tools: file.tools,
meter: h.meter,
maxUsd: h.meter.usd + allowance,
maxTurns: REPAIR_MAX_TURNS,
signal: deps.signal,
onEvent,
});
h.turns([{ kind: "note", turn: 0, at: (deps.now?.() ?? new Date()).toISOString(), text: "repair round" }, ...repair.transcript]);
if (repair.stopReason === "cancelled") return { status: "failed", summary: "cancelled" };
const again = await convertAndCheck(h, file, { origin, resolver, round: 2 });
if (again.convertProblems) {
return { status: "failed", summary: `the repaired report does not convert: ${again.convertProblems.slice(0, 3).join("; ")}` };
}
problems = again.problems;
}
let dropped: string[] = [];
if (problems.length) {
const d = dropFailedFindings(file.text(), problems);
dropped = d.dropped;
for (const item of d.items) {
h.trace({ t: "check", quote: item.problem.quote, cite: citeOfProblem(item.problem), ok: false, reason: item.problem.why, stage: "drop", dropped: true, claim: item.claim });
}
if (dropped.length) {
await file.set(d.md);
h.log(`dropped ${dropped.length} finding(s) whose quote still fails`);
}
const last = await convertAndCheck(h, file, { origin, resolver, round: 3 });
if (last.convertProblems) return { status: "failed", summary: `the report does not convert: ${last.convertProblems[0]}` };
problems = last.problems;
}
const report = await convertOnly(h, file);
if (!report) return { status: "failed", summary: "the report does not convert" };
const citations = Object.keys(report.citations ?? {}).length;
h.check({
name: "quotes",
ok: problems.length === 0,
detail: problems.length
? `${problems.length} quote(s) still fail: ${problems.map((p) => p.why).slice(0, 3).join("; ")}`
: `every quote verbatim (strict)${dropped.length ? `; ${dropped.length} finding(s) dropped: ${dropped.slice(0, 3).join("; ")}` : ""}`,
});
if (problems.length) {
return { status: "failed", summary: `${problems.length} quote(s) fail the strict check after the repair round` };
}
if (!citations) return { status: "failed", summary: "the report cites nothing" };
await writeIterationFile(h.article, h.n, "report.json", report, h.paths);
traceReport(h.trace, report as Report);
const claims = report.sections.reduce((s, x) => s + (x.claims?.length ?? 0), 0);
return {
status: "done",
summary: `“${report.title}”: ${report.sections.length} section(s), ${claims} claim(s), ${citations} citation(s)${dropped.length ? `, ${dropped.length} dropped` : ""} — ~$${h.meter.usd.toFixed(2)}`,
};
}
// The link backstop, then convert and the quote check.
async function convertAndCheck(
h: TaskHandle,
file: ReturnType,
o: { origin: string; resolver: ReturnType; round: number },
): Promise<{ report?: Awaited>; problems: Awaited>; convertProblems?: string[] }> {
const fixed = await rewriteLinks(file.text(), o.resolver, o.origin);
if (fixed.fixed) {
await file.set(fixed.md);
h.log(`${fixed.fixed} link(s) → moment links on ${o.origin}`);
}
const c = await convertSweepText(file.text(), {
id: h.article,
title: titleOfSweep(file.text()) ?? undefined,
cuesOf: h.deps.cuesOf,
postChannelOf: h.deps.postChannelOf,
});
h.check({ name: "convert", ok: c.ok, ...(c.ok ? (c.warnings.length ? { detail: c.warnings.slice(0, 3).join("; ") } : {}) : { detail: c.problems.slice(0, 3).join("; ") }) });
if (!c.ok) return { problems: [], convertProblems: c.problems };
const problems = await checkQuotes(c.report, h.deps);
// Every refused quote, traced with why (a later round may fix or drop it).
for (const p of problems) h.trace({ t: "check", quote: p.quote, cite: citeOfProblem(p), ok: false, reason: p.why, stage: "check", round: o.round });
return { report: c.report, problems };
}
export function citeOfProblem(p: QuoteProblem): TraceCite {
return { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) };
}
// A corpus tool, watched: an enumeration's ids and coverage, a read's ids.
function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool {
return {
...t,
run: async (input: unknown, ctx: { signal?: AbortSignal }) => {
const { turn, phase } = w;
let out: string;
try {
out = await t.run(input, ctx);
} catch (e) {
h.trace({ t: "note", text: `${t.name} failed: ${(e as Error).message}`, turn, phase });
throw e;
}
try {
if (t.name === "enumerate_matches") {
const e = enumerateOf(out);
w.cov.enumerated(e.ids, e.partial, e.unreached);
const q = (input as { query?: unknown } | null)?.query;
const counts = countsOf(e.rows);
h.trace({
t: "enumerate",
query: typeof q === "string" ? q : "",
n: e.ids.length,
ids: e.ids,
partial: e.partial,
unreached: e.unreached,
...(e.total !== null ? { total: e.total } : {}),
...(e.posts ? { posts: e.posts } : {}),
...(counts ? { counts } : {}),
turn,
phase,
});
} else {
const ids = idsReadBy(t.name, input);
if (ids.length) {
w.cov.readIds(ids);
h.trace({ t: "read", tool: t.name, ids, turn, phase });
}
}
} catch {
// watching never stops the tool
}
return out;
},
};
}
async function convertOnly(h: TaskHandle, file: ReturnType) {
const c = await convertSweepText(file.text(), {
id: h.article,
title: titleOfSweep(file.text()) ?? undefined,
cuesOf: h.deps.cuesOf,
postChannelOf: h.deps.postChannelOf,
});
return c.ok ? c.report : null;
}