// `report-draft {"task": "propose-groups", "project", "request"?, "model"?, // "maxUsd"?, "answers"?, "dryRun"?}` — claim groups proposed for a umtool // video project's cut (lane L4) as an editor job. umtool's Cut tab (Propose // groups) starts it through `editorCall`; `pnpm ops report-draft` and the // MCP's `generate` do the same. // // project the video project's directory (absolute; it must hold a // video.manifest.json) // request optional words for the ask ("group the October clips by day") // answers the `code` route: a Claude Code session's answer // (`{groups: [{section, claim, ids, why}]}`), checked exactly as // a model's — no model is called // dryRun (the ops route) the plan: the prompt, its estimate; nothing written // // Out: `/group-proposals.json` — PROPOSALS ONLY; nothing is applied // (umtool's Accept writes a group through the manifest's structural writer). // Routed by settings.generation.routes["propose-groups"] (local by default: // `draft:local`, every ollama call through the GPU arbiter; ollama unloaded // when the job ends) or the API (`draft:api`: the narration cap, the daily // cap, its usage in the ledger as task `propose-groups`). The log ends // `@@report-draft {article: "", iteration: 0, task: "propose-groups", // project, status, summary, usd, groups: {at, proposed, refused, file}}`. import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor } from "../lib/generationSettings"; import { providerOf, unloadOllama } from "../lib/llm"; import { usageOf } from "../lib/report/draft/tasks/run"; import { GROUPS_CODE_MODEL, PROPOSE_GROUPS_TASK, loadGroupsProject, planProposeGroups, runProposeGroups, type ProposeGroupsOutcome, type ProposeGroupsPlan, } from "../lib/report/draft/tasks/proposeGroups"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { projectDirOf } from "./clipsSuggest"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; export { GROUPS_CODE_MODEL, PROPOSE_GROUPS_TASK }; type Refused = { result: StreamActionResult & { ok: false } }; /** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */ export async function planProposeGroupsJob(body: ReportDraftBody, deps: Pick): Promise { const gen = (deps.settings ?? getSettings)().generation; const dir = projectDirOf(body.project ?? "", deps.paths); const route = gen.routes[PROPOSE_GROUPS_TASK]; const model = body.model ?? (route === "code" ? GROUPS_CODE_MODEL : modelFor(gen, PROPOSE_GROUPS_TASK)); return planProposeGroups({ project: dir, model, ...(body.request ? { request: body.request } : {}) }, { llm: llmConfigOf(gen, deps.paths) }); } export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDraftDeps): Promise { const refuse = (error: string): Refused => ({ result: { ok: false as const, error } }); const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; let dir: string; let model: string; try { dir = projectDirOf(body.project ?? "", paths); model = body.answers !== undefined ? GROUPS_CODE_MODEL : modelFor(gen, PROPOSE_GROUPS_TASK, body.model); // Refused at the ask, not at the job's turn: no manifest. await loadGroupsProject(dir); } catch (e) { return refuse((e as Error).message); } const provider = model === GROUPS_CODE_MODEL ? "code" : providerOf(model); let maxUsd: number | undefined; if (provider === "api") { try { maxUsd = capFor(gen.caps, "narration", body.maxUsd); } catch (e) { return refuse((e as Error).message); } const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, fn: modelLogged({ paths, task: "propose-groups" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); if (late) throw new Error(late); } onLog( `propose-groups in ${dir} on ${model} (` + (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter: it waits for a transcription" : "a Claude Code session's answer") + ")", ); setProgress?.({ metric: "turns", initial: 0, target: 1, current: 0 }); let out: ProposeGroupsOutcome | null = null; try { out = await runProposeGroups( { project: dir, model, ...(body.request ? { request: body.request } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), ...(body.answers !== undefined ? { answers: body.answers } : {}), }, { llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), log: onLog, signal, ...(deps.now ? { now: deps.now } : {}), }, ); } finally { if (provider === "local") { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } } setProgress?.({ metric: "turns", initial: 0, target: 1, current: 1 }); if (provider === "api") { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(out.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => { const u = usageOf(t); return { at: at.toISOString(), day: utcDay(at), jobId: ctx.jobId, article: "", iteration: 0, task: PROPOSE_GROUPS_TASK, 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).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } const p = out.proposals; onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: "", iteration: 0, task: PROPOSE_GROUPS_TASK, project: dir, status: out.status, summary: out.summary, usd: out.usd, groups: { at: p?.at ?? null, proposed: p?.groups.length ?? 0, refused: p?.refused.length ?? 0, file: out.file }, })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; }