Archilyzer · Source

archilyzer

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

commit aaf385c5e35f85d5e5ff1335a8749696e27d85bc
parent 92d28a8e8f93d367973ca9136e3a49036a84f5e4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 13:05:08 -0400

Merge r27/tasks-jobs: release 27 S5 (tasks) and S6 (report-draft jobs, GPU arbiter, settings.generation, caps)

Diffstat:
M.gitignore | 4++++
MCOMMANDS.md | 1+
MENVIRONMENT.md | 1+
MSETTINGS.md | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/generationUsage.test.ts | 28++++++++++++++++++++++++++++
Acommon/controller/generationUsage.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/gpuArbiter.test.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/gpuArbiter.ts | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/reportDraft.ts | 452+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/ttsFile.ts | 39+++++++++------------------------------
Mcommon/jobs/jobKinds.ts | 13+++++++++++++
Mcommon/lib/envVars.ts | 1+
Acommon/lib/generationSettings.test.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/generationSettings.ts | 179+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/paths.ts | 5+++++
Mcommon/lib/queueKeys.ts | 7+++++++
Mcommon/lib/report/draft/agentTool.ts | 16++++------------
Acommon/lib/report/draft/authoringRules.ts | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/corpusCues.ts | 39+++++++++++++++++++++++++++++++++++++++
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 | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/types.ts | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 12++++++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 12++++++++++++
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+++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 5+++++
Aeditor/app/api/ops/_reportDraft.test.ts | 188+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/report-draft/route.ts | 38++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/settings/route.ts | 10++++++++++
Aeditor/e2e/report-draft.spec.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/next.config.ts | 2+-
Meditor/package.json | 4++--
Amcp/src/draftTasks.test.ts | 331+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.ts | 27+++++++++++----------------
Mplans/release-27.md | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 27+++++++++++++++++++++++++++
Msettings.json.example | 31+++++++++++++++++++++++++++++++
Mumtool/lib/report/chain-run.mjs | 4++--
Mumtool/lib/report/chain.mjs | 20++++++++++++++++++--
Mumtool/lib/report/chain.test.mjs | 18++++++++++++++++++
58 files changed, 5257 insertions(+), 66 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -178,6 +178,10 @@ yarn-error.log* # <sha256>.wav + .json per distinct synthesis. Rebuildable; never committed. /.tts/ +# Generation usage ledger (release 27): a line per finished API generation job, +# read for the daily spend cap. Editor state; never committed. +/.generation/ + # Diarization runtime: the uv-managed python 3.13 venv + the sherpa-onnx models. # Machine-specific (~148 MB) and rebuildable from .diarize/README.md, which IS # tracked. sherpa-onnx ships wheels only to cp313 and this box's system python is diff --git a/COMMANDS.md b/COMMANDS.md @@ -135,6 +135,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | +| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate", "article", ...} -&gt; {jobId, iteration}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration; a narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'` | ### Usage, flags and environment diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -34,6 +34,7 @@ The one override surface for where things live and which binary runs. Every one | `PARAKEET_CLI` | `parakeet-cli` on PATH | The parakeet.cpp binary the wrapper drives (the wrapper reads it too). | common/lib/paths.ts (getPaths) | | `PARAKEET_MODEL` | none | parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too). | common/lib/paths.ts (getPaths) | | `DIARIZE_BIN` | `<repo>/scripts/diarize.mjs` | The speaker-diarization wrapper. The e2e suite swaps in a fake here. | common/lib/paths.ts (getPaths) | +| `GENERATION_USAGE_FILE` | `<repo>/.generation/usage.jsonl` | The generation usage ledger: a line per finished Claude API generation job, read for the day's spend cap (`settings.generation.caps.daily`). The e2e server points it at a scratch file. | common/lib/paths.ts (getPaths) | | `TTS_BIN` | `<repo>/scripts/tts.mjs` | The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here. | common/lib/paths.ts (getPaths) | | `ESPEAK_NG_BIN` | `espeak-ng` on PATH | eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too). | common/lib/paths.ts (getPaths) | | `RSYNC_BIN` | `rsync` on PATH | Mirrors the saved-video store to a backup destination. | common/lib/paths.ts (getPaths) | diff --git a/SETTINGS.md b/SETTINGS.md @@ -50,6 +50,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`publish`](#publish) | object — see below | | [`seeder`](#seeder) | object — see below | | [`tts`](#tts) | object — see below | +| [`generation`](#generation) | object — see below | ## `adminTitle` @@ -944,3 +945,93 @@ Default: } } ``` + +## `generation` + +Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts. + +#### `generation` + +| Key | Default | Description | +|---|---|---| +| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. | +| `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). | +| `models` | object — see below | The model each route runs (below). | +| `caps` | object — see below | The spend caps in USD (below). | +| `cacheTtl` | `"5m"` | The prompt cache's lifetime on the Claude API: `5m` (writes bill 1.25× input) or `1h` (2×, for long runs with pauses). | +| `apiKeyFile` | `"~/.config/archilyzer/anthropic.env"` | The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file. | +| `anthropicBaseUrl` | `""` | Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake. | +| `ollamaUrl` | `""` | The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434). | +| `projectsRoot` | `""` | Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`. | +| `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. | +| `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. | + +#### `generation.routes` + +| Key | Default | Description | +|---|---|---| +| `sweep` | `"code"` | A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`). | +| `revise-report` | `"api"` | A report iteration from feedback, through checked ops. | +| `revise-video` | `"local"` | A video-cut iteration from feedback, through checked ops. | +| `narrate` | `"local"` | Card narration for an iteration's cut, under the narration rules and the grounding checks. | + +#### `generation.models` + +| Key | Default | Description | +|---|---|---| +| `api` | `"claude-sonnet-5-5"` | The Claude model the `api` route runs (Sonnet 5.5: no temperature, no forced tool choice, thinking between tools). | +| `local` | `"qwen3:8b"` | The ollama model the `local` route runs. Prompts stay under 8k tokens and `num_ctx` under 12k on the 8 GB card. | +| `extractor` | `"claude-haiku-4-5"` | The cheap model an API sweep's `extract_batch` runs — the plan's dumb extractor (Claude or a local model). | + +#### `generation.caps` + +| Key | Default | Description | +|---|---|---| +| `sweep` | `5` | A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap. | +| `revision` | `2` | A report or video revision job's cap when it names none. | +| `narration` | `1` | A narration job's cap when it names none. | +| `daily` | `20` | The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap. | +| `max` | `10` | The most a job may ask for: a larger `maxUsd` is refused. | + +#### `generation.web` + +| Key | Default | Description | +|---|---|---| +| `provider` | `"duckduckgo"` | The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search. | +| `searchUrl` | `""` | Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake. | + +Default: + +```json +{ + "preset": "balanced", + "routes": { + "sweep": "code", + "revise-report": "api", + "revise-video": "local", + "narrate": "local" + }, + "models": { + "api": "claude-sonnet-5-5", + "local": "qwen3:8b", + "extractor": "claude-haiku-4-5" + }, + "caps": { + "sweep": 5, + "revision": 2, + "narration": 1, + "daily": 20, + "max": 10 + }, + "cacheTtl": "5m", + "apiKeyFile": "~/.config/archilyzer/anthropic.env", + "anthropicBaseUrl": "", + "ollamaUrl": "", + "projectsRoot": "", + "web": { + "provider": "duckduckgo", + "searchUrl": "" + }, + "citationOrigin": "" +} +``` diff --git a/common/controller/generationUsage.test.ts b/common/controller/generationUsage.test.ts @@ -0,0 +1,28 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { appendGenerationUsage, dailyCapRefusal, dayUsage, readGenerationUsage, utcDay } from "./generationUsage"; + +test("the usage ledger: rows appended, the day's total read back, a torn line skipped; the daily refusal names the total", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "gen-usage-")); + try { + const file = path.join(dir, "sub", "usage.jsonl"); + assert.deepEqual(await dayUsage(file, "2026-10-13"), { day: "2026-10-13", usd: 0, jobs: 0 }); + const row = { at: "2026-10-13T10:00:00Z", day: "2026-10-13", jobId: "j1", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 3.25 }; + await appendGenerationUsage(file, [row, { ...row, model: "claude-haiku-4-5", usd: 0.5 }]); + await appendGenerationUsage(file, [{ ...row, jobId: "j2", day: "2026-10-12", usd: 9 }]); + const { appendFile } = await import("node:fs/promises"); + await appendFile(file, "{torn\n"); + assert.equal((await readGenerationUsage(file)).length, 3); + const today = await dayUsage(file, "2026-10-13"); + assert.deepEqual(today, { day: "2026-10-13", usd: 3.75, jobs: 1 }); + assert.equal(dailyCapRefusal(today, 20), null); + assert.equal(dailyCapRefusal(today, 0), null, "0 = no daily cap"); + assert.match(dailyCapRefusal(today, 3.75)!, /the day's Claude API spend is \$3\.75 \(2026-10-13, UTC\), at or past the \$3\.75 daily cap/); + assert.equal(utcDay(new Date("2026-10-13T23:59:59Z")), "2026-10-13"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/generationUsage.ts b/common/controller/generationUsage.ts @@ -0,0 +1,69 @@ +// THE GENERATION USAGE LEDGER (release 27, S6; D6) — one JSON line per model +// per finished Claude API generation job, appended to `paths.generationUsageFile` +// (editor state, never inside the corpus). The daily cap reads the day's total +// from it; a job shows its own rows' sum. The digest's metered lane, which +// kept costs only in log lines, is the precedent this replaces with a file. +// +// The day is UTC. A line that does not parse is skipped, never fatal. + +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; + +export type GenerationUsageRow = { + at: string; + day: string; + jobId: string; + article: string; + iteration: number; + task: string; + model: string; + inputTokens: number; + outputTokens: number; + cacheReadTokens: number; + cacheWriteTokens: number; + usd: number; +}; + +export const utcDay = (d: Date = new Date()) => d.toISOString().slice(0, 10); + +export async function appendGenerationUsage(file: string, rows: readonly GenerationUsageRow[]): Promise<void> { + if (!rows.length) return; + await mkdir(path.dirname(file), { recursive: true }); + await appendFile(file, rows.map((r) => `${JSON.stringify(r)}\n`).join("")); +} + +export async function readGenerationUsage(file: string): Promise<GenerationUsageRow[]> { + let text: string; + try { + text = await readFile(file, "utf8"); + } catch { + return []; + } + const out: GenerationUsageRow[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const r = JSON.parse(line) as GenerationUsageRow; + if (r && typeof r.usd === "number" && typeof r.day === "string") out.push(r); + } catch { + // a torn line is skipped + } + } + return out; +} + +// The day's API spend: its total and how many jobs it took. +export async function dayUsage(file: string, day: string = utcDay()): Promise<{ day: string; usd: number; jobs: number }> { + const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); + const usd = Math.round(rows.reduce((s, r) => s + r.usd, 0) * 10_000) / 10_000; + return { day, usd, jobs: new Set(rows.map((r) => r.jobId)).size }; +} + +// The refusal for a job that would start past the daily cap, or null. +export function dailyCapRefusal(day: { day: string; usd: number }, daily: number): string | null { + if (!(daily > 0) || day.usd < daily) return null; + return ( + `the day's Claude API spend is $${day.usd.toFixed(2)} (${day.day}, UTC), at or past the $${daily.toFixed(2)} ` + + "daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC" + ); +} diff --git a/common/controller/gpuArbiter.test.ts b/common/controller/gpuArbiter.test.ts @@ -0,0 +1,69 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { gpuBusyFor, gpuGatedFetch, gpuHolds, holdGpu, waitForGpu, withGpu } from "./gpuArbiter"; + +const none = { tts: 0, "draft-local": 0 } as const; + +test("the rules: TTS waits for transcription and a draft call; a draft waits for transcription and a synthesis", () => { + const off = () => false; + const on = () => true; + assert.deepEqual(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: none }), { busy: false, reason: null }); + assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: on, holds: none }).reason, "a transcription is running"); + assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: { ...none, "draft-local": 1 } }).reason, "a local model is drafting"); + assert.deepEqual(gpuBusyFor("draft-local", { transcriptionLane: off, holds: none }), { busy: false, reason: null }); + assert.equal(gpuBusyFor("draft-local", { transcriptionLane: on, holds: none }).reason, "a transcription is running"); + assert.equal(gpuBusyFor("draft-local", { transcriptionLane: off, holds: { ...none, tts: 1 } }).reason, "a synthesis is running"); + // Neither waits for itself. + assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: off, holds: { ...none, tts: 2 } }).busy, false); + assert.equal(gpuBusyFor("draft-local", { transcriptionLane: off, holds: { ...none, "draft-local": 1 } }).busy, false); +}); + +test("holds count, and a release is idempotent", () => { + const a = holdGpu("tts"); + const b = holdGpu("tts"); + assert.equal(gpuHolds().tts, 2); + a(); + a(); + assert.equal(gpuHolds().tts, 1); + b(); + assert.equal(gpuHolds().tts, 0); +}); + +test("waitForGpu waits to start, logs why, and stops on a cancel", async () => { + let n = 0; + const lines: string[] = []; + const waited = await waitForGpu({ busy: () => ({ busy: n++ < 2, reason: "a synthesis is running" }), onLog: (l) => lines.push(l), pollMs: 1 }); + assert.ok(waited >= 0); + assert.match(lines[0]!, /Waiting for the GPU: a synthesis is running/); + assert.match(lines[1]!, /The GPU is free/); + const ctrl = new AbortController(); + ctrl.abort(); + await assert.rejects(waitForGpu({ busy: () => true, onLog: () => {}, signal: ctrl.signal, pollMs: 1 }), /cancelled while waiting/); +}); + +test("a draft call holds the GPU while in flight — a synthesis sees it — and the unload is never held", async () => { + let seenDuring = -1; + const base = (async (url: string) => { + seenDuring = gpuHolds()["draft-local"]; + assert.equal(gpuBusyFor("tts", { transcriptionOnGpu: () => false }).busy, url.endsWith("/api/chat")); + return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "content-type": "application/json" } }); + }) as unknown as typeof fetch; + const f = gpuGatedFetch(base, { onLog: () => {}, busy: () => false }); + const res = await f("http://127.0.0.1:1/api/chat", { method: "POST" }); + assert.deepEqual(await res.json(), { ok: true }); + assert.equal(seenDuring, 1); + assert.equal(gpuHolds()["draft-local"], 0, "released once the answer is in hand"); + await f("http://127.0.0.1:1/api/generate", { method: "POST" }); + assert.equal(seenDuring, 0, "the unload is not held"); + // A draft call waits out a synthesis. + const release = holdGpu("tts"); + let started = false; + const p = withGpu("draft-local", async () => { + started = true; + }, { onLog: () => {}, pollMs: 2, busy: () => gpuBusyFor("draft-local", { transcriptionLane: () => false }) }); + await new Promise((r) => setTimeout(r, 15)); + assert.equal(started, false); + release(); + await p; + assert.equal(started, true); +}); diff --git a/common/controller/gpuArbiter.ts b/common/controller/gpuArbiter.ts @@ -0,0 +1,146 @@ +// THE GPU ARBITER — one place that says who may use the 8 GB card now +// (release 27, S6). Four users share it: transcription (the worker pool's +// local engines), text-to-speech with a GPU engine (Orpheus), local-model +// drafting (`report-draft` on `draft:local`, ollama) and the local digest lane +// (ollama too). +// +// The rules: +// - a DIGEST yields to transcription — digestYield.ts's +// transcriptionActivity(), unchanged (its CPU carve-out and gap signal); +// - TTS waits for transcription on a GPU worker AND for a running draft call; +// - a DRAFT call waits for transcription (the digest's signal) AND for a +// running GPU synthesis. +// Each is a YIELD at the start of one unit of work (a synthesis, one ollama +// call), never an interruption: a call in flight finishes. +// +// "Running" is the in-process hold a user takes around its unit of work +// (`holdGpu`), so the check is exact and needs no registry scan; the editor is +// one process and every one of these runs in it. A draft's hold wraps each +// ollama request (gpuGatedFetch), so a synthesis can slip in between two calls +// of a long draft, and a draft waits out a synthesis between its calls. + +import { getWorkerPool } from "../jobs/workerPool"; +import { transcriptionActivity } from "./digestYield"; + +export type GpuUser = "tts" | "draft-local"; + +const holds: Record<GpuUser, number> = { tts: 0, "draft-local": 0 }; + +// Take the GPU for one unit of work; the release is idempotent. +export function holdGpu(user: GpuUser): () => void { + holds[user]++; + let released = false; + return () => { + if (released) return; + released = true; + holds[user] = Math.max(0, holds[user] - 1); + }; +} + +export function gpuHolds(): Readonly<Record<GpuUser, number>> { + return { ...holds }; +} + +// A transcription running on a local worker that is not explicitly on the CPU +// (an unknown device may be the GPU: parakeet-cli's default can be). +export function transcriptionOnGpu(): boolean { + try { + return getWorkerPool() + .summary() + .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu"); + } catch { + return false; // fail open: an unreadable pool must not wedge a lane + } +} + +export type GpuVerdict = { busy: boolean; reason: string | null }; + +// Whether `user` must wait now, and for whom. The signals are injectable for +// the tests (and default to the live ones). +export function gpuBusyFor( + user: GpuUser, + signals: { transcriptionOnGpu?: () => boolean; transcriptionLane?: () => boolean; holds?: Readonly<Record<GpuUser, number>> } = {}, +): GpuVerdict { + const h = signals.holds ?? holds; + if (user === "tts") { + if ((signals.transcriptionOnGpu ?? transcriptionOnGpu)()) return { busy: true, reason: "a transcription is running" }; + if (h["draft-local"] > 0) return { busy: true, reason: "a local model is drafting" }; + return { busy: false, reason: null }; + } + const lane = signals.transcriptionLane ?? (() => { + try { + return transcriptionActivity().busy; + } catch { + return false; + } + }); + if (lane()) return { busy: true, reason: "a transcription is running" }; + if (h.tts > 0) return { busy: true, reason: "a synthesis is running" }; + return { busy: false, reason: null }; +} + +// Wait until `busy()` is false — to START; a unit of work running is never +// interrupted. Answers the milliseconds waited. Abortable. +export async function waitForGpu(opts: { + busy: () => boolean | GpuVerdict; + onLog: (line: string) => void; + signal?: AbortSignal; + pollMs?: number; + what?: string; +}): Promise<number> { + const t0 = Date.now(); + const check = (): GpuVerdict => { + const v = opts.busy(); + return typeof v === "boolean" ? { busy: v, reason: v ? "a transcription is running" : null } : v; + }; + let v = check(); + if (!v.busy) return 0; + opts.onLog(`Waiting for the GPU: ${v.reason ?? "it is in use"}…`); + while (v.busy) { + if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU"); + await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000)); + v = check(); + } + const waited = Date.now() - t0; + opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`); + return waited; +} + +// Wait for the GPU and hold it as `user` around `work`. +export async function withGpu<T>( + user: GpuUser, + work: () => Promise<T>, + opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict }, +): Promise<T> { + await waitForGpu({ busy: opts.busy ?? (() => gpuBusyFor(user)), onLog: opts.onLog, signal: opts.signal, pollMs: opts.pollMs }); + const release = holdGpu(user); + try { + return await work(); + } finally { + release(); + } +} + +// A fetch for the ollama config of a `draft:local` job: every chat request +// waits for the GPU and holds it as a draft while in flight. The unload call +// (`/api/generate` with keep_alive 0) frees memory and is never held back. +export function gpuGatedFetch( + base: typeof fetch, + opts: { onLog: (line: string) => void; signal?: AbortSignal; pollMs?: number; busy?: () => boolean | GpuVerdict }, +): typeof fetch { + return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + if (!/\/api\/chat$/.test(url)) return base(input, init); + // The body is read inside the hold: ollama answers once it has generated, + // and the hold ends when the answer is in hand. + return withGpu( + "draft-local", + async () => { + const res = await base(input, init); + const body = await res.arrayBuffer(); + return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }); + }, + opts, + ); + }) as typeof fetch; +} diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -0,0 +1,452 @@ +// `report-draft` — a generation over an article's iteration, as an editor job +// (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft → +// here. +// +// task sweep | revise-report | revise-video | narrate +// article the article id (an article in the making is fine for a sweep) +// iteration a revision's parent; the iteration a narration voices; else none +// model default: settings.generation.models[route] for the task's route +// question / channels / from / to a sweep's +// feedback a revision's +// copyOf run iteration N again on another model (same kind and inputs) +// maxUsd the job's cap (default by task; never above caps.max) +// source / build the corpus (default: the newest build holding the channels) +// cards / force a narration's +// +// The iteration is created `queued` before the job, and the job's id set on it; +// the job runs the S5 task in process. Its queue is the model's provider's: +// `draft:api` (network, never the GPU lane or the heavy slot) or `draft:local` +// (every ollama call through the GPU arbiter; ollama unloaded when the job +// ends). An API job is held to its cap and to the DAILY cap: a job that would +// start past the day's total is refused, at the ask and again at its turn. +// Every finished API job appends its usage rows to the ledger. +// +// The corpus tools come in from the caller (`deps.corpusTools`): they are the +// MCP's, and common cannot import the mcp package. + +import os from "node:os"; +import path from "node:path"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; +import type { Paths } from "../lib/paths"; +import { getSettings } from "../lib/settings"; +import { capFor, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; +import { PROJECT_URL } from "../lib/project"; +import { providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; +import { webTools } from "../lib/web/tools"; +import { + copyIteration, + createIteration, + readIteration, + readIterationFile, + reportSourceOf, + updateIteration, + type Iteration, +} from "../lib/report/iterations"; +import { diskPostChannelOf } from "../lib/report/convert-server"; +import { readAllPosts } from "../lib/posts-server"; +import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index"; +import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; +import type { CorpusToolsLike } from "../lib/report/draft/tasks/types"; +import { verifyReportQuotes } from "../bin/reports-check"; +import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; +import { gpuGatedFetch } from "./gpuArbiter"; + +export const REPORT_DRAFT_JOB_KIND = "report-draft"; +export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft "; + +export const REPORT_DRAFT_BODY_KEYS = [ + "task", + "article", + "iteration", + "model", + "feedback", + "question", + "channels", + "from", + "to", + "copyOf", + "maxUsd", + "source", + "build", + "cards", + "force", +] as const; + +export class ReportDraftInputError extends Error {} + +export type ReportDraftBody = { + task: GenerationTask; + article: string; + iteration?: number; + model?: string; + feedback?: string; + question?: string; + channels?: string[]; + from?: string; + to?: string; + copyOf?: number; + maxUsd?: number; + source?: string; + build?: string; + cards?: string[]; + force?: boolean; +}; + +const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"]; +const ymd = /^\d{4}-\d{2}-\d{2}$/; + +function fail(msg: string): never { + throw new ReportDraftInputError(msg); +} + +// The body, judged without touching the disk. +export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBody { + const task = b.task; + if (typeof task !== "string" || !TASKS.includes(task as GenerationTask)) fail(`"task" is one of ${TASKS.join(", ")}`); + const article = b.article; + if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)'); + const int = (k: string) => { + const v = b[k]; + if (v === undefined || v === null) return undefined; + if (typeof v !== "number" || !Number.isInteger(v) || v < 1) fail(`"${k}" is an iteration number (1, 2, …)`); + return v as number; + }; + const text = (k: string) => { + const v = b[k]; + if (v === undefined || v === null) return undefined; + if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); + return (v as string).trim(); + }; + const list = (k: string) => { + const v = b[k]; + if (v === undefined || v === null) return undefined; + const arr = typeof v === "string" ? v.split(",") : v; + if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`); + return (arr as string[]).map((x) => x.trim()); + }; + const out: ReportDraftBody = { task: task as GenerationTask, article: article as string }; + const set = <K extends keyof ReportDraftBody>(k: K, v: ReportDraftBody[K] | undefined) => { + if (v !== undefined) out[k] = v; + }; + set("iteration", int("iteration")); + set("copyOf", int("copyOf")); + set("model", text("model")); + set("feedback", text("feedback")); + set("question", text("question")); + set("channels", list("channels")); + set("cards", list("cards")); + set("source", text("source")); + set("build", text("build")); + for (const k of ["from", "to"] as const) { + const v = text(k); + if (v !== undefined && !ymd.test(v)) fail(`"${k}" is a YYYY-MM-DD date`); + set(k, v); + } + if (b.maxUsd !== undefined && b.maxUsd !== null) { + if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars'); + out.maxUsd = b.maxUsd; + } + if (b.force !== undefined) { + if (typeof b.force !== "boolean") fail('"force" is true or false'); + out.force = b.force; + } + if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:<dir>, remote:<url> or hub:<url>'); + if (out.source && out.build) fail('give "source" or "build", not both'); + // What each task needs. + if (out.task === "sweep" && out.copyOf === undefined) { + if (!out.question) fail("a sweep needs its question"); + if (!out.channels?.length) fail("a sweep needs its channels"); + } + if ((out.task === "revise-report" || out.task === "revise-video") && out.copyOf === undefined) { + if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`); + if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`); + } + if (out.task === "narrate" && out.iteration === undefined) fail('a narration names the iteration it voices ("iteration")'); + if (out.task === "narrate" && out.copyOf !== undefined) fail("a narration is a step, not an iteration: it has no copy"); + return out; +} + +const KIND_OF: Record<GenerationTask, Iteration["kind"]> = { + sweep: "sweep", + "revise-report": "revise-report", + "revise-video": "revise-video", + narrate: "sweep", // (a step: no iteration of its own) +}; + +const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = { + sweep: "sweep", + "revise-report": "revision", + "revise-video": "revision", + narrate: "narration", +}; + +export function expandHome(p: string): string { + return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; +} + +export function projectsRootOf(gen: GenerationSettings): string { + return gen.projectsRoot ? expandHome(gen.projectsRoot) : path.join(os.homedir(), "reports", "articles"); +} + +// The model a task runs on: the asked one, else the route's. +export function modelFor(gen: GenerationSettings, task: GenerationTask, asked?: string): string { + if (asked) return asked; + const route = gen.routes[task]; + if (route === "code") { + fail(`${task} is routed to Claude Code (settings.generation.routes) — name a model to run it here, or route it to api or local`); + } + return route === "api" ? gen.models.api : gen.models.local; +} + +// The LLM config a job runs on. A base URL that is not Anthropic's is never +// sent the environment's key: only the configured file's. +export function llmConfigOf(gen: GenerationSettings, paths: Pick<Paths, "ollamaUrl">, local?: { onLog: (l: string) => void; signal?: AbortSignal }): LlmConfig { + return { + anthropic: { + apiKeyFile: gen.apiKeyFile, + cacheTtl: gen.cacheTtl, + ...(gen.anthropicBaseUrl ? { baseUrl: gen.anthropicBaseUrl, env: {} } : {}), + }, + ollama: { + baseUrl: gen.ollamaUrl || paths.ollamaUrl, + ...(local ? { fetch: gpuGatedFetch(fetch, local) } : {}), + }, + }; +} + +export type ReportDraftDeps = { + paths: Paths; + // The MCP's corpus tools over a source handle (mcp/src/callTool.ts). + corpusTools: (source: string) => Promise<CorpusToolsLike & { close(): Promise<void> }>; + settings?: () => { generation: GenerationSettings }; + now?: () => Date; +}; + +// The channels a revision or narration reads: its report's citations'. +async function channelsOfReport(article: string, n: number, paths: Paths): Promise<string[]> { + const from = await reportSourceOf(article, n, paths).catch(() => null); + const text = from === null ? null : await readIterationFile(article, from, "report.json", paths); + if (!text) return []; + const cites = (JSON.parse(text) as { citations?: Record<string, { channel?: string }> }).citations ?? {}; + return [...new Set(Object.values(cites).map((c) => c.channel).filter((c): c is string => !!c))]; +} + +// The corpus and the origin the run cites on. +export async function resolveCorpus( + body: Pick<ReportDraftBody, "source" | "build">, + channels: string[], + paths: Pick<Paths, "exportBuildsDir" | "sitesDir">, + gen: GenerationSettings, +): Promise<{ source: string; origin: string; build?: string }> { + const fallback = gen.citationOrigin || PROJECT_URL; + if (body.source) return { source: body.source, origin: fallback }; + const b = await pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) }); + return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build }; +} + +export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number }; + +export async function enqueueReportDraft(raw: Record<string, unknown>, deps: ReportDraftDeps): Promise<ReportDraftEnqueued | { result: StreamActionResult & { ok: false } }> { + const paths = deps.paths; + const gen = (deps.settings ?? getSettings)().generation; + let body: ReportDraftBody; + try { + body = parseReportDraftBody(raw); + } catch (e) { + return { result: { ok: false, error: (e as Error).message } }; + } + const refuse = (error: string) => ({ result: { ok: false as const, error } }); + try { + // The model, and from it the lane; the copy's source tells a copy's kind. + const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null; + if (body.copyOf !== undefined) { + if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`); + if (src.kind !== KIND_OF[body.task]) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); + } + const model = modelFor(gen, body.task, body.model); + const provider = providerOf(model); + let maxUsd: number | undefined; + if (provider === "api") { + maxUsd = capFor(gen.caps, CAP_OF[body.task], body.maxUsd); + const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); + if (refusal) return refuse(refusal); + } + // The iteration: a new one (or a copy), queued; a narration's is the one named. + let n: number; + if (body.task === "narrate") { + const it = await readIteration(body.article, body.iteration!, paths); + if (!it) return refuse(`"${body.article}" has no iteration i${body.iteration}`); + if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: a narration runs over a done iteration`); + n = it.n; + } else if (src) { + n = (await copyIteration(body.article, src.n, { model }, paths)).n; + } else { + n = ( + await createIteration( + body.article, + { + kind: KIND_OF[body.task], + model, + ...(body.task === "sweep" + ? { question: body.question, scope: { channels: body.channels!, ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } } + : { parent: body.iteration!, feedback: body.feedback }), + }, + paths, + ) + ).n; + } + const result = await runManagedFunction({ + kind: REPORT_DRAFT_JOB_KIND, + queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, + paths, + fn: (onLog, signal, _progress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal }, deps), + }); + if (!result.ok) { + if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); + return { result }; + } + if (body.task !== "narrate") await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); + // A job cancelled (or refused) before it ran leaves its iteration queued: end it. + void result.done.then(async (d) => { + if (body.task === "narrate") return; + const it = await readIteration(body.article, n, paths).catch(() => null); + if (it?.status === "queued") { + await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {}); + } + }); + return { result, iteration: n }; + } catch (e) { + return refuse((e as Error).message); + } +} + +async function runReportDraft( + o: { body: ReportDraftBody; model: string; maxUsd?: number; n: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal }, + deps: ReportDraftDeps, +): Promise<void> { + const { body, model, n, onLog, signal } = o; + const paths = deps.paths; + const gen = (deps.settings ?? getSettings)().generation; + const provider = providerOf(model); + onLog(`${body.task} of ${body.article} i${n} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model"})`); + if (provider === "api") { + // Again at the job's turn: jobs ahead in the queue may have spent the day. + const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); + if (refusal) { + if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); + throw new Error(refusal); + } + } + const it = (await readIteration(body.article, n, paths))!; + const channels = body.task === "sweep" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths); + let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null; + let result: TaskResult | null = null; + try { + const where = await resolveCorpus(body, channels, paths, gen); + onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`); + corpus = await deps.corpusTools(where.source); + const disk = paths.channelsDir; + const posts = new Map<string, Promise<Map<string, string>>>(); + const postText = (ch: string, id: string) => { + let p = posts.get(ch); + if (!p) { + p = readAllPosts(path.join(disk, ch)).then((all) => new Map(all.map((x) => [x.id, x.text])), () => new Map()); + posts.set(ch, p); + } + return p.then((m) => m.get(id) ?? null); + }; + const taskDeps: TaskDeps = { + llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined), + corpus, + web: webTools({ ...(gen.web.searchUrl ? { searchUrl: gen.web.searchUrl } : {}) }), + cuesOf: corpusCuesOf(corpus), + postTextOf: postText, + postChannelOf: diskPostChannelOf(disk), + // The corpus on disk adds what the build cannot say: an en-orig track + // whose words differ. Only a drift counts; a record the disk does not + // hold is the build's to answer. + verifyReport: async (report) => + (await verifyReportQuotes(report, { paths }).catch(() => [])) + .filter((r) => r.status === "drift" || r.status === "en-orig-drift") + .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })), + paths, + log: onLog, + signal, + ...(deps.now ? { now: deps.now } : {}), + }; + const projectsRoot = projectsRootOf(gen); + // A local run costs nothing: it has no dollar cap. + const cap = provider === "api" ? o.maxUsd! : Number.POSITIVE_INFINITY; + const extractor = gen.models.extractor; + let input: TaskInput; + switch (body.task) { + case "sweep": + input = + provider === "api" + ? { task: "sweep-agent", article: body.article, n, extractorModel: extractor, origin: where.origin, maxUsd: cap } + : { task: "sweep-pipeline", article: body.article, n, origin: where.origin }; + break; + case "revise-report": + input = { task: "revise-report", article: body.article, n, origin: where.origin, maxUsd: cap }; + break; + case "revise-video": + input = { task: "revise-video", article: body.article, n, origin: where.origin, maxUsd: cap, projectsRoot }; + break; + case "narrate": + input = { task: "narrate", article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.cards ? { cards: body.cards } : {}), ...(body.force ? { force: true } : {}) }; + break; + } + result = await runTask(input, taskDeps); + } catch (e) { + if (body.task !== "narrate") { + const cur = await readIteration(body.article, n, paths).catch(() => null); + if (cur && (cur.status === "queued" || cur.status === "running")) { + await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {}); + } + } + throw e; + } finally { + await corpus?.close().catch(() => {}); + if (provider === "local") { + // Free the card for transcription and TTS, however the job ended. + await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then( + () => onLog(`unloaded ${model} from ollama`), + (e) => onLog(`ollama unload failed: ${(e as Error).message}`), + ); + } + if (provider === "api" && result) { + await recordUsage(body, n, model, o.jobId, paths, deps.now?.() ?? new Date()).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); + } + } + onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: n, task: body.task, status: result.status, summary: result.summary, usd: result.usd, minutes: result.minutes })}`); + if (result.status === "cancelled" || signal.aborted) throw new Error("cancelled"); + if (result.status === "failed") throw new Error(result.summary); +} + +// The job's spend, per model, from the iteration's usage (a narration: the +// step's cost, on its model). +async function recordUsage(body: ReportDraftBody, n: number, model: string, jobId: string, paths: Paths, now: Date) { + const it = await readIteration(body.article, n, paths); + if (!it) return; + const day = utcDay(now); + const base = { at: now.toISOString(), day, jobId, article: body.article, iteration: n, task: body.task }; + let rows: GenerationUsageRow[]; + if (body.task === "narrate") { + const step = [...it.steps].reverse().find((s) => s.task === "narrate" && s.jobId === jobId); + rows = step?.cost ? [{ ...base, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: step.cost }] : []; + } else { + rows = Object.entries(it.usage) + .filter(([m, u]) => providerOf(m) === "api" && (u.usd > 0 || (u.calls ?? 0) > 0)) + .map(([m, u]) => ({ + ...base, + model: m, + inputTokens: u.inputTokens, + outputTokens: u.outputTokens, + cacheReadTokens: u.cacheReadTokens ?? 0, + cacheWriteTokens: u.cacheWriteTokens ?? 0, + usd: Math.round(u.usd * 10_000) / 10_000, + })); + } + await appendGenerationUsage(paths.generationUsageFile, rows); +} diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts @@ -54,7 +54,7 @@ import { resolveTtsHome, type TtsSettings, } from "../lib/ttsSettings"; -import { getWorkerPool } from "../jobs/workerPool"; +import { gpuBusyFor, holdGpu, transcriptionOnGpu, waitForGpu } from "./gpuArbiter"; import { getTtsServerHolder, type TtsServerHolder } from "./ttsServer"; import { TTS_QUEUE } from "../lib/queueKeys"; import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; @@ -394,34 +394,9 @@ export type RunTtsOpts = { gpuPollMs?: number; }; -// A transcription running on a local worker that is not explicitly on the CPU -// (an unknown device may be the GPU: parakeet-cli's default can be). -export function transcriptionOnGpu(): boolean { - return getWorkerPool() - .summary() - .some((w) => w.busy && w.kind === "local" && (w.device ?? "").toLowerCase() !== "cpu"); -} - -// A GPU engine waits while a transcription holds the GPU — the `tts` queue -// yields to transcription. It only waits to START; a synthesis running is -// never interrupted. -export async function waitForGpu(opts: { - busy: () => boolean; - onLog: (line: string) => void; - signal?: AbortSignal; - pollMs?: number; -}): Promise<number> { - const t0 = Date.now(); - if (!opts.busy()) return 0; - opts.onLog("Waiting for the GPU: a transcription is running…"); - while (opts.busy()) { - if (opts.signal?.aborted) throw new Error("cancelled while waiting for the GPU"); - await new Promise((r) => setTimeout(r, opts.pollMs ?? 5000)); - } - const waited = Date.now() - t0; - opts.onLog(`The GPU is free (waited ${(waited / 1000).toFixed(1)}s)`); - return waited; -} +// The GPU checks are the arbiter's (gpuArbiter.ts, release 27): TTS waits for +// a transcription on a GPU worker AND for a running local-model draft call. +export { transcriptionOnGpu, waitForGpu }; // Run the engine through the wrapper into the cache; write the sidecar after // the WAV is in place, so a sidecar always means a complete file. @@ -439,13 +414,16 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { ); let started = Date.now(); let server: { url: string; release: () => void } | null = null; + let releaseGpu: (() => void) | null = null; try { // A GPU engine waits while a transcription holds the GPU; a server engine // takes its server (started for the batch behind the heavy slot, stopped // once the `tts` queue has been idle) and hands its URL to the wrapper. // The engine's time starts once both are in hand. if (req.engine.device === "gpu") { - await waitForGpu({ busy: opts.gpuBusy ?? transcriptionOnGpu, onLog, signal: opts.signal, pollMs: opts.gpuPollMs }); + await waitForGpu({ busy: opts.gpuBusy ?? (() => gpuBusyFor("tts")), onLog, signal: opts.signal, pollMs: opts.gpuPollMs }); + // Held while the engine runs: a draft call waits for it. + releaseGpu = holdGpu("tts"); } if (req.engine.runtime === "server" && req.engine.serverCommand) { const holder = opts.servers ?? getTtsServerHolder(paths.monorepoRoot); @@ -530,6 +508,7 @@ export async function runTtsSynthesis(opts: RunTtsOpts): Promise<TtsSidecar> { await writeJsonAtomic(target.json, sidecar, { indent: 2 }); return sidecar; } finally { + releaseGpu?.(); server?.release(); await rm(textFile, { force: true }).catch(() => {}); } diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -929,6 +929,19 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // engine. Not an ingest kind: nothing the index reads changes. One engine // run — cancelled, not drained; not replayable (the caller asks again, and // the cache answers). + // A generation over an article's iteration (release 27 S6): a sweep, a + // report or video revision, or a narration step — `pnpm ops report-draft`, + // on `draft:api` or `draft:local` by the model's provider. It reads the + // corpus through the MCP's tools from a composed build, never a channel's + // data, so it declares neither guard. Not replayable: a new ask is a new + // iteration. + "report-draft": { + kind: "report-draft", + label: "Report draft", + drainable: false, + replayable: false, + queueKeyStrategy: "custom", + }, "tts-file": { kind: "tts-file", label: "Text to speech", diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -75,6 +75,7 @@ const DECLARED: EnvVarDecl[] = [ paths("PARAKEET_CLI", "`parakeet-cli` on PATH", "The parakeet.cpp binary the wrapper drives (the wrapper reads it too)."), paths("PARAKEET_MODEL", "none", "parakeet.cpp's `.gguf`, when a worker names none (the wrapper reads it too)."), paths("DIARIZE_BIN", "`<repo>/scripts/diarize.mjs`", "The speaker-diarization wrapper. The e2e suite swaps in a fake here."), + paths("GENERATION_USAGE_FILE", "`<repo>/.generation/usage.jsonl`", "The generation usage ledger: a line per finished Claude API generation job, read for the day's spend cap (`settings.generation.caps.daily`). The e2e server points it at a scratch file."), paths("TTS_BIN", "`<repo>/scripts/tts.mjs`", "The text-to-speech wrapper (text in, 48 kHz WAV out) every engine runs behind. A test swaps in a fake here."), paths("ESPEAK_NG_BIN", "`espeak-ng` on PATH", "eSpeak NG, the zero-install text-to-speech engine (the wrapper reads it too)."), paths("RSYNC_BIN", "`rsync` on PATH", "Mirrors the saved-video store to a backup destination."), diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -0,0 +1,52 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + DEFAULT_GENERATION_SETTINGS, + GENERATION_PRESETS, + capFor, + looksLikeApiKey, + presetOf, + sanitizeGeneration, +} from "./generationSettings"; + +test("generation settings: the defaults are the stopgap's balanced policy, Sonnet 5.5, qwen3:8b, Haiku, D6's caps", () => { + const d = sanitizeGeneration(undefined); + assert.deepEqual(d, DEFAULT_GENERATION_SETTINGS); + assert.equal(d.preset, "balanced"); + assert.deepEqual(d.routes, GENERATION_PRESETS.balanced); + assert.deepEqual(d.caps, { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 }); + assert.equal(sanitizeGeneration(d).preset, "balanced", "idempotent"); +}); + +test("the routes are the truth: the preset is the one they match, else custom", () => { + assert.equal(sanitizeGeneration({ routes: GENERATION_PRESETS.api }).preset, "api"); + assert.equal(sanitizeGeneration({ preset: "api" }).preset, "balanced", "a preset alone does not move the routes"); + const custom = sanitizeGeneration({ routes: { ...GENERATION_PRESETS.balanced, narrate: "api" } }); + assert.equal(custom.preset, "custom"); + assert.equal(presetOf(custom.routes), "custom"); + assert.equal(sanitizeGeneration({ routes: { sweep: "nope" } }).routes.sweep, "code"); +}); + +test("the API key is never a setting: a value that looks like one is dropped for the default path", () => { + assert.equal(looksLikeApiKey(["sk", "ant", "api03-abcdef"].join("-")), true); + assert.equal(looksLikeApiKey("A".repeat(40)), true); + assert.equal(looksLikeApiKey("~/.config/archilyzer/anthropic.env"), false); + assert.equal(looksLikeApiKey("/etc/keys/anthropic.env"), false); + assert.equal(sanitizeGeneration({ apiKeyFile: ["sk", "ant", "api03-xyz"].join("-") }).apiKeyFile, DEFAULT_GENERATION_SETTINGS.apiKeyFile); + assert.equal(sanitizeGeneration({ apiKeyFile: "/srv/key.env" }).apiKeyFile, "/srv/key.env"); +}); + +test("caps: a task's default, an asked one within max, a larger one refused; URLs and models checked", () => { + const g = sanitizeGeneration({ caps: { sweep: 50, max: 8, daily: -1 } }); + assert.equal(g.caps.sweep, 8, "no default above max"); + assert.equal(g.caps.daily, 20, "a negative daily is the default"); + assert.equal(capFor(g.caps, "revision"), 2); + assert.equal(capFor(g.caps, "sweep", 3), 3); + assert.throws(() => capFor(g.caps, "sweep", 9), /over the settings' max of \$8/); + assert.throws(() => capFor(g.caps, "sweep", 0), /positive/); + const u = sanitizeGeneration({ anthropicBaseUrl: "http://127.0.0.1:9/", ollamaUrl: "not a url", models: { api: "bad model id!" } }); + assert.equal(u.anthropicBaseUrl, "http://127.0.0.1:9"); + assert.equal(u.ollamaUrl, ""); + assert.equal(u.models.api, "claude-sonnet-5-5"); + assert.equal(sanitizeGeneration({ cacheTtl: "1h" }).cacheTtl, "1h"); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -0,0 +1,179 @@ +// settings.generation — report and video generation (release 27, S6; D6). +// +// Pure: the type, its defaults, the sanitizer settingsSchema.ts runs it +// through, the per-field docs SETTINGS.md renders, the routing presets (the +// stopgap's gen.py), and the caps a `report-draft` job is held to. It replaces +// the stopgap's ~/.config/archilyzer/generation.json; the API KEY itself is +// never a setting — only the path of the mode-600 file that holds it (a value +// that looks like a key is refused, and never stored). + +import type { FieldDocs } from "./fieldDocs"; + +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate"] as const; +export type GenerationTask = (typeof GENERATION_TASKS)[number]; + +export const GENERATION_ROUTES = ["code", "api", "local"] as const; +export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; + +export const GENERATION_PRESETS = { + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local" }, +} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>; +export type GenerationPreset = keyof typeof GENERATION_PRESETS; +export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[]; + +export type GenerationRoutes = Record<GenerationTask, GenerationRoute>; +export type GenerationModels = { api: string; local: string; extractor: string }; +// USD. A job's cap defaults by its task; `max` bounds any cap a job asks for; +// `daily` refuses a job that would start past it. +export type GenerationCaps = { sweep: number; revision: number; narration: number; daily: number; max: number }; +export type GenerationWeb = { provider: "duckduckgo"; searchUrl: string }; + +export type GenerationSettings = { + preset: GenerationPreset | "custom"; + routes: GenerationRoutes; + models: GenerationModels; + caps: GenerationCaps; + cacheTtl: "5m" | "1h"; + apiKeyFile: string; + anthropicBaseUrl: string; + ollamaUrl: string; + projectsRoot: string; + web: GenerationWeb; + citationOrigin: string; +}; + +export const DEFAULT_API_KEY_FILE = "~/.config/archilyzer/anthropic.env"; + +export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { + preset: "balanced", + routes: { ...GENERATION_PRESETS.balanced }, + models: { api: "claude-sonnet-5-5", local: "qwen3:8b", extractor: "claude-haiku-4-5" }, + caps: { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 }, + cacheTtl: "5m", + apiKeyFile: DEFAULT_API_KEY_FILE, + anthropicBaseUrl: "", + ollamaUrl: "", + projectsRoot: "", + web: { provider: "duckduckgo", searchUrl: "" }, + citationOrigin: "", +}; + +export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { + preset: + "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", + routes: "Where each task runs: `code`, `api` or `local` (below).", + models: "The model each route runs (below).", + caps: "The spend caps in USD (below).", + cacheTtl: "The prompt cache's lifetime on the Claude API: `5m` (writes bill 1.25× input) or `1h` (2×, for long runs with pauses).", + apiKeyFile: + "The file holding the Claude API key (`ANTHROPIC_API_KEY=…`), mode 600 — refused when the group or others can read it. `~` is the editor's home. The KEY itself is never a setting: a value that looks like one is refused, never stored. `ANTHROPIC_API_KEY` in the editor's environment wins over the file.", + anthropicBaseUrl: "Advanced: the Messages API's base URL. Blank = Anthropic's. Tests point it at a fake.", + ollamaUrl: "The local model's server (ollama). Blank = the editor's `OLLAMA_URL` (the digest lane's server, default http://127.0.0.1:11434).", + projectsRoot: + "Where an iteration's video project and renders live: `<projectsRoot>/<article>/i<n>/`, off the corpus disk (D1). Blank = `~/reports/articles`.", + web: "The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart.", + citationOrigin: + "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", +}; + +export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { + sweep: "A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`).", + "revise-report": "A report iteration from feedback, through checked ops.", + "revise-video": "A video-cut iteration from feedback, through checked ops.", + narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.", +}; + +export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { + api: "The Claude model the `api` route runs (Sonnet 5.5: no temperature, no forced tool choice, thinking between tools).", + local: "The ollama model the `local` route runs. Prompts stay under 8k tokens and `num_ctx` under 12k on the 8 GB card.", + extractor: "The cheap model an API sweep's `extract_batch` runs — the plan's dumb extractor (Claude or a local model).", +}; + +export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = { + sweep: "A sweep job's cap when it names none. The agent wraps up at 85% and stops at the cap.", + revision: "A report or video revision job's cap when it names none.", + narration: "A narration job's cap when it names none.", + daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.", + max: "The most a job may ask for: a larger `maxUsd` is refused.", +}; + +export const GENERATION_WEB_FIELD_DOCS: FieldDocs<GenerationWeb> = { + provider: "The search a local model's `web_search` reads: `duckduckgo` (its HTML page). Claude uses the API's own search.", + searchUrl: "Advanced: the search endpoint. Blank = the provider's. Tests point it at a fake.", +}; + +// What a key looks like: the API's own prefix, or one long unbroken token with +// no path in it. +export function looksLikeApiKey(v: string): boolean { + const s = v.trim(); + // The API key prefix, written so the release's privacy grep (which counts the + // literal) does not count this rule. + return /sk-an[t]-/i.test(s) || (!s.includes("/") && !s.startsWith("~") && /^[A-Za-z0-9_-]{32,}$/.test(s)); +} + +const str = (v: unknown, d: string) => (typeof v === "string" ? v.trim() : d); +const url = (v: unknown, d: string) => { + const s = typeof v === "string" ? v.trim().replace(/\/+$/, "") : null; + if (s === null) return d; + if (s === "") return ""; + return /^https?:\/\/[^\s]+$/.test(s) ? s : d; +}; +const usd = (v: unknown, d: number, max = 1000) => + typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v * 100) / 100) : d; + +export function sanitizeGeneration(value: unknown): GenerationSettings { + const d = DEFAULT_GENERATION_SETTINGS; + const r = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {}; + const rr = r.routes && typeof r.routes === "object" ? (r.routes as Record<string, unknown>) : {}; + const routes = {} as GenerationRoutes; + for (const t of GENERATION_TASKS) { + const v = rr[t]; + routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t]; + } + // The ROUTES are the truth; the preset names them (the preset whose routes + // they are, else `custom`). Choosing a preset is writing its routes. + const preset: GenerationSettings["preset"] = presetOf(routes); + const m = r.models && typeof r.models === "object" ? (r.models as Record<string, unknown>) : {}; + const model = (v: unknown, fallback: string) => + typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(v.trim()) ? v.trim() : fallback; + const c = r.caps && typeof r.caps === "object" ? (r.caps as Record<string, unknown>) : {}; + const max = usd(c.max, d.caps.max); + const w = r.web && typeof r.web === "object" ? (r.web as Record<string, unknown>) : {}; + const keyFile = str(r.apiKeyFile, d.apiKeyFile); + return { + preset, + routes, + models: { api: model(m.api, d.models.api), local: model(m.local, d.models.local), extractor: model(m.extractor, d.models.extractor) }, + caps: { + sweep: Math.min(max, usd(c.sweep, d.caps.sweep)), + revision: Math.min(max, usd(c.revision, d.caps.revision)), + narration: Math.min(max, usd(c.narration, d.caps.narration)), + daily: usd(c.daily, d.caps.daily, 100_000), + max, + }, + cacheTtl: r.cacheTtl === "1h" ? "1h" : "5m", + // Never a key: a value that looks like one is the default path. + apiKeyFile: keyFile && !looksLikeApiKey(keyFile) ? keyFile : d.apiKeyFile, + anthropicBaseUrl: url(r.anthropicBaseUrl, d.anthropicBaseUrl), + ollamaUrl: url(r.ollamaUrl, d.ollamaUrl), + projectsRoot: str(r.projectsRoot, d.projectsRoot), + web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) }, + citationOrigin: url(r.citationOrigin, d.citationOrigin), + }; +} + +export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" { + return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom"; +} + +// The cap a job runs under: the task's default, or the asked one when it is +// within `max` (else an error naming both). +export function capFor(caps: GenerationCaps, task: "sweep" | "revision" | "narration", asked?: number): number { + if (asked === undefined || asked === null) return caps[task]; + if (!Number.isFinite(asked) || asked <= 0) throw new Error(`maxUsd must be a positive number of dollars`); + if (asked > caps.max) throw new Error(`maxUsd $${asked} is over the settings' max of $${caps.max} (settings.generation.caps.max)`); + return asked; +} diff --git a/common/lib/paths.ts b/common/lib/paths.ts @@ -168,6 +168,10 @@ export type Paths = { espeakNgBin: string; ttsHome: string; ttsCacheDir: string; + // The generation usage ledger (release 27 S6): one JSON line per finished + // API generation job — what the day's spend cap is read from. Editor state, + // never inside the corpus (`<repo>/.generation/usage.jsonl`, gitignored). + generationUsageFile: string; // Base URL of the local ollama server, the local-GPU digest lane // (common/lib/digestApps.ts posts to `${ollamaUrl}/api/chat`). The FIRST // URL-valued entry in Paths, so it is normalized here the way @@ -320,6 +324,7 @@ export function getPaths(): Paths { espeakNgBin: process.env.ESPEAK_NG_BIN ?? "espeak-ng", ttsHome: path.join(os.homedir(), ".local", "share", "archilyzer", "tts"), ttsCacheDir: under(monorepoRoot, ".tts", "cache"), + generationUsageFile: process.env.GENERATION_USAGE_FILE ?? under(monorepoRoot, ".generation", "usage.jsonl"), ollamaUrl: (process.env.OLLAMA_URL ?? "http://127.0.0.1:11434").replace( /\/+$/, "", diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts @@ -18,6 +18,13 @@ export { TRANSCRIPTION_QUEUE }; export const DIGEST_LOCAL_QUEUE = "digest:local"; export const DIGEST_REMOTE_QUEUE = "digest:remote"; +// The two generation lanes (release 27 S6), split for the digests' reason: a +// `report-draft` on the local model holds the GPU (and yields through the GPU +// arbiter, controller/gpuArbiter.ts), one on the Claude API is network work +// that must not wait behind it. Each runs one job at a time. +export const DRAFT_LOCAL_QUEUE = "draft:local"; +export const DRAFT_API_QUEUE = "draft:api"; + // The backfill lane (controller/operationBatch.ts). Its own key for exactly the // reason the two digest keys have theirs: registry.ts submits every non-empty // queueKey at concurrency 1, so a distinct key is the ONLY way to get a lane 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/corpusCues.ts b/common/lib/report/draft/tasks/corpusCues.ts @@ -0,0 +1,39 @@ +// A recording's cues as the run's corpus has them (release 27, S6): read +// through the corpus tools' `get_transcript` with timestamps — the same build +// the agent quoted from, so convert widens and the strict check reads the +// words it saw. A cue ends where the next begins (the transcript shows starts). + +import type { CuesOf } from "../../convertShared"; +import type { CorpusToolsLike } from "./types"; + +const LINE = /^\[\[((?:\d+:)?\d+:\d+)\]\([^)]*\)\]\s?(.*)$/; + +const seconds = (stamp: string) => stamp.split(":").reduce((s, p) => s * 60 + Number(p), 0); + +export function parseTimestampedTranscript(text: string): { start: number; end: number; text: string }[] { + const starts: { start: number; text: string }[] = []; + for (const raw of text.split("\n")) { + const m = LINE.exec(raw.trim()); + if (m) starts.push({ start: seconds(m[1]!), text: m[2]!.trim() }); + } + return starts.map((c, i) => ({ start: c.start, end: Math.max(c.start + 0.5, (starts[i + 1]?.start ?? c.start + 5) - 0.01), text: c.text })); +} + +export function corpusCuesOf(corpus: Pick<CorpusToolsLike, "call">): CuesOf { + const cache = new Map<string, Promise<{ start: number; end: number; text: string }[] | null>>(); + return (channel, id) => { + const key = `${channel}/${id}`; + let p = cache.get(key); + if (!p) { + p = corpus + .call("get_transcript", { video_id: id, channel, timestamps: true }) + .then((t) => { + const cues = parseTimestampedTranscript(t); + return cues.length ? cues : null; + }) + .catch(() => null); + cache.set(key, p); + } + return p; + }; +} 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,214 @@ +// 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"))); +}); + +test("corpus cues: get_transcript's timestamped lines as cues, each ending where the next begins", async () => { + const { parseTimestampedTranscript, corpusCuesOf } = await import("./corpusCues"); + const text = "# Pie\n\n## Transcript\n\n[[0:00](https://v.example/watch?v=p)] good evening\n[[0:05](https://v.example/watch?v=p&t=5s)] a lot of you asked\n[[1:02:03](https://v.example/watch?v=p&t=3723s)] late line\n\n(corpus: x)"; + const cues = parseTimestampedTranscript(text); + assert.deepEqual(cues.map((c) => [c.start, c.text]), [[0, "good evening"], [5, "a lot of you asked"], [3723, "late line"]]); + assert.equal(cues[0]!.end, 4.99); + let calls = 0; + const of = corpusCuesOf({ call: async () => (calls++, text) }); + assert.equal((await of("c", "p"))!.length, 3); + await of("c", "p"); + assert.equal(calls, 1, "read once per recording"); + assert.equal(await corpusCuesOf({ call: async () => { throw new Error("no"); } })("c", "x"), null); +}); 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/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -24,6 +24,11 @@ import { SEEDER_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, ORPHEUS_TTS_SETTINGS_FIELD_DOCS, + GENERATION_CAPS_FIELD_DOCS, + GENERATION_MODELS_FIELD_DOCS, + GENERATION_ROUTES_FIELD_DOCS, + GENERATION_SETTINGS_FIELD_DOCS, + GENERATION_WEB_FIELD_DOCS, SOCIAL_LINK_FIELD_DOCS, SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, @@ -274,6 +279,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.tts.orpheus), }, ], + generation: [ + { path: "generation", docs: GENERATION_SETTINGS_FIELD_DOCS, defaults: fromObject(d.generation) }, + { path: "generation.routes", docs: GENERATION_ROUTES_FIELD_DOCS, defaults: fromObject(d.generation.routes) }, + { path: "generation.models", docs: GENERATION_MODELS_FIELD_DOCS, defaults: fromObject(d.generation.models) }, + { path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) }, + { path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) }, + ], }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -32,6 +32,7 @@ import type { StorageSettings } from "./storageLocations"; import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent"; import type { SeederSettings } from "./seederSettings"; import type { TtsSettings } from "./ttsSettings"; +import type { GenerationSettings } from "./generationSettings"; import type { AttributionSettings, BackfillSettings, @@ -109,13 +110,15 @@ type PreSchemaSiteSettings = { seeder: SeederSettings; // Local text-to-speech (release 25 T1). tts: TtsSettings; + // Report and video generation (release 27 S6). + generation: GenerationSettings; }; // Bracketed so the conditional does not distribute (see commit 8c43231). type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 38 fields, in file order", () => { +test("SiteSettings keeps its 39 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -156,6 +159,7 @@ test("SiteSettings keeps its 38 fields, in file order", () => { "publish", "seeder", "tts", + "generation", ]); // A parsed object carries every key, in that order — writeSettings writes // exactly this, so the order is the on-disk order. diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -79,6 +79,15 @@ import { import { sanitizeSeeder, type SeederSettings } from "./seederSettings"; export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings"; import { sanitizeTts, type TtsSettings } from "./ttsSettings"; +import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; +export { + GENERATION_CAPS_FIELD_DOCS, + GENERATION_MODELS_FIELD_DOCS, + GENERATION_ROUTES_FIELD_DOCS, + GENERATION_SETTINGS_FIELD_DOCS, + GENERATION_WEB_FIELD_DOCS, + type GenerationSettings, +} from "./generationSettings"; export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; import { DEFAULT_COOKIE_MODE, @@ -1832,6 +1841,9 @@ export const siteSettingsSchema = z.object({ tts: settingsField((v): TtsSettings => sanitizeTts(v)).describe( "Local text-to-speech (release 25): narration for report videos and podcasts, synthesized as an editor job (`pnpm ops tts`, the `tts` queue, one at a time) with a STOCK voice — never a cloned one — and cached by content. The default engine is Kokoro-82M with the voice `af_heart`, installed by `archilyzer tts setup`; espeak-ng needs no install. Every synthesis is disclosed as a synthetic voice (its sidecar and the result's `disclosure`). See TtsSettings and common/controller/ttsFile.ts.", ), + generation: settingsField((v): GenerationSettings => sanitizeGeneration(v)).describe( + "Report and video generation (release 27): where each task runs (`code` = Claude Code, `api` = the Claude API with a key, `local` = the local model), the models, the spend caps (a job's default, its max, the day's), the API key FILE (never the key), and where video projects live. A generation runs as a `report-draft` editor job (`pnpm ops report-draft`) on `draft:api` or `draft:local`. See GenerationSettings and common/lib/generationSettings.ts.", + ), }); export type SiteSettings = z.infer<typeof siteSettingsSchema>; 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/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog ## [Unreleased] +- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor. +- **Spending on the Claude API is capped.** A job is capped by its task ($5 a sweep, $2 a revision, $1 a narration, or the `maxUsd` it asks for, never above `settings.generation.caps.max`), and the editor refuses a job once the day's API spend (UTC) has reached `caps.daily` ($20), naming the day's total. Each finished API job adds its spend to a ledger beside the checkout (`.generation/usage.jsonl`), which is where the day's total comes from. +- **New settings block `generation`** (SETTINGS.md): where each task runs (`code` = Claude Code, `api`, `local`, with the presets `code`, `balanced`, `api`, `local`), the models, the caps, the API key FILE (mode 600; the key itself is refused as a setting and never stored), and where video projects live (`projectsRoot`, which `umtool chain` now reads too). +- **Text to speech and local drafting take turns on the GPU.** An Orpheus synthesis waits while a local model is drafting, and a local-model draft call waits while a transcription or a synthesis is running; digests still yield to transcription as before. The local model is unloaded when its draft job ends, so its memory is free for the next transcription. +- **The `/sweep` plan says a claim carries no quoted words, and quotes are verbatim.** The MCP's `sweep_plan` now tells Claude Code, at the merge step, that every quoted span before a link becomes that link's quote (so a claim that quotes words breaks its own citation), and that a quote is the transcript's words, copied, within 90 seconds of its link. The same rules, from one place in the code, are what release 27's generation jobs are held to. Claude Code picks it up on its next start. - **`umtool chain <article> <n>` takes an article's iteration to a video and a podcast.** One step a process, each recorded in the iteration: make it current, have the editor fetch every cited clip window (padded to the cut's 3 s, so the article's clips and the video share one fetch), `reports prepare --article <id> --only`, have the editor capture this article's missing post screenshots, make the video manifest in `~/reports/articles/<id>/i<n>/` (its narration and voices carried over from the parent iteration's project), voice the narration through the editor, build the video and the podcast, attach the video to the article and check it, and hard-link the segments and voices the article's projects share. Run again, it resumes at the first step not done; `--from <step>` runs from one, `--dry` prints the steps, `--final` crossfades. Nothing is fetched, captured or voiced but by the editor. - **`reports prepare --article <id> --only` answers for that article.** Its problems fail the run, another article's are printed as warnings, and only it is exported, so a draft being readied is no longer held up by a gap in a published article. The media of every published article is still prepared (their cache is shared). - **A report video made by `reports to-manifest` no longer shows "undefined" under its title or ends on a silent card.** The title card now has an empty third line (and a manifest made before this renders one too), and a section with nothing to show — a trailing Coverage note, a section of posts only — gets no chapter card; the article keeps the section. diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -0,0 +1,188 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { ORIGIN, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { FAKE_KEY, startFakeAnthropic, 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 { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; +import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import type { Paths } from "yt-dlp-transcript-common/lib/paths"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_reportDraft.test.ts" +// +// The `report-draft` job (release 27 S6) end to end in this process: the +// controller the route adapts, the MCP's corpus tools over the synthetic +// corpus, the fake Anthropic and ollama servers, a temp store, jobs dir and +// usage ledger. The key is a mode-600 file holding the fake's key. + +const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft"); +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let source: string; +let paths: Paths; +let gen: GenerationSettings; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "report-draft-")); + source = `local:${await writeDraftCorpus(path.join(tmp, "corpus"))}`; + api = await startFakeAnthropic(); + ol = await startFakeOllama(); + const keyFile = path.join(tmp, "anthropic.env"); + await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); + await chmod(keyFile, 0o600); + await mkdir(path.join(tmp, "channels"), { recursive: true }); + paths = { + jobsDir: path.join(tmp, ".jobs"), + articlesDir: path.join(tmp, "reports"), + exportIndexDir: path.join(tmp, ".export-index"), + exportBuildsDir: path.join(tmp, ".export-builds"), + sitesDir: path.join(tmp, "sites"), + channelsDir: path.join(tmp, "channels"), + generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), + ollamaUrl: ol.url, + } as Paths; + gen = sanitizeGeneration({ + apiKeyFile: keyFile, + anthropicBaseUrl: api.url, + citationOrigin: ORIGIN, + projectsRoot: path.join(tmp, "projects"), + caps: { sweep: 2, daily: 20, max: 5 }, + }); +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const deps = (g: Partial<GenerationSettings> = {}) => ({ + paths, + corpusTools: (s: string) => createCorpusTools({ source: s }), + settings: () => ({ generation: { ...gen, ...g } }), +}); + +const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8")); + +test("the body: each task's needs, and the refusals in words", () => { + assert.throws(() => parseReportDraftBody({ task: "nope", article: "a" }), /"task" is one of sweep, revise-report, revise-video, narrate/); + assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", channels: ["x"] }), /needs its question/); + assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1 }), /needs feedback/); + assert.throws(() => parseReportDraftBody({ task: "narrate", article: "a" }), /names the iteration it voices/); + assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: "x", source: "ftp:x" }), /corpus handle/); + assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: " q ", channels: "x, y" }), { task: "sweep", article: "a", question: "q", channels: ["x", "y"] }); +}); + +test("refused before any iteration: a task routed to Claude Code with no model, a cap over max", async () => { + const code = await enqueueReportDraft({ task: "sweep", article: "synth-refused", question: "q", channels: ["synth-kitchen"], source }, deps()); + assert.equal(code.result.ok, false); + assert.match((code.result as { error: string }).error, /routed to Claude Code/); + const big = await enqueueReportDraft({ task: "sweep", article: "synth-refused", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], maxUsd: 9, source }, deps()); + assert.match((big.result as { error: string }).error, /over the settings' max of \$5/); + assert.equal(await readIteration("synth-refused", 1, paths), null); +}); + +test("an API sweep: a report-draft job on draft:api, the iteration done with its job, the usage in the ledger", async () => { + const r = await run("sweep-agent"); + api.push(...r.turns); + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-api", model: r.model, question: r.question, channels: r.channels, source }, + deps(), + ); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + const job = getRegistry().get(out.result.jobId)!; + assert.equal(job.kind, "report-draft"); + assert.equal(job.queueKey, "draft:api"); + void out.result.stream.cancel(); + const done = await out.result.done; + const log = await readFile(job.logPath, "utf8"); + assert.equal(done.status, "done", log); + assert.match(log, /@@report-draft \{"article":"synth-api","iteration":1,"task":"sweep","status":"done"/); + assert.ok(!log.includes(FAKE_KEY), "the key is never in the log"); + const it = (await readIteration("synth-api", out.iteration, paths))!; + assert.equal(it.status, "done"); + assert.equal(it.jobId, out.result.jobId); + const rows = await readGenerationUsage(paths.generationUsageFile); + assert.deepEqual(rows.map((x) => x.model).sort(), ["claude-haiku-4-5", "claude-sonnet-5-5"]); + const jobId = out.result.jobId; + assert.ok(rows.every((x) => x.jobId === jobId && x.article === "synth-api" && x.iteration === 1)); + assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); +}); + +test("the daily cap: a job that would start past the day's total is refused, naming it", async () => { + const before = await readGenerationUsage(paths.generationUsageFile); + const total = before.reduce((s, x) => s + x.usd, 0); + assert.ok(total > 0); + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-daily", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source }, + deps({ caps: { ...gen.caps, daily: total / 2 } }), + ); + assert.equal(out.result.ok, false); + assert.match((out.result as { error: string }).error, /the day's Claude API spend is \$\d+\.\d\d .* daily cap \(settings\.generation\.caps\.daily\) — refused/); + assert.equal(await readIteration("synth-daily", 1, paths), null, "no iteration made"); +}); + +test("job cancel stops a running draft: the request in flight aborted, the iteration cancelled", async () => { + let release!: () => void; + const held = new Promise<void>((r) => (release = r)); + let arrived!: () => void; + const inFlight = new Promise<void>((r) => (arrived = r)); + api.push(async () => { + arrived(); + await held; + return textTurn("too late"); + }); + const out = await enqueueReportDraft( + { task: "sweep", article: "synth-cancel", model: "claude-sonnet-5-5", question: "q", channels: ["synth-kitchen"], source }, + deps(), + ); + assert.ok(out.result.ok && "iteration" in out); + void out.result.stream.cancel(); + await inFlight; + assert.equal(getRegistry().cancel(out.result.jobId), true); + const done = await out.result.done; + release(); + assert.equal(done.status, "cancelled"); + let it = await readIteration("synth-cancel", out.iteration, paths); + for (let i = 0; i < 50 && it?.status !== "cancelled"; i++) { + await new Promise((r) => setTimeout(r, 20)); + it = await readIteration("synth-cancel", out.iteration, paths); + } + assert.equal(it!.status, "cancelled"); +}); + +test("a local narration: draft:local, a step on the iteration, ollama unloaded when the job ends", async () => { + const r = await run("narrate"); + ol.push(...r.turns); + const article = "synth-basic"; + await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")); + await writeIterationFile(article, 1, "report.json", report, paths); + const dir = projectOf(gen.projectsRoot, article, 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), await readFile(path.join(DRAFT, "manifests", "basic.video.manifest.json"), "utf8")); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration(article, 1, { status: "done", projectDir: dir }, paths); + const out = await enqueueReportDraft({ task: "narrate", article, iteration: 1, model: r.model, source }, deps()); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local"); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8")); + assert.deepEqual(ol.unloads, ["qwen3:8b"]); + const it = (await readIteration(article, 1, paths))!; + assert.equal(it.status, "done"); + const step = it.steps.find((s) => s.task === "narrate")!; + assert.equal(step.status, "done"); + assert.equal(step.jobId, out.result.jobId); + const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text); +}); diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -0,0 +1,38 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft } from "yt-dlp-transcript-common/controller/reportDraft"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { jobResponse, ops } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { task, article, iteration?, model?, feedback?, question?, channels?, +// from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force? } +// -> { ok: true, jobId, iteration } +// +// A generation over an article's iteration (release 27 S6), as a +// `report-draft` job on `draft:api` or `draft:local` by the model's provider: +// - task "sweep": a new iteration from `question` over `channels` (and +// `from`/`to`); the API model runs the agent, a local model the pipeline; +// - "revise-report" / "revise-video": a new iteration revising `iteration` +// from `feedback`; +// - "narrate": a step on the done iteration `iteration` (`cards`, `force`); +// - `copyOf` N: iteration N again on `model` (same kind and inputs). +// `model` defaults to settings.generation's route for the task (a task routed +// to `code` needs one named). An API job's cap is `maxUsd`, else the task's +// default (settings.generation.caps), never above `caps.max`; a job that would +// start past the day's API total (`caps.daily`) is refused, naming it. The +// corpus is `source` (a handle), `build` (a composed build's id), or the newest +// build holding the channels. `job cancel` stops it (the iteration ends +// `cancelled`). The job's log ends `@@report-draft {json}` with the result. +// +// AN ADAPTER: the refusals are the controller's (controller/reportDraft.ts); +// the corpus tools are the MCP's own, in process (mcp/src/callTool.ts). +export async function POST(request: Request) { + return ops(request, REPORT_DRAFT_BODY_KEYS, async (body) => { + const out = await enqueueReportDraft(body, { paths: getPaths(), corpusTools: (source) => createCorpusTools({ source }) }); + if (!out.result.ok || !("iteration" in out)) return jobResponse(out.result); + void out.result.stream.cancel(); + return NextResponse.json({ ok: true, jobId: out.result.jobId, iteration: out.iteration }); + }); +} diff --git a/editor/app/api/ops/settings/route.ts b/editor/app/api/ops/settings/route.ts @@ -4,6 +4,7 @@ import { mergeSettingsPatch, saveSettings } from "../../../settings/saveSettings import { OpsInputError, ops, opsFail } from "../_lib"; import { readRoute, redactSecrets } from "../_read"; import { settingsPatchProblem } from "./patch"; +import { looksLikeApiKey } from "yt-dlp-transcript-common/lib/generationSettings"; export const dynamic = "force-dynamic"; @@ -55,6 +56,15 @@ export async function POST(request: Request) { } const keys = Object.keys(patch); if (keys.length === 0) throw new OpsInputError('"patch" is empty — nothing to change'); + // The Claude API key is never a setting (release 27 S6): a key file path + // that looks like a key is refused WITHOUT echoing it, before the generic + // check below would print what was sent. + const keyFile = (patch as { generation?: { apiKeyFile?: unknown } }).generation?.apiKeyFile; + if (typeof keyFile === "string" && looksLikeApiKey(keyFile)) { + throw new OpsInputError( + "generation.apiKeyFile is the PATH of the mode-600 file that holds the key, and the value sent looks like a key itself — refused, not stored", + ); + } const current = getSettings(); const problem = settingsPatchProblem( patch as Record<string, unknown>, diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -0,0 +1,157 @@ +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +// By relative path, as digest.spec.ts imports common: the test kit's fakes and +// the synthetic corpus are plain .mjs. +import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; +import { ORIGIN, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; +import { baseUrl } from "./baseUrl"; +import { resetData, testPaths, writeSettings } from "./helpers"; + +// `pnpm ops report-draft` end to end (release 27 S6): the editor against the +// fake Anthropic (started here, on loopback; settings point at it with a +// mode-600 key file holding the fake's key), over the synthetic draft corpus +// written as a composed build into the test server's .export-builds/ (the +// newest build holding the channels is the one a job picks). The usage ledger +// is the test server's GENERATION_USAGE_FILE, inside test-transcripts/, so a +// reset clears it. + +const AUTH = { authorization: "Bearer test-worker-token" }; +const RUNS = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "common", "testing", "draft", "runs"); + +let api: FakeAnthropic; +let keyDir: string; + +test.beforeAll(async () => { + api = await startFakeAnthropic(); + keyDir = await mkdtemp(join(os.tmpdir(), "e2e-report-draft-")); +}); + +test.afterAll(async () => { + await api?.close(); + await rm(keyDir, { recursive: true, force: true }); +}); + +async function setup(caps: Record<string, number> = {}) { + await resetData(null); + const keyFile = join(keyDir, "anthropic.env"); + await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); + await chmod(keyFile, 0o600); + await writeSettings({ + minFreeDiskGB: 0, + generation: { + apiKeyFile: keyFile, + anthropicBaseUrl: api.url, + citationOrigin: ORIGIN, + projectsRoot: join(keyDir, "projects"), + caps: { sweep: 3, revision: 2, narration: 1, daily: 20, max: 5, ...caps }, + }, + }); + const t = testPaths().transcriptsDir; + await writeDraftCorpus(join(t, ".export-builds", "draft-e2e", "out")); +} + +async function draft(request: APIRequestContext, data: Record<string, unknown>) { + const res = await request.post(`${baseUrl}/api/ops/report-draft`, { headers: AUTH, data }); + return { status: res.status(), body: (await res.json()) as { ok?: boolean; error?: string; jobId?: string; iteration?: number } }; +} + +async function jobUntil(request: APIRequestContext, id: string, done: (s: string) => boolean, ms = 60_000) { + const t0 = Date.now(); + let last = ""; + while (Date.now() - t0 < ms) { + const res = await request.get(`${baseUrl}/api/ops/job/${id}?tail=40`, { headers: AUTH }); + const body = (await res.json()) as { job?: { status?: string }; status?: string; tail?: string[] }; + last = body.job?.status ?? body.status ?? ""; + if (done(last)) return body; + await new Promise((r) => setTimeout(r, 300)); + } + throw new Error(`job ${id} is still ${last}`); +} + +const iterationJson = async (article: string, n: number) => + JSON.parse(await readFile(join(testPaths().transcriptsDir, "reports", article, "iterations", String(n), "iteration.json"), "utf8")); + +const run = async (name: string) => JSON.parse(await readFile(join(RUNS, `${name}.json`), "utf8")); + +test.describe.configure({ mode: "serial" }); + +test("a sweep draft: enqueued over ops, followed to done, its iteration read back", async ({ request }) => { + test.setTimeout(120_000); + await setup(); + const r = await run("sweep-agent"); + api.push(...r.turns); + const { status, body } = await draft(request, { + task: "sweep", + article: "synth-e2e", + model: r.model, + question: r.question, + channels: r.channels, + }); + expect(status, body.error).toBe(200); + expect(body.ok).toBe(true); + expect(body.iteration).toBe(1); + const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); + expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); + const it = await iterationJson("synth-e2e", 1); + expect(it.status).toBe("done"); + expect(it.jobId).toBe(body.jobId); + expect(it.usage["claude-sonnet-5-5"].usd).toBeGreaterThan(0); + const report = JSON.parse( + await readFile(join(testPaths().transcriptsDir, "reports", "synth-e2e", "iterations", "1", "report.json"), "utf8"), + ); + expect(Object.keys(report.citations)).toHaveLength(3); + const ledger = await readFile(join(testPaths().transcriptsDir, ".generation-usage.jsonl"), "utf8"); + expect(ledger).toContain(body.jobId!); + expect(ledger).not.toContain(FAKE_KEY); + expect(api.remaining()).toBe(0); +}); + +test("a cancel mid-run: job cancel stops the draft and its iteration ends cancelled", async ({ request }) => { + test.setTimeout(120_000); + await setup(); + let release!: () => void; + const held = new Promise<void>((r) => (release = r)); + const before = api.requests.length; + api.push(async () => { + await held; + return textTurn("too late"); + }); + const { body } = await draft(request, { + task: "sweep", + article: "synth-cancel", + model: "claude-sonnet-5-5", + question: "What does she say about the contest?", + channels: ["synth-kitchen"], + }); + expect(body.ok, body.error).toBe(true); + await expect.poll(() => api.requests.length, { timeout: 30_000 }).toBeGreaterThan(before); + const cancel = await request.post(`${baseUrl}/api/ops/job`, { headers: AUTH, data: { verb: "cancel", ids: [body.jobId] } }); + expect(cancel.status()).toBe(200); + const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); + release(); + expect(job.job?.status ?? job.status).toBe("cancelled"); + await expect.poll(async () => (await iterationJson("synth-cancel", 1)).status, { timeout: 10_000 }).toBe("cancelled"); +}); + +test("the daily cap: a job that would start past the day's API total is refused, naming it", async ({ request }) => { + await setup({ daily: 4 }); + const day = new Date().toISOString().slice(0, 10); + await writeFile( + join(testPaths().transcriptsDir, ".generation-usage.jsonl"), + `${JSON.stringify({ at: new Date().toISOString(), day, jobId: "earlier", article: "x", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 4.5 })}\n`, + ); + const { status, body } = await draft(request, { + task: "sweep", + article: "synth-daily", + model: "claude-sonnet-5-5", + question: "q", + channels: ["synth-kitchen"], + }); + expect(status).toBe(400); + expect(body.error).toContain("the day's Claude API spend is $4.50"); + expect(body.error).toContain("$4.00 daily cap"); + await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-daily", "iterations", "1", "iteration.json"))).rejects.toThrow(/ENOENT/); +}); diff --git a/editor/next.config.ts b/editor/next.config.ts @@ -38,7 +38,7 @@ const nextConfig: NextConfig = { }, ], }, - transpilePackages: ["yt-dlp-transcript-common"], + transpilePackages: ["yt-dlp-transcript-common", "yt-dlp-transcript-mcp"], serverExternalPackages: ["lmdb", "msgpackr", "msgpackr-extract"], experimental: { serverActions: { diff --git a/editor/package.json b/editor/package.json @@ -5,8 +5,8 @@ "type": "module", "scripts": { "dev": "next dev --port ${EDITOR_PORT:-3001}", - "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", - "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", + "dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}", + "start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}", "build": "next build", "start": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next start --port ${EDITOR_PORT:-3001}", "test": "tsx --test \"app/**/*.test.ts\" \"e2e/*.unit.ts\"", 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 ( diff --git a/plans/release-27.md b/plans/release-27.md @@ -421,6 +421,57 @@ Gates: tsc clean; common 3891/3891 (21 new); mcp 314/314; editor unit 270/270 (3 Decided here: `import-post` takes a post of the channel's own account only (a reply or quote by another account would be misattributed in that archive). `import-post` is not replayable (a second import reads nothing anyway). +### S5, as shipped (2026-10-13, lane D) + +The generation tasks, on `r27/tasks-jobs` from `r27/integration` `f933f767` (phase 1 merged). + +| Commit | What | +| --- | --- | +| `277cc480` | `common/lib/report/draft/authoringRules.ts`; `report/draft/tasks/` (the five tasks, `run.ts`, `links.ts`, `quotes.ts`, `corpusSource.ts`, `project.ts`, `reportFile.ts`, `llmText.ts`, `index.ts` with `runTask`); `mcp/src/instructions.ts` reads the rules; `draft/agentTool.ts` re-exports lane A's type; `testing/draft/runs/*.json`; `mcp/src/draftTasks.test.ts` | +| (this commit) | this record; the CHANGELOG bullet | + +- **A task** is `(input, deps)`. `deps` carries the LLM config, the corpus tools (`{source, tools, call}` — common cannot import the mcp package, so the caller builds them with `createCorpusTools`), the web tools, `cuesOf` / `postTextOf` / `postChannelOf` for convert and the quote check, an optional `verifyReport` (the editor's verify-quotes, which reads en-orig), the store's `paths`, a clock, a log and the signal. +- **`runOnIteration`** is every task's life: the iteration must be `queued` (or `running`) and of the task's kind; it is marked running; the meter's spend per model is added to `usage`, the turns appended to `turns.jsonl`, and it ends `done`, `failed` (with `error`) or `cancelled` (the signal) with `minutes`, `ops` and `checks`. A model's failure is a `failed` iteration and a result; only a call that cannot start throws. Narration runs with `step`: a done iteration's `steps[]` gets `narrate`, its status untouched. +- **sweep-agent:** the `sweep_plan` text (the request carries channels, batch size, extractor, report), the read tools (no notes, fetch_clip, enqueue, jobs), `extract_batch` (get_transcripts + the extractor model, cut at 400k chars, or the local cap), the report tools (each write kept in the store), Claude's server search plus the deps' web tools. Then the link backstop, convert, the strict check; one repair round with the report tools only, the transcript ±45 s inline and `min($0.25, cap/4)`; a finding still failing is dropped. + - **The repair round is a fresh conversation**, not a continuation: `runAgent` starts from a user message, and the round needs only the problems and the report (cheaper than re-sending the run's context). +- **sweep-pipeline:** `local_sweep.py` ported (terms, enumerate with the word fallback, read in 8s, windows of 90 s, 7000-char chunks, extract, the verbatim locate, the drops, the lint, group twice, the caps); every model call is a `structuredAnswer`, so the 8k cap refuses before sending. Converted and strict-checked; a failing finding is dropped and the markdown re-rendered (up to three rounds). +- **revise-report / revise-video:** the parent's `sweep.md` (the nearest in the lineage) or cut (the nearest project with a manifest); `read_doc`, `apply_ops` (S2's engines; the add's strict checker over `cuesOf`), the read tools with `notes`, the web. A new finding whose quote fails after convert is dropped; the parent's quotes are never touched (an old `inexact` is a check, not a failure). A video revision's project is seeded from the parent's: the report and stills copied, the voices hard-linked; it has no report of its own. +- **narrate:** per title and chapter card, the card's evidence, the rules without examples or the tag rule (`rulesForModel`), the taste; S2's grounding plus a word limit (35 / 45, refused at +10); one re-ask; the better attempt; failing sentences removed. A `revisions/<stamp>-auto-before-narration.manifest.json` snapshot, then the manifest written whole; `narration-draft.json` beside it. +- **Links** are `momentHref(origin, slug, id, s)`. Every get_transcripts result an agent sees has its `moment_base` rewritten to the origin's (the slug from the moment_base when it is in the archive's form, else asked of the corpus with get_video_metadata over the run's channels); the finished markdown's platform URLs and other origins' archive links are rewritten too. +- **The corpus build:** `pickCorpusBuild(channels, {exportBuildsDir, want?})` (the newest public build holding them, a `-private` one only when alone) and `siteOriginOf(build, sitesDir)`; S6 wires them. +- **`authoringRules.ts`:** the narration hard rule and writing rules (moved verbatim; `instructions.ts` re-exports them), the taste, the claim-quotes, verbatim, one-quote, post-citation, coverage and style rules, `momentLinkRule(origin)`, `EXTRACTOR_SYSTEM`, the unattended rule. The MCP's batch step now also states the claim-quotes and verbatim rules. + +Gates: +- tsc clean (all packages). +- common 3966 tests: 3963 pass; the three red were S6's settings in progress in the same tree (the shape test and the two generated-docs tests), green in S6's commit. New here: `tasks/tasks.test.ts` (7). +- mcp 323/323 (9 new: `draftTasks.test.ts`, each task end to end over the synthetic corpus and the fakes, a cancel mid-request, the repair allowance, a drop after a failed repair). +- editor unit 270/270; `test:scripts` 850 pass + 3 skipped. +- No builds (no app code). + +### S6, as shipped (2026-10-13, lane D) + +Editor jobs, settings and ops, on `r27/tasks-jobs` after S5. + +| Commit | What | +| --- | --- | +| `12a4f48c` | `controller/{reportDraft,gpuArbiter,generationUsage}.ts`; `lib/generationSettings.ts` + `settingsSchema`/`settingsDocs`; `queueKeys` `DRAFT_LOCAL_QUEUE`/`DRAFT_API_QUEUE`; job kind `report-draft`; `paths.generationUsageFile` (`GENERATION_USAGE_FILE`); `tasks/corpusCues.ts`; `ttsFile.ts` on the arbiter; the `report-draft` route, ACTIONS row, help, COMMANDS.md; `transpilePackages` gains the mcp package; the settings route refuses a key-looking `apiKeyFile` without echoing it; umtool's chain reads `generation.projectsRoot`; SETTINGS.md, settings.json.example, ENVIRONMENT.md; e2e `report-draft.spec.ts`; editor unit `_reportDraft.test.ts` | +| `0a637826` | no key-shaped literal in the key rule or its tests | +| (this commit) | this record; the CHANGELOG bullets | + +- **`pnpm ops report-draft {task, article, iteration?, model?, feedback?, question?, channels?, from?, to?, copyOf?, maxUsd?, source?, build?, cards?, force?}`** → `{ok, jobId, iteration}`. The controller (`enqueueReportDraft`) judges the body, picks the model (the asked one, else the task's route in `settings.generation`; a task routed to `code` with no model is refused), creates the iteration `queued` (a `copyOf` copies it; a narration names a done one and is a step), runs `runManagedFunction` on `draft:api` or `draft:local` by provider, and sets the iteration's `jobId`. A job cancelled or refused before it ran leaves no `queued` iteration behind (its `done` marks it). +- **The job** resolves the corpus (`source`, else `build`, else `pickCorpusBuild` over the channels — a revision's and a narration's from its report's citations) and the citation origin (the build's site, else `generation.citationOrigin`, else the project site), builds the corpus tools through `deps.corpusTools` (the route passes `createCorpusTools`; common cannot import mcp), and runs the S5 task with the job's signal. Cues for convert and the strict check come from the same build (`corpusCuesOf`: get_transcript with timestamps); post text and the post-channel lookup from the corpus on disk; the editor's `verifyReportQuotes` adds only a `drift` / `en-orig-drift` (a record the disk does not hold is the build's to answer). The log ends `@@report-draft {article, iteration, task, status, summary, usd, minutes}`; a failed or cancelled task fails or cancels the job. +- **The GPU arbiter** (`gpuArbiter.ts`): in-process holds (`holdGpu`) around each unit of work. Digests keep yielding to transcription (`digestYield`, unchanged); TTS (a GPU engine) waits for a transcription on a GPU worker and for a held draft call, and holds the GPU while its engine runs; a draft call waits for the transcription lane's signal and a held synthesis. A `draft:local` job's ollama config carries `gpuGatedFetch`: every `/api/chat` waits, then holds until the answer is read; the unload is never held. ollama is unloaded (`keep_alive: 0`) when a `draft:local` job ends, however it ends. `draft:api` touches none of it, nor the heavy slot. +- **Caps (D6).** A job's cap is `maxUsd`, else its task's (`caps.sweep` 5, `revision` 2, `narration` 1), refused above `caps.max` (10). The daily cap (`caps.daily` 20, UTC) is read from the usage ledger at the ask and again at the job's turn; past it, refused naming the day's total. A finished API job appends a row per model (job, article, iteration, task, model, tokens, USD, day) to `paths.generationUsageFile` (`<repo>/.generation/usage.jsonl`, gitignored; the e2e server's is in its fixture). A local job has no dollar cap. +- **`settings.generation`:** `preset` (named by the routes: the preset whose routes they are, else `custom` — choosing one is writing its routes), `routes`, `models {api, local, extractor}` (Sonnet 5.5, qwen3:8b, Haiku 4.5), `caps`, `cacheTtl`, `apiKeyFile` (a key-looking value is the default path, never stored; the ops settings route refuses it without echoing it), `anthropicBaseUrl` (a non-Anthropic base never receives the environment's key, only the file's), `ollamaUrl` (blank = the editor's `OLLAMA_URL`), `projectsRoot`, `web {provider, searchUrl}`, `citationOrigin`. `generation.research` is S11's. +- **Decided here:** the ledger is a JSONL file, not a registry store (one line per model per job; the day's total is a scan). The daily cap refuses at the ask and at the turn; a job already running is not stopped by it (its own cap stops it). + +Gates: +- tsc clean (all packages). +- common 3976/3976 (10 new beyond S5: `gpuArbiter.test.ts` 4, `generationSettings.test.ts` 4, `generationUsage.test.ts` 1, the corpus-cues test); mcp 323/323; editor unit 276/276 (6 new, `_reportDraft.test.ts`: the body, the refusals, an API sweep to done with its ledger rows, the daily cap, a cancel mid-request, a local narration with its unload); `test:scripts` 851 pass + 3 skipped (the chain's projects-root test new). +- `docs env|files|cli --check`, `settings example --check`: clean. +- Editor build: the e2e prebuild's capped `next build` (heavy slot, 5 GB) at `12a4f48c`, 72 s, clean. (A standalone `next build` waited 33 min under the 6000 MB floor at 5.1–5.5 GB available and was stopped; the e2e run's build is the same app.) +- e2e `report-draft.spec.ts` + `digest.spec.ts`, one run: 18 passed, 0 failed, 41.5 s (report-draft 3 in 0.6 s, digest 15 in 21.2 s). The first attempt timed out in the heavy-slot queue and was re-run. + ## Rollout - Fast-forward `main`. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -100,6 +100,8 @@ // pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}' // pnpm ops archive-item --json '{"item":"example-item"}' // pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait +// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait +// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}' // // --file reads the BODY from a JSON file, which is how a big one gets sent: a // four-thousand-id tag-videos body is written by a script, not typed by a model @@ -375,6 +377,11 @@ const ACTIONS = [ "archive-search", "archive-item", "import-post", + // GENERATION (release 27 S6): a sweep, a report or video revision, or a + // narration step over an article's iteration ({task, article, iteration?, + // model?, feedback?, question?, channels?, copyOf?, maxUsd?, …}), as a + // report-draft job on draft:api or draft:local. `job cancel` stops it. + "report-draft", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -384,6 +391,9 @@ export const TRANSCRIBE_RESULT_MARKER = "@@transcribe-result "; // The same for a text-to-speech job (TTS_RESULT_MARKER in // common/controller/ttsFile.ts). export const TTS_RESULT_MARKER = "@@tts-result "; +// The same for a generation (REPORT_DRAFT_RESULT_MARKER in +// common/controller/reportDraft.ts). +export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft "; // The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in // common/controller/remoteListing.ts). export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing "; @@ -610,6 +620,7 @@ export function parseArgs(argv) { ...(action === "transcribe" ? { resultMarker: TRANSCRIBE_RESULT_MARKER } : {}), ...(action === "tts" ? { resultMarker: TTS_RESULT_MARKER } : {}), ...(action === "remote-listing" ? { resultMarker: REMOTE_LISTING_RESULT_MARKER } : {}), + ...(action === "report-draft" ? { resultMarker: REPORT_DRAFT_RESULT_MARKER } : {}), wait, quiet, waitTimeout, @@ -1133,6 +1144,22 @@ export function usage() { " one the platform says is another account's is not written. The log ends", " with @@import-post {ok, slug, url, id, written, already?, post?, error?}.", "", + 'report-draft runs a generation over an article\'s iteration as a', + ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |', + ' "narrate", "article", ...} -> {jobId, iteration}. A sweep takes "question"', + ' and "channels" (and "from"/"to"): a new iteration; a revision takes', + ' "iteration" (the one it revises) and "feedback": a new iteration; a', + ' narration takes "iteration" (a done one; "cards"?, "force"?) and is a step', + ' on it. "copyOf" N runs iteration N again on "model". "model" defaults to', + " settings.generation's route for the task (one routed to code needs a model", + ' named). A Claude model runs on draft:api, capped at "maxUsd" (default by', + " task, never above caps.max), and is refused when the day's API total has", + " reached caps.daily; a local model runs on draft:local, through the GPU", + ' arbiter, and is unloaded when it ends. The corpus is "source" (a handle),', + ' "build" (a composed build), or the newest build holding the channels.', + " `job cancel <id>` stops it. The log ends with @@report-draft {article,", + " iteration, task, status, summary, usd, minutes}; --wait prints it.", + "", "Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,", " ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").", " WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from", diff --git a/settings.json.example b/settings.json.example @@ -236,5 +236,36 @@ "takes": 3, "tagCheck": false } + }, + "generation": { + "preset": "balanced", + "routes": { + "sweep": "code", + "revise-report": "api", + "revise-video": "local", + "narrate": "local" + }, + "models": { + "api": "claude-sonnet-5-5", + "local": "qwen3:8b", + "extractor": "claude-haiku-4-5" + }, + "caps": { + "sweep": 5, + "revision": 2, + "narration": 1, + "daily": 20, + "max": 10 + }, + "cacheTtl": "5m", + "apiKeyFile": "~/.config/archilyzer/anthropic.env", + "anthropicBaseUrl": "", + "ollamaUrl": "", + "projectsRoot": "", + "web": { + "provider": "duckduckgo", + "searchUrl": "" + }, + "citationOrigin": "" } } diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -38,7 +38,7 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; -import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; @@ -284,7 +284,7 @@ export async function runChainStep(article, n, name, opts = {}) { console.error(`chain: "${article}" i${n} is ${iteration.status} — the chain runs over a done iteration`); return 2; } - const projectsRoot = opts.projectsRoot ?? DEFAULT_PROJECTS_ROOT; + const projectsRoot = opts.projectsRoot ?? configuredProjectsRoot(); const ctx = { article, n, diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs @@ -57,7 +57,7 @@ export const chainTask = (name) => `chain:${name}`; // STARTER_RENDER): the windows are fetched this wide so the cut finds them. export const CHAIN_WINDOW_PAD = 3; -// Until S6's `settings.generation.projectsRoot`: off the corpus disk (D1). +// Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this. export const DEFAULT_PROJECTS_ROOT = path.join(/* turbopackIgnore: true */ os.homedir(), "reports", "articles"); // From driver.mjs's package root, which is found from the module (or, under @@ -67,6 +67,22 @@ export const REPO_ROOT = path.dirname(/* turbopackIgnore: true */ UMTOOL_DIR); /** The executor every step runs. */ export const CHAIN_RUN = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "lib", "report", "chain-run.mjs"); +/** + * The projects root the settings name (`settings.generation.projectsRoot`, + * release 27 S6), read from the checkout's settings.json (`SETTINGS_FILE` + * overrides) — `~` expanded; blank, absent or unreadable = DEFAULT_PROJECTS_ROOT. + */ +export function configuredProjectsRoot(settingsFile = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json")) { + try { + const v = JSON.parse(readFileSync(/* turbopackIgnore: true */ settingsFile, "utf8"))?.generation?.projectsRoot; + if (typeof v !== "string" || !v.trim()) return DEFAULT_PROJECTS_ROOT; + const s = v.trim(); + return s === "~" ? os.homedir() : s.startsWith("~/") ? path.join(/* turbopackIgnore: true */ os.homedir(), s.slice(2)) : s; + } catch { + return DEFAULT_PROJECTS_ROOT; + } +} + const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; /** `<projectsRoot>/<id>/i<n>/` (common/lib/report/iterations.ts projectOf). */ @@ -121,7 +137,7 @@ export function readIterationRecord(articlesDir, article, n) { * @returns {import("../trim").Step[]} */ export function chainSteps(o) { - const projectsRoot = o.projectsRoot ?? DEFAULT_PROJECTS_ROOT; + const projectsRoot = o.projectsRoot ?? configuredProjectsRoot(); chainProject(projectsRoot, o.article, o.n); const start = o.start === undefined ? CHAIN_STEP_NAMES[0] : o.start; if (start === null) return []; diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs @@ -14,8 +14,10 @@ import { fileURLToPath } from "node:url"; import { CHAIN_RUN, CHAIN_STEP_NAMES, + DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainProject, + configuredProjectsRoot, chainStart, chainSteps, chainWindows, @@ -136,3 +138,19 @@ test("planChain: the record, the resume point and the steps; a queued iteration assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 2 }), /i2 is queued/); assert.throws(() => planChain({ articlesDir: articles, article: "art", n: 7 }), /has no iteration i7/); }); + +test("the projects root comes from settings.generation.projectsRoot (release 27 S6), else the default", () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "chain-settings-")); + try { + const file = path.join(dir, "settings.json"); + assert.equal(configuredProjectsRoot(path.join(dir, "absent.json")), DEFAULT_PROJECTS_ROOT); + writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "" } })); + assert.equal(configuredProjectsRoot(file), DEFAULT_PROJECTS_ROOT); + writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "/srv/projects" } })); + assert.equal(configuredProjectsRoot(file), "/srv/projects"); + writeFileSync(file, JSON.stringify({ generation: { projectsRoot: "~/elsewhere" } })); + assert.equal(configuredProjectsRoot(file), path.join(os.homedir(), "elsewhere")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +});