Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 6d6cd79c21ac218176aa79b6f9938526e20e46d5
parent 78c692779b23166c41f237e496a58559a7b78d78
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:25:43 -0400

common: local-first revisions — one ops batch over a view trimmed to the 8k cap (r28 Q3)

On an ollama model, revise-report and revise-video skip the tool loop: one
structuredAnswer for the ops batch (release 27's fallback is the local path's
only path), the user text fitted under the prompt cap as ollamaChat counts it
(structuredPromptEstimate; fitLocalAsk shrinks the budget until it fits).
The views are trimmed in sweepModel (trimmedNumberedView, sectionsNamedBy)
and videoOps (trimmedCutView, chaptersOf): what the feedback names first,
then the rest in order; quotes shortened and links cut to labels in the view
only, the ops numbering the whole document. The API path is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/lib/llm/structured.ts | 15++++++++++++++-
Mcommon/lib/report/draft/sweepModel.test.ts | 48+++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/report/draft/sweepModel.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/revise-report.ts | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/lib/report/draft/tasks/revise-video.ts | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
Mcommon/lib/report/draft/videoOps.test.ts | 18+++++++++++++++++-
Mcommon/lib/report/draft/videoOps.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/draftTasks.test.ts | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
8 files changed, 583 insertions(+), 89 deletions(-)

diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -20,7 +20,7 @@ import { } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; import type { Meter } from "./meter"; -import { ollamaChat, OllamaError, PromptTooLargeError } from "./ollama"; +import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; const ASK = "Answer by calling the `answer` tool."; @@ -105,6 +105,19 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`); } +// What a local structuredAnswer's prompt is estimated at — the very request +// localAnswer sends (its messages and its format), counted as ollamaChat +// counts it against the cap (release 28 Q3: a caller fits its text first). +export function structuredPromptEstimate(o: { system: string; user: string; schema: object }): number { + return promptEstimate({ + messages: [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ], + format: o.schema, + }); +} + async function localAnswer<T>(o: Opts): Promise<T> { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; diff --git a/common/lib/report/draft/sweepModel.test.ts b/common/lib/report/draft/sweepModel.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, splitFinding } from "./sweepModel"; +import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, sectionsNamedBy, splitFinding, trimmedNumberedView } from "./sweepModel"; const SWEEPS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/sweeps"); @@ -86,3 +86,49 @@ test("the numbered view a model reads", async () => { const p = numberedView(parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8"))); assert.match(p, /## Coverage {2}\(coverage — keep\)/); }); + +// A synthetic report of `sections` × `per` findings with long quotes. +function bigSweep(sections: number, per: number): string { + const out = ["# Big", "", "A summary.", ""]; + let n = 0; + for (let s = 1; s <= sections; s++) { + out.push(`## Part ${s}`); + for (let k = 0; k < per; k++) { + n++; + out.push(`- Claim ${n} of part ${s}: "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen" [Rec @ 0:${k}](https://synth.example/?v=ch%2Fv${n}&t=${k})`); + } + } + return out.join("\n"); +} + +test("trimmed view (Q3): the named sections first, the rest while the budget lasts; numbers the document's; the omitted said", () => { + const doc = parseSweep(bigSweep(20, 5)); + const full = numberedView(doc); + const v = trimmedNumberedView(doc, { maxChars: 2500, feedback: "Rework Part 17 and drop 3." }); + assert.ok(v.text.length <= 2500 + 400, String(v.text.length)); + assert.ok(full.length > 4 * v.text.length); + assert.deepEqual(v.named, [0, 16], "part 17 by its title; finding 3's section by its number"); + for (const n of [81, 82, 83, 84, 85, 3]) assert.ok(v.shown.includes(n), `[${n}] shown`); + assert.match(v.text, /## Part 17\n\[81\] Claim 81 of part 17/); + // Shown in document order; the left-out findings named by number. + assert.ok(v.text.indexOf("## Part 1\n") < v.text.indexOf("## Part 17")); + assert.match(v.text, /## Part 20 {2}\(findings \[96\]–\[100\] not shown\)/); + assert.equal(v.shown.length + v.omitted.length, 100); + // Quotes shortened and links reduced to their labels, in the view only. + assert.match(v.text, /\[81\] Claim 81 of part 17: "one two three four five six seven eight …" \[Rec @ 0:0\]/); + assert.ok(!v.text.includes("https://")); + assert.ok(renderSweep(doc).includes("fifteen\" [Rec @ 0:0](https://synth.example/?v=ch%2Fv81&t=0)"), "the document is untouched"); + // No feedback: document order. + const plain = trimmedNumberedView(doc, { maxChars: 2500 }); + assert.ok(plain.shown.includes(1) && !plain.shown.includes(81)); + // A budget that holds everything shows everything. + assert.equal(trimmedNumberedView(doc, { maxChars: 1e6 }).omitted.length, 0); +}); + +test("sectionsNamedBy: titles, section numbers, finding numbers", () => { + const doc = parseSweep(bigSweep(4, 2)); + assert.deepEqual([...sectionsNamedBy(doc, "In part 2, reword the claim.")], [1]); + assert.deepEqual([...sectionsNamedBy(doc, "section 4 is too long")].sort(), [3]); + assert.deepEqual([...sectionsNamedBy(doc, "merge [5] into 6")].sort(), [2]); + assert.deepEqual([...sectionsNamedBy(doc, "trim it to 30 s")], []); +}); diff --git a/common/lib/report/draft/sweepModel.ts b/common/lib/report/draft/sweepModel.ts @@ -212,3 +212,115 @@ export function numberedView(doc: SweepDoc): string { export function quotesOf(f: Finding): string[] { return [...evidenceOf(f).matchAll(new RegExp(QUOTED_RE.source, "g"))].map((m) => m[0].slice(1, -1)); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// A local model gets the numbered view in ONE prompt under the 8k cap, so the +// view is trimmed to a character budget: the sections the feedback names +// first (a section's title, "section N", or the number of a finding in it), +// then the rest in document order, finding by finding while the budget lasts. +// It is shown in document order; what is left out is said, with its numbers. +// Quotes are shortened and links reduced to their labels IN THE VIEW ONLY: an +// op still numbers against the whole document and never reaches a quote. + +export const VIEW_QUOTE_WORDS = 12; + +const normWords = (s: string) => + s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s]/gu, " ") + .replace(/\s+/g, " ") + .trim(); + +// A quoted span cut to its first words when it is long. +function shortQuote(q: string, words: number): string { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +} + +// A finding's evidence as the trimmed view shows it. +export function shortEvidence(f: Finding, quoteWords = VIEW_QUOTE_WORDS): string { + return evidenceOf(f) + .replace(new RegExp(QUOTED_RE.source, "g"), (m) => `"${shortQuote(m.slice(1, -1), quoteWords)}"`) + .replace(new RegExp(LINK_RE.source, "g"), (m) => m.slice(0, m.indexOf("](") + 1)); +} + +// The sections (their indices) the feedback names. +export function sectionsNamedBy(doc: SweepDoc, feedback: string): Set<number> { + const fb = ` ${normWords(feedback)} `; + const out = new Set<number>(); + // What is left once the titles and "section N" are taken out: its numbers + // are findings' ("drop 3", "[5]"). + let rest = ` ${normWords(feedback)} `; + doc.sections.forEach((s, i) => { + const t = normWords(s.title); + if (t.length >= 3 && fb.includes(` ${t} `)) { + out.add(i); + rest = rest.split(` ${t} `).join(" "); + } + if (new RegExp(`\\b(?:section|§)\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + rest = rest.replace(/\bsection \d+/g, " ").replace(/\b\d+ ?(?:s|sec|secs|seconds|min|minutes|percent)\b/g, " "); + const numbers = new Set([...rest.matchAll(/\b(\d{1,4})\b/g)].map((m) => Number(m[1]))); + for (const x of numberFindings(doc)) if (numbers.has(x.n)) out.add(doc.sections.indexOf(x.section)); + return out; +} + +export type TrimmedView = { text: string; shown: number[]; omitted: number[]; named: number[] }; + +export function trimmedNumberedView( + doc: SweepDoc, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): TrimmedView { + const numbered = numberFindings(doc); + const numberOf = new Map(numbered.map((x) => [x.finding, x.n])); + const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" "); + const head = [`TITLE: ${doc.title}`, `SUMMARY: ${summary.length > 600 ? `${summary.slice(0, 600)} …` : summary}`]; + const named = o.feedback ? sectionsNamedBy(doc, o.feedback) : new Set<number>(); + const order = [...doc.sections.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + let used = head.join("\n").length + doc.sections.reduce((n, s) => n + s.title.length + 40, 0); + // Which blocks of each section are shown. + const keep = new Map<number, Set<SweepBlock>>(); + for (const i of order) { + const set = new Set<SweepBlock>(); + keep.set(i, set); + for (const b of doc.sections[i]!.body) { + const line = + b.type === "finding" ? `[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}` : b.text.trim(); + if (!line) continue; + if (used + line.length + 1 > o.maxChars) continue; + used += line.length + 1; + set.add(b); + } + } + const lines = [...head]; + const shown: number[] = []; + const omitted: number[] = []; + doc.sections.forEach((s, i) => { + const set = keep.get(i)!; + const left = findingsOf(s).filter((f) => !set.has(f)).map((f) => numberOf.get(f)!); + const note = left.length ? ` (findings ${ranges(left)} not shown)` : ""; + lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}${note}`); + for (const b of s.body) { + if (!set.has(b)) continue; + if (b.type === "finding") { + lines.push(`[${numberOf.get(b)}] ${b.claim}${b.sep || " "}${shortEvidence(b, o.quoteWords)}`.trimEnd()); + shown.push(numberOf.get(b)!); + } else lines.push(b.text); + } + omitted.push(...left); + }); + return { text: lines.join("\n"), shown: shown.sort((a, b) => a - b), omitted: omitted.sort((a, b) => a - b), named: [...named].sort((a, b) => a - b) }; +} + +// 1, 2, 3, 5 → "[1]–[3], [5]". +function ranges(ns: readonly number[]): string { + const out: string[] = []; + for (let i = 0; i < ns.length; ) { + let j = i; + while (j + 1 < ns.length && ns[j + 1] === ns[j]! + 1) j++; + out.push(j > i ? `[${ns[i]}]–[${ns[j]}]` : `[${ns[i]}]`); + i = j + 1; + } + return out.join(", "); +} diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts @@ -8,12 +8,28 @@ // 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. +// +// 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 { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; +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, type SweepDoc } from "../sweepModel"; +import { numberedView, parseSweep, renderSweep, trimmedNumberedView, type SweepDoc } from "../sweepModel"; import { extractJsonObject } from "../../../parseStdoutJson"; import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes"; @@ -31,9 +47,20 @@ export const COMMON_REVISE_RULES = (what: string) => "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(" "); -export const REPORT_OPS_TEXT = (origin: string) => +// A local revision's rules: one answer, no tools (release 28 Q3). +export const LOCAL_REVISE_RULES = (what: string) => [ - "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):", + `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', @@ -89,6 +116,29 @@ export type ReviseReportInput = { 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); @@ -145,7 +195,17 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis const applied: AppliedOp[] = []; const refused: RefusedOp[] = []; const added: string[] = []; - h.log(`revising the report of i${parent.from} on ${model}`); + const local = providerOf(model) === "local"; + h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}`); + const applyOps = async (ops: unknown[]) => { + const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); + 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), @@ -161,56 +221,70 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis 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 ops = Array.isArray(inp?.ops) ? inp.ops : []; - const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin }); - 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`); + 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)}`; }, }, ]; - 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 ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) 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[] }>({ + 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)}\n\nAnswer with the ops batch that carries out the feedback.`, - schema: OPS_SCHEMA, + 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, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - 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 tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + 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, @@ -261,3 +335,31 @@ async function reviseReportBody(h: TaskHandle, input: ReviseReportInput): Promis 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> }, +): Promise<void> { + const { deps } = h; + const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema: OPS_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 asked = await structuredAnswer<{ ops?: unknown[] }>({ + llm: deps.llm, + model: o.model, + system: o.system, + user: fitted.user, + schema: OPS_SCHEMA, + meter: h.meter, + signal: deps.signal, + }).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 }]); + if (asked && Array.isArray(asked.ops) && asked.ops.length) await o.apply(asked.ops); +} diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts @@ -8,13 +8,18 @@ // new cut is this iteration's project, seeded from the parent's: the report // and stills copied, the voices hard-linked. A video revision has no report of // its own (its article's report stays its nearest ancestor's). +// +// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound ask +// for the ops batch over the cut trimmed to the prompt cap (videoOps +// trimmedCutView: the chapters the feedback names first, quotes shortened in +// the view only), as revise-report does. The API path is unchanged. import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; import { readIteration, type Iteration } from "../../iterations"; -import { applyVideoOps, cutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; +import { applyVideoOps, cutView, trimmedCutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; import { rewriteMomentBases, slugResolver } from "./links"; import { projectDirOf, readManifest, readProjectReport, seedProject, writeManifest } from "./project"; -import { COMMON_REVISE_RULES, OPS_SCHEMA, reviseCorpusTools } from "./revise-report"; +import { COMMON_REVISE_RULES, LOCAL_REVISE_RULES, OPS_SCHEMA, localOpsBatch, reviseCorpusTools } from "./revise-report"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; @@ -29,6 +34,11 @@ export const VIDEO_OPS_TEXT = [ '- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}', ].join("\n"); +const shortQuote = (q: string, words = 12) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q; +}; + export type ReviseVideoInput = { article: string; n: number; @@ -82,6 +92,14 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< .map(([cid, c]) => `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${String(c?.quote ?? "").slice(0, 160)}"`) .join("\n"); const view = () => `${cutView(manifest)}\n\nREPORT CITATIONS (add_clip takes these ids):\n${cites}`; + const applyOps = (ops: unknown[]) => { + const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest }); + manifest = r.manifest; + applied.push(...r.applied); + refused.push(...r.refused); + h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + return r; + }; h.log(`revising the cut of i${parent.it.n} on ${model}`); const tools: AgentTool[] = [ @@ -93,11 +111,7 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.", inputSchema: OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { - const r = applyVideoOps(manifest, Array.isArray(inp?.ops) ? inp.ops : [], { report, parent: parent.manifest }); - manifest = r.manifest; - applied.push(...r.applied); - refused.push(...r.refused); - h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); + const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return ( JSON.stringify({ applied: r.applied.map((a) => ({ index: a.index, op: a.op.op, ...(a.warnings ? { warnings: a.warnings } : {}) })), @@ -107,45 +121,81 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise< }, }, ]; - const system = `${COMMON_REVISE_RULES("video cut (an evidence video: cards with spoken narration between clips of what was said)")}\n\n${VIDEO_OPS_TEXT}`; - const run = await runAgent({ - llm: deps.llm, - model, - system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, - tools, - meter: h.meter, - maxUsd: input.maxUsd, - maxTurns: input.maxTurns ?? (providerOf(model) === "api" ? 30 : 12), - ...(providerOf(model) === "api" && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), - signal: deps.signal, - onEvent: (e) => { - if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); - }, - }); - h.turns(run.transcript); - if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; - // A model that ends without calling apply_ops (a local model's tool call often - // comes back empty) 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[] }>({ + const what = "video cut (an evidence video: cards with spoken narration between clips of what was said)"; + if (providerOf(model) === "local") { + // Release 28 Q3: one ops batch over the cut trimmed to the prompt cap. + const citeRows = Object.entries(report.citations ?? {}).map(([cid, c]) => ({ + cid, + line: `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${shortQuote(String(c?.quote ?? ""))}"`, + })); + const named = (cid: string) => new RegExp(`\\b${cid}\\b`).test(feedback); + const citeOrder = [...citeRows].sort((a, b) => Number(named(b.cid)) - Number(named(a.cid))); + await localOpsBatch(h, { + model, + system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`, + what: "cut", + build: (maxChars) => { + const budget = maxChars - feedback.length - 400; + const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback }); + let left = budget - cut.text.length; + const shown: string[] = []; + for (const c of citeOrder) { + if (c.line.length + 1 > left) continue; + left -= c.line.length + 1; + shown.push(c.cid); + } + const lines = citeRows.filter((c) => shown.includes(c.cid)).map((c) => c.line); + const more = citeRows.length - lines.length; + return ( + `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW (quotes shortened in this view only):\n${cut.text}\n\n` + + `REPORT CITATIONS (add_clip takes these ids${more ? `; ${more} more not shown` : ""}):\n${lines.join("\n")}\n\n` + + `THE REPORT IT IS CUT FROM: ${String(report.title ?? "")}\n\nAnswer with the ops batch that carries out the feedback.` + ); + }, + apply: async (ops) => applyOps(ops), + }); + } else { + const system = `${COMMON_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT}`; + const run = await runAgent({ llm: deps.llm, model, system, - user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`, - schema: OPS_SCHEMA, + user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, + tools, meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 30, + ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, - }).catch((e: unknown) => { - h.log(`the ops ask failed: ${(e as Error).message}`); - return null; + onEvent: (e) => { + if (e.type === "turn") h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); + }, }); - 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 tools.find((t) => t.name === "apply_ops")!.run({ ops: asked.ops }, { signal: deps.signal }); + h.turns(run.transcript); + if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; + // 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 VIDEO NOW:\n${view()}\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)`); + applyOps(asked.ops); + } } } + if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { applyVideoOps, cutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; +import { applyVideoOps, chaptersNamedBy, chaptersOf, cutView, trimmedCutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; const DRAFT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft"); const json = async (p: string) => JSON.parse(await readFile(path.join(DRAFT, p), "utf8")); @@ -131,3 +131,19 @@ test("the cut as a model reads it", () => { assert.match(v, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUBTITLE: \n- card title \(title\) heading: /); assert.match(v, /\n- clip c01 synth-kitchen\/bread-day-01 15–19\.8 s quote: "I would never sell the bakery to a chain"/); }); + +test("trimmed cut view (Q3): the named chapter in full, every entry still listed by id", () => { + const full = cutView(manifest); + const chapters = chaptersOf(manifest); + assert.ok(chapters.length >= 3); + const last = chapters.at(-1)!; + const card = last.find((e) => e.type === "card")!; + const v = trimmedCutView(manifest, { maxChars: 600, feedback: `Rename ${card.id}.` }); + assert.deepEqual([...chaptersNamedBy(manifest, `Rename ${card.id}.`)], [chapters.length - 1]); + for (const e of last) assert.ok(v.full.includes(e.id), `${e.id} in full`); + for (const e of manifest.timeline) assert.ok(v.text.includes(` ${e.id}`), `${e.id} listed`); + assert.ok(v.short.length > 0); + assert.match(v.text, /\(not shown in full\)/); + assert.ok(v.text.length < full.length); + assert.equal(trimmedCutView(manifest, { maxChars: 1e6 }).short.length, 0); +}); diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts @@ -210,3 +210,88 @@ export function cutView(m: VideoManifest): string { } return lines.join("\n"); } + +// ─── The trimmed view (release 28 Q3: a local model's one ops batch) ─── +// +// The cut in timeline order under a character budget: the chapters the +// feedback names (a card's heading or an entry's id, or "chapter N") are shown +// in full first, then the rest in order while the budget lasts; an entry left +// out is listed by its id alone, so an op may still name it. Quotes are +// shortened IN THE VIEW ONLY. + +export const CUT_VIEW_QUOTE_WORDS = 12; + +const shortQ = (q: string, words: number) => { + const w = q.split(/\s+/).filter(Boolean); + return w.length > words ? `${w.slice(0, Math.max(4, words - 4)).join(" ")} …` : q; +}; + +const lowWords = (s: string) => + ` ${s + .toLowerCase() + .replace(/[^\p{L}\p{N}\s-]/gu, " ") + .replace(/\s+/g, " ") + .trim()} `; + +export function entryLine(e: ManifestEntry, quoteWords = CUT_VIEW_QUOTE_WORDS): string { + if (e.type === "card") { + const n = e.narration?.text ?? ""; + return `- card ${e.id} (${e.style ?? ""}) heading: ${JSON.stringify(e.heading ?? "")}` + (n ? ` narration: ${JSON.stringify(n)}` : ""); + } + if (e.type === "clip") return `- clip ${e.id} ${e.channel}/${e.video} ${e.start}–${e.end} s quote: ${JSON.stringify(shortQ(e.quote ?? "", quoteWords))}`; + return `- ${e.type} ${e.id}`; +} + +// The chapters of a cut: each card starts one; entries before the first card +// are chapter 0's. +export function chaptersOf(m: VideoManifest): ManifestEntry[][] { + const out: ManifestEntry[][] = [[]]; + for (const e of m.timeline ?? []) { + if (e.type === "card" && out.at(-1)!.length) out.push([]); + out.at(-1)!.push(e); + } + return out.filter((c) => c.length); +} + +export function chaptersNamedBy(m: VideoManifest, feedback: string): Set<number> { + const fb = lowWords(feedback); + const out = new Set<number>(); + chaptersOf(m).forEach((ch, i) => { + for (const e of ch) { + if (fb.includes(lowWords(e.id))) out.add(i); + const h = lowWords(e.heading ?? "").trim(); + if (e.type === "card" && h.length >= 3 && fb.includes(` ${h} `)) out.add(i); + } + if (new RegExp(`\\bchapter\\s*${i + 1}\\b`, "i").test(feedback)) out.add(i); + }); + return out; +} + +export function trimmedCutView( + m: VideoManifest, + o: { maxChars: number; feedback?: string; quoteWords?: number }, +): { text: string; full: string[]; short: string[] } { + const head = [`TITLE: ${m.title ?? ""}`, `SUBTITLE: ${m.subtitle ?? ""}`]; + const chapters = chaptersOf(m); + const named = o.feedback ? chaptersNamedBy(m, o.feedback) : new Set<number>(); + const order = [...chapters.keys()].sort((a, b) => Number(named.has(b)) - Number(named.has(a)) || a - b); + // Every entry costs at least its id line; the full line is bought from what is left. + const idLine = (e: ManifestEntry) => `- ${e.type} ${e.id} (not shown in full)`; + let used = head.join("\n").length + (m.timeline ?? []).reduce((n, e) => n + idLine(e).length + 1, 0); + const full = new Set<ManifestEntry>(); + for (const i of order) { + for (const e of chapters[i]!) { + const extra = entryLine(e, o.quoteWords).length - idLine(e).length; + if (used + extra > o.maxChars) continue; + used += extra; + full.add(e); + } + } + const lines = [...head]; + for (const e of m.timeline ?? []) lines.push(full.has(e) ? entryLine(e, o.quoteWords) : idLine(e)); + return { + text: lines.join("\n"), + full: [...full].map((e) => e.id), + short: (m.timeline ?? []).filter((e) => !full.has(e)).map((e) => e.id), + }; +} diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -354,24 +354,94 @@ test("a task refuses an iteration that is not its own or not queued", async () = assert.ok(CHANNELS.length > 0); }); -test("revise-report on a local model that never calls apply_ops: one schema-bound ask for the batch, then the check says so", async () => { +test("revise-report on a local model: no tool loop — one schema-bound ask for the batch; nothing proposed is a failing check", async () => { await drainFake(); await doneSweep("synth-basic", "basic"); const it = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - // read_doc, then an empty answer (no tool call); then the ask answers with the batch. - ol.push(toolCallsReply([{ name: "read_doc", arguments: {} }]), reply(""), jsonReply({ ops: [{ op: "drop", n: 3 }] })); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 3 }] })); const d = deps(); const out = await runTask({ task: "revise-report", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one call"); + const req = ol.requests.at(-1); + assert.ok(req.format, "schema-bound"); + assert.ok(!req.tools, "no tools"); + assert.ok(!/apply_ops|read_doc/.test(req.messages[0].content), "the local rules name no tools"); const after = (await readIteration("synth-basic", it.n, paths))!; assert.deepEqual((after.ops!.applied as { op: string }[]).map((o) => o.op), ["drop"]); assert.ok(after.checks!.some((c) => c.name === "ops" && c.ok)); assert.ok(!(await readIterationFile("synth-basic", it.n, "sweep.md", paths))!.includes("new mixer")); - // A model that proposes nothing even then: done, with a failing ops check. + // A model that proposes nothing: done, with a failing ops check. const it2 = await createIteration("synth-basic", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "Drop the mixer finding." }, paths); - ol.push(reply(""), jsonReply({ ops: [] })); + ol.push(jsonReply({ ops: [] })); await runTask({ task: "revise-report", article: "synth-basic", n: it2.n, origin: ORIGIN, maxUsd: 1 }, deps()); const after2 = (await readIteration("synth-basic", it2.n, paths))!; assert.ok(after2.checks!.some((c) => c.name === "ops" && !c.ok && /no edits/.test(String(c.detail)))); }); + +test("revise-report on a local model: a large report's view fits the 8k cap — the named section in it, one ops call, the numbers the document's", async () => { + await drainFake(); + await createIteration("synth-big", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const basic = JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")); + await writeIterationFile("synth-big", 1, "report.json", { ...basic, id: "synth-big" }, paths); + await updateIteration("synth-big", 1, { status: "done" }, paths); + // 40 sections of 6 findings over real corpus moments: ~45k characters, far past the cap. + const lines = ["# A large report", "", "The summary.", ""]; + const moments = [ + ["bread-day-01", 15, "I would never sell the bakery to a chain"], + ["bread-day-01", 45, "I paid for the new mixer myself"], + ["pie-stream-02", 10, "I did not enter the contest this year"], + ["pie-stream-02", 30, "I have never met the other finalist"], + ["pie-stream-02", 40, "my lawyer told me not to talk about the lease"], + ["bread-day-01", 30, "the oven was fine it just ran hot"], + ] as const; + let n = 0; + for (let s = 1; s <= 40; s++) { + lines.push(`## Topic ${s}`, ""); + for (const [id, t, q] of moments) { + n++; + lines.push(`- Finding number ${n} says something about topic ${s} at some length, to fill the view: "${q}" [${id} @ 0:${t}](${ORIGIN}/?v=synth-kitchen%2F${id}&t=${t})`); + } + lines.push(""); + } + const big = lines.join("\n"); + assert.ok(big.length > 40_000, String(big.length)); + await writeIterationFile("synth-big", 1, "sweep.md", big, paths); + const it = await createIteration("synth-big", { kind: "revise-report", model: "qwen3:8b", parent: 1, feedback: "In Topic 37, drop finding 220." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "drop", n: 220 }] })); + const d = deps(); + const out = await runTask({ task: "revise-report", article: "synth-big", n: it.n, origin: ORIGIN, maxUsd: 1 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.requests.length - before, 1, "one ops call, sent (not refused by the cap)"); + const req = ol.requests.at(-1); + assert.ok(Math.ceil(JSON.stringify([req.messages, null, req.format]).length / 3.5) <= 8000, "under the client's 8k estimate"); + const user = req.messages[1].content as string; + assert.match(user, /## Topic 37\n\[217\] Finding number 217/, "the named section, in full"); + assert.ok(user.includes("[220] Finding number 220")); + assert.match(user, /not shown/, "what is left out is said"); + assert.ok(!user.includes(`${ORIGIN}/?v=`), "links cut to their labels in the view"); + const md = (await readIterationFile("synth-big", it.n, "sweep.md", paths))!; + assert.ok(!md.includes("Finding number 220 "), "the op numbered against the whole document"); + assert.ok(md.includes("Finding number 219 ") && md.includes("Finding number 221 ")); + assert.ok(md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=40)`), "links whole in the report"); +}); + +test("revise-video on a local model: one ops batch over the trimmed cut", async () => { + await drainFake(); + await doneSweep("synth-basic", "basic", { manifest: true }); + const it = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Rename the-bakery to About the bakery." }, paths); + const before = ol.requests.length; + ol.push(jsonReply({ ops: [{ op: "heading", id: "the-bakery", text: "About the bakery" }] })); + const out = await runTask({ task: "revise-video", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps()); + assert.equal(out.status, "done", out.summary); + assert.equal(ol.requests.length - before, 1); + const req = ol.requests.at(-1); + assert.ok(req.format && !req.tools); + assert.match(req.messages[1].content, /- card the-bakery \(chapter\) heading: "The bakery"/); + assert.match(req.messages[1].content, /REPORT CITATIONS \(add_clip takes these ids\):\nc01: synth-kitchen\/bread-day-01/); + const m = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", it.n), "video.manifest.json"), "utf8")); + assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery"); +});