Archilyzer · Source

archilyzer

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

commit 0c7e0504d10f5d1a723dec15b4526d13836e2b45
parent dd40274204f6fb7cb6f2941df98bb072a51b50ac
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 13:20:25 -0400

mcp: release 27 S9 — generation_policy and generate; sweep_plan routes by the policy

generation_policy reads settings.generation through the editor (routes,
models, caps, the day's spend; never the key) and, when the operator asks,
writes a preset or one route as the routes object. generate enqueues a
report-draft job (sweep, revise-report, revise-video, narrate, research),
refuses a task routed to code, and with wait: true follows the job politely
(one poll every 5 s, bounded, resumable by job id) and summarises the
iteration: status, cost, ops refused, checks, where its files are, and the
review to do. sweep_plan reads the policy at plan time: a sweep routed to api
or local becomes generate, then a review; ask_plan names the routed tasks.
via= and article= in a plan request.

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

Diffstat:
Amcp/src/generation.test.ts | 315+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amcp/src/generation.ts | 608+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/instructions.ts | 175++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mmcp/src/promptRequest.test.ts | 15+++++++++++++++
Mmcp/src/promptRequest.ts | 19+++++++++++++++++++
Mmcp/src/protocol.test.ts | 2++
Mmcp/src/server.ts | 48++++++++++++++++++++++++++++++++++++++++--------
8 files changed, 1261 insertions(+), 9 deletions(-)

diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -0,0 +1,315 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; +import { + GENERATE_POLL_MS, + GENERATE_TASKS, + generateTool, + generationPolicyTool, + planGeneration, + resultMarkerOf, + validateGenerateArgs, +} from "./generation"; + +// ─── The Claude Code balance (release 27 S9) ─── +// +// generation_policy and generate against a fake editor: no network, no timers +// (sleep advances a fake clock). + +const POLICY = { + 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", + // The editor redacts it (its key matches the secret pattern); the tool must + // not render it either way. + apiKeyFile: "<redacted>", + anthropicBaseUrl: "", + ollamaUrl: "", + projectsRoot: "/srv/projects-root-never-shown", +}; + +type Sent = { url: string; method: string; body?: unknown }; + +// An editor that serves the policy, the day's usage, a report-draft POST, a +// job that runs for `runPolls` polls and then ends `end`, and the iteration. +function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean } = {}) { + let policy = { ...POLICY, ...(opts.policy ?? {}) }; + let polls = 0; + const runPolls = opts.runPolls ?? 0; + const iteration = { + n: 3, + kind: "revise-report", + model: "claude-sonnet-5-5", + status: opts.end ?? "done", + parent: 2, + copyOf: null, + usage: { "claude-sonnet-5-5": { usd: 0.42, inputTokens: 1, outputTokens: 1 }, "claude-haiku-4-5": { usd: 0.03, inputTokens: 1, outputTokens: 1 } }, + ops: { applied: [{ op: "drop" }, { op: "title" }], refused: [{ op: "merge", why: "finding 9 does not exist" }] }, + minutes: 2.5, + checks: [ + { name: "strict-quotes", ok: true }, + { name: "verify-quotes", ok: false, detail: "1 inexact (an old quote)" }, + ], + steps: [], + ...(opts.iteration ?? {}), + }; + const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; + const fake = fakeEditor((s) => { + const u = new URL(s.url); + if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } }; + if (u.pathname === "/api/ops/settings" && s.method === "POST") { + const routes = (s.body as { patch: { generation: { routes: Record<string, string> } } }).patch.generation.routes; + const presets: Record<string, string> = { "code,code,code,code": "code", "api,api,api,api": "api", "local,local,local,local": "local", "code,api,local,local": "balanced" }; + policy = { ...policy, routes: routes as typeof policy.routes, preset: presets[Object.values(routes).join(",")] ?? "custom" }; + return { status: 200, body: { ok: true, changed: ["generation"], value: { generation: policy } } }; + } + if (u.pathname === "/api/ops/generation-usage") return { status: 200, body: { ok: true, day: "2026-10-13", usd: 1.75, jobs: 2, daily: 20 } }; + if (u.pathname === "/api/ops/report-draft") return { status: 200, body: { ok: true, jobId: "job-1", iteration: 3 } }; + if (u.pathname === "/api/ops/job/job-1") { + polls++; + const status = polls > runPolls ? (opts.end ?? "done") : "running"; + const tail = status === "running" ? [`turn ${polls}: reading`] : ["applying ops", ...(opts.marker === false ? [] : [marker])]; + return { status: 200, body: { ok: true, job: { id: "job-1", kind: "report-draft", status }, tail } }; + } + if (u.pathname === "/api/ops/iterations") { + return { + status: 200, + body: { + ok: true, + article: "synth-a", + iteration, + dir: "/srv/t/reports/synth-a/iterations/3", + files: { + "report.json": "/srv/t/reports/synth-a/iterations/3/report.json", + "sweep.md": "/srv/t/reports/synth-a/iterations/3/sweep.md", + "turns.jsonl": "/srv/t/reports/synth-a/iterations/3/turns.jsonl", + "proposals.json": null, + }, + }, + }; + } + return { status: 404, body: { ok: false, error: `no route ${u.pathname}` } }; + }); + // A clock that a sleep advances. + let clock = 0; + fake.deps.now = () => clock; + fake.deps.sleep = async (ms: number) => { + clock += ms; + }; + return { ...fake, sentOf: (path: string) => fake.sent.filter((x: Sent) => new URL(x.url).pathname === path) }; +} + +test("generation_policy reads the routes, models, caps and the day's spend — never the key file or other settings", async () => { + const e = editor(); + const a = await generationPolicyTool({}, e.deps as never); + assert.equal(a.isError, undefined, a.text); + assert.match(a.text, /preset \*\*balanced\*\*/); + assert.match(a.text, /- sweep → code \(this Claude Code session\)/); + assert.match(a.text, /- revise-report → api \(the Claude API, claude-sonnet-5-5\)/); + assert.match(a.text, /- narrate → local \(the local model, qwen3:8b\)/); + assert.match(a.text, /extractor claude-haiku-4-5/); + assert.match(a.text, /sweep \$5\.00 · revision \$2\.00 · narration \$1\.00 · any job at most \$10\.00 · daily \$20\.00/); + assert.match(a.text, /Today \(2026-10-13, UTC\): \$1\.75 spent on the Claude API in 2 job\(s\) of the \$20\.00 daily cap/); + assert.doesNotMatch(a.text, /redacted|apiKey|anthropic\.env|projects-root-never-shown/); + assert.deepEqual(e.sentOf("/api/ops/settings").map((s) => s.url), ["http://editor.test/api/ops/settings?key=generation"]); + // Nothing written by a read. + assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); +}); + +test("generation_policy sets a preset as its routes, and one route alone", async () => { + const e = editor(); + const a = await generationPolicyTool({ preset: "api" }, e.deps as never); + assert.equal(a.isError, undefined, a.text); + const post = e.sentOf("/api/ops/settings").find((s) => s.method === "POST")!; + assert.deepEqual(post.body, { + patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api" } } }, + }); + assert.match(a.text, /^Set preset api\./); + assert.match(a.text, /preset \*\*api\*\*/); + + const one = await generationPolicyTool({ task: "sweep", route: "local" }, e.deps as never); + const post2 = e.sentOf("/api/ops/settings").filter((s) => s.method === "POST")[1]; + // The whole routes object (the writer merges one level; a nested object replaces). + assert.deepEqual(post2.body, { + patch: { generation: { routes: { sweep: "local", "revise-report": "api", "revise-video": "api", narrate: "api" } } }, + }); + assert.match(one.text, /^Routed sweep to local\./); + assert.match(one.text, /preset \*\*custom\*\*/); +}); + +test("generation_policy refuses a muddle before it asks the editor", async () => { + const e = editor(); + for (const [args, re] of [ + [{ preset: "api", task: "sweep", route: "api" }, /not both/], + [{ task: "sweep" }, /names both task and route/], + [{ preset: "cheap" }, /preset is one of code, balanced, api, local/], + [{ task: "sweep", route: "cloud" }, /route is one of code, api, local/], + ] as const) { + const a = await generationPolicyTool(args as Record<string, unknown>, e.deps as never); + assert.equal(a.isError, true); + assert.match(a.text, re); + } + assert.equal(e.sent.length, 0); + const unknown = await generationPolicyTool({ task: "teaser", route: "api" }, e.deps as never); + assert.match(unknown.text, /no task "teaser" — the policy routes sweep, revise-report, revise-video, narrate/); + assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); + const none = await generationPolicyTool({}, fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never); + assert.equal(none.isError, true); + assert.match(none.text, /ARCHILYZER_EDITOR_URL.*WORKER_TOKEN/); +}); + +test("generate: a task routed to code is this session's — nothing is enqueued", async () => { + const e = editor(); + const a = await generateTool({ task: "sweep", article: "synth-a", question: "q?", channels: ["synth-kitchen"] }, e.deps as never); + assert.equal(a.isError, true); + assert.match(a.text, /sweep is routed to Claude Code \(preset balanced\) — do it in this session/); + assert.equal(e.sentOf("/api/ops/report-draft").length, 0); + // via overrides it, with the route's model. + const b = await generateTool({ task: "sweep", article: "synth-a", question: "q?", channels: ["synth-kitchen"], via: "api" }, e.deps as never); + assert.equal(b.isError, undefined, b.text); + assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { + task: "sweep", + article: "synth-a", + question: "q?", + channels: ["synth-kitchen"], + model: "claude-sonnet-5-5", + }); + assert.match(b.text, /queued as job job-1, making synth-a i3 on claude-sonnet-5-5\. .*generate \(job: "job-1", article: "synth-a", iteration: 3, wait: true\)/); +}); + +test("generate: enqueue, follow politely, and summarise the iteration with what to review", async () => { + const e = editor({ runPolls: 3 }); + const progress: string[] = []; + const a = await generateTool( + { task: "revise-report", article: "synth-a", iteration: 2, feedback: "Drop the second finding.", wait: true }, + e.deps as never, + (p) => { + progress.push(p.status); + }, + ); + assert.equal(a.isError, false, a.text); + // The route's model is the editor's to pick: no model sent. + assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { + task: "revise-report", + article: "synth-a", + iteration: 2, + feedback: "Drop the second finding.", + }); + assert.deepEqual(progress, ["running: turn 1: reading", "running: turn 2: reading", "running: turn 3: reading"]); + assert.match(a.text, /^generate: revise-report of synth-a i3 — \*\*done\*\* on claude-sonnet-5-5 \(job job-1\)/); + assert.match(a.text, /2 op\(s\) applied, 1 refused/); + assert.match(a.text, /Cost: \$0\.45 \(claude-sonnet-5-5 \$0\.42, claude-haiku-4-5 \$0\.03\) · 2\.5 min/); + assert.match(a.text, /Ops: 2 applied, 1 refused\n {2}- refused merge: finding 9 does not exist/); + assert.match(a.text, /Checks: 1 passed, 1 not\n {2}- verify-quotes: 1 inexact/); + assert.match(a.text, /sweep\.md: \/srv\/t\/reports\/synth-a\/iterations\/3\/sweep\.md/); + assert.doesNotMatch(a.text, /turns\.jsonl/); + assert.match(a.text, /Review it — you are the reviewer/); + assert.match(a.text, /`get_transcript`/); + assert.match(a.text, /Use this iteration/); + // Polite: one poll per GENERATE_POLL_MS; the iteration read once at the end. + assert.equal(e.sentOf("/api/ops/job/job-1").length, 5); + assert.equal(e.sentOf("/api/ops/iterations").length, 1); + assert.equal(new URL(e.sentOf("/api/ops/iterations")[0].url).search, "?article=synth-a&n=3"); +}); + +test("generate: a wait that runs out answers how to resume; resuming summarises", async () => { + const e = editor({ runPolls: 1000 }); + const a = await generateTool( + { task: "revise-video", article: "synth-a", iteration: 2, feedback: "Shorter.", wait: true, wait_seconds: 12 }, + e.deps as never, + ); + assert.equal(a.isError, undefined, a.text); + assert.match(a.text, /Still running after 15s\. Last log line: turn 4: reading/); + assert.match(a.text, /generate again with job: "job-1", article: "synth-a", iteration: 3 to keep waiting — never start the same task again/); + assert.equal(e.sentOf("/api/ops/job/job-1").length, Math.floor((12 * 1000) / GENERATE_POLL_MS) + 2); + + const done = editor(); + const b = await generateTool({ job: "job-1" }, done.deps as never); + assert.equal(b.isError, false, b.text); + assert.equal(done.sentOf("/api/ops/report-draft").length, 0); + assert.match(b.text, /revise-report of synth-a i3 — \*\*done\*\*/); +}); + +test("generate: a failed job says why, with its log; a job whose log names no iteration still answers", async () => { + const e = editor({ end: "failed", iteration: { status: "failed", error: "the daily cap" } }); + const a = await generateTool({ job: "job-1" }, e.deps as never); + assert.equal(a.isError, true); + assert.match(a.text, /\*\*failed\*\*/); + assert.match(a.text, /error: the daily cap/); + assert.match(a.text, /last log lines:\n```\napplying ops\n```/); + assert.match(a.text, /Running it again, or here instead, is their call/); + + const bare = editor({ marker: false }); + const b = await generateTool({ job: "job-1" }, bare.deps as never); + assert.match(b.text, /its log names no iteration \(pass article and iteration to read it\)/); + const named = await generateTool({ job: "job-1", article: "synth-a", iteration: 3 }, editor({ marker: false }).deps as never); + assert.match(named.text, /of synth-a i3 — \*\*done\*\*/); +}); + +test("generate: the arguments are checked before any request; research is a task", () => { + assert.ok(GENERATE_TASKS.includes("research")); + const ok = validateGenerateArgs({ task: "research", article: "synth-a", question: "what was said?", channels: ["synth-kitchen"] }); + assert.equal(ok.ok, true); + for (const [args, re] of [ + [{ task: "teaser", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research/], + [{ task: "sweep", article: "Not An Id" }, /article is an article id/], + [{ task: "sweep", article: "a", channels: [] }, /channels is a non-empty list/], + [{ task: "sweep", article: "a", iteration: 0 }, /iteration is an iteration number/], + [{ task: "sweep", article: "a", maxUsd: -1 }, /maxUsd is a positive number/], + [{ task: "sweep", article: "a", via: "code" }, /via is "api" or "local"/], + [{ task: "sweep", article: "a", via: "api", model: "x" }, /model or via, not both/], + [{ task: "sweep", article: "a", wait_seconds: -2 }, /wait_seconds/], + [{ job: "../etc" }, /is not a job id/], + ] as const) { + const v = validateGenerateArgs(args as Record<string, unknown>); + assert.equal(v.ok, false, JSON.stringify(args)); + assert.match((v as { error: string }).error, re); + } +}); + +test("resultMarkerOf reads the job's @@report-draft line", () => { + assert.deepEqual(resultMarkerOf(["x", '@@report-draft {"article":"a","iteration":2}', "y"]), { article: "a", iteration: 2 }); + assert.equal(resultMarkerOf(["nothing here"]), null); +}); + +test("planGeneration: the policy when the editor answers; nothing without an editor; a note when it fails", async () => { + const p = await planGeneration(editor().deps as never); + assert.deepEqual(p.generation, { + preset: "balanced", + routes: POLICY.routes, + models: { api: "claude-sonnet-5-5", local: "qwen3:8b" }, + }); + assert.deepEqual(await planGeneration(fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never), {}); + const down = await planGeneration(fakeEditor(() => new TypeError("fetch failed")).deps as never); + assert.match(down.note!, /the generation policy could not be read \(.*did not answer: fetch failed\) — this plan is for this session/); +}); + +test("the server serves both tools, and sweep_plan routes by the policy it reads", async () => { + const routed = editor({ policy: { routes: { ...POLICY.routes, sweep: "api" }, preset: "custom" } }); + const client = await connectWith(routed.deps); + const policy = await client.callTool({ name: "generation_policy", arguments: {} }); + assert.equal(isError(policy), false, textOf(policy)); + assert.match(textOf(policy), /- sweep → api/); + const plan = await client.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } }); + const text = textOf(plan); + assert.match(text, /^A \*\*corpus sweep\*\* for "coffee", scoped to channels "demo" — \*\*routed to the Claude API\*\*/); + assert.match(text, /1\. \*\*Generate — do not sweep it yourself\.\*\*.*Call `generate` with task: "sweep"/); + assert.match(text, /channels: \["demo"\], model: "claude-sonnet-5-5", wait: true/); + assert.doesNotMatch(text, /enumerate_matches/); + + const local = await connectWith(editor().deps); + const unrouted = textOf(await local.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } })); + assert.match(unrouted, /^Run a \*\*corpus sweep\*\*/); + assert.match(unrouted, /`enumerate_matches`/); + + const down = await connectWith(fakeEditor(() => new TypeError("fetch failed")).deps); + const fallback = textOf(await down.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } })); + assert.match(fallback, /^Run a \*\*corpus sweep\*\*/); + assert.match(fallback, /the generation policy could not be read/); + + const gen = await client.callTool({ name: "generate", arguments: { task: "sweep", article: "synth-a", question: "q?", channels: ["demo"] } }); + assert.equal(isError(gen), false, textOf(gen)); + assert.match(textOf(gen), /queued as job job-1/); +}); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -0,0 +1,608 @@ +import { + GENERATION_PRESETS, + GENERATION_PRESET_NAMES, + GENERATION_ROUTES, + GENERATION_TASKS, + type GenerationPreset, +} from "yt-dlp-transcript-common/lib/generationSettings"; +import { describeEditorFailure, editorGet, editorPost, type EditorAnswer } from "./editorOps"; +import type { FetchClipDeps, PollProgress } from "./fetchClip"; +import { reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions"; +import type { ToolAnswer } from "./archivalTools"; + +// ─── The Claude Code balance (release 27 S9; D8) ─── +// +// Report and video generation runs in the editor, as `report-draft` jobs on +// the Claude API or the local model, routed per task by settings.generation. +// These two tools are Claude Code's side of that balance: +// +// generation_policy GET /api/ops/settings?key=generation (the routes) +// GET /api/ops/generation-usage (the day's spend) +// POST /api/ops/settings {patch: {generation: {routes}}} +// — a preset or one route, ONLY when the operator asks +// generate POST /api/ops/report-draft (enqueue) +// GET /api/ops/job/<id>?tail=N (follow) +// GET /api/ops/iterations?article=&n= (the result) +// +// The release 19 ruling keeps settings out of the MCP; D8 (ratified +// 2026-10-13) makes the generation ROUTES the one exception, so the operator +// can move the balance from a Claude Code session. Nothing else in settings is +// reachable, and the API key never is: it is not a setting (only its file's +// path is, and the editor redacts that), and this module renders neither. +// +// Pure apart from the injected deps (env, fetch, sleep, now); server.ts adapts. + +export type GenerationDeps = FetchClipDeps; + +// The policy as the editor answers it (sanitizeGeneration's output). +export type GenerationPolicy = PlanGeneration & { + models: { api: string; local: string; extractor?: string }; + caps?: { sweep?: number; revision?: number; narration?: number; daily?: number; max?: number }; +}; +export type GenerationUsageDay = { day: string; usd: number; jobs: number; daily: number }; + +// The tasks `generate` takes: the policy's, and `research` (S11 makes it run; +// the editor refuses it until then, in its own words). +export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS, "research"])]; + +const ARTICLE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; +const JOB_RE = /^[A-Za-z0-9_-]+$/; +const trimmed = (v: unknown) => (typeof v === "string" ? v.trim() : ""); + +const isRoute = (v: unknown): v is GenerationRoute => + typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v); + +// The editor's `generation` block, or why not. +function policyOf(value: unknown): GenerationPolicy | null { + if (!value || typeof value !== "object") return null; + const v = value as Record<string, unknown>; + const routes = v.routes && typeof v.routes === "object" ? (v.routes as Record<string, unknown>) : null; + const models = v.models && typeof v.models === "object" ? (v.models as Record<string, unknown>) : null; + if (!routes || !models || typeof models.api !== "string" || typeof models.local !== "string") return null; + const r: Record<string, GenerationRoute> = {}; + for (const [task, route] of Object.entries(routes)) if (isRoute(route)) r[task] = route; + return { + preset: typeof v.preset === "string" ? v.preset : "custom", + routes: r, + models: { + api: models.api, + local: models.local, + ...(typeof models.extractor === "string" ? { extractor: models.extractor } : {}), + }, + ...(v.caps && typeof v.caps === "object" ? { caps: v.caps as GenerationPolicy["caps"] } : {}), + }; +} + +export async function readPolicy( + deps: GenerationDeps, +): Promise<{ ok: true; policy: GenerationPolicy } | { ok: false; answer: Exclude<EditorAnswer, { kind: "ok" }> | null }> { + const a = await editorGet(deps, "/api/ops/settings?key=generation"); + if (a.kind !== "ok") return { ok: false, answer: a }; + const policy = policyOf(a.body.value); + return policy ? { ok: true, policy } : { ok: false, answer: null }; +} + +async function readUsage(deps: GenerationDeps): Promise<GenerationUsageDay | string> { + const a = await editorGet(deps, "/api/ops/generation-usage"); + if (a.kind !== "ok") return describeEditorFailure("the day's spend", a); + const b = a.body; + if (typeof b.usd !== "number" || typeof b.day !== "string") return "the day's spend: the editor's answer carried none"; + return { day: b.day, usd: b.usd, jobs: Number(b.jobs) || 0, daily: Number(b.daily) || 0 }; +} + +// What a plan needs: the policy when the editor answers, else nothing (with a +// note when an editor was configured and did not answer). +export async function planGeneration(deps: GenerationDeps): Promise<{ generation?: PlanGeneration; note?: string }> { + const r = await readPolicy(deps); + if (r.ok) return { generation: { preset: r.policy.preset, routes: r.policy.routes, models: { api: r.policy.models.api, local: r.policy.models.local } } }; + if (r.answer?.kind === "no_editor") return {}; + return { + note: + `the generation policy could not be read (${r.answer ? describeEditorFailure("generation_policy", r.answer) : "the editor's answer carried no generation block"}) — ` + + `this plan is for this session`, + }; +} + +const usd = (n: number) => `$${n.toFixed(2)}`; + +export function renderPolicy(p: GenerationPolicy, usage: GenerationUsageDay | string | null, changed?: string): string { + const lines: string[] = []; + if (changed) lines.push(changed, ""); + lines.push(`Generation policy (settings.generation): preset **${p.preset}**`); + for (const [task, route] of Object.entries(p.routes)) { + lines.push( + `- ${task} → ${route}` + + (route === "code" ? " (this Claude Code session)" : ` (${route === "api" ? "the Claude API" : "the local model"}, ${p.models[route]})`), + ); + } + lines.push( + `Models: api ${p.models.api} · local ${p.models.local}${p.models.extractor ? ` · extractor ${p.models.extractor}` : ""}`, + ); + const c = p.caps; + if (c) { + const parts = [ + c.sweep !== undefined ? `sweep ${usd(c.sweep)}` : "", + c.revision !== undefined ? `revision ${usd(c.revision)}` : "", + c.narration !== undefined ? `narration ${usd(c.narration)}` : "", + c.max !== undefined ? `any job at most ${usd(c.max)}` : "", + c.daily !== undefined ? (c.daily > 0 ? `daily ${usd(c.daily)}` : "no daily cap") : "", + ].filter(Boolean); + if (parts.length) lines.push(`Caps (Claude API, per job unless said): ${parts.join(" · ")}`); + } + if (typeof usage === "string") lines.push(`Today's spend: unknown (${usage})`); + else if (usage) { + lines.push( + `Today (${usage.day}, UTC): ${usd(usage.usd)} spent on the Claude API in ${usage.jobs} job(s)` + + (usage.daily > 0 ? ` of the ${usd(usage.daily)} daily cap` : ""), + ); + } + lines.push( + "", + "A task routed to api or local: call generate (wait: true) and REVIEW what it makes. " + + "A task routed to code: do it in this session (/sweep for a report). " + + "Change the routes only when the operator asks (generation_policy with preset, or task and route).", + ); + return lines.join("\n"); +} + +// ─── generation_policy ─── + +export async function generationPolicyTool(args: Record<string, unknown>, deps: GenerationDeps): Promise<ToolAnswer> { + const preset = trimmed(args.preset); + const task = trimmed(args.task); + const route = trimmed(args.route); + if (preset && (task || route)) { + return { text: "generation_policy: give a preset, or a task and its route — not both", isError: true }; + } + if ((task && !route) || (route && !task)) { + return { text: "generation_policy: a route change names both task and route (code, api or local)", isError: true }; + } + if (preset && !(GENERATION_PRESET_NAMES as string[]).includes(preset)) { + return { text: `generation_policy: preset is one of ${GENERATION_PRESET_NAMES.join(", ")}`, isError: true }; + } + if (route && !isRoute(route)) { + return { text: `generation_policy: route is one of ${GENERATION_ROUTES.join(", ")}`, isError: true }; + } + const read = await readPolicy(deps); + if (!read.ok) { + return { + text: read.answer ? describeEditorFailure("generation_policy", read.answer) : "generation_policy: the editor's answer carried no generation block", + isError: true, + }; + } + const policy = read.policy; + if (!preset && !task) return { text: renderPolicy(policy, await readUsage(deps)) }; + + if (task && !Object.hasOwn(policy.routes, task)) { + return { text: `generation_policy: no task "${task}" — the policy routes ${Object.keys(policy.routes).join(", ")}`, isError: true }; + } + // The ROUTES are the truth (S6): a preset is written as its routes, and the + // preset is read back from them. The patch names the whole routes object — + // the settings writer merges one level, so a nested object replaces. + const routes: Record<string, GenerationRoute> = preset + ? { ...policy.routes, ...GENERATION_PRESETS[preset as GenerationPreset] } + : { ...policy.routes, [task]: route as GenerationRoute }; + const a = await editorPost(deps, "/api/ops/settings", { patch: { generation: { routes } } }); + if (a.kind !== "ok") return { text: describeEditorFailure("generation_policy", a), isError: true }; + const saved = policyOf((a.body.value as Record<string, unknown> | undefined)?.generation) ?? { ...policy, routes }; + const what = preset ? `Set preset ${preset}.` : `Routed ${task} to ${route}.`; + return { text: renderPolicy(saved, await readUsage(deps), what) }; +} + +// ─── generate ─── + +export const GENERATE_POLL_MS = 5000; +export const DEFAULT_GENERATE_WAIT_SECONDS = 90; +export const MAX_GENERATE_WAIT_SECONDS = 300; +const RESULT_MARKER = "@@report-draft "; +const SUMMARY_TAIL = 60; + +type Body = Record<string, unknown>; + +export type GenerateRequest = + | { kind: "start"; body: Body; via?: "api" | "local"; wait: boolean; waitSeconds: number } + | { kind: "resume"; job: string; article?: string; iteration?: number; waitSeconds: number }; + +function waitSecondsOf(v: unknown): number | null { + if (v === undefined) return DEFAULT_GENERATE_WAIT_SECONDS; + if (typeof v !== "number" || !Number.isFinite(v) || v < 0) return null; + return Math.min(MAX_GENERATE_WAIT_SECONDS, Math.round(v)); +} + +// The arguments, checked as far as the tool can say without asking; the +// editor judges the rest (controller/reportDraft.ts parseReportDraftBody). +export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; request: GenerateRequest } | { ok: false; error: string } { + const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` }); + const waitSeconds = waitSecondsOf(args.wait_seconds); + if (waitSeconds === null) return bad("wait_seconds is a number of seconds, 0 or more"); + const intOf = (k: string): number | undefined | null => { + const v = args[k]; + if (v === undefined) return undefined; + return typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : null; + }; + const job = trimmed(args.job); + if (job) { + if (!JOB_RE.test(job)) return bad(`"${job}" is not a job id`); + const article = trimmed(args.article); + if (article && !ARTICLE_RE.test(article)) return bad(`"${article}" is not an article id`); + const iteration = intOf("iteration"); + if (iteration === null) return bad("iteration is an iteration number (1, 2, …)"); + return { + ok: true, + request: { kind: "resume", job, ...(article ? { article } : {}), ...(iteration ? { iteration } : {}), waitSeconds }, + }; + } + const task = trimmed(args.task); + if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`); + const article = trimmed(args.article); + if (!ARTICLE_RE.test(article)) return bad("article is an article id (a lowercase slug: a-z, 0-9, -)"); + const body: Body = { task, article }; + for (const k of ["iteration", "copyOf"] as const) { + const n = intOf(k); + if (n === null) return bad(`${k} is an iteration number (1, 2, …)`); + if (n !== undefined) body[k] = n; + } + for (const k of ["model", "feedback", "question", "from", "to"] as const) { + if (args[k] === undefined) continue; + const v = trimmed(args[k]); + if (!v) return bad(`${k} is text`); + body[k] = v; + } + for (const k of ["channels", "cards"] as const) { + if (args[k] === undefined) continue; + const v = args[k]; + if (!Array.isArray(v) || v.length === 0 || v.some((x) => typeof x !== "string" || !x.trim())) { + return bad(`${k} is a non-empty list of names`); + } + body[k] = v.map((x: string) => x.trim()); + } + if (args.maxUsd !== undefined) { + if (typeof args.maxUsd !== "number" || !(args.maxUsd > 0)) return bad("maxUsd is a positive number of dollars"); + body.maxUsd = args.maxUsd; + } + if (args.force !== undefined) { + if (typeof args.force !== "boolean") return bad("force is true or false"); + body.force = args.force; + } + let via: "api" | "local" | undefined; + if (args.via !== undefined) { + const v = trimmed(args.via); + if (v !== "api" && v !== "local") return bad('via is "api" or "local" (a task routed to code is this session\'s)'); + if (body.model) return bad("give model or via, not both"); + via = v; + } + if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false"); + return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } }; +} + +type JobView = { id: string; status: string; kind?: string; detail?: string; queue?: { key: string; position: number; queued: number } }; +type Followed = + | { kind: "ended"; job: JobView; tail: string[] } + | { kind: "waiting"; job: JobView; waited: number; last?: string } + | { kind: "error"; text: string }; + +const ENDED = new Set(["done", "failed", "cancelled"]); + +async function jobOnce(deps: GenerationDeps, id: string, tail: number): Promise<{ job: JobView; tail: string[] } | { error: string }> { + const a = await editorGet(deps, `/api/ops/job/${encodeURIComponent(id)}?tail=${tail}`); + if (a.kind === "refused" && a.status === 404) return { error: `generate: the editor knows no job ${id}` }; + if (a.kind !== "ok") return { error: `${describeEditorFailure("generate", a)} (job ${id} keeps running on the editor; resume with job: "${id}")` }; + const job = a.body.job as JobView | undefined; + if (!job || typeof job.status !== "string") return { error: "generate: the editor's answer carried no job" }; + return { job, tail: Array.isArray(a.body.tail) ? (a.body.tail as unknown[]).map(String) : [] }; +} + +// Poll the job politely (every GENERATE_POLL_MS) until it ends or the wait +// runs out. A wait that runs out is not a failure: the job keeps running. +export async function followGeneration( + deps: GenerationDeps, + id: string, + waitSeconds: number, + onPoll?: (p: PollProgress) => void | Promise<void>, +): Promise<Followed> { + const started = deps.now(); + const deadline = started + waitSeconds * 1000; + const waited = () => Math.round((deps.now() - started) / 1000); + let polls = 0; + for (;;) { + const r = await jobOnce(deps, id, 1); + if ("error" in r) return { kind: "error", text: r.error }; + if (ENDED.has(r.job.status)) { + const full = await jobOnce(deps, id, SUMMARY_TAIL); + return "error" in full ? { kind: "ended", job: r.job, tail: r.tail } : { kind: "ended", job: full.job, tail: full.tail }; + } + const last = r.tail[r.tail.length - 1]; + if (deps.now() >= deadline) return { kind: "waiting", job: r.job, waited: waited(), ...(last ? { last } : {}) }; + polls++; + if (onPoll) { + try { + await onPoll({ jobId: id, status: last ? `${r.job.status}: ${last.slice(0, 120)}` : r.job.status, polls, waited: waited() }); + } catch { + /* a progress report is a courtesy */ + } + } + await deps.sleep(GENERATE_POLL_MS); + } +} + +type Marker = { article?: string; iteration?: number; task?: string; status?: string; summary?: string; usd?: number; minutes?: number }; + +export function resultMarkerOf(tail: readonly string[]): Marker | null { + for (let i = tail.length - 1; i >= 0; i--) { + const at = tail[i].indexOf(RESULT_MARKER); + if (at < 0) continue; + try { + return JSON.parse(tail[i].slice(at + RESULT_MARKER.length)) as Marker; + } catch { + return null; + } + } + return null; +} + +type IterationView = { + n: number; + kind: string; + model: string; + status: string; + error?: string; + parent: number | null; + copyOf: number | null; + usage: Record<string, { usd: number }>; + ops?: { applied: unknown[]; refused: unknown[] }; + minutes?: number; + checks?: { name: string; ok: boolean; detail?: string }[]; + steps?: { task: string; model?: string; status: string; cost?: number; jobId?: string; detail?: string }[]; + projectDir?: string; +}; + +const MAX_LISTED = 12; + +// A refused op as the tasks store it: the op's own fields plus `why`. +function opLine(o: unknown): string { + const r = (o ?? {}) as { op?: { op?: string } | string; why?: string }; + const name = typeof r.op === "string" ? r.op : (r.op?.op ?? "op"); + return `${name}${r.why ? `: ${r.why}` : ""}`; +} + +export function renderIterationSummary( + o: { task: string; article: string; jobId: string; marker: Marker | null; iteration: IterationView; dir?: string; files?: Record<string, string | null> }, +): string { + const it = o.iteration; + const step = o.task === "narrate" ? [...(it.steps ?? [])].reverse().find((s) => s.task === "narrate" && s.jobId === o.jobId) : undefined; + const status = step?.status ?? o.marker?.status ?? it.status; + const lines: string[] = []; + lines.push(`generate: ${o.task} of ${o.article} i${it.n} — **${status}** on ${step?.model ?? it.model} (job ${o.jobId})`); + if (o.marker?.summary) lines.push(o.marker.summary); + if (it.error && status !== "done") lines.push(`error: ${it.error}`); + if (step?.detail) lines.push(`narration: ${step.detail}`); + const per = Object.entries(it.usage ?? {}).filter(([, u]) => u.usd > 0); + const total = step ? (step.cost ?? 0) : per.reduce((s, [, u]) => s + u.usd, 0); + const minutes = o.marker?.minutes ?? it.minutes; + lines.push( + `Cost: ${usd(total)}` + + (!step && per.length > 1 ? ` (${per.map(([m, u]) => `${m} ${usd(u.usd)}`).join(", ")})` : "") + + (typeof minutes === "number" ? ` · ${minutes.toFixed(1)} min` : ""), + ); + if (it.ops) { + const refused = it.ops.refused ?? []; + lines.push(`Ops: ${it.ops.applied?.length ?? 0} applied, ${refused.length} refused`); + for (const r of refused.slice(0, MAX_LISTED)) lines.push(` - refused ${opLine(r)}`); + if (refused.length > MAX_LISTED) lines.push(` - … (+${refused.length - MAX_LISTED} more)`); + } + const checks = it.checks ?? []; + if (checks.length) { + const failing = checks.filter((c) => !c.ok); + lines.push(`Checks: ${checks.length - failing.length} passed, ${failing.length} not`); + for (const c of failing.slice(0, MAX_LISTED)) lines.push(` - ${c.name}${c.detail ? `: ${c.detail}` : ""}`); + if (failing.length > MAX_LISTED) lines.push(` - … (+${failing.length - MAX_LISTED} more)`); + } + if (o.dir) { + const present = Object.entries(o.files ?? {}).filter(([, p]) => p) as [string, string][]; + lines.push(`Where (the editor's disk): ${o.dir}`); + for (const [name, p] of present) if (name !== "turns.jsonl") lines.push(` - ${name}: ${p}`); + } + if (it.projectDir) lines.push(`Video project: ${it.projectDir}`); + if (status === "done") lines.push("", reviewGuidance()); + else if (status === "failed") lines.push("", "It failed: say why to the operator. Running it again, or here instead, is their call."); + return lines.join("\n"); +} + +async function summarise( + deps: GenerationDeps, + f: Extract<Followed, { kind: "ended" }>, + hint: { task?: string; article?: string; iteration?: number }, +): Promise<ToolAnswer> { + const marker = resultMarkerOf(f.tail); + const article = marker?.article ?? hint.article; + const n = marker?.iteration ?? hint.iteration; + const task = marker?.task ?? hint.task ?? "report-draft"; + const logTail = f.tail.filter((l) => !l.includes(RESULT_MARKER)).slice(-8); + if (!article || !n) { + return { + text: + `generate: job ${f.job.id} ended **${f.job.status}**${f.job.detail ? ` (${f.job.detail})` : ""}; its log names no iteration ` + + `(pass article and iteration to read it).` + + (logTail.length ? `\n\nlast log lines:\n\`\`\`\n${logTail.join("\n")}\n\`\`\`` : ""), + isError: f.job.status !== "done", + }; + } + const a = await editorGet(deps, `/api/ops/iterations?article=${encodeURIComponent(article)}&n=${n}`); + if (a.kind !== "ok") { + return { + text: `generate: job ${f.job.id} ended ${f.job.status}; ${article} i${n} could not be read: ${describeEditorFailure("generate", a)}`, + isError: true, + }; + } + const iteration = a.body.iteration as IterationView; + const text = renderIterationSummary({ + task, + article, + jobId: f.job.id, + marker, + iteration, + ...(typeof a.body.dir === "string" ? { dir: a.body.dir } : {}), + ...(a.body.files && typeof a.body.files === "object" ? { files: a.body.files as Record<string, string | null> } : {}), + }); + const failed = f.job.status !== "done"; + return { + text: failed && logTail.length ? `${text}\n\nlast log lines:\n\`\`\`\n${logTail.join("\n")}\n\`\`\`` : text, + isError: failed, + }; +} + +function waitingText(f: Extract<Followed, { kind: "waiting" }>, hint: { article?: string; iteration?: number }): string { + const q = f.job.queue; + const where = + f.job.status === "queued" && q && q.position > 0 ? ` (position ${q.position} of ${q.queued} on ${q.key})` : ""; + const resume = [`job: "${f.job.id}"`, hint.article ? `article: "${hint.article}"` : "", hint.iteration ? `iteration: ${hint.iteration}` : ""] + .filter(Boolean) + .join(", "); + return ( + `Still ${f.job.status}${where} after ${f.waited}s.` + + (f.last ? ` Last log line: ${f.last}` : "") + + `\nCall generate again with ${resume} to keep waiting — never start the same task again. ` + + `A sweep takes minutes; nothing is lost while you wait.` + ); +} + +export async function generateTool( + args: Record<string, unknown>, + deps: GenerationDeps, + onPoll?: (p: PollProgress) => void | Promise<void>, +): Promise<ToolAnswer> { + const v = validateGenerateArgs(args); + if (!v.ok) return { text: v.error, isError: true }; + const req = v.request; + + if (req.kind === "resume") { + const f = await followGeneration(deps, req.job, req.waitSeconds, onPoll); + if (f.kind === "error") return { text: f.text, isError: true }; + if (f.kind === "waiting") return { text: `generate: job ${req.job}. ${waitingText(f, req)}` }; + return summarise(deps, f, req); + } + + const body = { ...req.body }; + const task = String(body.task); + // Who runs it: the asked model, the asked route's model, else the policy's + // route — and a task routed to code is this session's, not the editor's. + if (!body.model) { + const read = await readPolicy(deps); + if (!read.ok) { + return { + text: read.answer ? describeEditorFailure("generate", read.answer) : "generate: the editor's answer carried no generation block", + isError: true, + }; + } + const p = read.policy; + if (req.via) body.model = p.models[req.via]; + else if (p.routes[task] === "code") { + return { + text: + `generate: ${task} is routed to Claude Code (preset ${p.preset}) — do it in this session ` + + `(sweep_plan for a sweep). Pass via: "api" or "local" only when the operator asks to run it elsewhere.`, + isError: true, + }; + } + } + const a = await editorPost(deps, "/api/ops/report-draft", body); + if (a.kind !== "ok") return { text: describeEditorFailure("generate", a), isError: true }; + const jobId = typeof a.body.jobId === "string" ? a.body.jobId : ""; + const n = typeof a.body.iteration === "number" ? a.body.iteration : undefined; + if (!jobId) return { text: `generate: the editor accepted it and started no job (${JSON.stringify(a.body)})`, isError: true }; + const article = String(body.article); + const head = + `generate ${task}: queued as job ${jobId}` + + (n ? `, ${task === "narrate" ? "narrating" : "making"} ${article} i${n}` : ` for ${article}`) + + (body.model ? ` on ${String(body.model)}` : " on the policy's model") + + "."; + if (!req.wait) { + return { + text: + `${head} It runs on the editor's draft queue. Follow it with generate (job: "${jobId}", article: "${article}"` + + `${n ? `, iteration: ${n}` : ""}, wait: true), or get_job.`, + }; + } + const f = await followGeneration(deps, jobId, req.waitSeconds, onPoll); + if (f.kind === "error") return { text: `${head}\n${f.text}`, isError: true }; + if (f.kind === "waiting") return { text: `${head}\n${waitingText(f, { article, ...(n ? { iteration: n } : {}) })}` }; + return summarise(deps, f, { task, article, ...(n ? { iteration: n } : {}) }); +} + +// ─── The tool definitions (server.ts's TOOLS takes them in order) ─── + +export const GENERATION_TOOLS = [ + { + name: "generation_policy", + description: + "The operator's generation balance (settings.generation, read from the local editor): for each " + + "generation task — sweep (a new cited report), revise-report, revise-video, narrate — whether this " + + "Claude Code session does it (code), the Claude API does it (api) or the local model does it " + + "(local), on which model; the spend caps; and the day's Claude API spend against the daily cap. " + + "With preset (code, balanced, api, local) it routes every task at once; with task and route it " + + "routes one — ONLY when the operator asks to move the balance. Never shows the API key. Needs " + + "ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", + inputSchema: { + type: "object", + properties: { + preset: { + type: "string", + enum: [...GENERATION_PRESET_NAMES], + description: "Route every task by this preset: code (all here), balanced, api, local.", + }, + task: { type: "string", description: "Route one task (with route): sweep, revise-report, revise-video, narrate." }, + route: { type: "string", enum: [...GENERATION_ROUTES], description: "Where that task runs." }, + }, + additionalProperties: false, + }, + }, + { + name: "generate", + description: + "Run a generation task on the local editor as a report-draft job — on the Claude API or the " + + "local model, by the policy's route (generation_policy) unless model or via says otherwise — and, " + + "with wait: true, follow it and return the iteration it made: status, cost, the ops applied and " + + "refused, the checks, and where its files are on the editor's disk. task sweep makes a new " + + "iteration of article from question over channels; revise-report and revise-video make one from " + + "iteration and feedback; narrate voices a done iteration's cut; research (when the editor supports " + + "it) searches, proposes acquisitions and sweeps. copyOf runs an iteration again on another model. " + + "A task routed to code is refused: do it in this session. The wait is bounded (wait_seconds, " + + "default 90, at most 300) and polite (one poll every 5 s, a progress notification each); if the " + + "job is still running it answers its id — call again with job (and article, iteration) to keep " + + "waiting; the job keeps running either way. Then REVIEW what it made before anything is made " + + "current. Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", + inputSchema: { + type: "object", + properties: { + task: { type: "string", enum: GENERATE_TASKS, description: "What to generate." }, + article: { type: "string", description: "The article id (a lowercase slug). A sweep may name a new one." }, + iteration: { + type: "integer", + minimum: 1, + description: "revise-report / revise-video: the iteration revised; narrate: the iteration voiced; with job: the iteration to summarise.", + }, + question: { type: "string", description: "sweep / research: the question, in words." }, + channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." }, + from: { type: "string", description: "sweep: only videos on or after this date (YYYY-MM-DD)." }, + to: { type: "string", description: "sweep: only videos on or before this date (YYYY-MM-DD)." }, + feedback: { type: "string", description: "A revision's feedback: what to change, concretely." }, + copyOf: { type: "integer", minimum: 1, description: "Run this iteration again (same kind and inputs) on model or via." }, + model: { type: "string", description: "The model to run on (else the route's)." }, + via: { type: "string", enum: ["api", "local"], description: "Run on this route's model instead of the policy's route — only when the operator asks." }, + maxUsd: { type: "number", description: "An API job's cap in USD (else the task's default; never above the settings' max)." }, + cards: { type: "array", items: { type: "string" }, description: "narrate: only these card ids." }, + force: { type: "boolean", description: "narrate: redraft cards that already have narration." }, + wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." }, + wait_seconds: { + type: "number", + description: `How long to follow it before answering with its job id (default ${DEFAULT_GENERATE_WAIT_SECONDS}, max ${MAX_GENERATE_WAIT_SECONDS}).`, + }, + job: { + type: "string", + description: "Resume: the job id an earlier call returned. Every argument but article, iteration and wait_seconds is then ignored.", + }, + }, + additionalProperties: false, + }, + }, +] as const; diff --git a/mcp/src/instructions.test.ts b/mcp/src/instructions.test.ts @@ -230,3 +230,91 @@ test("a sweep carries the narration hard rule: delivery, never the claims", () = assert.match(text, /own sentence after a colon lead-in/); assert.match(text, /serves Kokoro too/); }); + +// ─── Routing by the generation policy (release 27 S9) ─── + +const POLICY = (sweep: "code" | "api" | "local", rest: "code" | "api" | "local" = "code") => ({ + generation: { + preset: "custom", + routes: { sweep, "revise-report": rest, "revise-video": rest, narrate: rest }, + models: { api: "claude-sonnet-5-5", local: "qwen3:8b" }, + }, +}); + +test("a sweep routed to code (or with no policy) is the plan it always was", () => { + const plain = sweep("coffee channels=chan-a"); + assert.equal(sweep("coffee channels=chan-a", POLICY("code")), plain); + // via=code overrides a policy that routes it away. + assert.equal( + sweep("coffee channels=chan-a via=code", POLICY("api")), + sweep("coffee channels=chan-a via=code"), + ); + assert.match(plain, /`enumerate_matches`/); +}); + +test("a sweep routed to api or local: the first step is generate, then the review", () => { + const text = sweep("coffee channels=chan-a article=coffee-claims", POLICY("api")); + assert.match(text, /— \*\*routed to the Claude API\*\* \(the generation policy, preset custom\)/); + const steps = text.split(/\n\n(?=\d+\. )/).slice(1); + assert.match(steps[0], /^1\. \*\*Generate — do not sweep it yourself\.\*\*/); + assert.match( + steps[0], + /Call `generate` with task: "sweep", article: "coffee-claims", question: "coffee", channels: \["chan-a"\], model: "claude-sonnet-5-5", wait: true/, + ); + assert.match(steps[0], /never enqueue the same sweep twice/); + assert.match(steps[1], /^2\. \*\*Review it — you are the reviewer, not the author\.\*\*/); + assert.match(steps[1], /`get_transcript` \(source: "remote:https:\/\/site\.example", /); + assert.match(steps[1], /\*\*make it current\*\*.*Use this iteration.*\*\*revise\*\*/); + assert.match(steps[2], /^3\. \*\*Report back\.\*\*/); + // The sweep engine's steps are not in it. + assert.doesNotMatch(text, /enumerate_matches|DUMB EXTRACTOR/); + + const local = sweep("coffee channels=chan-a", POLICY("local")); + assert.match(local, /routed to the local model/); + assert.match(local, /model: "qwen3:8b"/); + assert.match(local, /article: "<a new article id/); + // via=local with no policy at all still routes, by route name. + const via = sweep("coffee channels=chan-a via=local"); + assert.match(via, /routed to the local model\*\* \(via=local\)/); + assert.match(via, /channels: \["chan-a"\], via: "local", wait: true/); +}); + +test("a routed sweep still stops on an unknown scope, and asks for one not given", () => { + const halted = sweep("coffee channels=ghost", { ...POLICY("api"), unknownChannels: ["ghost"] }); + assert.match(halted, /1\. \*\*Fix the scope first\.\*\*/); + assert.doesNotMatch(halted, /`generate`/); + const open = sweep("coffee", POLICY("api")); + assert.match(open, /1\. \*\*Generate/); + assert.match(open, /channels: \[<the slugs I choose>\]/); + assert.match(open, /2\. \*\*Choose the scope first/); + const report = sweep("coffee channels=a report=./out.md", POLICY("api")); + assert.match(report, /The report lands in the iteration, not at `\.\/out\.md`/); +}); + +test("ask: answered here whatever the policy; the routed tasks are named", () => { + const plain = ask("what did they say about coffee"); + assert.equal(ask("what did they say about coffee", POLICY("code")), plain); + const routed = ask("what did they say about coffee", POLICY("code", "local")); + assert.match(routed, /\*\*Generation goes by the policy\.\*\* This answer is yours to give here\./); + assert.match(routed, /revise-report → local \(qwen3:8b\), revise-video → local \(qwen3:8b\), narrate → local \(qwen3:8b\) \(preset custom\)/); + assert.doesNotMatch(routed, /sweep → /); + assert.match(routed, /call `generate` \(wait: true\) and review/); +}); + +test("every tool a routed plan names exists", () => { + const known = new Set(TOOLS.map((t) => t.name)); + const texts = [ + sweep("coffee channels=chan-a", POLICY("api")), + sweep("https://site.example/?q=a follow this", POLICY("local")), + ask("what about coffee", POLICY("api", "api")), + ]; + const NOT_TOOLS = new Set(["dry_run", "moment_base", "date_from", "date_to", "media_type", "link_style", "content_types", "max_pages"]); + for (const text of texts) { + for (const m of text.matchAll(/`([a-z][a-z0-9]*(?:_[a-z0-9]+)*)`/g)) { + const name = m[1]; + if (!name.includes("_") && name !== "generate") continue; + if (NOT_TOOLS.has(name)) continue; + assert.ok(known.has(name), `a routed plan names a nonexistent tool: ${name}`); + } + } +}); diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -34,6 +34,19 @@ export type PlanContext = { availableGroups?: { id: string; name: string; channels: number }[]; // Extra notes to surface (e.g. a decoded link's plan). notes?: string[]; + // The generation policy (settings.generation), read from the editor at plan + // time (release 27 S9). Absent when there is no editor to ask: the plan is + // then this session's, as it always was. + generation?: PlanGeneration; +}; + +export type GenerationRoute = "code" | "api" | "local"; + +// What a plan needs of the policy: who does each task, and on what model. +export type PlanGeneration = { + preset: string; + routes: Record<string, GenerationRoute>; + models: { api: string; local: string }; }; function quoted(xs: string[]): string { @@ -205,16 +218,173 @@ function archiveStep(): string { `by the day they were recorded). The operator's notes on articles and ` + `video projects: \`notes\` (list, read; reply — after editing the note's ` + `source and regenerating — writes the reply in umtool as the agent's). ` + - `Settings, storage and deletes are not reachable from here — name the ` + + `Settings (but for the generation routes \`generation_policy\` sets when ` + + `I ask), storage and deletes are not reachable from here — name the ` + `\`pnpm ops\` command instead.` ); } +// ─── Routing by the generation policy (release 27 S9; D8) ─── +// +// settings.generation routes each generation task to `code` (this session), +// `api` (the Claude API) or `local` (the local model). A sweep routed to api or +// local is NOT run here: the plan's first step calls `generate` (the editor's +// report-draft job), waits, and the rest is a REVIEW of what it made. Routed to +// code — or with no policy to read — the plan is the one it always was. A +// request's `via=` overrides the policy for that one plan. + +export const ROUTE_WORDS: Record<Exclude<GenerationRoute, "code">, string> = { + api: "the Claude API", + local: "the local model", +}; + +// Where a task goes for this plan, and why. +export function routeFor( + task: string, + req: Pick<PromptRequest, "via">, + ctx: Pick<PlanContext, "generation">, +): { route: GenerationRoute; model?: string; by: string } { + if (req.via) { + const model = req.via === "code" ? undefined : ctx.generation?.models[req.via]; + return { route: req.via, ...(model ? { model } : {}), by: `via=${req.via}` }; + } + const g = ctx.generation; + const route = g?.routes[task]; + if (!g || !route || route === "code") return { route: "code", by: g ? `preset ${g.preset}` : "no policy" }; + return { route, model: g.models[route], by: `the generation policy, preset ${g.preset}` }; +} + +// The review of a generated iteration — the step Claude Code owns when the +// work itself was routed away. Shared by the routed plan and `generate`'s +// answer, so the two say the same thing. +export function reviewGuidance(corpus?: string): string { + const src = corpus ? `source: "${corpus}", ` : ""; + return ( + `**Review it — you are the reviewer, not the author.** When \`generate\` ` + + `reports the iteration done: (1) read the iteration's \`sweep.md\` end to ` + + `end (the path \`generate\` names; \`report.json\` is its converted form; ` + + `a video revision names its project instead). (2) Spot-check the quotes: ` + + `for at least five findings — every one when there are fewer, and always ` + + `the ones the conclusions rest on — call \`get_transcript\` (${src}the ` + + `cited video, timestamps on) around the cited second, and check the quote ` + + `is verbatim, the speaker is the one the claim names, and the claim says ` + + `no more than the words do. The strict check proved each generated quote is in the ` + + `transcript within ±90 s; nothing has checked attribution or reading. (3) ` + + `Read its checks and the ops it refused (\`generate\` lists them). (4) Tell ` + + `me in a few lines what is good and what is not, and recommend ONE of: ` + + `**make it current** — I do that in umtool (the article's Iterations tab, ` + + `"Use this iteration"), you do not unless I ask; or **revise** — call ` + + `\`generate\` with task "revise-report" (or "revise-video"), the article, ` + + `iteration: <n>, concrete feedback (which finding, what to change) and ` + + `wait: true, then review that iteration the same way. Never edit an ` + + `iteration's files by hand.` + ); +} + +// The generate call a routed sweep makes, with its scope settled. +function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; model?: string; by: string }): string { + const article = req.article + ? `article: "${req.article}"` + : `article: "<a new article id: a short lowercase slug you choose from the subject — a-z, 0-9, ->"`; + const question = req.query + ? `question: "${req.query}${req.directive ? ` — extract ${req.directive}` : ""}"` + : `question: "<the subject in words — decode the share link with \`open_link\` (dry_run: true) first>"`; + const channels = + req.channels.length > 0 + ? `channels: [${quoted(req.channels)}]` + : req.groups.length > 0 + ? `channels: [<the channel slugs of group(s) ${quoted(req.groups)}, from \`list_channels\`>]` + : `channels: [<the slugs I choose>]`; + const model = r.model ? `, model: "${r.model}"` : req.via && req.via !== "code" ? `, via: "${req.via}"` : ""; + return ( + `**Generate — do not sweep it yourself.** This sweep is routed to ` + + `${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}${r.model ? ` (${r.model})` : ""} by ${r.by}. ` + + `Call \`generate\` with task: "sweep", ${article}, ${question}, ${channels}${model}, ` + + `wait: true (add from/to, YYYY-MM-DD, when I named a period). The editor runs ` + + `it as a report-draft job on its own corpus build and caps; the article's ` + + `iteration is what it makes, never its published report. If the answer ` + + `says it is still running, call \`generate\` again with the job, article ` + + `and iteration it names and wait: true — never enqueue the same sweep ` + + `twice. If it is refused (the daily cap, no editor, no build holding the ` + + `channels), tell me why and stop: running it here instead is my call ` + + `(\`/sweep … via=code\`).` + + (req.reportPath + ? ` The report lands in the iteration, not at \`${req.reportPath}\`; copy it there only if I ask.` + : "") + ); +} + +function buildRoutedSweepInstructions( + req: PromptRequest, + ctx: PlanContext, + r: { route: GenerationRoute; model?: string; by: string }, +): string { + const subject = req.query ? `"${req.query}"` : req.link ? "the share link's search" : "the subject below"; + const scope = scopeSteps(req, ctx); + // A scope that did not resolve still stops everything; a scope not yet + // chosen is asked for inside the generate step's own words. + const steps: string[] = scope.halt + ? [...scope.steps] + : [ + generateSweepStep(req, r), + ...scope.steps, + reviewGuidance(ctx.corpus), + `**Report back.** Say which iteration it made, what it cost, how many ` + + `findings you checked and what you found, and your recommendation. ` + + `Keep every citation you quote clickable — \`[title @ mm:ss](url)\`.`, + ]; + const numbered = steps.map((s, i) => `${i + 1}. ${s}`).join("\n\n"); + const scopeNote = scopeProse(req); + const head = + `A **corpus sweep** for ${subject}` + + (scopeNote ? `, scoped to ${scopeNote}` : "") + + ` — **routed to ${r.route === "code" ? "Claude Code" : ROUTE_WORDS[r.route]}** (${r.by}). ` + + `You do not run this sweep: the editor does, as a report-draft job, and ` + + `your work is to start it, wait for it, and REVIEW what it made.\n\n` + + `**Corpus: \`${ctx.corpus}\`.** Pass \`source: "${ctx.corpus}"\` on every ` + + `read you make while reviewing.`; + const notes = + ctx.notes && ctx.notes.length > 0 + ? `\n\nContext already resolved for you:\n${ctx.notes.map((n) => `- ${n}`).join("\n")}` + : ""; + return renderWarnings(req.warnings) + `${head}${notes}\n\nFollow these steps:\n\n${numbered}`; +} + +// The ask variant's one addition: a question is answered here whatever the +// policy says (the policy routes generation tasks, and an answer in the +// conversation is not one), but the tasks it does route are named, so a +// follow-up ("make that a report") goes the right way. +function routedTasksStep(req: PromptRequest, ctx: PlanContext): string | null { + const g = ctx.generation; + const away = g + ? Object.entries(g.routes).filter(([t]) => routeFor(t, req, ctx).route !== "code") + : req.via && req.via !== "code" + ? [["sweep", req.via] as const] + : []; + if (away.length === 0) return null; + const list = away + .map(([t]) => { + const r = routeFor(t, req, ctx); + return `${t} → ${r.route}${r.model ? ` (${r.model})` : ""}`; + }) + .join(", "); + return ( + `**Generation goes by the policy.** This answer is yours to give here. ` + + `If I then ask for a report on it, a revision of an article or its video, ` + + `or narration, those are routed: ${list}${g ? ` (preset ${g.preset})` : ""}. ` + + `For a routed task call \`generate\` (wait: true) and review what it makes ` + + `— read its files, spot-check its quotes with \`get_transcript\` — instead ` + + `of doing the work yourself; a task routed to code is yours (\`/sweep\` for a report).` + ); +} + // The full sweep instructions. export function buildSweepInstructions( req: PromptRequest, ctx: PlanContext, ): string { + const routed = routeFor("sweep", req, ctx); + if (routed.route !== "code") return buildRoutedSweepInstructions(req, ctx, routed); const reportPath = req.reportPath ?? DEFAULT_REPORT_PATH; const directive = req.directive ?? DEFAULT_DIRECTIVE; const subject = req.query @@ -420,6 +590,9 @@ export function buildAskInstructions( steps.push(clipStep(ctx)); steps.push(archiveStep()); + + const routedTasks = routedTasksStep(req, ctx); + if (routedTasks) steps.push(routedTasks); } const numbered = steps.map((s, i) => `${i + 1}. ${s}`).join("\n\n"); diff --git a/mcp/src/promptRequest.test.ts b/mcp/src/promptRequest.test.ts @@ -325,3 +325,18 @@ test("a genuinely bad value is refused even from a form client", () => { ["report_path"], ); }); + +test("via= and article= (release 27 S9): routed plans", () => { + const r = parsePromptRequest("coffee channels=a via=API article=coffee-claims"); + assert.equal(r.via, "api"); + assert.equal(r.article, "coffee-claims"); + assert.equal(r.query, "coffee"); + assert.deepEqual(r.warnings, []); + assert.equal(parsePromptRequest("coffee route=local").via, "local"); + const bad = parsePromptRequest("coffee via=cloud article=Not_An_Id"); + assert.equal(bad.via, undefined); + assert.equal(bad.article, undefined); + assert.equal(bad.warnings.length, 2); + assert.match(bad.warnings[0], /via "cloud" is not code, api or local/); + assert.match(bad.warnings[1], /article "Not_An_Id" is not an article id/); +}); diff --git a/mcp/src/promptRequest.ts b/mcp/src/promptRequest.ts @@ -37,6 +37,12 @@ export type PromptRequest = { source?: string; contentTypes?: ("video" | "post")[]; regex: boolean; + // Who does the work, overriding the generation policy for this one plan + // (release 27 S9): `code` (this session), `api` or `local` (the editor's + // report-draft job, through the MCP's generate). + via?: "code" | "api" | "local"; + // The article a routed sweep becomes an iteration of. + article?: string; warnings: string[]; }; @@ -57,6 +63,8 @@ const KEYS: Record<string, string[]> = { source: ["corpus"], content_types: ["content_type", "types", "type"], regex: ["re"], + via: ["route"], + article: ["article_id"], }; const CANONICAL = new Map<string, string>(); @@ -341,6 +349,17 @@ export function parsePromptRequest(input: string): PromptRequest { if (t) req.contentTypes = t; } + if (seen.has("via")) { + const v = seen.get("via")!.trim().toLowerCase(); + if (v === "code" || v === "api" || v === "local") req.via = v; + else warnings.push(`via "${seen.get("via")}" is not code, api or local — the generation policy decides.`); + } + if (seen.has("article")) { + const a = seen.get("article")!.trim(); + if (/^[a-z0-9][a-z0-9-]{0,63}$/.test(a)) req.article = a; + else warnings.push(`article "${a}" is not an article id (a lowercase slug: a-z, 0-9, -) — ignored.`); + } + if (!req.link && req.query === "") { warnings.push( "no query and no link — say what to sweep for, or paste a share link.", diff --git a/mcp/src/protocol.test.ts b/mcp/src/protocol.test.ts @@ -49,6 +49,8 @@ const EXPECTED_TOOLS = [ "enqueue", "channel_coverage", "notes", + "generation_policy", + "generate", "list_sources", "resolve_source", "open_link", diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -97,6 +97,12 @@ import { notesTool, type ToolAnswer, } from "./archivalTools"; +import { + GENERATION_TOOLS, + generateTool, + generationPolicyTool, + planGeneration, +} from "./generation"; import { extractVideoId } from "yt-dlp-transcript-common/lib/videoId"; import { decodeShareLink, @@ -895,6 +901,8 @@ export const TOOLS: Tool[] = [ }, // Archival writes through the editor (release 19 A9): archivalTools.ts. ...(ARCHIVAL_TOOLS as unknown as Tool[]), + // The Claude Code balance (release 27 S9): generation.ts. + ...(GENERATION_TOOLS as unknown as Tool[]), { name: "list_sources", description: @@ -1042,10 +1050,14 @@ export const TOOLS: Tool[] = [ "share link — into the step-by-step plan for a corpus sweep, with the " + "scope, corpus handle and batch count already resolved. Call this when " + "the user asks to sweep, survey, or systematically go through the " + - "archive. It only RETURNS instructions: it reads nothing, writes " + - "nothing, and starts nothing. Following the plan it returns is a long " + - "job that writes a report file with your own Write/Edit tools, so run " + - "it when that is what was asked for, and show the plan's ⚠ warnings.", + "archive. It only RETURNS instructions: it writes nothing and starts " + + "nothing (it reads the corpus's channel list and, when an editor is " + + "configured, the generation policy). Following the plan it returns is " + + "a long job that writes a report file with your own Write/Edit tools, " + + "so run it when that is what was asked for, and show the plan's ⚠ " + + "warnings. When the policy routes sweeps to the Claude API or the " + + "local model, the plan says instead to start it with generate and " + + "review what it makes.", inputSchema: { type: "object", properties: { @@ -1057,7 +1069,10 @@ export const TOOLS: Tool[] = [ "what to sweep for, in the user's own words, punctuation intact. " + "Recognised settings may be appended as key=value — channels=, " + "groups=, batch_size=, parse_model=, report=, directive=, " + - "source=, content_types=, regex= (quote a multi-word value). " + + "source=, content_types=, regex=, via= (code, api or local: " + + "overrides the generation policy for this plan), article= (the " + + "article a routed sweep becomes an iteration of) — quote a " + + "multi-word value. " + "Anything else stays part of the question.", }, }, @@ -1073,7 +1088,8 @@ export const TOOLS: Tool[] = [ "to run, against which corpus handle, and how to cite the answer. Use " + "it for a question to be answered in conversation (sweep_plan is for a " + "systematic pass that writes a report). It only RETURNS instructions: " + - "it reads nothing and writes nothing.", + "it writes nothing (when an editor is configured it reads the " + + "generation policy, and names the tasks it routes away).", inputSchema: { type: "object", properties: { @@ -1301,6 +1317,16 @@ export function createServer( return fromAnswer(await channelCoverageTool(args, fetchClipDeps)); case "notes": return fromAnswer(await notesTool(args, fetchClipDeps)); + case "generation_policy": + return fromAnswer(await generationPolicyTool(args, fetchClipDeps)); + case "generate": + return fromAnswer( + await generateTool( + args, + fetchClipDeps, + progressNotifier(ctx.mcpReq._meta?.progressToken, ctx.mcpReq.notify), + ), + ); case "list_sources": return handleListSources(registry, resolved); case "resolve_source": @@ -1312,9 +1338,9 @@ export function createServer( case "open_link": return handleOpenLink(registry, resolved, args); case "sweep_plan": - return handlePlan("sweep", registry, resolved, args); + return handlePlan("sweep", registry, resolved, args, fetchClipDeps); case "ask_plan": - return handlePlan("ask", registry, resolved, args); + return handlePlan("ask", registry, resolved, args, fetchClipDeps); default: return errorText(`unknown tool: ${name}`); } @@ -3234,6 +3260,7 @@ async function handlePlan( registry: SourceRegistry, callerCorpus: ResolvedSource, args: Record<string, unknown>, + deps: FetchClipDeps, ): Promise<ToolResult> { const raw = typeof args.request === "string" ? args.request : ""; if (raw.trim() === "") { @@ -3259,6 +3286,11 @@ async function handlePlan( } const ctx = await buildPlanContext(corpus, req); + // Who does the work (release 27 S9): the generation policy, asked of the + // editor at plan time. No editor: the plan is this session's, as before. + const routing = await planGeneration(deps); + if (routing.generation) ctx.generation = routing.generation; + if (routing.note) ctx.notes = [...(ctx.notes ?? []), routing.note]; return text( kind === "sweep" ? buildSweepInstructions(req, ctx)