// THE `propose-groups` TASK (lane L4, 2026-11-02): claim groups proposed for // a umtool video project's cut, as PROPOSALS the operator accepts or rejects. // // in a video project's directory (its video.manifest.json), optional // words for the ask (`request`: "group the October clips by day"), // and on the `code` route a Claude Code session's answer (`answers`, // read exactly as a model's) // ask ONE schema-bound ask (GROUPS_SCHEMA: `{groups: [{section, claim, // ids, why}]}`) over the cut's compact view -- per section its // clips in order with their deck title, date and quote, the clips // already in a group marked taken -- fitted to the prompt cap on a // local model; the same ask on the Claude API (one answer is the // batch) // check every group against the manifest as it is after the answer // (groupProposals.mjs checkGroupProposals: clips of the cut, // together, in one section, in no group yet, a claim of at most 160 // characters) // out `/group-proposals.json`: the kept groups, each `proposed`, // and the refused with their reasons. NOTHING IS APPLIED: umtool's // Accept writes one group through the manifest's structural writer. // // It never writes the manifest or notes.json. An API model is held to // `maxUsd` (the ask's estimate checked first). import { CallSlot, recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; import { GROUPS_PROMPT_VERSION, PROPOSED_CLAIM_MAX, checkGroupProposals, cutSections, groupProposalsDocOf, writeGroupProposals, type GroupProposals, } from "../../groupProposals.mjs"; import { fitLocalAsk } from "./revise-report"; export const PROPOSE_GROUPS_TASK = "propose-groups" as const; /** The `model` a Claude Code session's answer is written under (the `code` route). */ export const GROUPS_CODE_MODEL = "claude-code"; /** The ask's own words, at most. */ export const GROUPS_REQUEST_MAX = 2000; const ANSWER_TOKENS = 3000; /** The view's budget on the API (a local model's is fitted to its cap). */ const API_VIEW_CHARS = 60_000; export class ProposeGroupsRefusal extends Error {} export type ProposeGroupsDeps = { llm: LlmConfig; // The model, stubbed (tests). ask?: (system: string, user: string, schema: object, model: string, maxTokens: number) => Promise; log?: (line: string) => void; signal?: AbortSignal; now?: () => Date; }; export type ProposeGroupsInput = { project: string; model: string; request?: string; maxUsd?: number; answers?: unknown; }; export const GROUPS_SCHEMA = Object.freeze({ type: "object", properties: { groups: { type: "array", items: { type: "object", properties: { section: { type: "integer" }, claim: { type: "string" }, ids: { type: "array", items: { type: "string" } }, why: { type: "string" }, }, required: ["section", "claim", "ids", "why"], }, }, }, required: ["groups"], }); /** A video project: its manifest (refused without one). */ export async function loadGroupsProject(dir: string): Promise<{ dir: string; manifest: Record }> { let raw: string; try { raw = await readFile(path.join(dir, "video.manifest.json"), "utf8"); } catch { throw new ProposeGroupsRefusal(`${dir} holds no video.manifest.json: claim groups are proposed for a video project's cut`); } try { const manifest = JSON.parse(raw) as Record; if (!manifest || typeof manifest !== "object" || !Array.isArray(manifest.timeline)) throw new Error("no timeline"); return { dir, manifest }; } catch (e) { throw new ProposeGroupsRefusal(`${dir}/video.manifest.json is not a cut (${(e as Error).message})`); } } type Entry = { id?: unknown; type?: unknown; kind?: unknown; title?: unknown; date?: unknown; quote?: unknown; onscreen?: { title?: unknown } }; const str = (v: unknown) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); /** * The cut as the model reads it, in at most `maxChars`: per section its * clips in order -- id, deck title, date, the quote cut to `q` characters -- * and the clips already in a group marked taken. The quotes are cut shorter * until it fits; past that a section's clips are listed by id alone. */ export function groupsView(manifest: Record, { maxChars = API_VIEW_CHARS }: { maxChars?: number } = {}): { text: string; clips: number } { const cut = cutSections(manifest); const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[]; const byId = new Map(); for (const e of tl) if (typeof e?.id === "string" && !byId.has(e.id)) byId.set(e.id, e); const sections = new Map(); for (const id of cut.order) { const s = cut.sectionOf.get(id) ?? 0; sections.set(s, [...(sections.get(s) ?? []), id]); } const render = (q: number, idsOnly: boolean) => { const lines: string[] = []; for (const [s, ids] of [...sections.entries()].sort((a, b) => a[0] - b[0])) { lines.push(`§${s}${cut.labels[s] ? ` ${cut.labels[s]}` : s === 0 ? " (the opening)" : ""}`); if (idsOnly) { lines.push(` ${ids.map((id) => (cut.grouped.has(id) ? `${id}(taken)` : id)).join(" ")}`); continue; } for (const id of ids) { const e = byId.get(id) ?? {}; if (cut.grouped.has(id)) { lines.push(`- ${id}: (taken: in ${cut.grouped.get(id)})`); continue; } const title = str(e.onscreen?.title) || str(e.title); const quote = str(e.quote); const head = [title, str(e.date)].filter(Boolean).join(" · "); lines.push(`- ${id}:${head ? ` [${head}]` : ""}${quote ? ` "${quote.length > q ? `${quote.slice(0, q - 1)}…` : quote}"` : ""}`); } } return lines.join("\n"); }; for (const q of [400, 240, 160, 100, 60, 30]) { const text = render(q, false); if (text.length <= maxChars) return { text, clips: cut.order.length }; } return { text: render(0, true).slice(0, Math.max(0, maxChars)), clips: cut.order.length }; } const SYSTEM = [ "You organise a video's cut for its editor. The cut is a list of short clips of one person speaking, in sections. You propose CLAIM GROUPS: runs of clips that stand next to each other in a section and together make one claim.", "Rules: a group's ids are clips that stand together in the order shown (no other clip between them), all in one section; give its `section` number; never use a clip marked taken, and no clip in two groups.", "Leave a clip that makes no claim with its neighbours out of every group; a group may be one clip when it is a claim of its own.", `\`claim\` says what the clips claim, in a short line of plain words in the speaker's own register (at most ${PROPOSED_CLAIM_MAX} characters; quote her when a phrase says it best). \`why\` is one short sentence: why these clips are one claim.`, "Do not reorder anything and do not invent ids.", ].join("\n"); const userOf = (request: string, view: string) => `${request ? `THE EDITOR ASKS:\n${request}\n\n` : ""}THE CUT NOW:\n${view}\n\nAnswer with the claim groups.`; /** The prompt one ask sends: on a local model the view is fitted to its prompt cap. */ export function groupsPrompt(o: { manifest: Record; request: string; model: string; llm: LlmConfig }): { system: string; user: string; tokens: number } { const build = (maxChars: number) => userOf(o.request, groupsView(o.manifest, { maxChars: maxChars - o.request.length - 120 }).text); if (providerOf(o.model) === "local") { const fitted = fitLocalAsk({ llm: o.llm, model: o.model, system: SYSTEM, schema: GROUPS_SCHEMA, build }); return { system: SYSTEM, user: fitted.user, tokens: fitted.tokens }; } const user = build(API_VIEW_CHARS); return { system: SYSTEM, user, tokens: structuredPromptEstimate({ system: SYSTEM, user, schema: GROUPS_SCHEMA }) }; } export type ProposeGroupsPlan = { project: string; model: string; provider: "api" | "local" | "code"; promptVersion: string; estimate: { inputTokens: number; outputTokens: number; usd: number }; // The request a Claude Code session answers (the `code` route). request: { system: string; user: string; schema: object }; }; const CODE_PRICED = "claude-sonnet-5-5"; /** What one ask would send, and roughly what it costs — nothing called, nothing written. */ export async function planProposeGroups(input: Omit, deps: Pick): Promise { const { manifest } = await loadGroupsProject(input.project); const code = input.model === GROUPS_CODE_MODEL; const pr = groupsPrompt({ manifest, request: requestOf(input.request), model: code ? CODE_PRICED : input.model, llm: deps.llm }); const p = priceOf(code ? CODE_PRICED : input.model); const usd = code || providerOf(input.model) === "local" ? 0 : (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; return { project: input.project, model: input.model, provider: code ? "code" : providerOf(input.model), promptVersion: GROUPS_PROMPT_VERSION, estimate: { inputTokens: pr.tokens, outputTokens: ANSWER_TOKENS, usd: Math.round(usd * 10_000) / 10_000 }, request: { system: pr.system, user: pr.user, schema: GROUPS_SCHEMA }, }; } export type ProposeGroupsOutcome = { status: "done" | "cancelled" | "failed"; project: string; model: string; proposals: GroupProposals | null; file: string | null; usd: number; byModel: ReturnType["byModel"]; summary: string; }; const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; function requestOf(r: string | undefined): string { const t = (r ?? "").replace(/\s+/g, " ").trim(); if (t.length > GROUPS_REQUEST_MAX) throw new ProposeGroupsRefusal(`a request is at most ${GROUPS_REQUEST_MAX} characters`); return t; } /** The answer's groups, or why it is not one. */ export function parseGroupsAnswer(raw: unknown): { ok: true; groups: unknown[] } | { ok: false; error: string } { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "the answer is not { groups: [...] }" }; const a = raw as { groups?: unknown }; if (!Array.isArray(a.groups)) return { ok: false, error: "the answer has no groups list" }; return { ok: true, groups: a.groups }; } /** One ask (or a session's answer), checked, written as proposals. */ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeGroupsDeps): Promise { const log = deps.log ?? (() => {}); const now = () => deps.now?.() ?? new Date(); const request = requestOf(input.request); const { manifest } = await loadGroupsProject(input.project); const meter = new Meter(); const base = { project: input.project, model: input.model }; const cancelled = (): ProposeGroupsOutcome => ({ ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }); let raw: unknown; // What code did with the answer's groups (the model log). const slot = new CallSlot(); if (input.answers !== undefined) { log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); raw = input.answers; const pr = groupsPrompt({ manifest, request, model: CODE_PRICED, llm: deps.llm }); recordSessionAnswer({ phase: "groups", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = groupsPrompt({ manifest, request, model: input.model, llm: deps.llm }); log(`propose-groups ${input.project} on ${input.model}: one ask, ~${pr.tokens} prompt tokens (prompt ${GROUPS_PROMPT_VERSION})`); if (providerOf(input.model) === "api" && input.maxUsd !== undefined) { const p = priceOf(input.model); const est = (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; if (est > input.maxUsd) throw new ProposeGroupsRefusal(`the ask (~$${est.toFixed(4)}) is over its cap of $${input.maxUsd}`); } const ask = deps.ask ?? ((system: string, user: string, schema: object, model: string, maxTokens: number) => structuredAnswer({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens, call: { phase: "groups", slot } })); try { raw = await ask(pr.system, pr.user, GROUPS_SCHEMA, input.model, 4096); } catch (e) { if (deps.signal?.aborted) return cancelled(); throw e; } } const parsed = parseGroupsAnswer(raw); if (!parsed.ok) { slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new ProposeGroupsRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } if (deps.signal?.aborted) return cancelled(); // Checked against the manifest as it is NOW: a cut edited while the model thought is what the groups meet. const fresh = (await loadGroupsProject(input.project)).manifest; const checked = checkGroupProposals(fresh, { groups: parsed.groups }); for (const g of checked.groups) log(` proposed: §${g.section} ${g.ids.join(" ")} — ${g.claim}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.group).slice(0, 120)} — ${r.why}`); slot.decide(checked.groups.length ? "kept" : "dropped", `${checked.groups.length} group(s) proposed, ${checked.refused.length} refused`, [ ...checked.groups.map((g) => ({ text: `§${g.section} ${g.ids.join(" ")} — ${g.claim}`, outcome: "kept" as const, why: "proposed" })), ...checked.refused.map((r) => ({ text: JSON.stringify(r.group).slice(0, 200), outcome: "dropped" as const, why: r.why })), ]); const proposals = groupProposalsDocOf({ at: now().toISOString(), model: input.model, request: request || null, checked }); const file = await writeGroupProposals(input.project, proposals); const usd = Math.round(meter.usd * 1e6) / 1e6; const summary = (checked.groups.length ? `${plural(checked.groups.length, "group")} proposed` : "no group proposed") + (checked.refused.length ? `, ${checked.refused.length} refused` : "") + ` on ${input.model}` + (usd ? ` · $${usd.toFixed(4)}` : ""); return { ...base, status: "done", proposals, file, usd, byModel: meter.summary().byModel, summary }; }