// TASK revise-report — a new iteration of an article's report from the // operator's feedback (release 27, S5; the stopgap's `revise.py report`). // // The model reads the parent iteration's sweep.md as numbered findings and // changes it ONLY through `apply_ops` (./reportOps.ts: checked ops code // applies — quotes are never edited, a new finding's quote is strict-checked // before it exists, every refusal comes back with its reason). It may read the // corpus (the MCP's read tools), the operator's notes, and the web for context. // Then the link backstop, convert and the quote check: a NEW finding whose // quote fails is dropped, never repaired. // // A SPEAKER-NEUTRAL report (the local sweep's neutral form, ./neutralClaim.ts, // known by its coverage line) stays neutral: its lines, headings and title are // code's, and the ops keep them so (reportOps' `neutral` rules: a line is not // rewritten, an added finding's line is written by code from its topic and // its recording, a heading or a summary that attributes is refused). A claim's // FLAG (a read-aloud "check by ear") lives in report.json, not sweep.md: the // revision carries it to the claim that still cites the same words. // // ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound // ask (`structuredAnswer`) for the whole ops batch, over the numbered view // trimmed to the model's prompt cap (sweepModel trimmedNumberedView: the // sections the feedback names first, quotes shortened in the view only). The // ops still number against the whole document. The API path is unchanged. import { CHARS_PER_TOKEN, ollamaConfigOf, promptCapOf, providerOf, runAgent, structuredAnswer, structuredPromptEstimate, type AgentTool, type LlmConfig, } from "../../../llm"; import { lineage, readIterationFile, writeIterationFile } from "../../iterations"; import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule } from "../authoringRules"; import { applyReportOps, strictCheckerOver, type AppliedOp, type RefusedOp } from "../reportOps"; import { numberedView, parseSweep, renderSweep, trimmedNumberedView, type SweepDoc } from "../sweepModel"; import { extractJsonObject } from "../../../parseStdoutJson"; import { strictNormalize } from "../../../citations/verify"; import type { Report } from "../../schema"; import { isNeutralSweep, labelProblem, neutralSentence, topicLabel, ungrounded } from "./neutralClaim"; import { subjectNames } from "./selection"; import type { AppliedOp as Applied, NeutralOpsRules, RefusedOp as Refused } from "../reportOps"; import type { CallItem } from "../../../llm/callLog"; import { CallSlot } from "../../../llm/callLog-server"; import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; export const REVISE_READ_TOOLS = ["get_transcripts", "get_transcript", "search_transcripts", "get_video_metadata", "notes"] as const; export const COMMON_REVISE_RULES = (what: string) => [ `You revise one ${what} of a report built from video transcripts, following the operator's feedback.`, UNATTENDED_RULE, "Change it ONLY with the `apply_ops` tool (you may call it several times; it says what it applied and what it refused, and why). Read before you change: `read_doc` shows the current state.", "The corpus tools read transcripts; `notes` lists and reads the operator's notes; the web tools are for context only — a web page is never cited as what someone said.", "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words. When done, stop calling tools and say in one line what you changed.", ].join(" "); // A local revision's rules: one answer, no tools (release 28 Q3). export const LOCAL_REVISE_RULES = (what: string) => [ `You revise one ${what} of a report built from video transcripts, following the operator's feedback.`, UNATTENDED_RULE, "Answer with ONE batch of edit operations, the `ops` list, that carries out the feedback: code applies it and refuses any op that breaks a rule. The view may leave some of it out (it says what); an op may still name what is not shown.", "Do what the feedback asks and nothing else; keep everything it does not mention. Plain, concise words.", ].join(" "); export const REPORT_OPS_TEXT = (origin: string, local = false) => [ local ? "Operations (objects in the `ops` list; `n` is a finding's number as the view shows it — the batch numbers against the report as shown):" : "Operations (objects for apply_ops; `n` is a finding's number as read_doc shows it — one batch numbers against the document at its start):", '- {"op":"drop","n":N} remove finding N', '- {"op":"claim","n":N,"text":"..."} rewrite finding N\'s claim (its quote and link stay as they are)', '- {"op":"merge","n":N,"into":M,"text":"..."} fold finding N into finding M: M keeps every quote with its own link; "text" (optional) is M\'s new claim', '- {"op":"move","n":N,"section":"
"} move finding N (a new title makes a new section)', `- {"op":"add","section":"","text":"<claim>","quote":"<the transcript's exact words>","link":"${origin}/?v=<channel slug>%2F<video id>&t=<seconds>"} a new finding`, '- {"op":"section","section":"<old title>","text":"<new title>"} rename a section', '- {"op":"title","text":"..."} / {"op":"summary","text":"..."}', CLAIM_QUOTES_RULE, VERBATIM_QUOTES_RULE, WHOLE_SENTENCE_QUOTE_RULE, momentLinkRule(origin), ].join("\n"); export const OPS_SCHEMA = { type: "object", properties: { ops: { type: "array", items: { type: "object", properties: { op: { type: "string" }, n: { type: "integer" }, into: { type: "integer" }, id: { type: "string" }, text: { type: "string" }, section: { type: "string" }, quote: { type: "string" }, link: { type: "string" }, after: { type: "string" }, citation: { type: "string" }, start: { type: "number" }, end: { type: "number" }, }, required: ["op"], }, }, }, required: ["ops"], }; export type ReviseReportInput = { article: string; n: number; model?: string; feedback?: string; origin: string; maxUsd: number; // The report's channels (default: its citations'). channels?: string[]; web?: boolean; webSearchMaxUses?: number; maxTurns?: number; }; // A local ask's user text, fitted under the model's prompt cap: `build` makes // it at a character budget, which shrinks until the whole request — system, // user and the ops schema, counted as ollamaChat counts them — fits. export function fitLocalAsk(o: { llm: LlmConfig; model: string; system: string; schema: object; build: (maxChars: number) => string; }): { user: string; tokens: number; cap: number } { const cap = promptCapOf(ollamaConfigOf(o.llm, o.model)); let maxChars = Math.floor(cap * CHARS_PER_TOKEN) - o.system.length - JSON.stringify(o.schema).length; let user = ""; let tokens = Number.POSITIVE_INFINITY; for (let k = 0; k < 40 && maxChars >= 400; k++) { user = o.build(maxChars); tokens = structuredPromptEstimate({ system: o.system, user, schema: o.schema }); if (tokens <= cap) break; maxChars = Math.floor(maxChars * 0.85); } return { user, tokens, cap }; } // The nearest iteration in `n`'s lineage (n excluded) with a sweep.md. export async function parentSweep(h: Pick<TaskHandle, "article" | "n" | "paths">): Promise<{ from: number; md: string } | null> { const line = await lineage(h.article, h.n, h.paths); for (let i = line.length - 2; i >= 0; i--) { const md = await readIterationFile(h.article, line[i]!, "sweep.md", h.paths); if (md !== null) return { from: line[i]!, md }; } return null; } // The corpus tools a revision reads with, `get_transcripts` with the origin's // moment_base. export function reviseCorpusTools(deps: TaskDeps, rewrite: (t: string) => Promise<string>): AgentTool[] { return deps.corpus.tools .filter((t) => (REVISE_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, ); } export async function reviseReport(input: ReviseReportInput, deps: TaskDeps): Promise<TaskResult> { return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["revise-report"] }, (h) => reviseReportBody(h, input), ); } // The revision's body over a handle (exported: a refresh runs it on its own // iteration with the feedback it composes — draft/refresh/task.ts). export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promise<TaskOutcome> { const { deps, iteration } = h; const model = input.model ?? iteration.model; const feedback = (input.feedback ?? iteration.feedback ?? "").trim(); if (!feedback) throw new TaskInputError("a revision needs feedback"); const parent = await parentSweep(h); if (!parent) throw new TaskInputError(`"${h.article}" i${h.n}: no iteration it revises has a sweep.md`); const origin = input.origin.replace(/\/+$/, ""); const parentReport = await readIterationFile(h.article, parent.from, "report.json", h.paths); const cited = parentReport ? [...new Set(Object.values((JSON.parse(parentReport) as { citations?: Record<string, { channel?: string }> }).citations ?? {}).map((c) => c.channel).filter((c): c is string => !!c))] : []; const channels = input.channels ?? cited; const resolver = slugResolver(deps.corpus, channels); const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin); const metaOf = async (channel: string, id: string): Promise<{ title?: unknown; uploadDate?: unknown; date?: unknown } | null> => { try { return extractJsonObject(await deps.corpus.call("get_video_metadata", { channel, video_id: id })) as { title?: unknown } | null; } catch { return null; } }; const titleOf = async (channel: string, id: string) => { const meta = await metaOf(channel, id); return typeof meta?.title === "string" ? meta.title : null; }; const checkQuote = strictCheckerOver(deps.cuesOf); let doc: SweepDoc = parseSweep(parent.md); const applied: AppliedOp[] = []; const refused: RefusedOp[] = []; const added: string[] = []; const local = providerOf(model) === "local"; const neutral = isNeutralSweep(parent.md) ? neutralRules(parent.md, channels, metaOf) : undefined; h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}${neutral ? "; speaker-neutral: its lines, headings and title stay code's" : ""}`); // The flags the claims carried: the parent's, and those of a sweep this // iteration already ran (a refresh's, whose findings it adds). const flagSources = [parentReport, await readIterationFile(h.article, h.n, "report.json", h.paths)].map((t) => { try { return t ? (JSON.parse(t) as Report) : null; } catch { return null; } }); const applyOps = async (ops: unknown[]) => { const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin, ...(neutral ? { neutral } : {}) }); doc = r.doc; applied.push(...r.applied); refused.push(...r.refused); for (const a of r.applied) if (a.op.op === "add") added.push(String(a.op.quote ?? "")); h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); return r; }; const tools: AgentTool[] = [ ...reviseCorpusTools(deps, rewrite), ...(input.web === false ? [] : (deps.web ?? [])), { name: "read_doc", description: "The report as it is now: its findings numbered.", inputSchema: { type: "object", properties: {} }, run: async () => numberedView(doc), }, { name: "apply_ops", description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the report after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { const r = await applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return `${JSON.stringify({ applied: r.applied.length, refused: r.refused.map((x) => ({ index: x.index, op: x.op.op, why: x.why })) })}\n\nNow:\n${numberedView(doc)}`; }, }, ]; if (local) { await localOpsBatch(h, { model, system: `${LOCAL_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin, true)}`, what: "report", build: (maxChars) => { const v = trimmedNumberedView(doc, { maxChars: maxChars - feedback.length - 300, feedback }); return ( `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW (findings numbered [n]; in this view quotes are shortened ` + `and links cut to their labels — the report keeps them whole):\n${v.text}\n\nAnswer with the ops batch that carries out the feedback.` ); }, apply: applyOps, }); } else { await apiRevision(); } async function apiRevision() { const system = `${COMMON_REVISE_RULES("iteration of the report")}\n\n${REPORT_OPS_TEXT(origin)}`; const run = await runAgent({ llm: deps.llm, model, system, user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}`, tools, meter: h.meter, maxUsd: input.maxUsd, maxTurns: input.maxTurns ?? 30, ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, onEvent: (e) => { if (e.type !== "turn") return; h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); }, }); h.turns(run.transcript); if (run.stopReason === "cancelled") return; // A model that ends without calling apply_ops gets ONE schema-bound ask for // the batch; nothing at all after that is a failing check, not a quiet "0 // applied". if (applied.length + refused.length === 0) { const asked = await structuredAnswer<{ ops?: unknown[] }>({ llm: deps.llm, model, system, user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE REPORT NOW:\n${numberedView(doc)}\n\nAnswer with the ops batch that carries out the feedback.`, schema: OPS_SCHEMA, meter: h.meter, signal: deps.signal, }).catch((e: unknown) => { h.log(`the ops ask failed: ${(e as Error).message}`); return null; }); if (asked && Array.isArray(asked.ops) && asked.ops.length) { h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); await applyOps(asked.ops); } } } if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, detail: applied.length + refused.length > 0 ? `${applied.length} applied, ${refused.length} refused` : "the model proposed no edits", }); let md = renderSweep(doc); const fixed = await rewriteLinks(md, resolver, origin); md = fixed.md; const ops = { applied: applied.map((a) => a.op), refused: refused.map((r) => ({ ...r.op, why: r.why })) }; let c = await convertSweepText(md, { id: h.article, title: titleOfSweep(md) ?? undefined, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf }); if (!c.ok) { await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); h.check({ name: "convert", ok: false, detail: c.problems.slice(0, 3).join("; ") }); return { status: "failed", summary: `the revised report does not convert: ${c.problems[0]}`, patch: { ops } }; } let problems = await checkQuotes(c.report, deps); if (problems.length) { // Only a finding this revision added may go; the parent's quotes stood. const mine = problems.filter((p) => added.some((q) => q && p.quote.includes(q.slice(0, 40)))); const d = dropFailedFindings(md, mine); if (d.dropped.length) { md = d.md; for (const why of d.dropped) ops.refused.push({ op: "add", why: `quote check: ${why}` }); c = await convertSweepText(md, { id: h.article, title: titleOfSweep(md) ?? undefined, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf }); if (!c.ok) return { status: "failed", summary: `the revised report does not convert: ${c.problems[0]}`, patch: { ops } }; problems = await checkQuotes(c.report, deps); } } await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); h.check({ name: "convert", ok: true }); // A fragment the parent already quoted is a warning, as verify-quotes says // of an existing report (release 28 Q2); what fails the words is a failure. const failing = problems.filter((p) => !p.fragment); const fragments = problems.filter((p) => p.fragment); const warn = fragments.length ? `; ${fragments.length} fragment quote(s) from the iteration revised (a warning)` : ""; h.check({ name: "quotes", ok: failing.length === 0, detail: failing.length ? `${failing.length} quote(s) fail the strict check (from the iteration revised): ${failing.map((p) => p.why).slice(0, 3).join("; ")}${warn}` : `every quote verbatim (strict)${warn}`, }); const carried = carryClaimFlags(c.report as Report, flagSources); if (carried) h.log(`${carried} claim flag(s) carried over (a flag lives in report.json, not in sweep.md)`); await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths); return { status: "done", summary: `${ops.applied.length} op(s) applied, ${ops.refused.length} refused — “${c.report.title}”`, patch: { ops }, }; } // A local revision's one ops batch: the view fitted under the prompt cap, one // structuredAnswer, the ops applied. A failed ask is logged (the ops check // then says nothing was proposed); a cancel is rethrown. export async function localOpsBatch( h: TaskHandle, o: { model: string; system: string; what: string; build: (maxChars: number) => string; apply: (ops: unknown[]) => Promise<unknown>; schema?: object }, ): Promise<void> { const { deps } = h; const schema = o.schema ?? OPS_SCHEMA; const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema, build: o.build }); h.log(`one ops batch over the ${o.what} (~${fitted.tokens} of ${fitted.cap} prompt tokens)`); const t0 = Date.now(); const slot = new CallSlot(); const asked = await structuredAnswer<{ ops?: unknown[] }>({ llm: deps.llm, model: o.model, system: o.system, user: fitted.user, schema, meter: h.meter, signal: deps.signal, call: { phase: "revision", label: `ops batch (${o.what})`, slot }, }).catch((e: unknown) => { if (deps.signal?.aborted) throw e; h.log(`the ops ask failed: ${(e as Error).message}`); return null; }); h.turns([{ kind: "model", what: "ops batch", tokens: fitted.tokens, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: asked }]); h.progress({ metric: "turns", current: 1, total: 1 }); if (!asked || !Array.isArray(asked.ops) || !asked.ops.length) { if (asked) slot.decide("dropped", "no ops proposed"); return; } const r = (await o.apply(asked.ops)) as { applied?: Applied[]; refused?: Refused[] } | undefined; // The model log: each op applied or refused, with code's reason (a neutral // report's refusals among them). if (r && Array.isArray(r.applied) && Array.isArray(r.refused)) { const items: CallItem[] = [ ...r.applied.map((a): CallItem => ({ text: opText(a.op), outcome: "kept", why: "applied" })), ...r.refused.map((x): CallItem => ({ text: opText(x.op), outcome: "dropped", why: `refused: ${x.why}` })), ]; slot.decide(r.applied.length ? "kept" : "dropped", `${r.applied.length} op(s) applied, ${r.refused.length} refused`, items); } } const opText = (op: { op: string } & Record<string, unknown>) => [op.op, op.n !== undefined ? `#${String(op.n)}` : "", typeof op.section === "string" ? `“${op.section}”` : "", typeof op.text === "string" ? op.text : ""].filter(Boolean).join(" "); // A claim's flags are not in sweep.md: each claim of the revised report whose // citation quotes the same words of the same recording as a flagged claim of // `from` gets that flag (the first found). Returns how many claims got one. export function carryClaimFlags(report: Report, from: readonly (Report | null)[]): number { const keyOf = (c: { kind?: string; id?: string; quote?: string } | undefined) => (c?.id && c.quote ? `${c.kind ?? ""}|${c.id}|${strictNormalize(c.quote)}` : null); const flags = new Map<string, string>(); for (const r of from) { if (!r) continue; for (const s of r.sections ?? []) { for (const k of s.claims ?? []) { if (!k.flag) continue; for (const cid of k.citations ?? []) { const key = keyOf(r.citations?.[cid] as { kind?: string; id?: string; quote?: string } | undefined); if (key && !flags.has(key)) flags.set(key, k.flag); } } } } let n = 0; if (!flags.size) return 0; for (const s of report.sections ?? []) { for (const k of s.claims ?? []) { if (k.flag) continue; const flag = (k.citations ?? []).map((cid) => keyOf(report.citations?.[cid] as { kind?: string; id?: string; quote?: string } | undefined)).find((key) => key && flags.has(key)); if (flag) { k.flag = flags.get(flag)!; n++; } } } return n; } // The neutral form's rules over a revision's ops (reportOps' NeutralOpsRules): // the report's question names whose report it is; its whole text is what a // heading's words must be found in. export function neutralRules( md: string, channels: readonly string[], metaOf: (channel: string, id: string) => Promise<{ title?: unknown; uploadDate?: unknown; date?: unknown } | null>, ): NeutralOpsRules { const question = /^Question:\s*(.+)$/m.exec(md)?.[1]?.trim() ?? ""; const hosts = [...subjectNames({ question, channels: channels.map((slug) => ({ slug })) })]; return { async line({ text, quote, channel, id }) { // "[Check by ear: ]In <title> (<date>), on <topic>:" — the topic is the // model's (held down like a label); the rest is written again by code. const ear = /^check by ear:\s*/i.exec(text); const body = ear ? text.slice(ear[0].length) : text; const at = body.lastIndexOf(", on "); if (!/^In /.test(body) || at < 0 || !body.endsWith(":")) return { why: "a speaker-neutral report's line is “In <title> (<date>), on <topic>:” — code writes it; give the topic in that shape" }; const meta = await metaOf(channel, id); const title = typeof meta?.title === "string" ? meta.title : ""; const date = typeof meta?.uploadDate === "string" ? meta.uploadDate : typeof meta?.date === "string" ? meta.date : ""; const label = topicLabel(body.slice(at + 5, -1), { fallback: "", hosts, ground: [quote, title, question] }); if (label.from !== "model") return { why: `the topic label is refused: ${label.why}` }; return { line: `${ear ? "Check by ear: " : ""}${neutralSentence({ title, date, topic: label.label })}` }; }, heading(text) { const bad = labelProblem(text, hosts); if (bad) return bad; const loose = ungrounded(text, md.split("\n")); return loose ? `“${loose}” is nowhere in the report` : null; }, summary(text) { return labelProblem(text, hosts, { sentence: true }); }, }; }