Archilyzer · Source

archilyzer

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

commit 9743a7cd9cca57d1b6dfe3c4bfb27a67a667d277
parent 92d28a8e8f93d367973ca9136e3a49036a84f5e4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 12:03:31 -0400

common, mcp: release 27 S5 — the generation tasks

The five tasks over an iteration, each a function of (input, deps) with
everything injected (LLM config, the MCP's corpus tools with the source
forced, web tools, cue/post readers, the iterations store):
sweep-agent (the sweep_plan worked by an agent, extract_batch, the report
tools, the link backstop, convert, the strict quote check, one bounded repair
round, failing findings dropped), sweep-pipeline (local_sweep.py ported: the
model proposes, judges, extracts and groups; code enumerates, windows,
verifies, cites, covers), revise-report and revise-video (checked ops over the
parent; quotes untouched; refusals recorded), narrate (a step on a done
iteration; grounding, one re-ask, failing sentences removed). Citation links
are built from slug, id and second on the article's citation origin.

authoringRules.ts holds the rules once; mcp/src/instructions.ts reads them.
A recorded run per task in common/testing/draft/runs/, run end to end in
mcp/src/draftTasks.test.ts.

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

Diffstat:
Mcommon/lib/report/draft/agentTool.ts | 16++++------------
Acommon/lib/report/draft/authoringRules.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/corpusSource.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/index.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/links.ts | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/llmText.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/narrate.ts | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/project.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/quotes.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/reportFile.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/revise-report.ts | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/revise-video.ts | 142+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/run.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/sweep-agent.ts | 322+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/sweep-pipeline.ts | 661+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/tasks.test.ts | 200+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/types.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/README.md | 1+
Acommon/testing/draft/runs/narrate.json | 34++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/revise-report.json | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/revise-video.json | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/sweep-agent.json | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/sweep-pipeline.json | 31+++++++++++++++++++++++++++++++
Amcp/src/draftTasks.test.ts | 331+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.ts | 27+++++++++++----------------
25 files changed, 3500 insertions(+), 28 deletions(-)

diff --git a/common/lib/report/draft/agentTool.ts b/common/lib/report/draft/agentTool.ts @@ -1,13 +1,5 @@ -// The tool shape the agent loop runs (common/lib/llm, release 27 lane A): -// a name, a description, a JSON schema for its input, and `run`, whose text -// goes back to the model. A thrown error is the tool's error result. -// -// Declared here (and in mcp/src/callTool.ts) until S5 imports lane A's one -// definition; the two must stay this exact shape. +// The tool shape the agent loop runs: lane A's one definition (common/lib/llm +// agent.ts), re-exported where the web and research tools import it (release +// 27; S5 unified the copies). mcp/src/callTool.ts keeps a structural copy. -export type AgentTool = { - name: string; - description: string; - inputSchema: Record<string, unknown>; - run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; // eslint-disable-line @typescript-eslint/no-explicit-any -}; +export type { AgentTool } from "../../llm/agent"; diff --git a/common/lib/report/draft/authoringRules.ts b/common/lib/report/draft/authoringRules.ts @@ -0,0 +1,111 @@ +// THE AUTHORING RULES — written once, read by both sides (release 27, S5): +// the MCP's plans for Claude Code (mcp/src/instructions.ts) and the generation +// tasks a job runs (./tasks/). A rule changes here, and both follow. +// +// Prompts carry RULES, never worked examples: a local model copies an example +// sentence verbatim (Q0, plans/local-llm-report-media.md). The narration +// writing rules keep their examples for Claude Code (the README's "Writing +// narration" is their source); `rulesForModel` strips them for a task's prompt. + +// ─── Narration (release 25, T5) ─── + +export const NARRATION_HARD_RULE = + "Storytelling and emotion live in the delivery, never in the claims: every " + + "factual statement stays exactly as the cited evidence supports — no invented " + + "quotes, no motives or feelings attributed to real people, no intensifiers " + + "that change a claim's strength."; + +export const NARRATION_WRITING_RULES = [ + "Short sentences; fragments are fine (\"One file. No title. Just a date.\").", + "\"...\" for a beat inside a sentence — at most one per sentence.", + "An expressive tag (<sigh>, <chuckle>, <gasp>, …) only where a person would make that sound, " + + "reacting to what was just said, at a sentence boundary — never mid-clause, never after a greeting; " + + "one per paragraph at most.", + "End a paragraph on a short punch or a rhetorical question.", + "A quote gets its own sentence after a colon lead-in, never chained to its attribution.", +] as const; + +// The operator's house taste for generated narration (the stopgap's TASTE; +// no tags at all — operator, 2026-10-11). +export const NARRATION_TASTE = [ + "Casual, concise and punchy; talk like a person, use contractions.", + "No expressive tags or stage directions of any kind, nothing in angle brackets.", + "No stock phrases or filler openers; start with the point.", + "Every number and every name you use must already be in the evidence below; add no facts.", + "Do not read quotes out; the clips that follow say them. Do not put a speaker's words in your own mouth.", + "Keep every negation and hedge the evidence has; say what was said, not why.", +] as const; + +// A rule as a model's prompt takes it: no parenthesised example (a quoted +// sentence, an `e.g.`, a list of tags). A rule about tags is dropped whole +// when `tags` is false (generated narration carries none). +export function ruleForModel(rule: string): string { + return rule + .replace(/\s*\((?:e\.g\.|for example)[^)]*\)/gi, "") + .replace(/\s*\([^()]*["“”<][^()]*\)/g, "") + .replace(/\s+([.;,])/g, "$1") + .trim(); +} + +export function rulesForModel(rules: readonly string[], opts: { tags?: boolean } = {}): string[] { + return rules + .filter((r) => opts.tags !== false || !/expressive tag|<[a-z]+>/i.test(r)) + .map(ruleForModel) + .filter(Boolean); +} + +// ─── Reports (the sweep, its revisions) ─── + +// convertSweep makes every quoted span between the previous link and a link +// THAT link's quote: a claim that quotes words breaks its own citation. +export const CLAIM_QUOTES_RULE = + "A claim never carries quotation marks or quoted words: every quoted span before a link becomes THAT " + + "link's quote, so a claim that quotes words — another moment's or its own — breaks its citation. Put the " + + "claim in plain words, then the quote, then its link."; + +export const VERBATIM_QUOTES_RULE = + "Quote the transcript's words VERBATIM, copied from a tool result: never quote words you did not see, " + + "never fix a transcript's spelling, grammar or names inside quotes, never join words from two moments " + + "into one quote. A quote that is not word for word what was said within 90 seconds of its link is refused."; + +export const ONE_QUOTE_PER_FINDING_RULE = + "Each finding is a list item under a `## section`: the claim in plain words, the quoted words in double " + + "quotes, then the citation link. One quote, one link per item."; + +export const POST_CITATION_RULE = + "A post has no timeline: cite it as `[post by <author>, <date>](<its url>)`, never with `@ mm:ss`."; + +export const REPORT_STYLE_RULE = "Plain, concise words. No hedged editorialising; the quotes carry it."; + +// The moment link a generated report cites a video with, on the article's +// citation origin — built from the channel slug, the video id and the second, +// never from a build's moment_base (null on a private build, FACTS). +export function momentLinkRule(origin: string): string { + return ( + `Cite a video as \`[<title> @ mm:ss](${origin}/?v=<channel slug>%2F<video id>&t=<seconds>)\`: the ` + + "moment_base a tool shows is already in that form, so append the line's integer second to it. Never cite a " + + "video by its platform URL (YouTube and the like)." + ); +} + +export const COVERAGE_RULE = + "End with a `## Coverage` section: the scope, N enumerated, how many you read, how many cited, and any " + + "COVERAGE PARTIAL caveat."; + +// ─── The sweep's dumb extractor (the plan's subagent, as a tool) ─── + +export const EXTRACTOR_SYSTEM = + "You are a DUMB EXTRACTOR for a transcript sweep. You get transcript excerpts and a directive. Return ONLY the " + + "lines relevant to the directive, VERBATIM — never analyze, summarize, rephrase, merge or fix a line. Group the kept " + + "lines per video as `### <title>`, then that video's `moment_base:` line copied exactly (or its `source:` line when " + + "there is no moment_base), then the kept lines in their `[mm:ss|seconds]` form exactly as given. Keep a line or two " + + "of context around a kept line when it is needed to know who is speaking or what is meant. Hard budget: at most 40 " + + "lines (~600 words) for the batch — if more match, keep the strongest and end with `(+N more matching lines)`. " + + "If nothing is relevant, return `(nothing relevant)`. Return nothing else."; + +// ─── Running unattended ─── + +export const UNATTENDED_RULE = + "You are running UNATTENDED — no person is watching, and nobody can answer. Where a plan says to show " + + "something or confirm, decide yourself, carry on, and note the decision in the report's summary. Never stop " + + "to ask."; diff --git a/common/lib/report/draft/tasks/corpusSource.ts b/common/lib/report/draft/tasks/corpusSource.ts @@ -0,0 +1,88 @@ +// Which corpus a generation reads, and which origin it cites on (release 27, +// S5; the stopgap's local_sweep.pick_build and site_origin). +// +// The corpus is a composed site build (`<exportBuildsDir>/<site>/out`, read +// with the MCP's `local:` source): the newest build holding every requested +// channel, a public one before a `-private` one (a public build is fresher +// and carries its site's origin); a named build must hold them all. +// +// The citation origin is the build's site's `siteUrl` (a `-private` build's +// public twin's), else the fallback the caller gives (settings). + +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; + +export type CorpusBuild = { build: string; dir: string; channels: string[]; mtimeMs: number }; + +export class NoCorpusBuildError extends Error {} + +async function readBuild(exportBuildsDir: string, build: string): Promise<CorpusBuild | null> { + const dir = path.join(exportBuildsDir, build, "out"); + const file = path.join(dir, "corpus.json"); + try { + const [text, st] = await Promise.all([readFile(file, "utf8"), stat(file)]); + const corpus = JSON.parse(text) as { channels?: { slug?: unknown }[] }; + const channels = (corpus.channels ?? []) + .map((c) => (c && typeof c === "object" ? c.slug : null)) + .filter((s): s is string => typeof s === "string"); + return { build, dir, channels, mtimeMs: st.mtimeMs }; + } catch { + return null; + } +} + +export async function listCorpusBuilds(exportBuildsDir: string): Promise<CorpusBuild[]> { + let names: string[]; + try { + names = (await readdir(exportBuildsDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name); + } catch { + return []; + } + const out: CorpusBuild[] = []; + for (const n of names) { + const b = await readBuild(exportBuildsDir, n); + if (b) out.push(b); + } + return out; +} + +export async function pickCorpusBuild( + channels: readonly string[], + o: { exportBuildsDir: string; want?: string }, +): Promise<CorpusBuild> { + const builds = await listCorpusBuilds(o.exportBuildsDir); + if (o.want) { + const b = builds.find((x) => x.build === o.want); + if (!b) { + throw new NoCorpusBuildError( + `no composed build "${o.want}" (have: ${builds.map((x) => x.build).sort().join(", ") || "none"})`, + ); + } + const missing = channels.filter((c) => !b.channels.includes(c)); + if (missing.length) throw new NoCorpusBuildError(`build ${o.want} does not hold ${missing.join(", ")}`); + return b; + } + const holding = builds.filter((b) => channels.every((c) => b.channels.includes(c))); + if (!holding.length) { + throw new NoCorpusBuildError( + `no composed build holds all of ${channels.join(", ") || "(no channels)"} — publish build the site that carries ` + + "them (a private site's build for private channels), or name a build", + ); + } + holding.sort((a, b) => Number(a.build.endsWith("-private")) - Number(b.build.endsWith("-private")) || b.mtimeMs - a.mtimeMs); + return holding[0]!; +} + +// The origin a build's links cite: its site's siteUrl, or for `<id>-private` +// the public site's; else null. +export async function siteOriginOf(build: string, sitesDir: string): Promise<string | null> { + for (const id of [build, build.replace(/-private$/, "")]) { + try { + const site = JSON.parse(await readFile(path.join(sitesDir, id, "site.json"), "utf8")) as { siteUrl?: unknown }; + if (typeof site.siteUrl === "string" && /^https?:\/\//.test(site.siteUrl)) return site.siteUrl.replace(/\/+$/, ""); + } catch { + // no such site + } + } + return null; +} diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -0,0 +1,46 @@ +// The generation tasks (release 27, S5), and one dispatcher the editor's +// `report-draft` job runs (S6). + +import { narrate, type NarrateInput } from "./narrate"; +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"; + +export * from "./types"; +export { TaskInputError, runOnIteration, usageOf } from "./run"; +export { sweepAgent, SWEEP_READ_TOOLS, type SweepAgentInput } from "./sweep-agent"; +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 { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource"; +export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; +export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes"; +export { projectDirOf } from "./project"; + +export type TaskInput = + | ({ task: "sweep-agent" } & SweepAgentInput) + | ({ task: "sweep-pipeline" } & SweepPipelineInput) + | ({ task: "revise-report" } & ReviseReportInput) + | ({ task: "revise-video" } & ReviseVideoInput) + | ({ task: "narrate" } & NarrateInput); + +export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { + switch (input.task) { + case "sweep-agent": + return sweepAgent(input, deps); + case "sweep-pipeline": + return sweepPipeline(input, deps); + case "revise-report": + return reviseReport(input, deps); + case "revise-video": + return reviseVideo(input, deps); + case "narrate": + return narrate(input, deps); + } +} + +export const isTaskName = (v: unknown): v is TaskName => + typeof v === "string" && ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate"].includes(v); diff --git a/common/lib/report/draft/tasks/links.ts b/common/lib/report/draft/tasks/links.ts @@ -0,0 +1,167 @@ +// Citation links for a generated report (release 27, S5): built from the +// channel slug, the video id and the second, on the article's CITATION +// ORIGIN — never from a build's moment_base, which is null on a private build +// (corpus.ts: a private site has no siteUrl) and then falls back to the +// platform's URL. +// +// - `rewriteMomentBases` gives every recording a tool result shows the +// origin's moment_base, so the model copies a right link from the start. +// - `rewriteLinks` is the backstop over the finished markdown: a video cited +// by its platform URL, or an archive link on another origin, becomes the +// moment (or post) link on the citation origin, when the recording is in +// the run's corpus. + +import { parseCitationHref } from "../../convertShared"; +import { extractJsonObject } from "../../../parseStdoutJson"; +import type { CorpusToolsLike } from "./types"; + +export function momentHref(origin: string, slug: string, id: string, seconds: number): string { + return `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&t=${Math.max(0, Math.floor(seconds))}`; +} + +export function postLinkHref(origin: string, slug: string, id: string): string { + return `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&vm=post`; +} + +export const momentBaseOf = (origin: string, slug: string, id: string) => + `${origin}/?v=${encodeURIComponent(`${slug}/${id}`)}&t=`; + +// Which channel (slug) holds a recording: read off a moment link when there is +// one, else asked of the corpus (get_video_metadata over the run's channels). +export type SlugResolver = { + slugOf(videoId: string): Promise<string | null>; + remember(videoId: string, slug: string): void; +}; + +export function slugResolver(corpus: Pick<CorpusToolsLike, "call">, channels: readonly string[]): SlugResolver { + const known = new Map<string, Promise<string | null>>(); + const ask = async (videoId: string): Promise<string | null> => { + const tries: Record<string, unknown>[] = channels.length + ? channels.map((channel) => ({ video_id: videoId, channel })) + : [{ video_id: videoId }]; + for (const args of tries) { + try { + const meta = extractJsonObject(await corpus.call("get_video_metadata", args)) as { channelSlug?: unknown; id?: unknown } | null; + if (meta && typeof meta.channelSlug === "string" && meta.channelSlug) return meta.channelSlug; + } catch { + // not in this channel + } + } + return null; + }; + return { + slugOf(videoId) { + let p = known.get(videoId); + if (!p) { + p = ask(videoId); + known.set(videoId, p); + } + return p; + }, + remember(videoId, slug) { + known.set(videoId, Promise.resolve(slug)); + }, + }; +} + +const VIDEO_ID_LINE = /video_id: (\S+)/; +const MOMENT_BASE_LINE = /^(\s*-?\s*)moment_base: (\S*)\s*$/m; +const SOURCE_LINE = /^(\s*-?\s*)source: \S+.*$/m; + +// get_transcripts' blocks (`## title`, `- video_id: …`, `- moment_base: …`), +// separated by `---`: each block's moment_base made the origin's. A block +// whose recording cannot be placed keeps what it had. +export async function rewriteMomentBases(text: string, resolver: SlugResolver, origin: string): Promise<string> { + const blocks = text.split(/\n---\n/); + const out: string[] = []; + for (const block of blocks) { + const id = VIDEO_ID_LINE.exec(block)?.[1]; + if (!id) { + out.push(block); + continue; + } + const mb = MOMENT_BASE_LINE.exec(block); + let slug: string | null = null; + if (mb) { + const parsed = parseCitationHref(`${mb[2]}0`); + if (parsed?.kind === "span" && parsed.id === id) slug = parsed.channel; + } + slug ??= await resolver.slugOf(id); + if (!slug) { + out.push(block); + continue; + } + resolver.remember(id, slug); + const base = momentBaseOf(origin, slug, id); + if (mb) out.push(block.replace(MOMENT_BASE_LINE, `${mb[1]}moment_base: ${base}`)); + else { + const src = SOURCE_LINE.exec(block); + out.push( + src + ? block.replace(SOURCE_LINE, (line) => `${line}\n${src[1]}moment_base: ${base}`) + : block.replace(VIDEO_ID_LINE, (line) => `${line}\n- moment_base: ${base}`), + ); + } + } + return out.join("\n---\n"); +} + +const MD_LINK = /\]\((https?:\/\/[^)\s]+)\)/g; + +// A platform's watch URL: `?v=<id>` (no slash in it) or youtu.be/<id>, and +// its `t` (`t=90`, `t=90s`). +function platformVideo(href: string): { id: string; seconds: number } | null { + let u: URL; + try { + u = new URL(href); + } catch { + return null; + } + let id: string | null = null; + if (u.hostname === "youtu.be") id = u.pathname.slice(1).split("/")[0] || null; + else { + const v = u.searchParams.get("v"); + if (v && !v.includes("/")) id = v; + } + if (!id) return null; + const t = /^(\d+)s?$/.exec(u.searchParams.get("t") ?? ""); + return { id, seconds: t ? Number(t[1]) : 0 }; +} + +// The backstop over finished markdown. Answers the text and how many links it +// rewrote. +export async function rewriteLinks( + md: string, + resolver: SlugResolver, + origin: string, +): Promise<{ md: string; fixed: number }> { + const hrefs = new Set<string>(); + for (const m of md.matchAll(MD_LINK)) hrefs.add(m[1]!); + const to = new Map<string, string>(); + for (const href of hrefs) { + if (href.startsWith(`${origin}/`)) continue; + const parsed = parseCitationHref(href); + if (parsed?.kind === "span") { + to.set(href, momentHref(origin, parsed.channel, parsed.id, parsed.seconds)); + continue; + } + if (parsed?.kind === "post") { + to.set(href, postLinkHref(origin, parsed.channel, parsed.id)); + continue; + } + if (parsed) continue; // a post on its own platform: convert places it + const v = platformVideo(href); + if (!v) continue; + const slug = await resolver.slugOf(v.id); + if (slug) to.set(href, momentHref(origin, slug, v.id, v.seconds)); + } + if (!to.size) return { md, fixed: 0 }; + let fixed = 0; + const out = md.replace(MD_LINK, (whole, href: string) => { + const next = to.get(href); + if (!next) return whole; + fixed++; + return `](${next})`; + }); + return { md: out, fixed }; +} diff --git a/common/lib/report/draft/tasks/llmText.ts b/common/lib/report/draft/tasks/llmText.ts @@ -0,0 +1,65 @@ +// One plain-text answer from either provider — the sweep's extractor call +// (release 27, S5; the stopgap's `claude_api.messages` with EXTRACTOR_SYSTEM). +// Metered on the run's meter. A local model's prompt is cut to fit its cap +// before it is sent (the 8k rule): the caller says what was cut. + +import { + AnthropicClient, + anthropicConfigOf, + isStrictModel, + ollamaChat, + ollamaConfigOf, + promptCapOf, + providerOf, + textOf, + type LlmConfig, + type Meter, +} from "../../../llm"; + +// Characters a token takes in the ollama estimate (lib/llm/ollama.ts). +const CHARS_PER_TOKEN = 3.5; + +export async function plainAnswer(o: { + llm: LlmConfig; + model: string; + system: string; + user: string; + meter: Meter; + signal?: AbortSignal; + maxTokens?: number; +}): Promise<string> { + if (providerOf(o.model) === "api") { + const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + const res = await client.messages( + { + model: o.model, + max_tokens: o.maxTokens ?? 4000, + ...(isStrictModel(o.model) ? {} : { temperature: 0 }), + system: o.system, + messages: [{ role: "user", content: o.user }], + }, + { meter: o.meter, signal: o.signal }, + ); + return textOf(res); + } + const cfg = ollamaConfigOf(o.llm, o.model); + const reply = await ollamaChat(cfg, { + model: o.model, + messages: [ + { role: "system", content: o.system }, + { role: "user", content: o.user }, + ], + signal: o.signal, + }); + o.meter.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); + return reply.message.content ?? ""; +} + +// How many characters of user text fit a model's one call beside `system`: +// unbounded on the API (the caller's own cap applies), the prompt cap less a +// margin on ollama. +export function userCharsFor(llm: LlmConfig, model: string, system: string, apiCap: number): number { + if (providerOf(model) === "api") return apiCap; + const cap = promptCapOf(ollamaConfigOf(llm, model)); + return Math.max(1000, Math.floor((cap - 300) * CHARS_PER_TOKEN) - system.length); +} diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts @@ -0,0 +1,214 @@ +// TASK narrate — card narration for an iteration's video cut (release 27, S5; +// the stopgap's local_narrate.py). A STEP on a done iteration (its `steps`), +// never an iteration of its own. +// +// For each title and chapter card the model drafts the words from that card's +// own evidence (the section's claims and quotes) under the authoring rules — +// the narration hard rule, the writing rules without their examples or the +// tag rule, the house taste. Code checks every draft (./grounding.ts: no tags, +// no stock phrases, every number and name in the report, no quote read out); +// a failing draft is re-asked once and the better attempt kept; one still +// failing a hard check loses its failing sentences, and a card with nothing +// left is not written. The manifest is snapshotted, then written whole; every +// draft and its checks go to the project's narration-draft.json. + +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { structuredAnswer } from "../../../llm"; +import { readIteration, reportSourceOf, readIterationFile } from "../../iterations"; +import { NARRATION_HARD_RULE, NARRATION_TASTE, NARRATION_WRITING_RULES, rulesForModel } from "../authoringRules"; +import { checkNarration, groundingInputOf, sentencesOf, type GroundingInput } from "../grounding"; +import type { ManifestEntry } from "../videoOps"; +import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project"; +import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export const TITLE_WORDS = 35; +export const CHAPTER_WORDS = 45; +// A draft this far over its limit is refused outright. +export const OVER_LIMIT_SLACK = 10; + +export type NarrateInput = { + article: string; + n: number; + model: string; + projectsRoot: string; + // Only these card ids (default: every title and chapter card). + cards?: string[]; + // Re-draft a card that has narration already. + force?: boolean; + maxUsd?: number; + jobId?: string; +}; + +type Section = { title?: string; body?: string | null; claims?: { text?: string; citations?: string[] }[] | null }; +type ReportLike = { + title?: string; + summary?: string | null; + sections?: Section[]; + citations?: Record<string, { quote?: string; date?: string } | undefined> | null; +}; + +export function narrationSystem(limit: number): string { + const rules = rulesForModel(NARRATION_WRITING_RULES, { tags: false }); + return ( + "You write the spoken narration for one card of a short evidence video; a stock synthetic voice reads it aloud. " + + `${NARRATION_HARD_RULE} Rules for the ear: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + `House style: ${NARRATION_TASTE.join(" ")} At most ${limit} words, one short paragraph, plain text.` + ); +} + +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, ""); + +// A card's evidence and the quotes it must not read out; null when the card +// matches no section of the report. +export function cardContext(card: ManifestEntry, report: ReportLike): { text: string; quotes: string[] } | null { + const cites = report.citations ?? {}; + if (card.style === "title") { + const claims = (report.sections ?? []).flatMap((s) => (s.claims ?? []).map((c) => stripCites(c.text ?? ""))).slice(0, 6); + return { + text: + "This is the OPENING card: set up what the video looks at in one or two short sentences, as a hook. Do not list " + + `the sections and do not give the findings away.\nReport title: ${report.title ?? ""}` + + (report.summary ? `\n${report.summary}` : "") + + `\nSome of what it found:\n${claims.map((c) => `- ${c}`).join("\n")}`, + quotes: Object.values(cites).map((c) => c?.quote ?? "").filter(Boolean), + }; + } + const s = (report.sections ?? []).find((x) => x.title === card.heading); + if (!s) return null; + const lines = [`Section: ${s.title}`]; + const quotes: string[] = []; + if (s.body) lines.push(`Section text: ${stripCites(s.body)}`); + for (const c of (s.claims ?? []).slice(0, 12)) { + const ids = (c.citations ?? []).filter((i) => cites[i]); + const q = ids.map((i) => cites[i]?.quote ?? "").filter(Boolean).join(" … "); + const dates = [...new Set(ids.map((i) => cites[i]?.date ?? "").filter(Boolean))].sort(); + lines.push(`- Claim: ${stripCites(c.text ?? "")}${dates.length ? ` (${dates.join(", ")})` : ""}${q ? `\n Quote: ${q}` : ""}`); + if (q) quotes.push(q); + } + return { text: lines.join("\n"), quotes }; +} + +type Attempt = { text: string; hard: string[]; soft: string[] }; + +function checkDraft(text: string, g: GroundingInput, limit: number): Attempt { + const r = checkNarration(text, g); + const hard = [...r.hard]; + const words = text.split(/\s+/).filter(Boolean).length; + if (words > limit + OVER_LIMIT_SLACK) hard.push(`${words} words (limit ${limit})`); + if (!text) hard.push("empty"); + return { text, hard, soft: r.soft }; +} + +// The best of the attempts; when it still fails a hard check, the attempts +// with their failing sentences REMOVED (never rewritten) and cut to the limit. +export function chooseDraft(attempts: Attempt[], g: GroundingInput, limit: number): Attempt { + const rank = [...attempts].sort((a, b) => a.hard.length - b.hard.length || a.soft.length - b.soft.length); + const best = rank[0] ?? { text: "", hard: ["no draft"], soft: [] }; + if (!best.hard.length) return best; + for (const cand of rank) { + const sents = sentencesOf(cand.text).filter((t) => !checkNarration(t, g).hard.length); + while (sents.length && sents.join(" ").split(/\s+/).length > limit) sents.pop(); + const text = sents.join(" ").trim(); + if (text.split(/\s+/).filter(Boolean).length < 5) continue; + const again = checkDraft(text, g, limit); + if (!again.hard.length) return { text, hard: [], soft: [...again.soft, "trimmed: failing or overlong sentences removed"] }; + } + return best; +} + +export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> { + return runOnIteration( + { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, step: { task: "narrate", model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } }, + (h) => narrateBody(h, input), + ); +} + +async function narrateBody(h: TaskHandle, input: NarrateInput): Promise<TaskOutcome> { + const { deps } = h; + const it = (await readIteration(h.article, h.n, h.paths))!; + const dir = projectDirOf(it, input.projectsRoot); + const manifest = await readManifest(dir); + if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`); + let report = (await readProjectReport(dir)) as ReportLike | null; + if (!report) { + const from = await reportSourceOf(h.article, h.n, h.paths); + const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths); + report = text ? (JSON.parse(text) as ReportLike) : null; + } + if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to narrate from`); + const base = groundingInputOf(report); + const only = input.cards?.length ? new Set(input.cards) : null; + const drafts = new Map<string, string>(); + const record: Record<string, unknown> = {}; + h.log(`narrating i${h.n} on ${input.model} (${dir})`); + + for (const card of manifest.timeline) { + if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue; + if (only && !only.has(card.id)) continue; + if (card.narration?.text && !input.force) continue; + if ((card.heading ?? "").trim().toLowerCase() === "coverage") { + record[card.id] = { skipped: "the Coverage card is not narrated (its numbers are on the page)" }; + continue; + } + const ctx = cardContext(card, report); + if (!ctx) { + record[card.id] = { skipped: "no section in the report matches this card's heading" }; + continue; + } + const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS; + const g: GroundingInput = { ...base, quotes: ctx.quotes }; + const system = narrationSystem(limit); + const user = `Card heading on screen: ${card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${ctx.text}\n\nWrite this card's narration.`; + const attempts: Attempt[] = []; + for (let k = 0; k < 2; k++) { + deps.signal?.throwIfAborted(); + const extra = attempts.length + ? `\n\nYour last draft was refused for: ${[...attempts.at(-1)!.hard, ...attempts.at(-1)!.soft].join("; ")}. Write it again without those problems.` + : ""; + let text = ""; + try { + const ans = await structuredAnswer<{ text?: unknown }>({ + llm: deps.llm, + model: input.model, + system, + user: user + extra, + schema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, + meter: h.meter, + signal: deps.signal, + }); + text = String(ans.text ?? "").replace(/\s+/g, " ").trim().replace(/^"+|"+$/g, ""); + } catch (e) { + if (deps.signal?.aborted) throw e; + attempts.push({ text: "", hard: [(e as Error).message], soft: [] }); + continue; + } + const a = checkDraft(text, g, limit); + attempts.push(a); + h.turns([{ kind: "narration", card: card.id, attempt: k + 1, ...a }]); + if (!a.hard.length && !a.soft.length) break; + } + const chosen = chooseDraft(attempts, g, limit); + record[card.id] = { heading: card.heading, attempts, chosen }; + if (chosen.hard.length) { + h.log(` ${card.id}: NOT written — ${chosen.hard.join("; ")}`); + continue; + } + drafts.set(card.id, chosen.text); + h.log(` ${card.id}: ${chosen.text}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`); + } + await writeFile(path.join(dir, "narration-draft.json"), `${JSON.stringify(record, null, 2)}\n`).catch(() => {}); + const refused = Object.values(record).filter((r) => (r as { chosen?: Attempt }).chosen?.hard.length).length; + h.check({ name: "narration", ok: refused === 0, detail: `${drafts.size} card(s) drafted${refused ? `, ${refused} not written (a hard check)` : ""}` }); + if (!drafts.size) return { status: "failed", summary: "no card narrated (see narration-draft.json)" }; + const snap = await snapshotManifest(dir, "narration", deps.now?.() ?? new Date()); + for (const e of manifest.timeline) { + const text = drafts.get(e.id); + if (e.type !== "card" || !text) continue; + e.narration = { ...(e.narration && typeof e.narration === "object" ? e.narration : {}), text }; + e.seconds = "auto"; + } + await writeManifest(dir, manifest); + return { status: "done", summary: `${drafts.size} card(s) narrated${snap ? ` (undo: ${snap})` : ""}` }; +} diff --git a/common/lib/report/draft/tasks/project.ts b/common/lib/report/draft/tasks/project.ts @@ -0,0 +1,101 @@ +// An iteration's video project on disk (release 27, S5): where it is, its +// manifest and report, a snapshot before a write, and a new project seeded +// from its parent's (the stopgap's revise.py video). +// +// Projects live off the corpus disk under the generation settings' projects +// root (D1): `projectOf(root, id, n)`, recorded in the iteration as +// `projectDir`. The manifest is written whole, through a temp and a rename. + +import { copyFile, link, mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { projectOf, type Iteration } from "../../iterations"; +import type { VideoManifest } from "../videoOps"; + +export const MANIFEST_NAME = "video.manifest.json"; +// umtool's snapshots (umtool/lib/report/snapshots.mjs): `revisions/<stamp>-<label>.manifest.json`. +export const REVISIONS_DIR = "revisions"; + +export function projectDirOf(it: Pick<Iteration, "projectDir" | "article" | "n">, projectsRoot: string): string { + return it.projectDir ?? projectOf(projectsRoot, it.article, it.n); +} + +const exists = (p: string) => stat(p).then(() => true, () => false); + +export async function readManifest(dir: string): Promise<VideoManifest | null> { + try { + const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")) as VideoManifest; + return m && typeof m === "object" && Array.isArray(m.timeline) ? m : null; + } catch { + return null; + } +} + +export async function readProjectReport(dir: string): Promise<Record<string, unknown> | null> { + try { + return JSON.parse(await readFile(path.join(dir, "report.json"), "utf8")) as Record<string, unknown>; + } catch { + return null; + } +} + +export async function writeManifest(dir: string, m: VideoManifest): Promise<void> { + await mkdir(dir, { recursive: true }); + const file = path.join(dir, MANIFEST_NAME); + const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + await writeFile(tmp, `${JSON.stringify(m, null, 2)}\n`); + await rename(tmp, file); +} + +function stampOf(d: Date): string { + const p = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`; +} + +// An undo point umtool's revisions panel lists: `auto-before-<op>`. +export async function snapshotManifest(dir: string, op: string, now: Date = new Date()): Promise<string | null> { + const src = path.join(dir, MANIFEST_NAME); + if (!(await exists(src))) return null; + await mkdir(path.join(dir, REVISIONS_DIR), { recursive: true }); + const name = `${stampOf(now)}-auto-before-${op}.manifest.json`; + const dst = path.join(dir, REVISIONS_DIR, name); + if (await exists(dst)) return null; + await copyFile(src, dst); + return path.posix.join(REVISIONS_DIR, name); +} + +// A new project from its parent's: the report and the stills the cut shows +// copied, the narration voices HARD-LINKED (a voice is never written in place, +// so an unchanged line is not voiced again). The manifest is the caller's. +export async function seedProject(parentDir: string, dir: string, manifest: VideoManifest): Promise<{ stills: number; voices: number }> { + await mkdir(dir, { recursive: true }); + if (await exists(path.join(parentDir, "report.json"))) await copyFile(path.join(parentDir, "report.json"), path.join(dir, "report.json")); + let stills = 0; + for (const e of manifest.timeline ?? []) { + const src = typeof e.src === "string" ? e.src : null; + if (e.type !== "image" || !src || path.isAbsolute(src) || src.split(/[\\/]/).includes("..")) continue; + if (!(await exists(path.join(parentDir, src))) || (await exists(path.join(dir, src)))) continue; + await mkdir(path.dirname(path.join(dir, src)), { recursive: true }); + await copyFile(path.join(parentDir, src), path.join(dir, src)); + stills++; + } + let voices = 0; + const pn = path.join(parentDir, "out", "narration"); + const nn = path.join(dir, "out", "narration"); + let names: string[] = []; + try { + names = await readdir(pn); + } catch { + names = []; + } + if (names.length) await mkdir(nn, { recursive: true }); + for (const f of names) { + if (await exists(path.join(nn, f))) continue; + try { + await link(path.join(pn, f), path.join(nn, f)); + voices++; + } catch { + // another device or a directory: the voices step makes it again + } + } + return { stills, voices }; +} diff --git a/common/lib/report/draft/tasks/quotes.ts b/common/lib/report/draft/tasks/quotes.ts @@ -0,0 +1,164 @@ +// Convert a generated sweep.md and check its quotes (release 27, S5; the +// stopgap's convert_and_verify + strict_check, in process). +// +// The check a GENERATED quote must pass is the strict one (D3): every quoted +// fragment verbatim (normalised) in the record's cues within ±90 s of its +// cited second; a post's quote in the post's text. An outside verifier (the +// editor's verify-quotes over the corpus on disk, which also reads the en-orig +// track) may add problems. A finding whose quote fails after the one repair +// round is DROPPED, never repaired by code. + +import { sweepToReport } from "../../convertSweep"; +import type { CuesOf, PostChannelOf } from "../../convertShared"; +import type { Report } from "../../schema"; +import { strictNormalize, strictQuoteCheck, strictTextCheck, quoteFragments } from "../../../citations/verify"; +import { findingsOf, parseSweep, quotesOf, renderSweep, LINK_RE, type SweepDoc } from "../sweepModel"; +import { parseCitationHref } from "../../convertShared"; +import { mmss } from "../reportOps"; +import type { TaskDeps } from "./types"; + +export type QuoteProblem = { + citation: string; + channel: string; + id: string; + second?: number; + quote: string; + why: string; + // The transcript ±45 s around the cited second, for a repair. + near?: string; +}; + +export type ConvertOutcome = + | { ok: true; report: Report; warnings: string[] } + | { ok: false; problems: string[]; warnings: string[] }; + +export function titleOfSweep(md: string): string | null { + const first = md.split("\n").find((l) => l.startsWith("# ")); + return first ? first.slice(2).trim() || null : null; +} + +export async function convertSweepText( + md: string, + o: { id: string; title?: string; cuesOf?: CuesOf; postChannelOf?: PostChannelOf }, +): Promise<ConvertOutcome> { + const converted = await sweepToReport(md, { + id: o.id, + ...(o.title ? { title: o.title } : {}), + ...(o.cuesOf ? { cuesOf: o.cuesOf } : {}), + ...(o.postChannelOf ? { postChannelOf: o.postChannelOf } : {}), + }); + if (converted.problems.length) { + return { + ok: false, + problems: converted.problems.map((p) => `${p.path || "(root)"}: ${p.message}`), + warnings: converted.warnings, + }; + } + return { ok: true, report: converted.report, warnings: converted.warnings }; +} + +const NEAR_SECONDS = 45; + +// Every video, audio and post citation with a quote, strictly checked. +export async function checkQuotes( + report: Report, + deps: Pick<TaskDeps, "cuesOf" | "postTextOf" | "verifyReport">, +): Promise<QuoteProblem[]> { + const problems: QuoteProblem[] = []; + for (const [cid, c] of Object.entries(report.citations ?? {})) { + if (c.kind !== "video" && c.kind !== "audio" && c.kind !== "post") continue; + const quote = (c as { quote?: string }).quote ?? ""; + if (!quote.trim()) continue; + if (c.kind === "post") { + const text = deps.postTextOf ? await deps.postTextOf(c.channel, c.id) : null; + if (text === null) { + if (deps.postTextOf) problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: `no post ${c.channel}/${c.id} to check the quote against` }); + continue; + } + const r = strictTextCheck(quote, text); + if (!r.ok) { + problems.push({ citation: cid, channel: c.channel, id: c.id, quote, why: `"${r.failed}" is not the post's words`, near: text }); + } + continue; + } + const cues = await deps.cuesOf(c.channel, c.id); + if (!cues || cues.length === 0) { + problems.push({ citation: cid, channel: c.channel, id: c.id, second: c.start, quote, why: `no transcript cues for ${c.channel}/${c.id}` }); + continue; + } + const r = strictQuoteCheck(quote, cues, c.start); + if (!r.ok) { + const near = cues + .filter((x) => x.start >= c.start - NEAR_SECONDS && x.start <= c.start + NEAR_SECONDS) + .map((x) => ` [${Math.floor(x.start)}] ${x.text}`) + .join("\n"); + problems.push({ + citation: cid, + channel: c.channel, + id: c.id, + second: c.start, + quote, + why: `not verbatim within 90 s of ${Math.floor(c.start)} s: "${r.failed}"`, + near, + }); + } + } + if (deps.verifyReport) { + const seen = new Set(problems.map((p) => p.citation)); + for (const p of await deps.verifyReport(report)) { + if (seen.has(p.citation) || p.status === "ok" || p.status === "inexact") continue; + const c = report.citations?.[p.citation] as { channel?: string; id?: string; start?: number; quote?: string } | undefined; + problems.push({ + citation: p.citation, + channel: c?.channel ?? "", + id: c?.id ?? "", + ...(typeof c?.start === "number" ? { second: c.start } : {}), + quote: c?.quote ?? "", + why: `verify-quotes: ${p.status}${p.message ? ` — ${p.message}` : ""}`, + }); + } + } + return problems; +} + +// The problems as the repair round's message lists them. +export function describeProblems(problems: readonly QuoteProblem[], max = 40): string { + return problems + .slice(0, max) + .map( + (p) => + `- ${p.why} — ${p.channel}/${p.id}${p.second !== undefined ? ` at ${mmss(p.second)}` : ""} (citation ${p.citation}): "${p.quote.slice(0, 200)}"` + + (p.near ? `\n The transcript there:\n${p.near}` : ""), + ) + .join("\n"); +} + +// The findings citing a failed quote, dropped: a finding goes when one of its +// links cites the problem's recording and its quoted words hold one of the +// failed quote's fragments. Answers the new markdown and what went. +export function dropFailedFindings(md: string, problems: readonly QuoteProblem[]): { md: string; dropped: string[] } { + const doc: SweepDoc = parseSweep(md); + const dropped: string[] = []; + for (const section of doc.sections) { + for (const f of findingsOf(section)) { + const links = [...f.rest.matchAll(new RegExp(LINK_RE.source, "g"))] + .map((m) => /\]\((.*)\)$/.exec(m[0])?.[1] ?? "") + .map((href) => parseCitationHref(href)) + .filter((x) => x !== null); + const quoted = strictNormalize(quotesOf(f).join(" ")); + const hit = problems.find( + (p) => + links.some((l) => "channel" in l && l.channel === p.channel && l.id === p.id) && + quoteFragments(p.quote).some((frag) => { + const n = strictNormalize(frag); + return n.length > 0 && quoted.includes(n); + }), + ); + if (!hit) continue; + section.body.splice(section.body.indexOf(f), 1); + dropped.push(`${f.claim.slice(0, 80)} — ${hit.why}`); + } + } + if (!dropped.length) return { md, dropped }; + return { md: renderSweep(doc), dropped }; +} diff --git a/common/lib/report/draft/tasks/reportFile.ts b/common/lib/report/draft/tasks/reportFile.ts @@ -0,0 +1,65 @@ +// The report file an agent writes (release 27, S5): `write_report`, +// `edit_report` and `read_report` — the plan's Write/Edit tools, for the +// iteration's sweep.md only. Every change is kept in the iterations store as +// it happens, so a run cut short leaves its report as far as it got. + +import type { AgentTool } from "../../../llm"; +import { writeIterationFile } from "../../iterations"; +import type { StorePaths } from "./types"; + +export type ReportFile = { + text(): string; + set(md: string): Promise<void>; + tools: AgentTool[]; +}; + +export function reportFile(o: { article: string; n: number; paths?: StorePaths; initial?: string; readOnly?: boolean }): ReportFile { + let md = o.initial ?? ""; + let written = md.length > 0; + const save = async (next: string) => { + md = next; + written = true; + await writeIterationFile(o.article, o.n, "sweep.md", md, o.paths); + }; + const tools: AgentTool[] = [ + { + name: "write_report", + description: "Replace the whole report file (sweep.md) with this markdown.", + inputSchema: { type: "object", properties: { markdown: { type: "string" } }, required: ["markdown"] }, + run: async (input: { markdown?: unknown }) => { + if (typeof input?.markdown !== "string" || !input.markdown.trim()) throw new Error("write_report needs the markdown"); + await save(input.markdown); + return `wrote sweep.md (${input.markdown.length} chars)`; + }, + }, + { + name: "edit_report", + description: "Replace one exact, unique passage of the report with new text (old_text must occur once).", + inputSchema: { + type: "object", + properties: { old_text: { type: "string" }, new_text: { type: "string" } }, + required: ["old_text", "new_text"], + }, + run: async (input: { old_text?: unknown; new_text?: unknown }) => { + const from = typeof input?.old_text === "string" ? input.old_text : ""; + const to = typeof input?.new_text === "string" ? input.new_text : null; + if (!from || to === null) throw new Error("edit_report needs old_text and new_text"); + const count = md.split(from).length - 1; + if (count !== 1) throw new Error(`old_text occurs ${count} times in the report — give a unique passage`); + await save(md.replace(from, () => to)); + return "edited"; + }, + }, + { + name: "read_report", + description: "Read the report file as it is now.", + inputSchema: { type: "object", properties: {} }, + run: async () => (written ? md : "(no report yet)"), + }, + ]; + return { + text: () => md, + set: save, + tools: o.readOnly ? tools.filter((t) => t.name === "read_report") : tools, + }; +} diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts @@ -0,0 +1,229 @@ +// 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. + +import { providerOf, runAgent, type AgentTool } from "../../../llm"; +import { lineage, readIterationFile, writeIterationFile } from "../../iterations"; +import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, momentLinkRule } from "../authoringRules"; +import { applyReportOps, strictCheckerOver, type AppliedOp, type RefusedOp } from "../reportOps"; +import { numberedView, parseSweep, renderSweep, type SweepDoc } from "../sweepModel"; +import { extractJsonObject } from "../../../parseStdoutJson"; +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(" "); + +export const REPORT_OPS_TEXT = (origin: 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):", + '- {"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":"<section title>"} move finding N (a new title makes a new section)', + `- {"op":"add","section":"<title>","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, + 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; +}; + +// 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), + ); +} + +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 titleOf = async (channel: string, id: string) => { + try { + const meta = extractJsonObject(await deps.corpus.call("get_video_metadata", { channel, video_id: id })) as { title?: unknown } | null; + return typeof meta?.title === "string" ? meta.title : null; + } catch { + return null; + } + }; + const checkQuote = strictCheckerOver(deps.cuesOf); + let doc: SweepDoc = parseSweep(parent.md); + const applied: AppliedOp[] = []; + const refused: RefusedOp[] = []; + const added: string[] = []; + h.log(`revising the report of i${parent.from} on ${model}`); + + 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 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`); + 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" }; + + 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 }); + h.check({ + name: "quotes", + ok: problems.length === 0, + detail: problems.length ? `${problems.length} quote(s) fail the strict check (from the iteration revised): ${problems.map((p) => p.why).slice(0, 3).join("; ")}` : "every quote verbatim (strict)", + }); + 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 }, + }; +} diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts @@ -0,0 +1,142 @@ +// TASK revise-video — a new iteration of an article's video cut from the +// operator's feedback (release 27, S5; the stopgap's `revise.py video`). +// +// The model reads the parent iteration's cut (its project's +// video.manifest.json) and changes it ONLY through `apply_ops` +// (./videoOps.ts: a narration passes grounding, a trim stays within the +// fetched window ±3 s, a clip added comes from the report's citations). The +// 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). + +import { providerOf, runAgent, type AgentTool } from "../../../llm"; +import { readIteration, type Iteration } from "../../iterations"; +import { applyVideoOps, cutView, 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 { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export const VIDEO_OPS_TEXT = [ + "Operations (objects for apply_ops; entries are named by id):", + '- {"op":"drop","id":"<entry id>"} remove an entry', + '- {"op":"move","id":"<entry id>","after":"<entry id, or \'start\'>"} reorder', + '- {"op":"heading","id":"<card id>","text":"..."} a card\'s on-screen heading', + '- {"op":"narration","id":"<card id>","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', + '- {"op":"trim","id":"<clip id>","start":S,"end":E} a clip\'s in/out seconds, within 3 s of its current ones', + '- {"op":"add_clip","citation":"<citation id from the report>","after":"<entry id>"} a clip for a cited moment not in the cut', + '- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}', +].join("\n"); + +export type ReviseVideoInput = { + article: string; + n: number; + model?: string; + feedback?: string; + origin: string; + maxUsd: number; + projectsRoot: string; + web?: boolean; + webSearchMaxUses?: number; + maxTurns?: number; +}; + +export async function reviseVideo(input: ReviseVideoInput, deps: TaskDeps): Promise<TaskResult> { + return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["revise-video"] }, (h) => + reviseVideoBody(h, input), + ); +} + +// The nearest iteration up `n`'s parents whose project has a manifest. +async function parentProject(h: TaskHandle, projectsRoot: string): Promise<{ it: Iteration; dir: string; manifest: VideoManifest } | null> { + let at = h.iteration.parent; + while (at !== null) { + const it = await readIteration(h.article, at, h.paths); + if (!it) return null; + const dir = projectDirOf(it, projectsRoot); + const manifest = await readManifest(dir); + if (manifest) return { it, dir, manifest }; + at = it.parent; + } + return null; +} + +async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): 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 parentProject(h, input.projectsRoot); + if (!parent) throw new TaskInputError(`"${h.article}" i${h.n}: no iteration it revises has a video cut (run the chain to its manifest first)`); + const report = (await readProjectReport(parent.dir)) as ReportForVideo | null; + if (!report) throw new TaskInputError(`${parent.dir} has no report.json beside its manifest`); + const origin = input.origin.replace(/\/+$/, ""); + const channels = [...new Set(Object.values(report.citations ?? {}).map((c) => c?.channel).filter((c): c is string => !!c))]; + const resolver = slugResolver(deps.corpus, channels); + const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin); + let manifest: VideoManifest = structuredClone(parent.manifest); + const applied: AppliedVideoOp[] = []; + const refused: RefusedVideoOp[] = []; + const cites = Object.entries(report.citations ?? {}) + .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}`; + h.log(`revising the cut of i${parent.it.n} on ${model}`); + + const tools: AgentTool[] = [ + ...reviseCorpusTools(deps, rewrite), + ...(input.web === false ? [] : (deps.web ?? [])), + { name: "read_doc", description: "The cut as it is now, and the report's citations.", inputSchema: { type: "object", properties: {} }, run: async () => view() }, + { + name: "apply_ops", + 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`); + return ( + JSON.stringify({ + applied: r.applied.map((a) => ({ index: a.index, op: a.op.op, ...(a.warnings ? { warnings: a.warnings } : {}) })), + refused: r.refused.map((x) => ({ index: x.index, op: x.op.op, why: x.why })), + }) + `\n\nNow:\n${cutView(manifest)}` + ); + }, + }, + ]; + 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" }; + + const ops = { + applied: applied.map((a) => (a.warnings ? { ...a.op, warnings: a.warnings } : a.op)), + refused: refused.map((r) => ({ ...r.op, why: r.why })), + }; + const dir = projectDirOf(iteration, input.projectsRoot); + const seeded = await seedProject(parent.dir, dir, manifest); + await writeManifest(dir, manifest); + h.check({ name: "cut", ok: true, detail: `${manifest.timeline.length} timeline entries; from i${parent.it.n}: ${seeded.voices} voice(s) linked, ${seeded.stills} still(s)` }); + return { + status: "done", + summary: `${ops.applied.length} op(s) applied, ${ops.refused.length} refused — the cut in ${dir}`, + patch: { ops, projectDir: dir }, + }; +} diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -0,0 +1,207 @@ +// The life of one task over an iteration (release 27, S5): mark it running, +// meter its spend, keep its turns, and record how it ended — done, failed or +// cancelled — with the minutes, the cost per model, the ops and the checks. +// +// A task's own failure (no report, nothing verified, the model refused) is a +// `failed` iteration and a result, never a throw; a cancel (the job's signal) +// is `cancelled`. What throws is a call that cannot start: no such iteration, +// or one that is not this task's to run. + +import { CancelledError, Meter, type ModelTally } from "../../../llm"; +import { + addIterationUsage, + appendIterationTurns, + readIteration, + recordIterationStep, + updateIteration, + type Iteration, + type IterationCheck, + type IterationPatch, +} from "../../iterations"; +import { ArticleRegistryError } from "../../registry"; +import type { StorePaths, TaskDeps, TaskResult, TaskStatus } from "./types"; + +export class TaskInputError extends Error {} + +// What a task body hands back when it ends on its own. +export type TaskOutcome = { + status: Exclude<TaskStatus, "cancelled">; + summary: string; + patch?: IterationPatch; +}; + +export type TaskHandle = { + article: string; + n: number; + iteration: Iteration; + meter: Meter; + deps: TaskDeps; + paths: StorePaths | undefined; + log(line: string): void; + // Turns for turns.jsonl (an agent's transcript, a pipeline's events). + turns(entries: readonly unknown[]): void; + check(c: IterationCheck): void; + checks: IterationCheck[]; +}; + +export function usageOf(t: ModelTally) { + return { + usd: t.usd, + inputTokens: t.input, + outputTokens: t.output, + cacheReadTokens: t.cacheRead, + cacheWriteTokens: t.cacheWrite, + calls: t.calls, + }; +} + +const isCancel = (err: unknown, signal?: AbortSignal) => + err instanceof CancelledError || (err as Error)?.name === "AbortError" || !!signal?.aborted; + +const round2 = (v: number) => Math.round(v * 100) / 100; + +// Run `body` as iteration `n` of `article`. `step` set: the task is a STEP on +// a done iteration (narration) — recorded in its `steps`, its status left as +// it is. Else the iteration itself is the task's: it must be queued (or +// running, a resumed job) and is marked running, then ended. +export async function runOnIteration( + o: { + article: string; + n: number; + deps: TaskDeps; + maxUsd?: number; + kinds?: readonly Iteration["kind"][]; + step?: { task: string; model: string; jobId?: string }; + }, + body: (h: TaskHandle) => Promise<TaskOutcome>, +): Promise<TaskResult> { + const { article, n, deps } = o; + const paths = deps.paths; + const now = deps.now ?? (() => new Date()); + const it = await readIteration(article, n, paths); + if (!it) throw new TaskInputError(`"${article}" has no iteration i${n}`); + if (o.kinds && !o.kinds.includes(it.kind)) { + throw new TaskInputError(`"${article}" i${n} is a ${it.kind} iteration, not ${o.kinds.join(" or ")}`); + } + if (o.step) { + if (it.status !== "done") throw new TaskInputError(`"${article}" i${n} is ${it.status}: a ${o.step.task} step runs over a done iteration`); + } else if (it.status !== "queued" && it.status !== "running") { + throw new TaskInputError(`"${article}" i${n} is ${it.status}: only a queued iteration is run`); + } + + const started = now(); + const meter = new Meter({ maxUsd: o.maxUsd }); + const turns: unknown[] = []; + const checks: IterationCheck[] = []; + const log = (line: string) => { + try { + deps.log?.(line); + } catch { + // a listener never stops the task + } + }; + const record = async (status: TaskStatus | "running", detail?: string) => { + const at = now(); + const minutes = round2((at.getTime() - started.getTime()) / 60_000); + if (o.step) { + await recordIterationStep( + article, + n, + { + task: o.step.task, + model: o.step.model, + status, + startedAt: started.toISOString(), + ...(status === "running" ? {} : { endedAt: at.toISOString(), minutes, cost: Math.round(meter.usd * 10_000) / 10_000 }), + ...(o.step.jobId ? { jobId: o.step.jobId } : {}), + ...(detail ? { detail: detail.slice(0, 500) } : {}), + }, + paths, + at, + ); + } + return minutes; + }; + + if (o.step) await record("running"); + else await updateIteration(article, n, { status: "running", error: undefined }, paths, started); + const handle: TaskHandle = { + article, + n, + iteration: o.step ? it : { ...it, status: "running" }, + meter, + deps, + paths, + log, + turns: (entries) => turns.push(...entries), + check: (c) => { + const i = checks.findIndex((x) => x.name === c.name); + if (i >= 0) checks[i] = c; + else checks.push(c); + }, + checks, + }; + + let status: TaskStatus; + let summary: string; + let patch: IterationPatch = {}; + try { + const out = await body(handle); + status = deps.signal?.aborted ? "cancelled" : out.status; + summary = deps.signal?.aborted ? "cancelled" : out.summary; + patch = out.patch ?? {}; + } catch (err) { + if (err instanceof TaskInputError || err instanceof ArticleRegistryError) { + // Not the model's doing: the iteration fails with the reason. + status = deps.signal?.aborted ? "cancelled" : "failed"; + summary = status === "cancelled" ? "cancelled" : (err as Error).message; + } else if (isCancel(err, deps.signal)) { + status = "cancelled"; + summary = "cancelled"; + } else { + status = "failed"; + summary = `${(err as Error)?.name ?? "Error"}: ${(err as Error)?.message ?? String(err)}`; + } + } + + // The record of the run, whatever happened: turns, spend, the ending. + if (turns.length) await appendIterationTurns(article, n, turns, paths).catch((e) => log(`turns not kept: ${(e as Error).message}`)); + const tallies = meter.summary().byModel; + for (const [model, t] of Object.entries(tallies)) { + if (!t.calls) continue; + await addIterationUsage(article, n, model, usageOf(t), paths, now()); + } + const minutes = await record(status, summary); + if (!o.step) { + await updateIteration( + article, + n, + (cur) => ({ + ...patch, + status, + minutes: round2((now().getTime() - started.getTime()) / 60_000), + ...(checks.length ? { checks: [...(cur.checks ?? []).filter((c) => !checks.some((x) => x.name === c.name)), ...checks] } : {}), + ...(status === "done" ? { error: undefined } : { error: summary.slice(0, 1000) }), + }), + paths, + now(), + ); + } else if (checks.length) { + await updateIteration( + article, + n, + (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => !checks.some((x) => x.name === c.name)), ...checks] }), + paths, + now(), + ); + } + log(`${status}: ${summary}`); + return { + article, + n, + status, + summary, + usd: Math.round(meter.usd * 10_000) / 10_000, + minutes: o.step ? minutes : round2((now().getTime() - started.getTime()) / 60_000), + }; +} diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -0,0 +1,322 @@ +// 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. + +import { providerOf, runAgent, type AgentTool } from "../../../llm"; +import { iterationLabel, 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, + momentLinkRule, +} from "../authoringRules"; +import { plainAnswer, userCharsFor } from "./llmText"; +import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; +import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep } from "./quotes"; +import { reportFile } from "./reportFile"; +import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +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[]; + // 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 }): string { + const terms = o.terms?.length ? ` The operator chose these terms: ${o.terms.join(", ")} — use them.` : ""; + 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}`, + "- 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 `# <title>`. The text before the first `##` is the summary.", + `- ${ONE_QUOTE_PER_FINDING_RULE}`, + `- ${CLAIM_QUOTES_RULE}`, + `- ${VERBATIM_QUOTES_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"); +} + +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}`, + "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), or remove the finding. Never invent words. Edit the report only, then stop.", +].join("\n"); + +function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise<string>, count: { n: number }): 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 args: Record<string, unknown> = { + 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, + }); + count.n++; + return out + note; + }, + }; +} + +export async function sweepAgent(input: SweepAgentInput, deps: TaskDeps): Promise<TaskResult> { + return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"] }, (h) => + sweepAgentBody(h, input), + ); +} + +async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<TaskOutcome> { + 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; + 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); + const file = reportFile({ article: h.article, n: h.n, paths: h.paths }); + const extracts = { n: 0 }; + h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}`); + + 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 }); + + const corpusTools = 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, + ); + const web = input.web === false ? [] : (deps.web ?? []); + const tools = [...corpusTools, extractTool(h, input, rewrite, extracts), ...file.tools, ...web]; + const isApi = providerOf(model) === "api"; + 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: runPreamble({ origin, maxUsd: input.maxUsd, terms: input.terms, from, to }), + user: plan, + tools, + meter: h.meter, + maxUsd: input.maxUsd, + maxTurns: input.maxTurns ?? 150, + ...(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)` : ""}`); + + 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 }); + 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`); + 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:\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 }); + 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; + 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 }); + 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); + 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<typeof reportFile>, + o: { origin: string; resolver: ReturnType<typeof slugResolver> }, +): Promise<{ report?: Awaited<ReturnType<typeof convertOnly>>; problems: Awaited<ReturnType<typeof checkQuotes>>; 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 }; + return { report: c.report, problems: await checkQuotes(c.report, h.deps) }; +} + +async function convertOnly(h: TaskHandle, file: ReturnType<typeof reportFile>) { + 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; +} diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -0,0 +1,661 @@ +// TASK sweep-pipeline — a cited sweep made by CODE around a small local model +// (release 27, S5, D4; the stopgap's local_sweep.py, the only sweep that fits +// qwen's 8k context). +// +// The model only: proposes search terms, judges each transcript window, +// copies quotes and writes a one-line claim, groups the claims into sections +// and names the report. Code does the rest: enumeration (the MCP's tools), +// windowing, the verbatim check (a quote not found in its window is DROPPED +// and logged), citation links on the article's origin, coverage, convert and +// the strict quote check (a finding that fails it is dropped, never fixed). +// Every prompt fits the local cap; one that would not is never sent (the +// ollama module refuses it) and that chunk is logged as failed. + +import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; +import { writeIterationFile } from "../../iterations"; +import { mmss } from "../reportOps"; +import { strictNormalize } from "../../../citations/verify"; +import { momentHref } from "./links"; +import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; +import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export const CHUNK_CHARS = 7000; // one model call's transcript text (~2k tokens) +export const MAX_ITEMS_PER_CHUNK = 3; +export const MAX_CLAIMS_PER_SECTION = 12; +export const MAX_SECTIONS = 6; +export const MAX_CLAIMS_TOTAL = 60; +export const MAX_CLAIMS_PER_VIDEO = 6; +export const MIN_QUOTE_WORDS = 7; +export const MAX_QUOTE_WORDS = 60; +export const READ_BATCH = 8; + +const STOP = new Set( + "what when where which about with from that this have said says their there they them were been into over under more most some such than then also just like make made making".split( + " ", + ), +); +const HEDGES = ["allegedly", "reportedly", "claims", "claimed", "may", "might", "maybe", "if", "probably", "likely", "i think", "apparently", "supposedly", "rumor", "rumour"]; +const NEGATIONS = /\b(never|not|no|nobody|nothing|none|neither|nor|cannot|without)\b|n't\b/i; + +export const TERMS_SYSTEM = + "You plan keyword searches over automatic speech-recognition transcripts of streams and videos. Given a research " + + "question, return search phrases likely to be SPOKEN, word for word, in the recordings that answer it. Mostly SINGLE " + + "words (a name, a noun, a distinctive verb); a two-word phrase only for a fixed name. Lowercase, no quotation marks, " + + "no boolean operators, no plural and singular of the same word. Prefer distinctive words over common ones. Return " + + "between three and six."; +export const TERMS_SCHEMA = { + type: "object", + properties: { terms: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 6 } }, + required: ["terms"], +}; + +export const EXTRACT_SYSTEM = + "You read excerpts of an automatic transcript and pick out evidence for a research question. Rules: (1) Only use the " + + "excerpt; never add facts. (2) Each quote is copied EXACTLY, character for character, from consecutive transcript " + + "lines, without the bracketed timestamps; at least 8 and at most 40 words; do not fix grammar, spelling or names. " + + "(3) Each claim is one plain sentence saying what the speaker says in that quote, attributed to the speaker; keep " + + "every negation (not, never, no) and every hedge (maybe, I think, allegedly, if) the quote has; do not state motives " + + "or feelings; do not exaggerate; paraphrase in the third person in at most 20 words, do not repeat the quote. Set " + + "on_topic to true only when the quote itself is about the question's subject. A message or donation the streamer " + + "reads aloud from chat is someone else's words: say so in the claim. Strength: 3 = the quote directly answers the " + + "question, 2 = it bears on it, 1 = it only mentions a search word. (4) If the excerpt does not bear on the question, " + + "set relevant to false and return no items. (5) Return at most three items, the strongest first."; +export const EXTRACT_SCHEMA = { + type: "object", + properties: { + relevant: { type: "boolean" }, + items: { + type: "array", + maxItems: MAX_ITEMS_PER_CHUNK, + items: { + type: "object", + properties: { + quote: { type: "string" }, + claim: { type: "string" }, + on_topic: { type: "boolean" }, + strength: { type: "integer", minimum: 1, maximum: 3 }, + }, + required: ["quote", "claim", "on_topic", "strength"], + }, + }, + }, + required: ["relevant", "items"], +}; + +export const GROUP_SYSTEM = + "You organise numbered findings into a short report. Return a plain, factual title (at most 90 characters, no " + + "clickbait, no verdicts) and between one and six sections. Each section has a short heading (at most 60 characters) " + + "naming what its findings have in common, and the numbers of the findings it holds, each number in exactly one " + + "section. Headings describe; they do not judge, exaggerate or add facts the findings do not state."; +export const GROUP_SCHEMA = { + type: "object", + properties: { + title: { type: "string" }, + sections: { + type: "array", + minItems: 1, + maxItems: MAX_SECTIONS, + items: { + type: "object", + properties: { heading: { type: "string" }, findings: { type: "array", items: { type: "integer" } } }, + required: ["heading", "findings"], + }, + }, + }, + required: ["title", "sections"], +}; + +export type SweepPipelineInput = { + article: string; + n: number; + question?: string; + channels?: string[]; + from?: string; + to?: string; + model?: string; + origin: string; + maxUsd?: number; + terms?: string[]; + maxVideos?: number; + maxClaims?: number; +}; + +// ─── Pure helpers (exported for the tests) ─── + +export const norm = (s: string) => strictNormalize(s); + +type Line = [number, string] | null; // null: an explicit window break + +export type EnumeratedVideo = { id: string; channel: string; date: string; title: string; hits: Record<string, number> }; + +const ENUM_LINE = /^- (\S+) \| (\w+) \| (.*?) \| (\d{4}-\d{2}-\d{2}|[^|]*?) \| (\d+) match\(es\) \| (.*)$/; + +// enumerate_matches' worklist lines. +export function parseEnumerate(text: string, term: string): EnumeratedVideo[] { + const out: EnumeratedVideo[] = []; + for (const raw of text.split("\n")) { + const m = ENUM_LINE.exec(raw.trim()); + if (!m || m[2] !== "video") continue; + out.push({ id: m[1]!, channel: m[3]!, date: m[4]!.trim(), title: m[6]!, hits: { [term]: Number(m[5]) } }); + } + return out; +} + +const STAMP = /^\[(?:\d+:)?\d+:\d+\|(\d+)\]\s?(.*)$/; + +export type ParsedTranscript = { title: string; momentBase: string | null; lines: Line[] }; + +// get_transcripts (link_style base) → per video id: title, moment_base, lines. +export function parseTranscripts(text: string): Map<string, ParsedTranscript> { + const out = new Map<string, ParsedTranscript>(); + for (const block of text.split(/\n---\n/)) { + const id = /video_id: (\S+)/.exec(block)?.[1]; + if (!id) continue; + const title = /^## (.*)$/m.exec(block)?.[1]?.trim() ?? id; + const mb = /moment_base: (\S+)/.exec(block)?.[1] ?? null; + const lines: Line[] = []; + for (const ln of block.split("\n")) { + const s = STAMP.exec(ln.trim()); + if (s) lines.push([Number(s[1]), s[2]!.trim()]); + else if (lines.length && ["…", "...", "⋯"].includes(ln.trim())) lines.push(null); + } + out.set(id, { title, momentBase: mb, lines }); + } + return out; +} + +export function windowsOf(lines: readonly Line[], gap = 90): [number, string][][] { + const wins: [number, string][][] = []; + let cur: [number, string][] = []; + let prev: number | null = null; + for (const l of lines) { + if (l === null) { + if (cur.length) wins.push(cur); + cur = []; + prev = null; + continue; + } + if (prev !== null && l[0] - prev > gap && cur.length) { + wins.push(cur); + cur = []; + } + cur.push(l); + prev = l[0]; + } + if (cur.length) wins.push(cur); + return wins; +} + +// One window in model-sized chunks, overlapping by three lines. +export function chunksOf(win: readonly [number, string][], chunkChars = CHUNK_CHARS): [number, string][][] { + const out: [number, string][][] = []; + let cur: [number, string][] = []; + let size = 0; + for (const ln of win) { + const l = ln[1].length + 12; + if (cur.length && size + l > chunkChars) { + out.push(cur); + cur = cur.slice(-3); + size = cur.reduce((s, x) => s + x[1].length + 12, 0); + } + cur.push(ln); + size += l; + } + if (cur.length) out.push(cur); + return out; +} + +// The second of the line where the verbatim quote starts, or null. +export function locate(quote: string, chunk: readonly [number, string][]): number | null { + const q = norm(quote); + if (!q) return null; + let text = ""; + const starts: [number, number][] = []; + for (const [sec, txt] of chunk) { + const n = norm(txt); + if (!n) continue; + if (text) text += " "; + starts.push([text.length, sec]); + text += n; + } + const i = ` ${text} `.indexOf(` ${q} `); + if (i < 0) return null; + let sec = starts[0]![1]; + for (const [off, s] of starts) { + if (off <= i) sec = s; + else break; + } + return sec; +} + +export function lintClaim(claim: string, quote: string): string[] { + const flags: string[] = []; + const qn = quote.toLowerCase(); + const cn = claim.toLowerCase(); + if (NEGATIONS.test(qn) && !NEGATIONS.test(cn)) flags.push("negation: the quote has a not/never/no the claim does not"); + if (!NEGATIONS.test(qn) && NEGATIONS.test(cn)) flags.push("negation: the claim has a not/never/no the quote does not"); + for (const h of HEDGES) { + const re = new RegExp(`\\b${h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`); + if (re.test(qn) && !re.test(cn)) { + flags.push(`hedge dropped: the quote says “${h}”`); + break; + } + } + for (const num of claim.match(/\d[\d,.]*/g) ?? []) { + if (!quote.includes(num.replace(/[.,]+$/, ""))) { + flags.push(`number ${num} is not in the quote`); + break; + } + } + return flags; +} + +// ─── The run ─── + +type Kept = { + video: string; + title: string; + channel: string; + slug: string; + date: string; + quote: string; + claim: string; + sec: number; + strength: number; + flags: string[]; +}; + +export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): Promise<TaskResult> { + return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"] }, (h) => + pipelineBody(h, input), + ); +} + +async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string): Promise<T> { + const t0 = Date.now(); + const out = await structuredAnswer<T>({ llm: h.deps.llm as LlmConfig, model, system, user, schema, meter: h.meter as Meter, signal: h.deps.signal }); + h.turns([{ kind: "model", what, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: out }]); + return out; +} + +async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> { + 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 since = input.from ?? iteration.scope?.from; + const until = input.to ?? iteration.scope?.to; + const origin = input.origin.replace(/\/+$/, ""); + const maxVideos = input.maxVideos ?? 40; + const maxClaims = input.maxClaims ?? 40; + if (!question) throw new TaskInputError("a sweep needs its question"); + if (!channels.length) throw new TaskInputError("a sweep needs its channels"); + const event = (e: Record<string, unknown>) => h.turns([e]); + h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}`); + + // 1. terms (the model, unless given) + let terms: string[] = []; + if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean); + else { + const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms"); + const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")])); + for (const t of Array.isArray(ans.terms) ? ans.terms : []) { + const v = String(t).replace(/["“”]/g, "").trim().toLowerCase(); + if (v && v.length <= 40 && !terms.includes(v) && !names.has(v)) terms.push(v); + } + terms = terms.slice(0, 6); + } + if (!terms.length) return { status: "failed", summary: "no search terms" }; + h.log(`terms: ${terms.join(", ")}`); + + // 2. enumerate (code) + const found = new Map<string, EnumeratedVideo>(); + const partial: string[] = []; + const enumerate = async (list: string[]) => { + for (const term of list) { + const text = await deps.corpus.call("enumerate_matches", { + query: term, + channels, + ...(since ? { date_from: since } : {}), + ...(until ? { date_to: until } : {}), + }); + if (text.includes("COVERAGE PARTIAL")) partial.push(term); + const vids = parseEnumerate(text, term); + for (const v of vids) { + const had = found.get(v.id); + if (had) Object.assign(had.hits, v.hits); + else found.set(v.id, v); + } + event({ kind: "enumerate", term, videos: vids.length, partial: text.includes("COVERAGE PARTIAL") }); + h.log(`term "${term}": ${vids.length} video(s)`); + } + }; + await enumerate(terms); + if (!input.terms?.length) { + // A phrase that matched nothing: its distinctive words alone. + const hit = new Set([...found.values()].flatMap((v) => Object.keys(v.hits))); + const extra: string[] = []; + for (const t of terms) { + if (hit.has(t) || !t.includes(" ")) continue; + for (const w of t.split(/\s+/)) if (w.length >= 4 && !STOP.has(w) && !terms.includes(w) && !extra.includes(w)) extra.push(w); + } + if (extra.length) { + h.log(`phrases with no match; trying words: ${extra.join(", ")}`); + await enumerate(extra); + const hitNow = new Set([...found.values()].flatMap((v) => Object.keys(v.hits))); + terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8); + } + } + const nEnum = found.size; + const weight = new Map(terms.map((t, i) => [t, 1 / (i + 1)])); + const order = [...found.values()].sort((a, b) => { + const wa = Object.keys(a.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0); + const wb = Object.keys(b.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0); + const ha = Object.values(a.hits).reduce((s, x) => s + x, 0); + const hb = Object.values(b.hits).reduce((s, x) => s + x, 0); + return wb - wa || hb - ha || a.date.localeCompare(b.date); + }); + const todo = order.slice(0, maxVideos); + h.log(`${nEnum} video(s) matched; reading ${todo.length}`); + + // 3. read windows and extract (the model judges, code verifies) + const kept: Kept[] = []; + const dropped: { video: string; quote: string; why: string }[] = []; + let nChunks = 0; + let nRelevant = 0; + const readIds: string[] = []; + for (let b = 0; b < todo.length; b += READ_BATCH) { + deps.signal?.throwIfAborted(); + const batch = todo.slice(b, b + READ_BATCH); + const text = await deps.corpus.call("get_transcripts", { + video_ids: batch.map((v) => v.id), + queries: terms.slice(0, 8), + link_style: "base", + channels, + }); + const parsed = parseTranscripts(text); + for (const v of batch) { + const p = parsed.get(v.id); + if (!p || !p.lines.length) { + event({ kind: "unread", video: v.id, why: "no windows returned" }); + continue; + } + readIds.push(v.id); + const title = p.title || v.title; + // The channel slug: off a moment_base in the archive's form, else asked. + let slug: string | null = null; + const mbm = p.momentBase ? /[?&]v=([^&%/]+)(?:%2F|\/)/i.exec(p.momentBase) : null; + if (mbm) slug = decodeURIComponent(mbm[1]!); + if (!slug && channels.length === 1) slug = channels[0]!; + if (!slug) { + for (const c of channels) { + try { + await deps.corpus.call("get_video_metadata", { video_id: v.id, channel: c }); + slug = c; + break; + } catch { + // not this channel's + } + } + } + slug ??= channels[0]!; + for (const win of windowsOf(p.lines)) { + for (const ch of chunksOf(win)) { + deps.signal?.throwIfAborted(); + nChunks++; + const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n"); + const user = `Research question: ${question}\n\nVideo: ${title} (${v.channel}, ${v.date})\n\nTranscript excerpt:\n${excerpt}`; + let ans: { relevant?: unknown; items?: unknown }; + try { + ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`); + } catch (e) { + if (deps.signal?.aborted) throw e; + event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message }); + h.log(` chunk failed: ${(e as Error).message}`); + continue; + } + if (!ans.relevant) continue; + nRelevant++; + const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; + for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { + const quote = String(raw.quote ?? "") + .replace(/["“”]/g, "") + .replace(/\s+/g, " ") + .trim() + .replace(/^\[[\d:]+\]\s*/, ""); + const claim = String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); + const wc = quote.split(" ").filter(Boolean).length; + const sec = locate(quote, ch); + let why: string | null = null; + if (sec === null) why = "not verbatim in its window"; + else if (wc < MIN_QUOTE_WORDS) why = `too short (${wc} words)`; + else if (wc > MAX_QUOTE_WORDS) why = `too long (${wc} words)`; + else if (!claim) why = "no claim"; + else if (raw.on_topic === false || (Number(raw.strength) || 2) < 2) why = "model: not on topic"; + const key = norm(quote); + if (!why && kept.some((k) => k.video === v.id && (norm(k.quote).includes(key) || key.includes(norm(k.quote))))) why = "duplicate"; + if (why) { + dropped.push({ video: v.id, quote, why }); + event({ kind: "dropped", why, video: v.id, quote, claim }); + continue; + } + kept.push({ + video: v.id, + title, + channel: v.channel, + slug, + date: v.date, + quote, + claim, + sec: sec!, + strength: Math.round(Number(raw.strength) || 2), + flags: lintClaim(claim, quote), + }); + } + } + } + h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); + } + } + if (!kept.length) { + h.check({ name: "evidence", ok: false, detail: `${nEnum} matched, ${readIds.length} read, ${dropped.length} quote(s) dropped` }); + return { status: "failed", summary: "no verbatim evidence found — nothing to report" }; + } + + // 4. group and title (the model); counts, balance and caps in code + kept.sort((a, b) => b.strength - a.strength || a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); + const perVideo = new Map<string, number>(); + const trimmed = kept.filter((r) => { + perVideo.set(r.video, (perVideo.get(r.video) ?? 0) + 1); + return perVideo.get(r.video)! <= MAX_CLAIMS_PER_VIDEO; + }); + const pool = trimmed + .slice(0, MAX_CLAIMS_TOTAL) + .sort((a, b) => a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); + const listing = pool.map((r, i) => `${i + 1}. (${r.date}) ${r.claim}`).join("\n"); + let best: { score: number; g: { title?: unknown; sections?: unknown } } | null = null; + for (let attempt = 0; attempt < 2; attempt++) { + let g: { title?: unknown; sections?: unknown }; + try { + g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`); + } catch (e) { + if (deps.signal?.aborted) throw e; + event({ kind: "group-failed", error: (e as Error).message }); + continue; + } + const secs = (Array.isArray(g.sections) ? g.sections : []).slice(0, MAX_SECTIONS) as { findings?: unknown }[]; + const nums = (s: { findings?: unknown }) => + (Array.isArray(s.findings) ? s.findings : []).filter((x): x is number => Number.isInteger(x) && x >= 1 && x <= pool.length); + const placed = new Set(secs.flatMap(nums)); + const biggest = Math.max(0, ...secs.map((s) => new Set(nums(s)).size)); + const score = placed.size - (secs.length > 1 && biggest > 0.7 * pool.length ? biggest : 0) * 0.5; + if (!best || score > best.score) best = { score, g }; + if (placed.size >= pool.length * 0.8 && biggest <= 0.7 * pool.length) break; + } + const g = best?.g ?? { title: question, sections: [] }; + const title = (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); + const raw = ((Array.isArray(g.sections) ? g.sections : []) as { heading?: unknown; findings?: unknown }[]) + .slice(0, MAX_SECTIONS) + .map((s) => ({ + heading: String(s.heading ?? "").replace(/[#"“”]/g, "").trim().slice(0, 60) || "Findings", + nums: [...new Set((Array.isArray(s.findings) ? s.findings : []).filter((x): x is number => Number.isInteger(x) && x >= 1 && x <= pool.length))].sort((a, b) => a - b), + })) + .filter((s) => s.nums.length); + // A finding in several sections goes to the smallest of them. + const home = new Map<number, number>(); + raw.forEach((s, i) => { + for (const n of s.nums) if (!home.has(n) || raw[home.get(n)!]!.nums.length > s.nums.length) home.set(n, i); + }); + let sections = raw.map((s, i) => ({ heading: s.heading, nums: s.nums.filter((n) => home.get(n) === i) })); + const rest = pool.map((_, i) => i + 1).filter((n) => !home.has(n)); + if (rest.length) sections.push({ heading: "Other findings", nums: rest }); + sections = sections.filter((s) => s.nums.length); + let leftOut = kept.length - pool.length; + for (const s of sections) { + s.nums.sort((a, b) => pool[b - 1]!.strength - pool[a - 1]!.strength || pool[a - 1]!.date.localeCompare(pool[b - 1]!.date) || pool[a - 1]!.sec - pool[b - 1]!.sec); + if (s.nums.length > MAX_CLAIMS_PER_SECTION) { + leftOut += s.nums.length - MAX_CLAIMS_PER_SECTION; + s.nums = s.nums.slice(0, MAX_CLAIMS_PER_SECTION); + } + } + let secs = sections.map((s) => ({ heading: s.heading, recs: s.nums.map((n) => pool[n - 1]!).sort((a, b) => b.strength - a.strength) })); + const total = secs.reduce((s, x) => s + x.recs.length, 0); + if (total > maxClaims) { + // Round-robin across sections, so every section keeps its first ones. + const keep = new Set<string>(); + for (let i = 0; keep.size < maxClaims; i++) { + secs.forEach((s, si) => { + if (i < s.recs.length && keep.size < maxClaims) keep.add(`${si}:${i}`); + }); + } + secs = secs.map((s, si) => ({ heading: s.heading, recs: s.recs.filter((_, ri) => keep.has(`${si}:${ri}`)) })).filter((s) => s.recs.length); + leftOut += total - maxClaims; + } + for (const s of secs) s.recs.sort((a, b) => a.date.localeCompare(b.date) || a.sec - b.sec); + + // 5. the markdown, convert, the strict check (a failing finding is dropped) + const ctx = { + question, + title, + channels, + origin, + terms, + source: deps.corpus.source, + model, + since, + until, + nEnum, + read: readIds.length, + nChunks, + nRelevant, + kept: kept.length, + leftOut, + partial, + todo: todo.length, + }; + let md = writeMarkdown(secs, { ...ctx, dropped: dropped.length }); + await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); + let report = null; + let lastProblems: string[] = []; + for (let round = 0; round < 3; round++) { + const c = await convertSweepText(md, { id: h.article, title, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf }); + h.check({ name: "convert", ok: c.ok, ...(c.ok ? {} : { detail: c.problems.slice(0, 3).join("; ") }) }); + if (!c.ok) return { status: "failed", summary: `the report does not convert: ${c.problems[0]}` }; + const problems = await checkQuotes(c.report, deps); + if (!problems.length) { + report = c.report; + break; + } + const d = dropFailedFindings(md, problems); + lastProblems = problems.map((p) => p.why); + for (const why of d.dropped) { + dropped.push({ video: "", quote: "", why: `quote check: ${why}` }); + event({ kind: "dropped", why: `quote check: ${why}` }); + } + if (!d.dropped.length) break; + // Re-render from what is left: the coverage counts the drop. + const left = new Set( + problems.map((p) => `${p.channel}/${p.id}`), + ); + secs = secs + .map((s) => ({ + heading: s.heading, + recs: s.recs.filter( + (r) => !(left.has(`${r.slug}/${r.video}`) && problems.some((p) => norm(r.quote).includes(norm(p.quote)) || norm(p.quote).includes(norm(r.quote)))), + ), + })) + .filter((s) => s.recs.length); + if (!secs.length) return { status: "failed", summary: "nothing left after the quote check" }; + md = writeMarkdown(secs, { ...ctx, dropped: dropped.length }); + await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); + } + if (!report) { + h.check({ name: "quotes", ok: false, detail: lastProblems.slice(0, 3).join("; ") }); + return { status: "failed", summary: "quotes still fail the strict check" }; + } + const cited = secs.flatMap((s) => s.recs); + const flagged = cited.filter((r) => r.flags.length); + h.check({ name: "quotes", ok: true, detail: `every quote verbatim (strict); ${dropped.length} dropped` }); + h.check({ + name: "lint", + ok: flagged.length === 0, + detail: flagged.length + ? `${flagged.length} claim(s) to read against their quote: ${flagged.slice(0, 3).map((r) => `${r.claim.slice(0, 50)} (${r.flags[0]})`).join("; ")}` + : "no claim flagged", + }); + await writeIterationFile(h.article, h.n, "report.json", report, h.paths); + return { + status: "done", + summary: `“${title}”: ${cited.length} claim(s) in ${secs.length} section(s) from ${new Set(cited.map((r) => r.video)).size} video(s); ${dropped.length} dropped, ${flagged.length} flagged`, + }; +} + +function citeLabel(r: Kept): string { + return `${r.title.replace(/[[\]()]/g, "").trim().slice(0, 80)} @ ${mmss(r.sec)}`; +} + +function writeMarkdown( + secs: { heading: string; recs: Kept[] }[], + c: { + question: string; + title: string; + channels: string[]; + origin: string; + terms: string[]; + source: string; + model: string; + since?: string; + until?: string; + nEnum: number; + read: number; + nChunks: number; + nRelevant: number; + kept: number; + dropped: number; + leftOut: number; + partial: string[]; + todo: number; + }, +): string { + const cited = secs.flatMap((s) => s.recs); + const md = [`# ${c.title}`, "", `Question: ${c.question}`, ""]; + for (const s of secs) { + md.push(`## ${s.heading}`, ""); + for (const r of s.recs) md.push(`- ${r.claim} "${r.quote}" — [${citeLabel(r)}](${momentHref(c.origin, r.slug, r.video, r.sec)})`); + md.push(""); + } + const scope = c.channels.join(", ") + (c.since ? `, from ${c.since}` : "") + (c.until ? ` to ${c.until}` : ""); + md.push( + "## Coverage", + "", + `Searched ${scope} for ${c.terms.join(", ")}. ${c.nEnum} video(s) matched; ${c.read} read (${c.nChunks} excerpt(s), ` + + `${c.nRelevant} judged relevant); ${new Set(cited.map((r) => r.video)).size} cited, ${cited.length} quote(s). Quotes ` + + `found ${c.kept}, dropped ${c.dropped} (not verbatim, unusable, or not passing the quote check), ${c.leftOut} left out ` + + `by the caps. Drafted by ${c.model}; every quote was checked word for word against its transcript.` + + (c.partial.length ? ` COVERAGE PARTIAL for: ${c.partial.join(", ")}.` : "") + + (c.nEnum > c.todo ? ` Only ${c.todo} of the ${c.nEnum} matching videos were read.` : ""), + "", + ); + return md.join("\n"); +} diff --git a/common/lib/report/draft/tasks/tasks.test.ts b/common/lib/report/draft/tasks/tasks.test.ts @@ -0,0 +1,200 @@ +// The tasks' pure parts (release 27, S5). The tasks end to end, over the MCP's +// own corpus tools and the fake model servers, are mcp/src/draftTasks.test.ts. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { ORIGIN, POSTS, cuesOf } from "../../../../testing/draft/corpus.mjs"; +import { NARRATION_WRITING_RULES, rulesForModel, ruleForModel } from "../authoringRules"; +import { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; +import { chunksOf, lintClaim, locate, parseEnumerate, parseTranscripts, windowsOf } from "./sweep-pipeline"; +import { pickCorpusBuild, siteOriginOf } from "./corpusSource"; +import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; +import { cardContext, chooseDraft } from "./narrate"; +import { groundingInputOf } from "../grounding"; + +const stubCorpus = (slugs: Record<string, string>) => ({ + calls: [] as unknown[], + async call(name: string, args: Record<string, unknown> = {}) { + this.calls.push([name, args]); + if (name !== "get_video_metadata") throw new Error(`no ${name}`); + const slug = slugs[String(args.video_id)]; + if (!slug || (args.channel && args.channel !== slug)) throw new Error("not found"); + return `${JSON.stringify({ id: args.video_id, channelSlug: slug })}\n\n(corpus: x)`; + }, +}); + +test("authoring rules: a model's prompt takes the rules without their examples, and without the tag rule", () => { + const rules = rulesForModel(NARRATION_WRITING_RULES, { tags: false }); + assert.equal(rules.length, NARRATION_WRITING_RULES.length - 1); + assert.equal(rules[0], "Short sentences; fragments are fine."); + for (const r of rules) { + assert.ok(!r.includes("One file."), r); + assert.ok(!/<[a-z]+>/.test(r), r); + } + assert.equal(ruleForModel("Say it plainly (e.g. like this)."), "Say it plainly."); + assert.equal(rulesForModel(NARRATION_WRITING_RULES).length, NARRATION_WRITING_RULES.length); +}); + +test("links: moment links are built on the origin; a platform URL and another origin's link are rewritten", async () => { + assert.equal(momentHref(ORIGIN, "synth-kitchen", "bread-day-01", 15.7), `${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=15`); + const corpus = stubCorpus({ "bread-day-01": "synth-kitchen" }); + const r = slugResolver(corpus, ["synth-other", "synth-kitchen"]); + const md = [ + "- a [Bread day @ 0:15](https://video.example/watch?v=bread-day-01&t=15s)", + "- b [Bread day @ 0:20](https://youtu.be/bread-day-01?t=20)", + "- c [Elsewhere @ 0:05](https://other.example/?v=synth-kitchen%2Fpie-stream-02&t=5)", + "- d [post](https://other.example/?v=synth-social%2F17&vm=post)", + `- e [Kept @ 0:30](${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=30)`, + "- f [Unknown](https://video.example/watch?v=nope&t=3)", + "- g [An X post](https://x.com/someone/status/123)", + ].join("\n"); + const out = await rewriteLinks(md, r, ORIGIN); + assert.equal(out.fixed, 4); + assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=15)`)); + assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=20)`)); + assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=5)`)); + assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-social%2F17&vm=post)`)); + assert.ok(out.md.includes("https://video.example/watch?v=nope&t=3"), "a recording not in the corpus is left"); + assert.ok(out.md.includes("https://x.com/someone/status/123")); + // The resolver asks once per video. + const asked = corpus.calls.filter((c) => (c as [string, { video_id: string }])[1].video_id === "bread-day-01").length; + assert.equal(asked, 2, "synth-other, then synth-kitchen — and cached for the second link"); +}); + +test("links: get_transcripts' moment_base becomes the origin's, by the moment_base's own slug or by asking", async () => { + const text = [ + "## Pie stream\n- video_id: pie-stream-02 | channel: Synth Kitchen\n- source: https://video.example/watch?v=pie-stream-02\n- moment_base: https://video.example/watch?v=pie-stream-02&t=\n[0:10|10] hello", + "## Bread\n- video_id: bread-day-01 | channel: Synth Kitchen\n- source: https://video.example/watch?v=bread-day-01\n[0:15|15] there", + "## Public\n- video_id: flat-loaf-01 | channel: Other\n- moment_base: https://pub.example/?v=synth-other%2Fflat-loaf-01&t=\n[0:05|5] x", + ].join("\n---\n"); + const r = slugResolver(stubCorpus({ "pie-stream-02": "synth-kitchen", "bread-day-01": "synth-kitchen" }), ["synth-kitchen"]); + const out = await rewriteMomentBases(text, r, ORIGIN); + assert.ok(out.includes(`- moment_base: ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=`)); + assert.ok(out.includes(`- source: https://video.example/watch?v=bread-day-01\n- moment_base: ${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=`)); + assert.ok(out.includes(`moment_base: ${ORIGIN}/?v=synth-other%2Fflat-loaf-01&t=`)); + assert.equal(out.split("\n---\n").length, 3); +}); + +test("pipeline helpers: enumerate lines, transcript blocks, windows, chunks, the verbatim locate, the claim lint", () => { + const vids = parseEnumerate( + "1 match(es)\n\n- pie-stream-02 | video | Synth Kitchen | 2026-02-10 | 2 match(es) | Pie stream\n- 17 | post | Synth Social | 2026-02-11 | 1 match(es) | a post", + "contest", + ); + assert.deepEqual(vids, [{ id: "pie-stream-02", channel: "Synth Kitchen", date: "2026-02-10", title: "Pie stream", hits: { contest: 2 } }]); + const parsed = parseTranscripts( + "## Pie stream\n- video_id: pie-stream-02\n- moment_base: https://x/?v=a%2Fb&t=\n[0:05|5] one\n[0:10|10] two\n…\n[3:00|180] three\n---\n## No id\n[0:01|1] x", + ); + const p = parsed.get("pie-stream-02")!; + assert.equal(p.title, "Pie stream"); + assert.equal(p.lines.length, 4); + assert.deepEqual(windowsOf(p.lines), [[[5, "one"], [10, "two"]], [[180, "three"]]]); + assert.deepEqual(windowsOf([[0, "a"], [200, "b"]]).length, 2, "a gap over 90 s splits"); + const long = Array.from({ length: 10 }, (_, i) => [i * 5, "x".repeat(100)] as [number, string]); + const chunks = chunksOf(long, 600); + assert.ok(chunks.length > 1); + assert.deepEqual(chunks[1]!.slice(0, 3), chunks[0]!.slice(-3), "chunks overlap by three lines"); + const chunk: [number, string][] = [[10, "I did not enter the contest"], [15, "this year at all"]]; + assert.equal(locate("not enter the contest this year", chunk), 10); + assert.equal(locate("contest this year", chunk), 10); + assert.equal(locate("I did enter the contest", chunk), null); + assert.equal(locate("ente the", chunk), null, "whole words only"); + assert.deepEqual(lintClaim("She entered", "I did not enter"), ["negation: the quote has a not/never/no the claim does not"]); + assert.match(lintClaim("She says 3 pies", "maybe two pies").join(" "), /hedge dropped.*number 3/); +}); + +test("corpus source: the newest public build holding every channel; a named build must hold them; the site's origin", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "draft-builds-")); + try { + const build = async (id: string, slugs: string[], ageS: number) => { + const out = path.join(root, "builds", id, "out"); + await mkdir(out, { recursive: true }); + await writeFile(path.join(out, "corpus.json"), JSON.stringify({ channels: slugs.map((slug) => ({ slug })) })); + const t = new Date(Date.now() - ageS * 1000); + await utimes(path.join(out, "corpus.json"), t, t); + }; + await build("alpha", ["a", "b"], 100); + await build("beta", ["a", "b", "c"], 10); + await build("beta-private", ["a", "b", "c", "d"], 1); + const dir = path.join(root, "builds"); + assert.equal((await pickCorpusBuild(["a", "b"], { exportBuildsDir: dir })).build, "beta"); + assert.equal((await pickCorpusBuild(["d"], { exportBuildsDir: dir })).build, "beta-private"); + assert.equal((await pickCorpusBuild(["a"], { exportBuildsDir: dir, want: "alpha" })).build, "alpha"); + await assert.rejects(pickCorpusBuild(["c"], { exportBuildsDir: dir, want: "alpha" }), /does not hold c/); + await assert.rejects(pickCorpusBuild(["z"], { exportBuildsDir: dir }), /no composed build holds all of z/); + await mkdir(path.join(root, "sites", "beta"), { recursive: true }); + await writeFile(path.join(root, "sites", "beta", "site.json"), JSON.stringify({ siteUrl: "https://beta.example/" })); + assert.equal(await siteOriginOf("beta-private", path.join(root, "sites")), "https://beta.example"); + assert.equal(await siteOriginOf("alpha", path.join(root, "sites")), null); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("quotes: the strict check over cues and posts; the failing finding dropped, the rest kept byte for byte", async () => { + const md = [ + "# T", + "", + "## S", + "", + `- She did not enter: "I did not enter the contest this year" [Pie @ 0:10](${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10)`, + `- She entered: "I did enter the contest this year" [Pie @ 0:11](${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=11)`, + `- Posted: "No, I did not enter the pie contest." [post by synthbaker, 2026-02-11](${ORIGIN}/?v=synth-social%2F1700000000000000001&vm=post)`, + `- Posted wrong: "The second shop closed in the spring." [post by synthbaker, 2026-03-02](${ORIGIN}/?v=synth-social%2F1700000000000000002&vm=post)`, + "", + ].join("\n"); + const c = await convertSweepText(md, { id: "t-1", cuesOf }); + assert.ok(c.ok); + const postTextOf = async (ch: string, id: string) => POSTS.find((p) => p.channelSlug === ch && p.id === id)?.text ?? null; + const problems = await checkQuotes(c.report, { cuesOf, postTextOf }); + assert.equal(problems.length, 2); + assert.match(problems[0]!.why, /not verbatim within 90 s/); + assert.match(problems[0]!.near!, /\[10\] I did not enter the contest this year/); + assert.match(problems[1]!.why, /not the post's words/); + const d = dropFailedFindings(md, problems); + assert.equal(d.dropped.length, 2); + assert.ok(!d.md.includes("I did enter the contest this year")); + assert.ok(!d.md.includes("The second shop closed")); + assert.ok(d.md.includes(md.split("\n")[4]!), "the good finding as it was"); + // An outside verifier adds what it found; an inexact (a warning) is not one. + const more = await checkQuotes(c.report, { + cuesOf, + postTextOf, + verifyReport: async () => [ + { citation: "p01", status: "drift", message: "x" }, + { citation: "c01", status: "inexact" }, + { citation: "c99", status: "en-orig-drift", message: "served en rewrote it" }, + ], + }); + assert.ok(more.some((p) => /verify-quotes: en-orig-drift — served en rewrote it/.test(p.why))); + assert.ok(!more.some((p) => /inexact/.test(p.why)), "an inexact is a warning, not a problem"); + assert.ok(more.length > problems.length); +}); + +test("narrate: a card's evidence; the better draft kept, failing sentences removed, never rewritten", async () => { + const report = { + title: "The baker", + summary: "She talks about the contest.", + sections: [{ title: "The contest", claims: [{ text: "She did not enter [x](cite:c1)", citations: ["c1"] }] }], + citations: { c1: { quote: "I did not enter the contest this year", date: "2026-02-10" } }, + }; + const ctx = cardContext({ type: "card", id: "c", style: "chapter", heading: "The contest" }, report)!; + assert.match(ctx.text, /- Claim: She did not enter x \(2026-02-10\)\n {2}Quote: I did not enter the contest this year/); + assert.deepEqual(ctx.quotes, ["I did not enter the contest this year"]); + assert.equal(cardContext({ type: "card", id: "c", style: "chapter", heading: "Nope" }, report), null); + assert.match(cardContext({ type: "card", id: "t", style: "title" }, report)!.text, /OPENING card/); + const g = { ...groundingInputOf(report), quotes: ctx.quotes }; + const best = chooseDraft( + [ + { text: "She stayed out of the contest this year. She said I did not enter the contest this year.", hard: ["repeats a quote"], soft: [] }, + { text: "x", hard: ["a", "b"], soft: [] }, + ], + g, + 45, + ); + assert.deepEqual(best.hard, []); + assert.equal(best.text.includes("I did not enter the contest this year"), false); + assert.ok(best.soft.some((s) => s.startsWith("trimmed"))); +}); diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -0,0 +1,65 @@ +// What every generation task takes and gives (release 27, S5). +// +// A task is a function of (input, deps). Everything it reaches is injected: +// the LLM config (S1), the corpus tools with their source forced (S3, the +// MCP's tools in process — mcp/src/callTool.ts; common cannot import the mcp +// package, so the caller builds them), the web tools (S3), the cue and post +// readers the quote checks use, the iterations store's paths (S4), a clock, a +// log and the job's AbortSignal. Nothing here reads settings: the editor job +// (S6) builds the deps from `settings.generation`. + +import type { AgentTool, LlmConfig } from "../../../llm"; +import type { CuesOf, PostChannelOf } from "../../convertShared"; +import type { readIteration } from "../../iterations"; +import type { Report } from "../../schema"; + +// The iterations store's paths (S4 takes them on every call). +export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>; + +// The corpus tools a task reads through (createCorpusTools' shape). +export type CorpusToolsLike = { + source: string; + tools: AgentTool[]; + call(name: string, args?: Record<string, unknown>): Promise<string>; +}; + +// A quote problem an outside verifier found (the editor's verify-quotes over +// the corpus on disk, which also sees the en-orig track). +export type ExternalQuoteProblem = { citation: string; status: string; message?: string }; + +export type TaskDeps = { + llm: LlmConfig; + corpus: CorpusToolsLike; + // The web for an agent: `web_search` / `web_fetch` (common/lib/web + // webTools). On Claude the API's own search replaces `web_search`. + web?: AgentTool[]; + // Cues of a recording: convert widens spans with them; the strict check + // reads them. + cuesOf: CuesOf; + // A post's text, for a post citation's strict check. + postTextOf?: (channel: string, id: string) => Promise<string | null>; + // Which archive channel holds a post cited by its platform URL. + postChannelOf?: PostChannelOf; + // An extra check of a converted report (the editor's verify-quotes). + verifyReport?: (report: Report) => Promise<ExternalQuoteProblem[]>; + // The iterations store (default: getPaths()). + paths?: StorePaths; + now?: () => Date; + log?: (line: string) => void; + signal?: AbortSignal; +}; + +export type TaskStatus = "done" | "failed" | "cancelled"; + +export type TaskResult = { + article: string; + n: number; + status: TaskStatus; + // One line: what it made, or why it failed. + summary: string; + usd: number; + minutes: number; +}; + +export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate"] as const; +export type TaskName = (typeof TASK_NAMES)[number]; diff --git a/common/testing/README.md b/common/testing/README.md @@ -18,6 +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/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/narrate.json b/common/testing/draft/runs/narrate.json @@ -0,0 +1,34 @@ +{ + "task": "narrate", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"text\":\"What does the baker say about her bakery? And about the contest?\"}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"text\":\"She said \\\"I would never sell the bakery to a chain\\\" and meant it.\"}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"text\":\"First, the bakery. She won't sell it, and she paid for the mixer herself.\"}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"text\":\"Then the contest. She stayed out of it this year.\"}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/revise-report.json b/common/testing/draft/runs/revise-report.json @@ -0,0 +1,76 @@ +{ + "task": "revise-report", + "model": "claude-sonnet-5", + "feedback": "Drop the mixer finding and add what she says about the other finalist.", + "turns": [ + { + "content": [ + { + "type": "text", + "text": "I'll read the transcript first." + }, + { + "type": "tool_use", + "id": "toolu_v01", + "name": "get_transcripts", + "input": { + "video_ids": [ + "pie-stream-02" + ], + "queries": [ + "finalist" + ], + "link_style": "base" + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "tool_use", + "id": "toolu_v02", + "name": "apply_ops", + "input": { + "ops": [ + { + "op": "drop", + "n": 3 + }, + { + "op": "claim", + "n": 1, + "text": "She says \"never\"" + }, + { + "op": "add", + "section": "The contest", + "text": "She says she has never met the other finalist", + "quote": "I have never met the other finalist", + "link": "https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=30" + }, + { + "op": "add", + "section": "The contest", + "text": "She says she met the finalist", + "quote": "I met the other finalist last week", + "link": "https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=30" + } + ] + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "text", + "text": "Dropped the mixer finding; added the finalist line." + } + ], + "stop_reason": "end_turn" + } + ] +} diff --git a/common/testing/draft/runs/revise-video.json b/common/testing/draft/runs/revise-video.json @@ -0,0 +1,63 @@ +{ + "task": "revise-video", + "model": "claude-sonnet-5", + "feedback": "Rename the bakery chapter, give it a line, and tighten the first clip.", + "turns": [ + { + "content": [ + { + "type": "tool_use", + "id": "toolu_w01", + "name": "read_doc", + "input": {} + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "tool_use", + "id": "toolu_w02", + "name": "apply_ops", + "input": { + "ops": [ + { + "op": "heading", + "id": "the-bakery", + "text": "About the bakery" + }, + { + "op": "narration", + "id": "the-bakery", + "text": "First, the bakery. She won't sell it." + }, + { + "op": "trim", + "id": "c01", + "start": 14, + "end": 21 + }, + { + "op": "trim", + "id": "c02", + "start": 0, + "end": 40 + } + ] + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "text", + "text": "Renamed the chapter, added a line, trimmed c01." + } + ], + "stop_reason": "end_turn" + } + ] +} diff --git a/common/testing/draft/runs/sweep-agent.json b/common/testing/draft/runs/sweep-agent.json @@ -0,0 +1,102 @@ +{ + "task": "sweep-agent", + "model": "claude-sonnet-5-5", + "extractorModel": "claude-haiku-4-5", + "question": "What does the baker say about the pie contest?", + "channels": [ + "synth-kitchen" + ], + "note": "Requests in order: agent turns, the extractor's answer between them, then the repair round.", + "turns": [ + { + "content": [ + { + "type": "tool_use", + "id": "toolu_r01", + "name": "enumerate_matches", + "input": { + "query": "contest", + "channels": [ + "synth-kitchen" + ] + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "tool_use", + "id": "toolu_r02", + "name": "extract_batch", + "input": { + "video_ids": [ + "pie-stream-02", + "bread-day-01" + ], + "queries": [ + "contest" + ], + "directive": "what she says about the contest" + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "text", + "text": "### Pie stream\nmoment_base: https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=\n[0:10|10] I did not enter the contest this year\n[0:15|15] the judges were friends of mine so it felt wrong" + } + ], + "stop_reason": "end_turn" + }, + { + "content": [ + { + "type": "tool_use", + "id": "toolu_r03", + "name": "write_report", + "input": { + "markdown": "# The baker on the pie contest\n\nShe says she did not enter this year's contest, and why.\n\n## The contest\n\n- She says she did not enter: \"I did not enter the contest this year\" [Pie stream @ 0:10](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=10)\n- She gives her reason: \"the judges were friends of mine so it felt right\" [Pie stream @ 0:15](https://synth.example/?v=synth-kitchen%2Fpie-stream-02&t=15)\n\n## The bakery\n\n- She says she would not sell: \"I would never sell the bakery to a chain\" [Bread day @ 0:15](https://video.example/watch?v=bread-day-01&t=15)\n\n## Coverage\n\nScope: synth-kitchen. N = 2 enumerated, 2 read, 2 cited.\n" + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "text", + "text": "sweep.md: 3 findings in 2 sections, 2 of 2 read." + } + ], + "stop_reason": "end_turn" + }, + { + "content": [ + { + "type": "tool_use", + "id": "toolu_r04", + "name": "edit_report", + "input": { + "old_text": "so it felt right", + "new_text": "so it felt wrong" + } + } + ], + "stop_reason": "tool_use" + }, + { + "content": [ + { + "type": "text", + "text": "Fixed the one quote." + } + ], + "stop_reason": "end_turn" + } + ] +} diff --git a/common/testing/draft/runs/sweep-pipeline.json b/common/testing/draft/runs/sweep-pipeline.json @@ -0,0 +1,31 @@ +{ + "task": "sweep-pipeline", + "model": "qwen3:8b", + "question": "Did the baker enter the pie contest?", + "channels": [ + "synth-kitchen" + ], + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"terms\":[\"contest\",\"judges\"]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"relevant\":true,\"items\":[{\"quote\":\"I did not enter the contest this year\",\"claim\":\"She says she did not enter the contest this year.\",\"on_topic\":true,\"strength\":3},{\"quote\":\"the judges were friends of mine so it felt wrong\",\"claim\":\"She says the judges were her friends, so entering felt wrong.\",\"on_topic\":true,\"strength\":3},{\"quote\":\"I entered the contest and I won it this year\",\"claim\":\"She says she won.\",\"on_topic\":true,\"strength\":3}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"title\":\"The baker and the pie contest\",\"sections\":[{\"heading\":\"Why she stayed out\",\"findings\":[1,2]}]}" + }, + "done": true + } + ] +} diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -0,0 +1,331 @@ +// The generation tasks end to end (release 27, S5): each task over the +// synthetic draft corpus read through the MCP's own tools in process, against +// the fake Anthropic and ollama servers, writing a real iterations store in a +// temp dir. The model side of each run is a recorded transcript +// (common/testing/draft/runs/<task>.json). Here and not in common: common may +// not import the mcp package, and the corpus tools are the MCP's. + +import { after, before, beforeEach, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { CHANNELS, POSTS, ORIGIN, cuesOf, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; +import { startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; +import { + createIteration, + readIteration, + readIterationFile, + updateIteration, + writeIterationFile, + projectOf, +} from "yt-dlp-transcript-common/lib/report/iterations"; +import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; +import { createCorpusTools, type CorpusTools } from "./callTool"; + +const RUNS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft/runs"); +const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft"); +const run = async (name: string) => JSON.parse(await readFile(path.join(RUNS, `${name}.json`), "utf8")); + +let tmp: string; +let corpus: CorpusTools; +let api: FakeAnthropic; +let ol: FakeOllama; +let paths: { articlesDir: string; exportIndexDir: string }; +let projectsRoot: string; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "draft-tasks-")); + const dir = await writeDraftCorpus(path.join(tmp, "corpus")); + corpus = await createCorpusTools({ source: `local:${dir}` }); + api = await startFakeAnthropic(); + ol = await startFakeOllama(); +}); + +after(async () => { + await corpus.close(); + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +beforeEach(async () => { + caseN++; + paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); +}); + +const postText = async (channel: string, id: string) => + POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null; + +function deps(extra: Partial<TaskDeps> = {}): TaskDeps & { lines: string[] } { + const lines: string[] = []; + return { + llm: { + anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, + ollama: { baseUrl: ol.url }, + }, + corpus, + cuesOf, + postTextOf: postText, + paths, + log: (l) => lines.push(l), + lines, + ...extra, + }; +} + +// i1: a done sweep holding a fixture's sweep.md and report.json (and, given a +// manifest, its video project). +async function doneSweep(article: string, fixture: string, o: { manifest?: boolean; voices?: boolean } = {}) { + await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "what does she say", scope: { channels: ["synth-kitchen"] } }, paths); + await writeIterationFile(article, 1, "sweep.md", await readFile(path.join(DRAFT, "sweeps", `${fixture}.md`), "utf8"), paths); + const report = JSON.parse(await readFile(path.join(DRAFT, "reports", `${fixture}.report.json`), "utf8")); + await writeIterationFile(article, 1, "report.json", report, paths); + let projectDir: string | undefined; + if (o.manifest) { + projectDir = projectOf(projectsRoot, article, 1); + await mkdir(path.join(projectDir, "out", "narration"), { recursive: true }); + await writeFile(path.join(projectDir, "video.manifest.json"), await readFile(path.join(DRAFT, "manifests", `${fixture}.video.manifest.json`), "utf8")); + await writeFile(path.join(projectDir, "report.json"), JSON.stringify(report)); + if (o.voices) await writeFile(path.join(projectDir, "out", "narration", "title.wav"), "RIFF fake voice"); + } + await updateIteration(article, 1, { status: "done", ...(projectDir ? { projectDir } : {}) }, paths); + return { report, projectDir }; +} + +test("sweep-agent: the plan, the corpus tools, extract_batch, the report file; the link backstop; one repair round; done", async () => { + const r = await run("sweep-agent"); + api.push(...r.turns); + const it = await createIteration("synth-contest", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-agent", article: "synth-contest", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(api.remaining(), 0, "every scripted turn was used"); + + // The plan is the MCP's own sweep_plan; the agent sees no source and no writes. + const first = api.requests[0]; + assert.match(first.messages[0].content, /Run a \*\*corpus sweep\*\*/); + const names = first.tools.map((t: { name: string }) => t.name); + for (const n of ["enumerate_matches", "get_transcripts", "extract_batch", "write_report", "edit_report", "read_report"]) assert.ok(names.includes(n), n); + for (const n of ["fetch_clip", "enqueue", "notes", "get_job"]) assert.ok(!names.includes(n), n); + assert.ok(first.tools.some((t: { type?: string }) => t.type === "web_search_20250305"), "Claude's server web search is on"); + const system = first.system[0].text as string; + assert.match(system, /UNATTENDED/); + assert.match(system, /A claim never carries quotation marks/); + assert.ok(system.includes(`${ORIGIN}/?v=<channel slug>%2F<video id>&t=<seconds>`), "the moment link rule names the origin"); + assert.equal(first.temperature, undefined, "Sonnet 5.5: no temperature"); + + // The extractor: the cheap model, the extractor rules, the origin's moment_base. + const ex = api.requests[2]; + assert.equal(ex.model, r.extractorModel); + assert.match(JSON.stringify(ex.system), /DUMB EXTRACTOR/); + assert.ok(ex.messages[0].content.includes(`moment_base: ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=`), "never the platform's moment_base"); + assert.ok(!ex.messages[0].content.includes("video.example/watch?v=pie-stream-02&t=")); + + // The repair round: the report tools only, the transcript inline. + const repair = api.requests[5]; + assert.deepEqual(repair.tools.map((t: { name: string }) => t.name).sort(), ["edit_report", "read_report", "write_report"]); + assert.match(repair.messages[0].content, /so it felt right/); + assert.match(repair.messages[0].content, /\[15\] the judges were friends of mine so it felt wrong/); + + const md = (await readIterationFile("synth-contest", it.n, "sweep.md", paths))!; + assert.ok(md.includes("so it felt wrong")); + assert.ok(!md.includes("video.example"), "the platform link became a moment link"); + assert.ok(md.includes(`${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=15`)); + const report = JSON.parse((await readIterationFile("synth-contest", it.n, "report.json", paths))!); + assert.equal(report.id, "synth-contest"); + assert.equal(Object.keys(report.citations).length, 3); + const after = (await readIteration("synth-contest", it.n, paths))!; + assert.equal(after.status, "done"); + assert.ok(after.usage["claude-sonnet-5-5"]!.usd > 0, "the orchestrator's spend"); + assert.ok(after.usage["claude-haiku-4-5"]!.calls === 1, "one extractor call"); + assert.deepEqual(after.checks?.map((c) => [c.name, c.ok]), [["convert", true], ["quotes", true]]); + const turns = (await readIterationFile("synth-contest", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); + assert.ok(turns.some((t) => t.kind === "tool" && t.name === "extract_batch")); + assert.ok(turns.some((t) => t.kind === "note" && t.text === "repair round")); +}); + +test("sweep-agent: a quote the repair round does not fix is dropped, and the iteration is still done", async () => { + const r = await run("sweep-agent"); + const turns = [...r.turns.slice(0, 5), textTurn("I could not find it.")]; + api.push(...turns); + const it = await createIteration("synth-drop", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const out = await runTask({ task: "sweep-agent", article: "synth-drop", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, deps()); + assert.equal(out.status, "done", out.summary); + const md = (await readIterationFile("synth-drop", it.n, "sweep.md", paths))!; + assert.ok(!md.includes("so it felt right"), "the failing finding is gone"); + const after = (await readIteration("synth-drop", it.n, paths))!; + assert.match(after.checks!.find((c) => c.name === "quotes")!.detail!, /1 finding\(s\) dropped/); +}); + +test("sweep-agent: the repair round has its own small allowance", async () => { + const r = await run("sweep-agent"); + // The repair round's first turn costs more than the allowance: it stops there. + const pricey = { ...r.turns[5], usage: { input_tokens: 200_000, output_tokens: 10 } }; + api.push(...r.turns.slice(0, 5), pricey, textTurn("never sent")); + const it = await createIteration("synth-allow", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const out = await runTask({ task: "sweep-agent", article: "synth-allow", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, deps()); + assert.equal(api.remaining(), 1, "the repair stopped at its allowance"); + assert.equal(out.status, "done", "the unfixed finding is dropped instead"); + const after = (await readIteration("synth-allow", it.n, paths))!; + assert.ok(after.usage["claude-sonnet-5-5"]!.usd > 0.25, "the pricey turn is metered"); + await drainFake(); +}); + +test("sweep-agent: a cancel mid-request ends the iteration cancelled, its spend and turns kept", async () => { + await drainFake(); + const ctrl = new AbortController(); + api.push(async () => { + ctrl.abort(); + await new Promise((r) => setTimeout(r, 50)); + return textTurn("too late"); + }); + const it = await createIteration("synth-cancel", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const out = await runTask( + { task: "sweep-agent", article: "synth-cancel", n: it.n, extractorModel: "claude-haiku-4-5", origin: ORIGIN, maxUsd: 5 }, + deps({ signal: ctrl.signal }), + ); + assert.equal(out.status, "cancelled"); + const after = (await readIteration("synth-cancel", it.n, paths))!; + assert.equal(after.status, "cancelled"); + assert.ok(after.endedAt); +}); + +async function drainFake() { + // A previous test may leave turns queued when it fails; start clean. + while (api.remaining() > 0) { + const res = await fetch(`${api.url}/v1/messages`, { method: "POST", headers: { "x-api-key": FAKE_KEY, "anthropic-version": "2023-06-01", "content-type": "application/json" }, body: JSON.stringify({ model: "claude-haiku-4-5", max_tokens: 1, messages: [{ role: "user", content: "x" }] }) }); + if (!res.ok) throw new Error(`drain: ${res.status} ${await res.text()}`); + } +} + +test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote dropped), group; every prompt under the cap", async () => { + const r = await run("sweep-pipeline"); + ol.push(...r.turns); + const it = await createIteration("synth-pipe", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-pipeline", article: "synth-pipe", n: it.n, origin: ORIGIN }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + for (const req of ol.requests.slice(-3)) { + assert.equal(req.stream, false); + assert.ok(req.format, "a schema every call"); + assert.ok(JSON.stringify(req.messages).length / 3.5 < 8000, "under the 8k cap"); + } + const md = (await readIterationFile("synth-pipe", it.n, "sweep.md", paths))!; + assert.match(md, /^# The baker and the pie contest/); + assert.match(md, /## Why she stayed out/); + assert.ok(md.includes(`${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10`)); + assert.ok(!md.includes("I entered the contest and I won"), "the invented quote never made it"); + assert.match(md, /## Coverage\n\nSearched synth-kitchen for contest, judges\. 1 video\(s\) matched; 1 read/); + const report = JSON.parse((await readIterationFile("synth-pipe", it.n, "report.json", paths))!); + assert.equal(Object.keys(report.citations).length, 2); + const turns = (await readIterationFile("synth-pipe", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); + assert.ok(turns.some((t) => t.kind === "dropped" && t.why === "not verbatim in its window")); + assert.ok(turns.some((t) => t.kind === "enumerate" && t.term === "contest")); + const after = (await readIteration("synth-pipe", it.n, paths))!; + assert.equal(after.usage["qwen3:8b"]!.usd, 0); + assert.equal(after.usage["qwen3:8b"]!.calls, 3); +}); + +test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => { + await drainFake(); + const r = await run("revise-report"); + api.push(...r.turns); + await doneSweep("synth-basic", "basic"); + const it = await createIteration("synth-basic", { kind: "revise-report", model: r.model, parent: 1, feedback: r.feedback }, paths); + const d = deps(); + const out = await runTask({ task: "revise-report", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 2 }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const after = (await readIteration("synth-basic", it.n, paths))!; + assert.deepEqual((after.ops!.applied as { op: string }[]).map((o) => o.op), ["drop", "add"]); + const refused = after.ops!.refused as { op: string; why: string }[]; + assert.equal(refused.length, 2); + assert.match(refused[0]!.why, /no quotation marks/); + assert.match(refused[1]!.why, /not the transcript's words/); + const md = (await readIterationFile("synth-basic", it.n, "sweep.md", paths))!; + assert.ok(!md.includes("new mixer"), "dropped"); + assert.ok(md.includes('"I have never met the other finalist"')); + assert.ok(md.includes('"I would never sell the bakery to a chain"'), "the parent's quotes stand as they were"); + const report = JSON.parse((await readIterationFile("synth-basic", it.n, "report.json", paths))!); + assert.ok(Object.values(report.citations).some((c) => (c as { quote?: string }).quote === "I have never met the other finalist")); + // The tools: corpus reads with the origin's moment_base, and no report writes. + const names = api.requests.at(-1).tools.map((t: { name: string }) => t.name); + assert.ok(names.includes("apply_ops") && names.includes("read_doc") && names.includes("notes")); + assert.ok(!names.includes("write_report")); + const tr = api.requests.at(-2).messages.at(-1).content.find((b: { type: string }) => b.type === "tool_result"); + assert.ok(String(tr.content).includes(`moment_base: ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=`)); +}); + +test("revise-video: ops over the parent's cut; the new project seeded (voices linked); no report of its own", async () => { + await drainFake(); + const r = await run("revise-video"); + api.push(...r.turns); + const { projectDir: parentDir } = await doneSweep("synth-basic", "basic", { manifest: true, voices: true }); + const it = await createIteration("synth-basic", { kind: "revise-video", model: r.model, parent: 1, feedback: r.feedback }, paths); + const out = await runTask({ task: "revise-video", article: "synth-basic", n: it.n, origin: ORIGIN, maxUsd: 2, projectsRoot }, deps()); + assert.equal(out.status, "done", out.summary); + const after = (await readIteration("synth-basic", it.n, paths))!; + const dir = projectOf(projectsRoot, "synth-basic", it.n); + assert.equal(after.projectDir, dir); + assert.deepEqual((after.ops!.applied as { op: string }[]).map((o) => o.op), ["heading", "narration", "trim"]); + assert.match((after.ops!.refused as { why: string }[])[0]!.why, /outside the fetched window/); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const bakery = m.timeline.find((e: { id: string }) => e.id === "the-bakery"); + assert.equal(bakery.heading, "About the bakery"); + assert.equal(bakery.narration.text, "First, the bakery. She won't sell it."); + assert.deepEqual([m.timeline.find((e: { id: string }) => e.id === "c01").start, m.timeline.find((e: { id: string }) => e.id === "c01").end], [14, 21]); + const parent = JSON.parse(await readFile(path.join(parentDir!, "video.manifest.json"), "utf8")); + assert.equal(parent.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "The bakery", "the parent's cut is untouched"); + const voice = await stat(path.join(dir, "out", "narration", "title.wav")); + assert.equal(voice.nlink, 2, "hard-linked from the parent"); + assert.equal(await readIterationFile("synth-basic", it.n, "report.json", paths), null); +}); + +test("narrate: a step on a done iteration; a quote read out is re-asked; the manifest snapshotted then written", async () => { + const r = await run("narrate"); + ol.push(...r.turns); + const { projectDir } = await doneSweep("synth-basic", "basic", { manifest: true }); + const d = deps(); + const out = await runTask({ task: "narrate", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = JSON.parse(await readFile(path.join(projectDir!, "video.manifest.json"), "utf8")); + const cards = Object.fromEntries(m.timeline.filter((e: { type: string }) => e.type === "card").map((e: { id: string; narration?: { text: string }; seconds?: unknown }) => [e.id, e])); + assert.equal(cards["title"].narration.text, "What does the baker say about her bakery? And about the contest?"); + assert.equal(cards["the-bakery"].narration.text, "First, the bakery. She won't sell it, and she paid for the mixer herself."); + assert.equal(cards["the-bakery"].seconds, "auto"); + assert.ok(cards["the-contest"].narration.text.startsWith("Then the contest.")); + const revisions = await readdir(path.join(projectDir!, "revisions")); + assert.equal(revisions.length, 1); + assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/); + const draft = JSON.parse(await readFile(path.join(projectDir!, "narration-draft.json"), "utf8")); + assert.equal(draft["the-bakery"].attempts.length, 2); + assert.match(draft["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/); + // The prompts carry rules, never worked examples, and no tag rule. + const sys = ol.requests.at(-1).messages[0].content as string; + assert.ok(!sys.includes("One file. No title."), "no worked example"); + assert.ok(!/expressive tag \(/.test(sys)); + const after = (await readIteration("synth-basic", 1, paths))!; + assert.equal(after.status, "done", "a step leaves the iteration's status"); + const step = after.steps.find((s) => s.task === "narrate")!; + assert.equal(step.status, "done"); + assert.equal(step.model, "qwen3:8b"); + assert.equal(after.usage["qwen3:8b"]!.calls, 4); +}); + +test("a task refuses an iteration that is not its own or not queued", async () => { + await doneSweep("synth-basic", "basic"); + await assert.rejects( + runTask({ task: "sweep-agent", article: "synth-basic", n: 1, extractorModel: "claude-haiku-4-5", origin: ORIGIN, maxUsd: 1 }, deps()), + /is done: only a queued iteration is run/, + ); + await assert.rejects( + runTask({ task: "revise-report", article: "synth-basic", n: 1, origin: ORIGIN, maxUsd: 1 }, deps()), + /is a sweep iteration, not revise-report/, + ); + assert.ok(CHANNELS.length > 0); +}); diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -1,4 +1,10 @@ import { + CLAIM_QUOTES_RULE, + NARRATION_HARD_RULE, + NARRATION_WRITING_RULES, + VERBATIM_QUOTES_RULE, +} from "yt-dlp-transcript-common/lib/report/draft/authoringRules"; +import { DEFAULT_DIRECTIVE, DEFAULT_REPORT_PATH, renderWarnings, @@ -131,7 +137,8 @@ function batchStep(req: PromptRequest, ctx: PlanContext, reportPath: string): st `to that video's moment_base (full link = \`<moment_base><seconds>\`; no ` + `moment_base → link the \`source:\` URL instead). A POST finding has no ` + `timestamp — cite it as **\`[post by <author>, <date>](<source url>)\`**, ` + - `never with \`@ mm:ss\`. Then discard the fragment. Batches are ` + + `never with \`@ mm:ss\`. ${CLAIM_QUOTES_RULE} ${VERBATIM_QUOTES_RULE} ` + + `Then discard the fragment. Batches are ` + `independent, so you may dispatch several subagents in parallel.\n` + ` - **Fallback:** with no Task tool, do the batch inline — call ` + `\`get_transcripts\` with \`link_style: "base"\` yourself, fold the ` + @@ -166,21 +173,9 @@ function clipStep(ctx: PlanContext): string { // voice (umtool/report-to-video README, "Narration"). The hard rule, and the // five writing rules that mattered most in the Orpheus tuning round; the README's // "Writing narration" has all ten with their evidence, and a worked example. -export const NARRATION_HARD_RULE = - "Storytelling and emotion live in the delivery, never in the claims: every " + - "factual statement stays exactly as the cited evidence supports — no invented " + - "quotes, no motives or feelings attributed to real people, no intensifiers " + - "that change a claim's strength."; - -export const NARRATION_WRITING_RULES = [ - "Short sentences; fragments are fine (\"One file. No title. Just a date.\").", - "\"...\" for a beat inside a sentence — at most one per sentence.", - "An expressive tag (<sigh>, <chuckle>, <gasp>, …) only where a person would make that sound, " + - "reacting to what was just said, at a sentence boundary — never mid-clause, never after a greeting; " + - "one per paragraph at most.", - "End a paragraph on a short punch or a rhetorical question.", - "A quote gets its own sentence after a colon lead-in, never chained to its attribution.", -] as const; +// The rules live in common (authoringRules.ts), read by this plan and by the +// generation tasks alike; re-exported here for this module's callers. +export { NARRATION_HARD_RULE, NARRATION_WRITING_RULES }; export function narrationStep(): string { return (