Archilyzer · Source

archilyzer

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

commit 0b7c6e9ac09942b501f788a4e5410db39bd46152
parent 0de24564f11fb54ef17c89c1d9bc07c71a6826d2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 00:26:22 -0500

common: the `propose-groups` generation task (lane L4) -- claim groups proposed for a umtool video project's cut, as PROPOSALS: one schema-bound ask (`{groups: [{section, claim, ids, why}]}`) over the cut's view by section (each clip's id, deck title, date and quote; clips already grouped marked taken), fitted to the local prompt cap, the API held to maxUsd, the code route's `answers` read as a model's; checked against the manifest as it is after the answer (lib/report/groupProposals.mjs checkGroupProposals: clips of the cut, together with no other clip between, in one deck section read by umtool's own marker rule, in no group yet or other kept proposal, a claim of at most 160 characters; each other one refused in words) and written as `<project>/group-proposals.json` (statuses proposed|accepted|rejected|failed; nothing applied). Routed by settings.generation: GENERATION_TASKS and every preset (local but in `api`; SETTINGS.md and settings.json.example regenerated), controller/proposeGroups.ts its own job (draft:local / draft:api, the narration cap, the daily cap, ledger task propose-groups, the @@report-draft marker with `groups: {at, proposed, refused, file}`), reportDraft's body (project, request optional, answers, dryRun; no note or scope) and dispatch, the editor's ops route (`dryRun` answers the plan), the MCP's `generate` (args, the code route's request, the summary); /gen and OPERATING.md name it

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

Diffstat:
M.claude/commands/gen.md | 7+++++++
MOPERATING.md | 1+
MSETTINGS.md | 4+++-
Acommon/controller/proposeGroups.ts | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/reportDraft.ts | 45++++++++++++++++++++++++++++++++++++++++-----
Mcommon/lib/generationSettings.test.ts | 15+++++++++++++++
Mcommon/lib/generationSettings.ts | 17++++++++++++-----
Acommon/lib/report/draft/tasks/proposeGroups.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/proposeGroups.ts | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/groupProposals.d.mts | 28++++++++++++++++++++++++++++
Acommon/lib/report/groupProposals.mjs | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Aeditor/app/api/ops/_proposeGroups.test.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 17+++++++++++++++++
Mmcp/src/generation.test.ts | 28++++++++++++++++++++++++++++
Mmcp/src/generation.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Msettings.json.example | 3++-
17 files changed, 1197 insertions(+), 16 deletions(-)

diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -55,6 +55,13 @@ each task. Use the archilyzer MCP tools only; run no script for it. (`answers: {"ops": [{"op", "id", "key", "value"}], "reply"}`); the editor checks them as a model's and writes `assist-proposals.json`. They are proposals: the operator applies them in umtool's Ask box. Never edit the manifest or that file yourself. + **And `propose-groups`** (claim groups for a umtool video project's cut — "propose claim groups for <dir>"): + `generate` with task `propose-groups`, `project` and optional `request` (words for the ask). Local in every preset + but `api`; routed to code, its answer is the request — the cut's clips by section — which you answer in this + session and send back with `generate` again (`answers: {"groups": [{"section", "claim", "ids", "why"}]}`: clips + standing together in one section that make one claim); the editor checks them as a model's and writes + `group-proposals.json`. They are proposals: the operator accepts or rejects each on umtool's Cut tab. Never edit + the manifest or that file yourself. 5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with `task` and `route` — only when the operator asks. diff --git a/OPERATING.md b/OPERATING.md @@ -617,6 +617,7 @@ pnpm ops report-draft --json '{"task":"revise-video","article":"example-article" pnpm ops report-draft --json '{"task":"narrate","article":"example-article","iteration":3}' --wait pnpm ops report-draft --json '{"task":"sweep","article":"example-article","copyOf":1,"model":"qwen3:8b"}' pnpm ops report-draft --json '{"task":"video-assist","project":"/abs/project/dir","request":"make the joins 0.15 s with less smear","dryRun":true}' +pnpm ops report-draft --json '{"task":"propose-groups","project":"/abs/project/dir"}' --wait pnpm ops job cancel <jobId> pnpm archilyzer reports iterations example-article umtool chain example-article 3 diff --git a/SETTINGS.md b/SETTINGS.md @@ -1080,6 +1080,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. | | `clips-suggest` | `"local"` | The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`). | | `video-assist` | `"local"` | The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words ("make the joins 0.15 s with less smear") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). | +| `propose-groups` | `"local"` | Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`). | | `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. | #### `generation.models` @@ -1187,7 +1188,8 @@ Default: "verdicts": "local", "frames": "api", "clips-suggest": "local", - "video-assist": "local" + "video-assist": "local", + "propose-groups": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/common/controller/proposeGroups.ts b/common/controller/proposeGroups.ts @@ -0,0 +1,165 @@ +// `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: `<project>/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 { 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<ReportDraftDeps, "paths" | "settings">): Promise<ProposeGroupsPlan> { + 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<ReportDraftEnqueued | Refused> { + 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: 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 }; +} diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -227,11 +227,13 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const article = b.article; // A clips-suggest job (release 36 lane D) and a video-assist job (release 38 // lane E) are on a umtool project, not an article. - const onProject = task === "clips-suggest" || task === "video-assist"; + // A propose-groups job (lane L4, ./proposeGroups.ts) is on a video project too. + const groups = task === "propose-groups"; + const onProject = task === "clips-suggest" || task === "video-assist" || groups; const assist = task === "video-assist"; if (onProject) { if (article !== undefined && article !== null && article !== "") { - fail(assist ? 'a video-assist job names its "project" (the video project\'s directory), not an article' : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); + fail(assist || groups ? `a ${task} job names its "project" (the video project's directory), not an article` : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); } } else 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) => { @@ -375,9 +377,32 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod const clipsGiven = clipsKeys.filter((k) => b[k] !== undefined && b[k] !== null); if (clipsGiven.length && !onProject) fail(`${clipsGiven.map((k) => `"${k}"`).join(", ")} ${clipsGiven.length === 1 ? "is" : "are"} a clips-suggest job's`); // The video assistant's (release 38 lane E). - const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null); + const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null && !(groups && k === "request")); if (assistGiven.length && !assist) fail(`${assistGiven.map((k) => `"${k}"`).join(", ")} ${assistGiven.length === 1 ? "is" : "are"} a video-assist job's`); - if (assist) { + if (groups) { + // Claim groups proposed for a video project's cut (lane L4): the project, + // optional words for the ask, a session's answer on the code route. + const project = b.project; + if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); + out.project = project as string; + if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s'); + if (b.note !== undefined && b.note !== null) fail('a propose-groups job takes no "note": give its words as "request"'); + if (b.request !== undefined && b.request !== null) { + if (typeof b.request !== "string") fail('"request" is words for the ask'); + if (b.request.length > 2000) fail('"request" is at most 2,000 characters'); + const r = b.request.replace(/\s+/g, " ").trim(); + if (r) out.request = r; + } + if (b.answers !== undefined && b.answers !== null) { + if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"groups": [{"section", "claim", "ids", "why"}]}'); + if (JSON.stringify(b.answers).length > 200_000) fail('"answers" is at most 200,000 characters'); + out.answers = b.answers; + } + if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); + if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"'); + const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); + if (extra.length) fail(`a propose-groups job reads its project: it takes no ${extra.join(", ")}`); + } else if (assist) { const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); out.project = project as string; @@ -468,7 +493,7 @@ function kindOf(task: GenerationTask): Iteration["kind"] { } const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => - isStepTask(task) || task === "clips-suggest" || task === "video-assist" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; + isStepTask(task) || task === "clips-suggest" || task === "video-assist" || task === "propose-groups" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; export function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; @@ -597,6 +622,15 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep return refuse((e as Error).message); } } + if (body.task === "propose-groups") { + if (body.dryRun) return refuse('a propose-groups plan is planProposeGroupsJob\'s ("dryRun": true at the ops route)'); + try { + const { enqueueProposeGroups } = await import("./proposeGroups"); + return await enqueueProposeGroups(body, deps); + } catch (e) { + return refuse((e as Error).message); + } + } if (body.task === "video-assist") { if (body.dryRun) return refuse('a video-assist plan is planVideoAssistJob\'s ("dryRun": true at the ops route)'); try { @@ -812,6 +846,7 @@ async function runReportDraft( case "frames": case "clips-suggest": case "video-assist": + case "propose-groups": // A refresh, a triage, verdict proposals, a frame scan, the clip finder's labels and the video assistant are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts, ./videoAssist.ts), never this one. throw new Error(`a ${body.task} runs as its own job`); case "sweep": diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -181,3 +181,18 @@ test("the video assistant (release 38 lane E): local in every preset but api; a // A file that routes nothing: the default (balanced) — local. assert.equal(sanitizeGeneration({}).routes["video-assist"], "local"); }); + +test("claim groups for a cut (lane L4): local in every preset but api; a file from before keeps its preset", () => { + assert.ok((GENERATION_TASKS as readonly string[]).includes("propose-groups")); + assert.deepEqual( + (["code", "balanced", "api", "local"] as const).map((p) => GENERATION_PRESETS[p]["propose-groups"]), + ["local", "local", "api", "local"], + ); + for (const p of ["code", "balanced", "api", "local"] as const) { + const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "propose-groups").map((t) => [t, GENERATION_PRESETS[p][t]])); + const g = sanitizeGeneration({ routes }); + assert.equal(g.preset, p); + assert.equal(g.routes["propose-groups"], GENERATION_PRESETS[p]["propose-groups"]); + } + assert.equal(sanitizeGeneration({}).routes["propose-groups"], "local"); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -34,7 +34,12 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri // (`<project>/assist-proposals.json`) the operator applies. LOCAL in every // preset but `api` (the point is small edits with no Claude at hand); // `code` = a Claude Code session answers the request. -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist"] as const; +// `propose-groups` (lane L4, 2026-11-02): claim groups proposed for a video +// project's cut — runs of clips in a section that make one claim +// (`<project>/group-proposals.json`), each accepted or rejected by the +// operator in umtool's Cut tab. Routed as video-assist: local in every preset +// but `api`; `code` = a Claude Code session answers the request. +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames", "clips-suggest", "video-assist", "propose-groups"] as const; export type GenerationTask = (typeof GENERATION_TASKS)[number]; // The tasks every settings file since release 27 S6 routes. const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"]; @@ -46,12 +51,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const; export const GENERATION_PRESETS = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local" }, + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code", "clips-suggest": "code", "video-assist": "local", "propose-groups": "local" }, // A frame scan is on the API in `balanced`: a vision model is not a given // on the local card, and the cheap model's reads cost cents an hour. - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local" }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api", "clips-suggest": "local", "video-assist": "local", "propose-groups": "local" }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api", "clips-suggest": "api", "video-assist": "api", "propose-groups": "api" }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local", "clips-suggest": "local", "video-assist": "local", "propose-groups": "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[]; @@ -229,6 +234,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { "The clip finder's optional AI pass on a reactions project (umtool's clip editor: Suggest, Ask the assistant): a label, a why and a rank for each proposal (`clip-suggestions.json` beside reactions.json; never a clip or the manifest), and an answer to a comment on a clip with at most one edit the operator applies. `code` = a Claude Code session answers the request (`/gen`).", "video-assist": "The video assistant (umtool's Ask box: the Build tab's Look panel, the clip editor, a note on the project): a request in words (\"make the joins 0.15 s with less smear\") → proposed edits of the look, the blur slide, the room, a clip's edges or room, or a composition's declared params (`assist-proposals.json` beside the manifest), each applied only by the operator's Apply. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).", + "propose-groups": + "Claim groups proposed for a video project's cut (umtool's Cut tab: Propose groups): runs of clips inside a section that make one claim, each with its claim in words (`group-proposals.json` beside the manifest), each accepted or rejected by the operator — never applied by the proposal. Local in every preset but `api`; `code` = a Claude Code session answers the request (`/gen`).", verdicts: "Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.", }; diff --git a/common/lib/report/draft/tasks/proposeGroups.test.ts b/common/lib/report/draft/tasks/proposeGroups.test.ts @@ -0,0 +1,164 @@ +// Lane L4: the `propose-groups` task on the fake ollama and the fake +// Anthropic — one ask, the answer checked (a kept group and every refusal), +// written as group-proposals.json; the code route's answer read as a +// model's; the manifest byte-identical after every run. +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, startFakeOllama, PROMPT_CAP_TOKENS, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { checkGroupProposals, cutSections, markGroupProposals, readGroupProposals } from "../../groupProposals.mjs"; +import { GROUPS_CODE_MODEL, ProposeGroupsRefusal, groupsView, planProposeGroups, runProposeGroups } from "./proposeGroups"; +import type { LlmConfig } from "../../../llm"; + +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let llm: LlmConfig; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "propose-groups-")); + api = await startFakeAnthropic(); + ol = await startFakeOllama(); + llm = { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }, ollama: { baseUrl: ol.url } }; +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const clip = (id: string, i: number, extra: Record<string, unknown> = {}) => ({ type: "clip", id, channel: "c", video: "v1", start: 10 * i, end: 10 * i + 8, quote: `words of ${id}`, ...extra }); +/** §0 c01 c02 | §1 "Two" c03 card c04 | §2 "Three" c05 c06; g1 = c06. */ +function manifestOf() { + return { + slug: "s", + render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }, { after: "c04", label: "Three" }] } } }, + timeline: [ + clip("c01", 0, { onscreen: { title: "24 Oct 2020" } }), + clip("c02", 1), + clip("c03", 2), + { type: "card", id: "k1", heading: "a card" }, + clip("c04", 3), + clip("c05", 4), + clip("c06", 5), + ], + groups: [{ id: "g1", section: 2, claim: "Taken already", ids: ["c06"] }], + }; +} +async function project(name: string) { + const dir = path.join(tmp, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifestOf(), null, 2) + "\n"); + return dir; +} + +const ANSWER = { + groups: [ + { section: 0, claim: "She opens on the claim", ids: ["c02", "c01"], why: "both say it" }, + { section: 1, claim: "A card between does not break it", ids: ["c03", "c04"], why: "w" }, + { section: 2, claim: "Already grouped", ids: ["c05", "c06"], why: "w" }, + { section: 0, claim: "Not together", ids: ["c01", "c03"], why: "w" }, + { section: 1, claim: "Across a boundary", ids: ["c02", "c03"], why: "w" }, + { section: 2, claim: "x".repeat(161), ids: ["c05"], why: "w" }, + { section: 2, claim: "", ids: ["c05"], why: "w" }, + { section: 2, claim: "Unknown clip", ids: ["zz"], why: "w" }, + { section: 0, claim: "Twice", ids: ["c01"], why: "w" }, + { section: 2, claim: "Lone claim", ids: ["c05"], why: "its own" }, + ], +}; + +test("checkGroupProposals: a kept group and every refusal, in words; the sections read as umtool reads them", () => { + const m = manifestOf(); + const cut = cutSections(m); + assert.deepEqual([...cut.sectionOf.entries()], [["c01", 0], ["c02", 0], ["c03", 1], ["c04", 1], ["c05", 2], ["c06", 2]]); + assert.deepEqual(cut.labels, [null, "Two", "Three"]); + const r = checkGroupProposals(m, ANSWER); + assert.deepEqual(r.groups, [ + { section: 0, claim: "She opens on the claim", ids: ["c01", "c02"], why: "both say it" }, + { section: 1, claim: "A card between does not break it", ids: ["c03", "c04"], why: "w" }, + { section: 2, claim: "Lone claim", ids: ["c05"], why: "its own" }, + ]); + assert.deepEqual(r.refused.map((x) => x.why), [ + "c06 (g1) is in a group already", + "its clips are not together: c02 stands between c01 and c03", + "it spans §0 and §1: a group never crosses a section boundary", + "its claim is 161 characters (at most 160)", + "it has no claim", + "zz is not a clip of the cut", + "c01 is in another proposed group (the proposal \"She opens on the claim\")", + ]); + // Across a boundary, where nothing else refuses it first. + assert.deepEqual(checkGroupProposals(m, { groups: [{ claim: "x", ids: ["c04", "c05"] }] }).refused.map((x) => x.why), ["it spans §1 and §2: a group never crosses a section boundary"]); + // No markers: one section. + assert.equal(checkGroupProposals({ timeline: m.timeline }, { groups: [{ claim: "x", ids: ["c04", "c05"] }] }).groups[0]!.section, 0); +}); + +for (const [route, model] of [ + ["local", "qwen3:8b"], + ["api", "claude-sonnet-5-5"], +] as const) { + test(`on the ${route} model: one ask over the cut's view, the answer checked, group-proposals.json written, the manifest untouched`, async () => { + const dir = await project(route); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + let prompt = ""; + if (route === "local") { + ol.push((body: { messages: { role: string; content: string }[] }) => { + prompt = body.messages.find((m) => m.role === "user")!.content; + return jsonReply(ANSWER); + }); + } else { + api.push((body: { messages: { content: unknown }[] }) => { + prompt = JSON.stringify(body.messages[0]!.content); + return toolTurn("answer", ANSWER); + }); + } + const out = await runProposeGroups({ project: dir, model, request: "by claim" }, { llm, now: () => new Date("2026-11-02T00:00:00.000Z") }); + assert.equal(out.status, "done"); + assert.match(out.summary, new RegExp(`^3 groups proposed, 7 refused on ${model}`)); + assert.ok(prompt.includes("§1 Two"), prompt.slice(0, 300)); + assert.ok(prompt.includes("c06: (taken: in g1)")); + assert.ok(prompt.includes('c01: [24 Oct 2020] \\"words of c01\\"') || prompt.includes('c01: [24 Oct 2020] "words of c01"')); + const { doc } = await readGroupProposals(dir); + assert.equal(doc!.model, model); + assert.equal(doc!.request, "by claim"); + assert.deepEqual(doc!.groups.map((g) => [g.id, g.status, g.ids.join(" ")]), [["p1", "proposed", "c01 c02"], ["p2", "proposed", "c03 c04"], ["p3", "proposed", "c05"]]); + assert.equal(doc!.refused.length, 7); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before, "nothing applied"); + const marked = markGroupProposals(doc!, { p1: { status: "accepted", group: "g2" }, p9: { status: "rejected" } }, "t"); + assert.deepEqual(marked.groups.map((g) => g.status), ["accepted", "proposed", "proposed"]); + assert.equal(marked.groups[0]!.group, "g2"); + }); +} + +test("the code route: a session's answer is checked as a model's, written as claude-code's; junk refused; no model asked", async () => { + const dir = await project("code"); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + const asked = api.requests.length + ol.requests.length; + const out = await runProposeGroups({ project: dir, model: GROUPS_CODE_MODEL, answers: { groups: [{ section: 0, claim: "Two clips", ids: ["c01", "c02"], why: "" }] } }, { llm }); + assert.equal(out.status, "done"); + assert.equal(api.requests.length + ol.requests.length, asked); + const { doc } = await readGroupProposals(dir); + assert.equal(doc!.model, "claude-code"); + assert.deepEqual(doc!.groups.map((g) => g.claim), ["Two clips"]); + await assert.rejects(runProposeGroups({ project: dir, model: GROUPS_CODE_MODEL, answers: { nope: 1 } }, { llm }), /the session's answer is refused: the answer has no groups list/); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); +}); + +test("refusals and the plan: no manifest, an API ask over its cap; the local view fitted to the prompt cap however long the cut", async () => { + await assert.rejects(runProposeGroups({ project: path.join(tmp, "none"), model: "qwen3:8b" }, { llm }), ProposeGroupsRefusal); + const dir = await project("cap"); + await assert.rejects(runProposeGroups({ project: dir, model: "claude-sonnet-5-5", maxUsd: 0.000001 }, { llm }), /is over its cap/); + const m = manifestOf() as { timeline: unknown[] }; + for (let i = 10; i <= 900; i++) m.timeline.push(clip(`r${i}`, i, { quote: "a long quote ".repeat(40) })); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m)); + const plan = await planProposeGroups({ project: dir, model: "qwen3:8b" }, { llm }); + assert.ok(plan.estimate.inputTokens <= PROMPT_CAP_TOKENS, String(plan.estimate.inputTokens)); + assert.equal(plan.estimate.usd, 0); + assert.ok(groupsView(m as Record<string, unknown>, { maxChars: 2000 }).text.length <= 2000); + const apiPlan = await planProposeGroups({ project: dir, model: "claude-sonnet-5-5" }, { llm }); + assert.ok(apiPlan.estimate.usd > 0); +}); diff --git a/common/lib/report/draft/tasks/proposeGroups.ts b/common/lib/report/draft/tasks/proposeGroups.ts @@ -0,0 +1,282 @@ +// 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 `<project>/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 { 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?: <T>(system: string, user: string, schema: object, model: string, maxTokens: number) => Promise<T>; + 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<string, unknown> }> { + 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<string, unknown>; + 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<string, unknown>, { 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<string, Entry>(); + for (const e of tl) if (typeof e?.id === "string" && !byId.has(e.id)) byId.set(e.id, e); + const sections = new Map<number, string[]>(); + 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<string, unknown>; 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<ProposeGroupsInput, "answers" | "maxUsd">, deps: Pick<ProposeGroupsDeps, "llm">): Promise<ProposeGroupsPlan> { + 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<Meter["summary"]>["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<ProposeGroupsOutcome> { + 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; + if (input.answers !== undefined) { + log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); + raw = input.answers; + } 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 ?? + (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + try { + raw = await ask<unknown>(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) { + 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}`); + 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 }; +} diff --git a/common/lib/report/groupProposals.d.mts b/common/lib/report/groupProposals.d.mts @@ -0,0 +1,28 @@ +// Types for ./groupProposals.mjs (lane L4): `<project>/group-proposals.json`. +export type GroupProposalStatus = "proposed" | "accepted" | "rejected" | "failed"; +export type CheckedGroup = { section: number; claim: string; ids: string[]; why?: string }; +export type RefusedGroup = { group: unknown; why: string }; +/** `group`: the claim group an accept made (its id in the manifest). */ +export type ProposedGroup = CheckedGroup & { id: string; status: GroupProposalStatus; at?: string; error?: string; group?: string }; +export type GroupProposals = { + version: 1; + promptVersion: string; + at: string; + model: string; + request?: string; + groups: ProposedGroup[]; + refused: RefusedGroup[]; +}; + +export const GROUP_PROPOSALS_NAME: string; +export const GROUPS_PROMPT_VERSION: string; +export const GROUP_PROPOSAL_STATUSES: readonly GroupProposalStatus[]; +export const PROPOSED_CLAIM_MAX: number; +export const PROPOSED_GROUPS_MAX: number; +export function cutSections(manifest: unknown): { order: string[]; sectionOf: Map<string, number>; labels: (string | null)[]; grouped: Map<string, string> }; +export function checkGroupProposals(manifest: unknown, answer: unknown): { groups: CheckedGroup[]; refused: RefusedGroup[] }; +export function groupProposalsDocOf(o: { at: string; model: string; request?: string | null; checked: { groups: CheckedGroup[]; refused: RefusedGroup[] } }): GroupProposals; +export function groupProposalsErrors(doc: unknown): string[]; +export function readGroupProposals(dir: string): Promise<{ doc: GroupProposals | null; error: string | null }>; +export function writeGroupProposals(dir: string, doc: GroupProposals): Promise<string>; +export function markGroupProposals(doc: GroupProposals, marks: Record<string, { status: GroupProposalStatus; error?: string; group?: string }>, at: string): GroupProposals; diff --git a/common/lib/report/groupProposals.mjs b/common/lib/report/groupProposals.mjs @@ -0,0 +1,229 @@ +// CLAIM-GROUP PROPOSALS (lane L4, 2026-11-02): `<project>/group-proposals.json`, +// beside a umtool video project's video.manifest.json. +// +// { "version": 1, "promptVersion": "propose-groups-1", "at": ISO, "model": "qwen3:8b", +// "request"?: "…", the operator's words for the ask, when given +// "groups": [ { "id": "p1", "section": 1, "claim": "…", "ids": ["ow1", "a01"], "why"?: "…", +// "status": "proposed" | "accepted" | "rejected" | "failed", "at"?: ISO, "error"?: "…" } ], +// "refused": [ { "group": {…}, "why": "…" } ] } +// +// Written whole by the editor's `propose-groups` task (a new ask replaces the +// file); each group's `status` marked by umtool's Accept and Reject. PROPOSALS +// ONLY: nothing here is applied by being here. Accept writes the group through +// umtool's structural writer (lib/report/manifest.mjs setGroup), which checks +// it again against the manifest as it is then (claimGroups.mjs validateGroups). +// +// checkGroupProposals is the task's check of a model's answer, PURE and +// self-contained (common never imports umtool): the cut's sections are read +// from `render.chrome.deck.markers` by umtool's own rule (sectionEdit.mjs +// sectionModel) -- a marker `{after}` opens the next section right after that +// clip, markers placed by where their clip stands; none, one section 0. +// +// Tmp + rename, so a reader never sees half a file. Plain ESM with a .d.mts. + +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +export const GROUP_PROPOSALS_NAME = "group-proposals.json"; +export const GROUPS_PROMPT_VERSION = "propose-groups-1"; +export const GROUP_PROPOSAL_STATUSES = Object.freeze(["proposed", "accepted", "rejected", "failed"]); +/** A claim's characters, at most (umtool claimGroups.mjs GROUP_CLAIM_MAX). */ +export const PROPOSED_CLAIM_MAX = 160; +/** Groups one answer may propose, at most. */ +export const PROPOSED_GROUPS_MAX = 200; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; +const fileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, GROUP_PROPOSALS_NAME); + +/** + * The cut as a proposal is checked against: its clips in order (each id + * once), each clip's section, the sections' labels, and the clips already in + * a group. + * + * @param {unknown} manifest + */ +export function cutSections(manifest) { + const m = isObj(manifest) ? manifest : {}; + const tl = Array.isArray(m.timeline) ? m.timeline : []; + const order = []; + const pos = new Map(); + tl.forEach((e, i) => { + if (isClip(e) && typeof e.id === "string" && !pos.has(e.id)) { + pos.set(e.id, i); + order.push(e.id); + } + }); + const chrome = isObj(m.render) && isObj(m.render.chrome) ? m.render.chrome : null; + const markers = chrome && isObj(chrome.deck) && Array.isArray(chrome.deck.markers) ? chrome.deck.markers : []; + const placed = []; + markers.forEach((mk, k) => { + const p = isObj(mk) ? pos.get(String(mk.after ?? "").trim()) : undefined; + if (p !== undefined) placed.push({ k, mk, pos: p }); + }); + placed.sort((a, b) => a.pos - b.pos || a.k - b.k); + const labels = [null, ...placed.map((p) => (typeof p.mk.label === "string" && p.mk.label.trim() ? p.mk.label.trim() : null))]; + const sectionOf = new Map(); + let s = 0; + let next = 0; + tl.forEach((e, i) => { + if (isClip(e) && !sectionOf.has(e.id)) sectionOf.set(e.id, s); + while (next < placed.length && placed[next].pos === i) { + next += 1; + s = next; + } + }); + const grouped = new Map(); + for (const g of Array.isArray(m.groups) ? m.groups : []) { + if (!isObj(g) || !Array.isArray(g.ids)) continue; + for (const id of g.ids) if (typeof id === "string") grouped.set(id, String(g.id ?? "a group")); + } + return { order, sectionOf, labels, grouped }; +} + +/** + * A model's (or a session's) answer, checked against the cut as it is now: + * a proposed group is kept only when its ids are clips of the cut, together + * (no other clip between them; a card does not count), in one section, in no + * group already and in no other kept proposal, and its claim is a sentence of + * at most 160 characters. Each other one is refused, in words. + * + * @param {unknown} manifest + * @param {unknown} answer `{ groups: [{ section?, claim, ids, why? }] }` + * @returns {{ groups: Array<{ section: number, claim: string, ids: string[], why?: string }>, refused: Array<{ group: unknown, why: string }> }} + */ +export function checkGroupProposals(manifest, answer) { + const cut = cutSections(manifest); + const at = new Map(cut.order.map((id, k) => [id, k])); + const list = isObj(answer) && Array.isArray(answer.groups) ? answer.groups : []; + const groups = []; + const refused = []; + const taken = new Map(); + const refuse = (group, why) => refused.push({ group, why }); + for (const g of list.slice(0, PROPOSED_GROUPS_MAX)) { + if (!isObj(g)) { + refuse(g, "a group is {section, claim, ids, why}"); + continue; + } + const claim = typeof g.claim === "string" ? g.claim.replace(/\s+/g, " ").trim() : ""; + if (!claim) { + refuse(g, "it has no claim"); + continue; + } + if ([...claim].length > PROPOSED_CLAIM_MAX) { + refuse(g, `its claim is ${[...claim].length} characters (at most ${PROPOSED_CLAIM_MAX})`); + continue; + } + const ids = Array.isArray(g.ids) ? [...new Set(g.ids.map((x) => String(x ?? "").trim()).filter(Boolean))] : []; + if (!ids.length) { + refuse(g, "it names no clip"); + continue; + } + const unknown = ids.filter((id) => !at.has(id)); + if (unknown.length) { + refuse(g, `${unknown.join(", ")} ${unknown.length === 1 ? "is not a clip" : "are not clips"} of the cut`); + continue; + } + const inGroup = ids.filter((id) => cut.grouped.has(id)); + if (inGroup.length) { + refuse(g, `${inGroup.map((id) => `${id} (${cut.grouped.get(id)})`).join(", ")} ${inGroup.length === 1 ? "is" : "are"} in a group already`); + continue; + } + const sorted = ids.slice().sort((a, b) => at.get(a) - at.get(b)); + const lo = at.get(sorted[0]); + const hi = at.get(sorted[sorted.length - 1]); + if (hi - lo + 1 !== sorted.length) { + const between = cut.order.slice(lo, hi + 1).filter((id) => !ids.includes(id)); + refuse(g, `its clips are not together: ${between.join(", ")} ${between.length === 1 ? "stands" : "stand"} between ${sorted[0]} and ${sorted[sorted.length - 1]}`); + continue; + } + const secs = [...new Set(sorted.map((id) => cut.sectionOf.get(id)))].sort((a, b) => a - b); + if (secs.length > 1) { + refuse(g, `it spans §${secs.join(" and §")}: a group never crosses a section boundary`); + continue; + } + const twice = ids.filter((id) => taken.has(id)); + if (twice.length) { + refuse(g, `${twice.join(", ")} ${twice.length === 1 ? "is" : "are"} in another proposed group (${[...new Set(twice.map((id) => taken.get(id)))].join(", ")})`); + continue; + } + const why = typeof g.why === "string" ? g.why.replace(/\s+/g, " ").trim().slice(0, 300) : ""; + const kept = { section: secs[0], claim, ids: sorted, ...(why ? { why } : {}) }; + const label = `the proposal "${claim.slice(0, 40)}"`; + for (const id of sorted) taken.set(id, label); + groups.push(kept); + } + if (list.length > PROPOSED_GROUPS_MAX) refuse({ more: list.length - PROPOSED_GROUPS_MAX }, `only the first ${PROPOSED_GROUPS_MAX} groups are read`); + return { groups, refused }; +} + +/** The file's document from one ask: the kept groups, each given an id and the status "proposed". */ +export function groupProposalsDocOf({ at, model, request = null, checked }) { + return { + version: 1, + promptVersion: GROUPS_PROMPT_VERSION, + at, + model, + ...(request ? { request: String(request).replace(/\s+/g, " ").trim().slice(0, 2000) } : {}), + groups: (checked?.groups ?? []).map((g, i) => ({ id: `p${i + 1}`, ...g, status: "proposed" })), + refused: (checked?.refused ?? []).map((r) => ({ group: r.group, why: r.why })), + }; +} + +/** The file's problems (empty: it can be read as proposals). */ +export function groupProposalsErrors(doc) { + if (!isObj(doc)) return ["not an object"]; + const errors = []; + if (doc.version !== 1) errors.push("version is not 1"); + if (typeof doc.model !== "string") errors.push("no model"); + if (!Array.isArray(doc.groups)) errors.push("no groups list"); + else + doc.groups.forEach((g, i) => { + if (!isObj(g) || typeof g.id !== "string" || typeof g.claim !== "string" || !Array.isArray(g.ids) || !Number.isInteger(g.section) || !GROUP_PROPOSAL_STATUSES.includes(g.status)) { + errors.push(`groups[${i}] is not { id, section, claim, ids, status }`); + } + }); + if (!Array.isArray(doc.refused)) errors.push("no refused list"); + return errors; +} + +/** `{ doc, error }`: the proposals, or null (no file, or one that is not proposals: `error` says why). */ +export async function readGroupProposals(dir) { + let raw; + try { + raw = await readFile(fileOf(dir), "utf8"); + } catch { + return { doc: null, error: null }; + } + try { + const doc = JSON.parse(raw); + const errors = groupProposalsErrors(doc); + return errors.length ? { doc: null, error: `${GROUP_PROPOSALS_NAME}: ${errors.join("; ")}` } : { doc, error: null }; + } catch (e) { + return { doc: null, error: `${GROUP_PROPOSALS_NAME}: ${e instanceof Error ? e.message : String(e)}` }; + } +} + +/** Write the whole file (tmp + rename). Returns its path. */ +export async function writeGroupProposals(dir, doc) { + const errors = groupProposalsErrors(doc); + if (errors.length) throw new Error(`not group proposals: ${errors.join("; ")}`); + const file = fileOf(dir); + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); + await rename(tmp, file); + return file; +} + +/** The doc with each group of `marks` (`{ [id]: { status, error?, group? } }`) marked at `at`; ids not there are ignored. */ +export function markGroupProposals(doc, marks, at) { + return { + ...doc, + groups: doc.groups.map((g) => { + const m = marks[g.id]; + if (!m) return g; + const { error: _e, ...rest } = g; + return { ...rest, status: m.status, at, ...(m.error ? { error: String(m.error).slice(0, 400) } : {}), ...(m.group ? { group: String(m.group) } : {}) }; + }), + }; +} diff --git a/common/package.json b/common/package.json @@ -55,6 +55,7 @@ "./lib/report/fxParams.mjs": "./lib/report/fxParams.mjs", "./lib/report/videoAssistOps.mjs": "./lib/report/videoAssistOps.mjs", "./lib/report/videoAssistProposals.mjs": "./lib/report/videoAssistProposals.mjs", + "./lib/report/groupProposals.mjs": "./lib/report/groupProposals.mjs", "./lib/report/respellManifest.mjs": "./lib/report/respellManifest.mjs", "./lib/report/panels.mjs": "./lib/report/panels.mjs", "./lib/report/social.mjs": "./lib/report/social.mjs", diff --git a/editor/app/api/ops/_proposeGroups.test.ts b/editor/app/api/ops/_proposeGroups.test.ts @@ -0,0 +1,118 @@ +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 { FAKE_KEY, startFakeAnthropic, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; +import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; +import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; +import { planProposeGroupsJob } from "yt-dlp-transcript-common/controller/proposeGroups"; +import { readGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; +import { GENERATION_PRESETS, 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 type { Paths } from "yt-dlp-transcript-common/lib/paths"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_proposeGroups.test.ts" +// +// The `report-draft` task `propose-groups` (lane L4) end to end in this +// process: the controller the ops route adapts, a synthetic deck cut in a temp +// dir, the fake Anthropic and ollama servers, a temp jobs dir and usage ledger. + +let tmp: string; +let api: FakeAnthropic; +let ol: FakeOllama; +let paths: Paths; +let gen: GenerationSettings; + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "propose-groups-")); + 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); + paths = { + jobsDir: path.join(tmp, ".jobs"), + transcriptsDir: path.join(tmp, "transcripts"), + channelsDir: path.join(tmp, "transcripts", "channels"), + generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), + ollamaUrl: ol.url, + } as Paths; + gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 }, routes: { ...GENERATION_PRESETS.balanced } }); +}); + +after(async () => { + await api.close(); + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +const deps = (g: Partial<GenerationSettings> = {}) => + ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }) }) as ReportDraftDeps; + +async function project(name: string) { + const dir = path.join(tmp, name); + await mkdir(dir, { recursive: true }); + const clip = (id: string, i: number) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8, quote: `words of ${id}` }); + const m = { slug: "s", render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }] } } }, timeline: ["c01", "c02", "c03", "c04"].map(clip) }; + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + return dir; +} + +async function finished(o: Awaited<ReturnType<typeof enqueueReportDraft>>) { + assert.ok(o.result.ok, (o.result as { error?: string }).error); + const job = getRegistry().get(o.result.jobId)!; + void o.result.stream.cancel(); + const done = await o.result.done; + return { job, done, log: await readFile(job.logPath, "utf8") }; +} + +const ANSWER = { groups: [{ section: 0, claim: "The opening claim", ids: ["c01", "c02"], why: "w" }, { section: 1, claim: "Across", ids: ["c02", "c03"], why: "w" }] }; + +test("the body: a project, words optional, no note or scope", () => { + assert.throws(() => parseReportDraftBody({ task: "propose-groups" }), /"project" is the video project's absolute directory/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", article: "a", project: "/p" }), /a propose-groups job names its "project"/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", note: "n_abcd1234" }), /takes no "note"/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", scope: "all" }), /a video-assist job's/); + assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", iteration: 2 }), /takes no iteration/); + assert.deepEqual(parseReportDraftBody({ task: "propose-groups", project: "/p", request: " by day ", dryRun: true }), { task: "propose-groups", article: "", project: "/p", request: "by day", dryRun: true }); +}); + +test("on the local model (the default route): draft:local, one ask, proposals written, ollama unloaded, the manifest untouched", async () => { + const dir = await project("local"); + const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + assert.equal(gen.routes["propose-groups"], "local"); + ol.push(jsonReply(ANSWER)); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps())); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:local"); + assert.match(log, /proposed: §0 c01 c02 — The opening claim/); + assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"propose-groups","project":"[^"]+local","status":"done","summary":"1 group proposed, 1 refused on qwen3:8b"/); + assert.match(log, /unloaded qwen3:8b from ollama/); + const { doc } = await readGroupProposals(dir); + assert.deepEqual(doc!.groups.map((g) => [g.id, g.status, g.claim]), [["p1", "proposed", "The opening claim"]]); + assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); +}); + +test("on the API: draft:api, a ledger row as task propose-groups; the code route: refused unanswered, planned, a session's answer on no model", async () => { + const dir = await project("api"); + api.push(toolTurn("answer", ANSWER)); + const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps({ routes: { ...gen.routes, "propose-groups": "api" } }))); + assert.equal(done.status, "done", log); + assert.equal(job.queueKey, "draft:api"); + const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.deepEqual(rows.map((r) => [r.task, r.model]), [["propose-groups", "claude-sonnet-5-5"]]); + const code = { routes: { ...gen.routes, "propose-groups": "code" as const } }; + const refused = await enqueueReportDraft({ task: "propose-groups", project: dir }, deps(code)); + assert.ok(!refused.result.ok && /routed to Claude Code/.test((refused.result as { error: string }).error)); + const plan = await planProposeGroupsJob(parseReportDraftBody({ task: "propose-groups", project: dir, dryRun: true }), deps(code)); + assert.equal(plan.provider, "code"); + assert.match(plan.request.user, /§1 Two/); + const asked = api.requests.length + ol.requests.length; + const r = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir, answers: { groups: [{ section: 1, claim: "Late", ids: ["c03", "c04"], why: "" }] } }, deps(code))); + assert.equal(r.done.status, "done", r.log); + assert.equal(api.requests.length + ol.requests.length, asked); + assert.equal((await readGroupProposals(dir)).doc!.model, "claude-code"); +}); diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -4,6 +4,7 @@ import { REPORT_DRAFT_BODY_KEYS, enqueueReportDraft, parseReportDraftBody } from import { planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh"; import { planClipsSuggestJob } from "yt-dlp-transcript-common/controller/clipsSuggest"; import { planVideoAssistJob } from "yt-dlp-transcript-common/controller/videoAssist"; +import { planProposeGroupsJob } from "yt-dlp-transcript-common/controller/proposeGroups"; import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; import { jobResponse, ops, opsFail } from "../_lib"; import { refreshEditor, researchEditor } from "../_researchEditor"; @@ -72,6 +73,14 @@ export const dynamic = "force-dynamic"; // umtool's Apply does that); `answers`: a Claude Code session's // `{ops, reply}` (the `code` route); `dryRun: true` answers `{ ok, plan }` // (the prompt, the estimate) and writes nothing. Answers +// `{ ok, jobId, iteration: 0 }`; +// - "propose-groups" (lane L4, controller/proposeGroups.ts): on a umtool +// video project, `project` (its absolute directory) and optional +// `request` (words for the ask) — ONE ask whose checked claim groups land +// in `<project>/group-proposals.json` as proposals (nothing applied; +// umtool's Accept does that, one group at a time); `answers`: a Claude +// Code session's `{groups: [{section, claim, ids, why}]}` (the `code` +// route); `dryRun: true` answers `{ ok, plan }`. Answers // `{ ok, jobId, iteration: 0 }`. // `model` defaults to settings.generation's route for the task (a task routed // to `code` needs one named). `extractorModel` is an API sweep's extractor @@ -109,6 +118,14 @@ export async function POST(request: Request) { return opsFail((e as Error).message); } } + if (body.task === "propose-groups" && body.dryRun === true) { + try { + const plan = await planProposeGroupsJob(parseReportDraftBody(body), deps); + return NextResponse.json({ ok: true, plan }); + } catch (e) { + return opsFail((e as Error).message); + } + } if (body.task === "video-assist" && body.dryRun === true) { try { const plan = await planVideoAssistJob(parseReportDraftBody(body), deps); diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -152,6 +152,8 @@ test("generation_policy sets a preset as its routes, and one route alone", async "clips-suggest": "api", // The video assistant (release 38 lane E): api only in the api preset. "video-assist": "api", + // Claim groups for a cut (lane L4): api only in the api preset. + "propose-groups": "api", }, }, }, @@ -543,3 +545,29 @@ test("generate video-assist: a project and a request (or a note); routed to code assert.match(b.text, /Nothing in the cut changed/); assert.equal(done.sentOf("/api/ops/iterations").length, 0); }); + +test("generate propose-groups: a project (words optional); routed to code, the plan is this session's request; the answer goes back to the editor", async () => { + assert.ok(GENERATE_TASKS.includes("propose-groups")); + assert.match(String((validateGenerateArgs({ task: "propose-groups", article: "a" }) as { error: string }).error), /names its project/); + assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", scope: "all" }) as { error: string }).error), /scope is not a propose-groups job's/); + assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", answers: [] }) as { error: string }).error), /answers is \{"groups"/); + const plan = { estimate: { inputTokens: 900 }, request: { system: "You organise a video's cut…", user: "THE CUT NOW:\n§0 (the opening)\n- c01: \"words\"" } }; + const code = editor({ policy: { routes: { ...POLICY.routes, "propose-groups": "code" } }, plan }); + const a = await generateTool({ task: "propose-groups", project: "/r/p" }, code.deps as never); + assert.equal(a.isError, undefined, a.text); + assert.match(a.text, /^generate propose-groups: routed to Claude Code \(preset balanced\) — propose the claim groups for this cut in this session\./); + assert.match(a.text, /call generate with task "propose-groups", project "\/r\/p", answers: \{"groups": \[\.\.\.\]\}/); + assert.match(a.text, /- c01: "words"/); + assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", dryRun: true }]); + + const answers = { groups: [{ section: 0, claim: "One claim", ids: ["c01"], why: "" }] }; + const done = editor({ + markerJson: { article: "", iteration: 0, task: "propose-groups", project: "/r/p", status: "done", summary: "1 group proposed on claude-code", usd: 0, groups: { proposed: 1, refused: 0, file: "/r/p/group-proposals.json" } }, + }); + const b = await generateTool({ task: "propose-groups", project: "/r/p", answers, wait: true }, done.deps as never); + assert.equal(b.isError, false, b.text); + assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", answers }]); + assert.match(b.text, /^generate propose-groups: job job-1 ended \*\*done\*\* — 1 group proposed on claude-code/); + assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused/); + assert.match(b.text, /Nothing in the cut changed/); +}); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -238,6 +238,7 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (!GENERATE_TASKS.includes(task)) return bad(`task is one of ${GENERATE_TASKS.join(", ")}`); if (task === CLIPS_SUGGEST) return validateClipsSuggestArgs(args, waitSeconds); if (task === VIDEO_ASSIST) return validateVideoAssistArgs(args, waitSeconds); + if (task === PROPOSE_GROUPS) return validateProposeGroupsArgs(args, waitSeconds); if (args.project !== undefined || args.answers !== undefined || args.proposals !== undefined) return bad("project, proposals and answers are a clips-suggest job's"); if (args.request !== undefined || args.scope !== undefined || args.note !== undefined) return bad("request, scope and note are a video-assist job's"); const article = trimmed(args.article); @@ -397,6 +398,80 @@ function validateVideoAssistArgs(args: Record<string, unknown>, waitSeconds: num return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } }; } +// ─── propose-groups (lane L4): claim groups proposed for a umtool project's cut ─── + +const PROPOSE_GROUPS = "propose-groups"; + +function validateProposeGroupsArgs(args: Record<string, unknown>, waitSeconds: number): { ok: true; request: GenerateRequest } | { ok: false; error: string } { + const bad = (error: string) => ({ ok: false as const, error: `generate: ${error}` }); + const project = trimmed(args.project); + if (!project.startsWith("/")) return bad("a propose-groups job names its project: the video project's absolute directory (project)"); + for (const k of ["article", "iteration", "copyOf", "question", "channels", "feedback", "from", "to", "cards", "entries", "force", "autonomy", "extractorModel", "proposals", "scope", "note"] as const) { + if (args[k] !== undefined) return bad(`${k} is not a propose-groups job's (it reads its project)`); + } + const body: Body = { task: PROPOSE_GROUPS, project }; + if (args.request !== undefined) { + const r = trimmed(args.request); + if (r) body.request = r; + } + if (args.model !== undefined) { + const m = trimmed(args.model); + if (!m) return bad("model is text"); + body.model = m; + } + 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.answers !== undefined) { + if (!args.answers || typeof args.answers !== "object" || Array.isArray(args.answers)) return bad('answers is {"groups": [{"section", "claim", "ids", "why"}]}'); + if (body.model) return bad("answers are this session's: no model"); + body.answers = args.answers; + } + 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"'); + if (body.model || body.answers) return bad("give model, via or answers — one"); + 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 GroupsPlanView = { estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } }; + +// The `code` route: this session proposes the groups the editor's plan describes. +export function renderProposeGroupsRequest(body: Body, plan: GroupsPlanView, preset: string): string { + const r = plan.request ?? {}; + return [ + `generate propose-groups: routed to Claude Code (preset ${preset}) — propose the claim groups for this cut in this session.`, + `Read the cut below and give the groups, each {"section", "claim", "ids", "why"}: clips standing together in one section that make one claim.`, + `Then call generate with task "propose-groups", project "${String(body.project)}"${body.request ? `, the same request ${JSON.stringify(String(body.request))}` : ""}, answers: {"groups": [...]} and wait: true — ` + + "the editor checks each group exactly as a model's (clips not together, across a section boundary or in a group already are refused, with the reason) and writes group-proposals.json. " + + "They are PROPOSALS: the operator accepts or rejects each in umtool (the Cut tab). Never write that file or the manifest yourself.", + "", + "## The instructions", + r.system ?? "", + "", + "## The cut", + r.user ?? "", + ].join("\n"); +} + +type GroupsMarker = { project?: string; groups?: { proposed?: number; refused?: number; file?: string | null } }; + +function proposeGroupsSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker & GroupsMarker): ToolAnswer { + const g = m.groups ?? {}; + const lines = [ + `generate propose-groups: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(), + `Project: ${m.project ?? "?"} · ${g.proposed ?? 0} proposed, ${g.refused ?? 0} refused` + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""), + "", + "These are proposals in group-proposals.json: the operator accepts or rejects each in umtool (the Cut tab's group proposals). Nothing in the cut changed.", + ]; + return { text: lines.join("\n"), isError: f.job.status !== "done" }; +} + type AssistPlanView = { scope?: string; estimate?: { inputTokens?: number }; request?: { system?: string; user?: string } }; // The `code` route: this session answers the request the editor's plan names. @@ -669,6 +744,7 @@ async function summarise( if (marker?.task === "verdicts") return verdictsSummary(f, marker); if (marker?.task === CLIPS_SUGGEST) return clipsSuggestSummary(f, marker); if (marker?.task === VIDEO_ASSIST) return videoAssistSummary(f, marker as Marker & AssistMarker); + if (marker?.task === PROPOSE_GROUPS) return proposeGroupsSummary(f, marker as Marker & GroupsMarker); const article = marker?.article ?? hint.article; const n = marker?.iteration ?? hint.iteration; const task = marker?.task ?? hint.task ?? "report-draft"; @@ -762,6 +838,11 @@ export async function generateTool( const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true }); if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true }; return { text: renderVideoAssistRequest(body, (plan.body.plan ?? {}) as AssistPlanView, p.preset) }; + } else if (task === PROPOSE_GROUPS && body.answers === undefined && p.routes[task] === "code") { + // The session proposes them: the editor's plan is the request. + const plan = await editorPost(deps, "/api/ops/report-draft", { ...body, dryRun: true }); + if (plan.kind !== "ok") return { text: describeEditorFailure("generate", plan), isError: true }; + return { text: renderProposeGroupsRequest(body, (plan.body.plan ?? {}) as GroupsPlanView, p.preset) }; } else if (task === "verdicts" && p.routes[task] === "code") { // Verdicts are not a session's to make: the bench's bar names the models. return { @@ -788,7 +869,7 @@ export async function generateTool( 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 = task === CLIPS_SUGGEST || task === VIDEO_ASSIST ? "" : String(body.article); + const article = task === CLIPS_SUGGEST || task === VIDEO_ASSIST || task === PROPOSE_GROUPS ? "" : String(body.article); const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : []; const head = `generate ${task}: queued as job ${jobId}` + @@ -900,20 +981,20 @@ export const GENERATION_TOOLS = [ project: { type: "string", description: - "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist: the video project's absolute directory (its video.manifest.json).", + "clips-suggest: the reactions project's absolute directory (umtool's clip finder) — labels, a why and a rank for its proposals, into clip-suggestions.json (never a clip). Routed to code: the answer is the request, which this session labels and returns as answers. video-assist and propose-groups: the video project's absolute directory (its video.manifest.json); propose-groups proposes claim groups for its cut into group-proposals.json, which the operator accepts or rejects in umtool.", }, proposals: { type: "array", items: { type: "string" }, description: "clips-suggest: only these proposal ids." }, request: { type: "string", description: - 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers.', + 'video-assist: what to change on the video project, in words ("make the joins 0.15 s with less smear") — one ask whose checked edits land in the project\'s assist-proposals.json as proposals the operator applies in umtool. Routed to code: the answer is the request, which this session answers and returns as answers. propose-groups: optional words for the ask ("group the October clips by day").', }, scope: { type: "string", enum: ["look", "clips", "fx", "all"], description: "video-assist: what the ask may touch (default all)." }, note: { type: "string", description: "video-assist: a note on the whole project (n_…) whose text is the request; the proposals are posted to it as the agent's reply." }, answers: { type: "object", description: - 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"} — read as a model\'s answer, written by the editor.', + 'clips-suggest routed to code: this session\'s labels, {"items": [{"id", "label" (≤ 6 words), "why" (one sentence), "score" (1–10)}]}; video-assist routed to code: {"ops": [{"op", "id", "key", "value"}], "reply"}; propose-groups routed to code: {"groups": [{"section", "claim", "ids", "why"}]} — read as a model\'s answer, written by the editor.', }, wait: { type: "boolean", description: "Follow the job and return its iteration's summary (default false)." }, wait_seconds: { diff --git a/settings.json.example b/settings.json.example @@ -274,7 +274,8 @@ "verdicts": "local", "frames": "api", "clips-suggest": "local", - "video-assist": "local" + "video-assist": "local", + "propose-groups": "local" }, "models": { "api": "claude-sonnet-5-5",